Skip to content

refactor(slack): run handle_message as phases in handler_runtime owners - #21040

Merged
bolichen97 merged 1 commit into
mainfrom
refactor/linecap-g22-handler
Oct 18, 2026
Merged

bolichen97 merged 1 commit into
mainfrom
refactor/linecap-g22-handler

Conversation

@bolichen97

@bolichen97 bolichen97 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: Bring src/kiro_crew/slack/handler.py under the repository's 2,000-line cap by splitting its 2,187-line handle_message into named phases in slack/handler_runtime/, with the native Slack turn behaving exactly as before.

slack/handler.py is 3,789 lines, and handle_message alone is 2,187 of them, so moving
whole definitions cannot bring the file under the cap: the turn itself has to be cut into
pieces that can live elsewhere.

Part of #20192

Why it matters

The rule is that no hand-written file exceeds 2,000 lines, and this file changes most
weeks (12 commits in the last 7 days), so it needs headroom: every feature PR that touches
the native turn would otherwise land on top of the cap. One 2,187-line coroutine is also
hard to review: a change to the permission ladder, the delivery verdict or the pre-turn
commands means reading the whole turn.

Not a goal

  • No behaviour change: what reaches Slack, the SEL ledger, the stats, the session manager
    and the provider is the same, in the same order.
  • No new facade mechanism: the facade keeps its compose() composition.
  • No change to the existing handler_runtime owners' code (only comments that name where a
    moved construct now runs), to any gate's strictness, or to the tests' assertions beyond
    the composition contract's own rows (its owner rows, the moved-name count 70 -> 81 and
    shape digest, and its two placement tests replaced by the exact-holder map
    _GUARDED_TOKEN_HOMES, as the campaign's design review approved).
  • No change to what handle_message or handle_interaction accept or return.

What changed (motivation → approach → change)

handle_message keeps its signature, docstring and entry (the stats count, the thread
keys, the channels-governance gate, the hydration and inbound admission), then builds one
_SlackTurn and runs three phases in order. Each phase is the old body text: it opens
with read-only aliases of the turn values it reads and ends by copying onto the turn what
the next phase reads.

new owner (slack/handler_runtime/) what it holds
dispatch.py _dispatch_before_turn: the short-circuits that answer without the model (hook reply, status, sessions, privacy modifiers, ! commands, keyword commands) and the first OPTIONS expiry; maybe_handle_keyword_command, _handle_sessions_command
turn.py _SlackTurn (the turn's state, plus its permit and single verdict) and _run_turn, the turn body from the queued reaction to the finally
permission_ladder.py the stream loop's tool-call screen and permission ladder, _request_approval, handle_interaction, the steer and orphan-reject helpers: every approve_tool / reject_tool site
delivery.py _deliver_answer: the answer's delivery and verdict, then what the finished turn posts
agent_names.py four agent-name helpers; the companion-plugin walk _iter_cc_agent_names stays in the facade below the matcher it reads, so its home-path lines are not re-added

Because the owners run on the facade's globals, every patch of
kiro_crew.slack.handler.<name> reaches the moved code unchanged. Guards that read the
turn's code by path now read the owner that holds each construct (path, row or join edits
only; in the composition contract, owner rows and the exact-holder map), and the
composition contract maps each guarded construct to its exact home files.

Backwards compatibility

Compatible: every name slack/handler.py bound before is still bound there, the same
object (pinned by test_slack_handler_composition_contract.py, and by the facade's frozen
inventory test/campaign_facade_inventories/kiro_crew.slack.handler.json), and the golden Slack /
SEL / session-manager transcripts are unchanged.

Reader: src/kiro_crew/slack/interactions.py:handle_interaction -- chat -- imports it from kiro_crew.slack.handler, which re-exports the permission_ladder.py function composed onto its globals; test_slack_handler_composition_contract.py::test_golden_transcript[interaction_edges]
Reader: src/kiro_crew/slack/transport_dispatch.py:maybe_handle_keyword_command -- chat -- imports it from kiro_crew.slack.handler, which re-exports the dispatch.py function; test_slack_handler_composition_contract.py::test_golden_transcript[keyword_commands]

Tests

  • test/test_handler_turn.py (new): SLACK_TURN_FUNCTIONS, the function list that the
    checks which read handle_message's source share, is handle_message and its phases in
    run order; _SlackTurn raises UnboundLocalError for a value
    read before it is set; release_permit / book_success / book_failure keep the
    closures' order, idempotence and side effects; every turn value a phase reads is set
    before it and every hand-off has a reader (with synthetic self-tests that go red); every
    facade import is read by the facade or an owner, and a function-local import in its own
    function (the property the new setup.cfg F401 row stands in for, with two red
    self-tests); no phase leaves a stale value on the turn (a value a later phase reads,
    through an alias or in place, that the phase rebinds in its body, an except arm or its
    finally is copied in the hand-off that ends the phase, which returns True only there,
    with red self-tests); the "Slack messages" sink redacts the final answer at its own
    boundary; the sync-io-in-async gate still flags a call planted in each owner coroutine.
    46 tests; 5 runs at -n0 and one at -n 3 pass.
  • test_slack_handler_composition_contract.py: owner rows, the moved-name count (70 -> 81)
    and shape digest (recomputed at the base); the two placement tests become
    _GUARDED_TOKEN_HOMES, an exact holder set per guarded construct, plus its counts in
    their homes. These are the only assertion edits in a test this PR does not add.
  • test/campaign_facade_inventories/kiro_crew.slack.handler.json (new): the facade's 200
    public names at the base, read by test_campaign_facades_base_public_names.py, with
    handle_interaction and maybe_handle_keyword_command checked to be their owners' own
    objects in a fresh interpreter.
  • Path re-points (assertions unchanged; one failure message names the new path), each
    proven by a mutation in the new home that turns the guard red: test_transport_permission_floor, test_messaging_deny_notice,
    test_hooks, test_turn_ceiling, test_memory_v2_isolation, test_reinjection_gate,
    test_runtime_death_is_a_process_event, test_security_posture,
    test_messaging_auto_title, test_options_click_validation,
    test_slack_options_lifecycle, test_agent_spec_hardened_reads,
    test_persist_off_loop, test_name_grant_surfaces, test_slack_status_keyword.

Move audit

move_audit.py (campaign tool, BASE 213339f671):

src/kiro_crew/slack/handler.py: 3789 -> 1065 lines; moved 29.93% (python-ast)
   changed: handle_message [AsyncFunctionDef] 2187 lines
   changed: _reject_orphaned_tool [AsyncFunctionDef] 37 lines
   changed: Expr [Expr] 14 lines
  • handle_message is decomposed, not moved whole. A statement-level audit finds every
    BASE statement of it unchanged in the facade or an owner except 30 leaf statements
    (63 lines): the two docstring wordings below, and the delivery's permit and verdict
    closures (_release_permit() -> turn.release_permit(), _book_success() ->
    turn.book_success(), await _book_failure() -> await turn.book_failure(), their
    bodies as _SlackTurn methods with self. re-plumbing, _verdict_booked / _had_error
    read off the turn). Other edits, all asserted by the recipe: bare return -> return False (7 in the dispatch, 4 in the turn body), continue -> return and the
    rejected-click break -> return True in the two ladder branches, the read-only
    aliases at each phase start and the hand-off blocks at each end (the turn carries the
    turn body's linked_session_key as routed_link_key, because an attribute of that name is a
    session's channel link to test_crew_log_class_recorder), _user_text: str (a
    declared type mypy needs once the closure lives in an owner), 18 comment wordings that
    named a place now in another phase or carried "no longer", and two nosemgrep lines.
  • _reject_orphaned_tool: its docstring's "no longer" is reworded (the comment-history
    gate reads moved lines).
  • Expr: the facade's _facade_compose(...) call (the shared helper), with the five new
    owners in its tuple.
  • Moved verbatim: four agent-name helpers, maybe_handle_keyword_command,
    _handle_sessions_command, _should_auto_approve_spawn, _steer_host_deny,
    _request_approval, handle_interaction.

Logger: owner functions read the facade's logger, so log records still come from
kiro_crew.slack.handler.

Diff alignment

Every changed file adds the same lines under git's default diff and --minimal, except
two whose default diff re-shows blank lines only: docs/system-specs/modules/slack-gateway.md
(109 / 106: three blank lines) and test/test_slack_handler_composition_contract.py
(137 / 135: two blank lines). Every block order of the new contract tests and every
paragraph order of the rewritten spec section gives the same or a larger difference; the
re-shown lines are blank (an accepted alignment exception).

CI path references

None: no workflow path filter or file list names slack/handler.py.

Re-points and citations

Guards that read a construct by path now read the owner that holds it (path, row or join
edits; no assertion changed): test_transport_permission_floor,
test_messaging_deny_notice, test_hooks, test_turn_ceiling, test_memory_v2_isolation,
test_reinjection_gate, test_runtime_death_is_a_process_event, test_security_posture
(census row split 3 -> 2 + 1), test_messaging_auto_title, test_options_click_validation,
test_slack_options_lifecycle, test_agent_spec_hardened_reads, test_persist_off_loop,
test_name_grant_surfaces, test_slack_status_keyword; negative scans read the facade and
every owner. Each re-point has a mutation in the new home that turns its guard red. Beyond
paths, rows and joins, the only assertion edits are the composition contract's own rows
(owner rows, the moved-name count 70 -> 81, the shape digest) and its two placement tests,
replaced by _GUARDED_TOKEN_HOMES as the campaign's design review approved; the two
handle_message source readers take their function list from test_handler_turn.py.
Citations corrected (comments and docstrings only):

  • source: platform/interfaces.py, slack/events.py (2), slack/transport_dispatch.py,
    session_map.py; in the unchanged owners, handler_runtime/stream.py (the _AnswerStream
    docstring and four comments on the turn loop's catch-all), handler_runtime/commands.py
    (3) and handler_runtime/turn_context.py;
  • tests: test_hooks.py:2093, test_messaging_auto_title.py:537 and :681,
    test_messaging_deny_notice.py:727, test_options_click_validation.py:298, and the
    failure message at test_runtime_death_is_a_process_event.py:1164;
  • the specs that named slack/handler.py as the home of moved code, and
    ops-mission-control.md's note that its Slack board is a separate egress boundary from
    the Slack messages sink (now slack/handler_runtime/delivery.py).
    setup.cfg turns F401 off for slack/handler.py (the slack/gateway.py precedent);
    test_handler_turn.py asserts the property it stood for. .github/file-line-cap-baseline.txt
    loses its slack/handler.py row (now 1,065 lines); the baselined files that grow are listed
    below.

Redaction sink row moves with its code (visible change)

The "Slack messages" row of security_posture._REDACTION_SINKS now names
slack/handler_runtime/delivery.py, which holds the sink's final redaction pass, so the
security posture panel shows that path instead of slack/handler.py. The sink-redacts
checks then read the module that actually redacts the posted answer. slack/handler.py,
which keeps only _display_redactor (the canonical-order pair the delivery's fallback egress
uses), moves into NON_EGRESS_REDACTION_MODULES, and delivery.py leaves that list. The Ops
Mission Control row's detail now says "a separate egress boundary from the Slack messages
sink" rather than naming slack/handler.py. A new test in test_handler_turn.py pins the
sink's own pass: with the render made pass-through and a key split across two chunks (so the
per-chunk pass sees no whole key), the final posted text is still redacted, both on the no-stream
chat.update fallback and in the text the stream is sealed with. Dropping delivery's final
credential pass turns both cases red. With that pass dropped, the 36 test files that drive
handle_message with credential-shaped text and test_security_posture.py all stayed green
(3,299 tests), so this test is the one that notices.

Baselined growth (L56 addendum 1)

Two baselined test files grow past their row on main. Their rows stay exactly as main has them:

file main row this head why
test/test_slack_options_lifecycle.py 2730 (the file on main: 2733) 2735 (+2 here) the handle_message source readers read the handler's phase functions as one text (imported from test_handler_turn.py)
test/test_slack_handler_composition_contract.py 2650 (the file on main: 2656) 2686 (+30 here) the owner rows and _GUARDED_TOKEN_HOMES, which replaces the two placement tests; accepted at Master review 26227984

Baselined growth (L56 addendum 1b)

file main row this head rows
src/kiro_crew/security_posture.py 3181 (the file on main: 3345) 3349 (+4) NON_EGRESS_REDACTION_MODULES: slack/handler.py, slack/handler_runtime/dispatch.py, slack/handler_runtime/permission_ladder.py, slack/handler_runtime/turn.py (the block's comment is rewritten in place, with no added lines)

References not edited (cost)

  • website/src/pages/settings/SecurityPanel.test.tsx:211: a mocked posture row reads
    'handler.py — final pass'; the "Slack messages" sink is now slack/handler_runtime/delivery.py.

Gate floor

scripts/local-gate.py --dry-run selects 2,835 backend and 1,382 frontend files, over the
campaign's local cap, so the floor ran instead: every test file that imports, patches or
reads the handler or its owners, the re-pointed guards and the repository guards that scan
them (166 files, -n 3): 11,959 passed. Cold mypy src/kiro_crew (2,437 files): clean.
black, isort and flake8 on the changed files, check_black_formatting,
check_subprocess_encoding, check_agent_sdk_boundary, check_sync_io_in_async, the
comment-history, brand, harness-parity, memory-store-seam and feature-map gates,
docs_lint.py (and --test), check_file_line_cap.py and
test_flake_pattern_ratchet.py: all pass. Semgrep 1.78 (the CI rule set) over the changed
files reports no finding the base did not already have. Per-file line coverage from the
floor run: agent_names.py 97.8%, dispatch.py 99.1%, turn.py 95.1%,
permission_ladder.py 94.7%, delivery.py 81.3%, handler.py 98.0%.
A wheel built from a git archive of the commit, installed in a fresh venv, imports
the facade and every new owner under an isolated HOME.

Manual verification

N/A — a structural move: the 65 recorded golden transcripts replay byte-identical, and
the existing handler, interaction and transport suites pass unchanged.

Related Issues

Part of #20192

Follow-up: #21320 (the deferred comment citation above)

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

@bolichen97
bolichen97 requested review from a team and KiroCrewCaptain as code owners October 16, 2026 01:46
@bolichen97
bolichen97 requested a review from buluoray October 16, 2026 01:46
@bolichen97

bolichen97 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Sensitive change review

  • Head commit: 7c997d2
  • What rule changed: no redaction rule changes; security_posture.NON_EGRESS_REDACTION_MODULES lists the four slack/handler_runtime owners (delivery, dispatch, permission_ladder, turn) that now hold redactor calls moved verbatim out of slack/handler.py, beside the owners already listed there.
  • Before -> after: the same redactor call sites run on the same inputs in the same handler process; they are classified under the owners' module paths instead of the facade's, and slack/handler.py stays the registered "Slack messages" sink.
  • Worst case if wrong: a redactor call in an owner would be unclassified and the drift guard in test/test_security_posture.py would go red; nothing reaches Slack differently, because the code that redacts is unchanged.
  • Evidence checked: test/test_security_posture.py passes with its log-site census row split 3 -> 2 + 1 (total unchanged); a mutation that adds a redactor call in an unlisted owner turns the omission guard red; the 65 recorded golden Slack, SEL and session-manager transcripts replay byte-identical.
  • Tools still work: the native Slack turn, approval clicks and keyword commands run the same code through the facade's compose(), covered by the unchanged handler, interaction and transport suites.
  • Backward compatible: every name kiro_crew.slack.handler bound before is still bound there as the same object, pinned by the composition contract.
  • Existing tests: assertions unchanged apart from path, row and join re-points (each proven by a mutation) and the composition contract's own owner rows, all listed in the PR body.
  • How to undo: revert this one commit; the registry rows and the owner files go together, and no stored data or config depends on them.

@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Oct 16, 2026
@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Sensitive Change Review

Sensitive files changed:

  • src/kiro_crew/security_posture.py

  • @bolichen97 posted a complete reasoning template for 35dc7e2.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — ⏭️ skipped

Revision 35dc7e2326dd2b642ed01d15bd7007de360977c3 touches no user-facing surface (no changes under website/ or committed screenshots), so the UX review was skipped. Advisory — does not block merge.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — ✅ PASS

Premise-level review of 35dc7e2326dd2b642ed01d15bd7007de360977c3 — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: PASS

Before merging, check the 30 rewritten leaf statements: the permit and verdict closures, now _SlackTurn methods, must release and book in the same order as before.

What this change ships

Inventory (8 items) — 8 justified

Intent: bring slack/handler.py under the 2,000-line cap without changing what a Slack turn does. This is a FIX for a documented invariant, done as a pure refactor.

  1. handle_message now runs as three phases (_dispatch_before_turn, _run_turn, _deliver_answer) that live in new handler_runtime/ owners — justified
  2. A per-turn state object, _SlackTurn, carries the old locals from one phase to the next and raises UnboundLocalError when a value is read before it is set — justified
  3. Approval and interaction handling moves to permission_ladder.py, still re-exported from the facade — justified
  4. The facade's row is removed from the line-cap baseline (3789 → 1065 lines) — justified
  5. setup.cfg turns off F401 for slack/handler.py, following the existing slack/gateway.py row, and a test asserts what F401 stood for — justified
  6. The "Slack messages" sink registration now points at delivery.py, and the security-posture egress list names the new owners — justified
  7. Guard tests and specs now point at the file that holds each construct; the composition contract uses _GUARDED_TOKEN_HOMES — justified
  8. New test_handler_turn.py (33 tests) and a frozen facade inventory JSON, one of 69 such inventories — justified

[FIRST-PRINCIPLES-REVIEWED] 35dc7e2

Description read

[DESCRIPTION-READ] 9c6b296af30aa4f3fc43cd8f78f7e563f11d49a87302b918e4ef3ed9df8e3662

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — ✅ PASS

Design-level review of 35dc7e2326dd2b642ed01d15bd7007de360977c3 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: PASS

Check that the golden transcripts reach the hand-off-heavy edges (compaction replay, session-not-found retry, an orphan reject mid-stream), since those are where a stale _SlackTurn copy would show.

[DESIGN-REVIEWED] 35dc7e2

Description read

[DESCRIPTION-READ] 9ec54cc81d900baf43928bfb0db0bd73fa2cf4e734d1024f26e674626e7f6b12

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

Reviewed 35dc7e2326dd2b642ed01d15bd7007de360977c3 — this comment is updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] 35dc7e2

Verdict parsed from the review's SHA-scoped output markers for commit 35dc7e2326dd2b642ed01d15bd7007de360977c3.

False positive or not applicable? A repository writer can comment:
/ai-review override fable 35dc7e2326dd2b642ed01d15bd7007de360977c3: <one-sentence reason>

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — ✅ no blocking findings

GPT 6.1 completed its review of 35dc7e2326dd2b642ed01d15bd7007de360977c3 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 35dc7e2

False positive or not applicable? A repository writer can comment:
/ai-review override gpt 35dc7e2326dd2b642ed01d15bd7007de360977c3: <one-sentence reason>

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • PASS punchline: a cancellation landing at _deliver_answer's first await — rebutted (already covered by an existing test)

test/test_slack_success_after_delivery_10050.py::test_native_cancel_at_predelivery_yield_releases_permit raises CancelledError at exactly that await, the asyncio.sleep(0) that opens _deliver_answer's structural try, and asserts the session permit is released.
It patches kiro_crew.slack.handler.asyncio, and compose() runs _deliver_answer on the facade's globals, so the patch reaches the owner. The test passes on this head.
Mutation proof: dropping turn.release_permit() from the release finally in delivery.py turns it red ("permit stranded by a cancellation at the pre-delivery yield").
No suspension point sits between _run_turn returning and _deliver_answer's try. Awaiting a coroutine runs it synchronously up to its first await, and _deliver_answer reaches the try through plain assignments only. The base function's await points are therefore the same ones, in the same order.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • PASS punchline: the setup.cfg F401 exemption for slack/handler.py — rebutted (the exemption is deliberate, and a test pins what F401 checked)

compose() runs each owner function on the facade's globals, so an import that only an owner reads is still a live name in the facade. flake8 cannot see such a read, so the per-file F401 row is the form slack/gateway.py already uses for the same mechanism.
test/test_handler_turn.py::test_every_facade_import_is_read_by_the_facade_or_an_owner asserts what F401 stood for. Every facade import is read by the facade or an owner, or is one of a frozen list of names the facade exported at the base for other modules. A function-local import must be read in its own function.
Three synthetic red self-tests prove that check is not vacuous: a dead module import, a dead function-local import and a dead owner re-export.

@bolichen97
bolichen97 enabled auto-merge (squash) October 16, 2026 02:05
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: checking Automated validation is still running labels Oct 16, 2026
@bolichen97
bolichen97 force-pushed the refactor/linecap-g22-handler branch from 261348b to da7392f Compare October 16, 2026 09:59
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge labels Oct 16, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author

Sensitive change review

  • Head commit: da7392f
  • What rule changed: no redaction rule changes; security_posture.NON_EGRESS_REDACTION_MODULES lists the four slack/handler_runtime owners (delivery, dispatch, permission_ladder, turn) that now hold redactor calls moved verbatim out of slack/handler.py, beside the owners already listed there.
  • Before -> after: the same redactor call sites run on the same inputs in the same handler process; they are classified under the owners' module paths instead of the facade's, and slack/handler.py stays the registered "Slack messages" sink.
  • Worst case if wrong: a redactor call in an owner would be unclassified and the drift guard in test/test_security_posture.py would go red; nothing reaches Slack differently, because the code that redacts is unchanged.
  • Evidence checked: test/test_security_posture.py passes with its log-site census row split 3 -> 2 + 1 (total unchanged); a mutation that adds a redactor call in an unlisted owner turns the omission guard red; the 65 recorded golden Slack, SEL and session-manager transcripts replay byte-identical.
  • Tools still work: the native Slack turn, approval clicks and keyword commands run the same code through the facade's compose(), covered by the unchanged handler, interaction and transport suites.
  • Backward compatible: every name kiro_crew.slack.handler bound before is still bound there as the same object, pinned by the composition contract.
  • Existing tests: assertions unchanged apart from path, row and join re-points (each proven by a mutation) and the composition contract's own owner rows, all listed in the PR body.
  • How to undo: revert this one commit; the registry rows and the owner files go together, and no stored data or config depends on them.

@bolichen97
bolichen97 force-pushed the refactor/linecap-g22-handler branch from da7392f to 81f5556 Compare October 16, 2026 10:24
@bolichen97

Copy link
Copy Markdown
Contributor Author

Repair push: 81f555662a is the head and supersedes da7392f69c and 261348b248. It is still one commit, rebuilt by the split recipe on 5c1f9970be.

da7392f69c was a rebase pushed from outside the review flow. Its thread_link_key naming and its setup.cfg row order were never reviewed. This head carries the reviewed repair instead, and in setup.cfg it keeps both main's config/sections.py row and this PR's slack/handler.py row.

Red guard: test/test_crew_log_class_recorder.py::test_every_link_assignment_records_the_class_it_changed (Backend Tests 3.12 shard 7, Windows shard 7, and Coverage Gate failing closed on it) — fixed in 81f555662a.

  • Cause: the guard reads any assignment to an attribute named linked_session_key as a commit of a session's channel link. The hand-off block at the end of _run_turn copied the turn body's local linked_session_key onto the turn under that same name, so the guard read split glue as a link commit. At the base the value was a bare local, so nothing matched.
  • Fix: the turn carries that value as routed_link_key. That covers _SlackTurn's declaration, with a comment saying why, the hand-off line in _run_turn, and the one alias line in _deliver_answer. The local names and all behaviour are unchanged, and the guard and its exemption list are untouched.
  • Proof: the guard passes, and planting turn.linked_session_key = ... back in turn.py turns it red again (it names slack/handler_runtime/turn.py:_run_turn), so it still scans every handler_runtime owner.

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Oct 16, 2026
@bolichen97
bolichen97 force-pushed the refactor/linecap-g22-handler branch from 81f5556 to 7c997d2 Compare October 16, 2026 12:32
@bolichen97

Copy link
Copy Markdown
Contributor Author
  • Watch: the alias/copy split can go stale with no test failing — fixed in 7c997d2972

test/test_handler_turn.py::test_no_phase_leaves_a_stale_value_on_the_turn now fails in three cases: a phase rebinds a local that a later phase reads back as turn.<x> without copying it in the hand-off that ends its body; a phase returns True anywhere but its last statement; or _run_turn rebinds a value it copied for the ladder before the loop that calls the ladder ends.
Each rule has a synthetic self-test on a string fixture that goes red, plus one sound fixture that stays green. On the real phases the scan reports 0 faults, and a non-vacuity check asserts that each handing phase does rebind a later-read value and copies it.
Mutation proof on real code: dropping turn.text = text from _dispatch_before_turn's hand-off turns the new test red while the old plumbing test stays green, which is the gap this item named. Dropping turn._stop_reason from _run_turn turns it red too.

@bolichen97

Copy link
Copy Markdown
Contributor Author

Round 2 push: 7c997d2972 supersedes 81f555662a. Main moved, so it is rebased onto 6362ff1c73 (range-diff =) and is still one commit. It adds one change: a test-only guard in test/test_handler_turn.py answering the Design Watch item (disposition above). 81f555662a was fully green, and the Opus re-run on it found nothing.

@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Oct 16, 2026
@bolichen97
bolichen97 force-pushed the refactor/linecap-g22-handler branch from 93511ca to b7b3590 Compare October 18, 2026 07:16
@github-actions github-actions Bot removed the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 18, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author

Sensitive change review

  • Head commit: b7b3590
  • What rule changed: no redaction rule changes. The "Slack messages" row of security_posture._REDACTION_SINKS names slack/handler_runtime/delivery.py, which now holds that sink's final redaction pass; NON_EGRESS_REDACTION_MODULES gains slack/handler.py (it keeps only _display_redactor, the canonical-order pair the delivery's fallback egress uses) and the dispatch, permission_ladder and turn owners, and delivery.py is no longer in it.
  • Before -> after: the same redactor calls run on the same inputs in the same handler process; the security posture panel shows the "Slack messages" sink at slack/handler_runtime/delivery.py instead of slack/handler.py, and the Ops Mission Control row's detail says "a separate egress boundary from the Slack messages sink" instead of naming slack/handler.py.
  • Worst case if wrong: a module would be misclassified and the drift guards in test/test_security_posture.py would go red, or the panel would show a path that does not hold the pass; nothing reaches Slack differently, because the code that redacts is unchanged.
  • Evidence checked: test/test_security_posture.py passes (sink-redacts, prose-claim, both-buckets and omission checks, the log-site census split 3 -> 2 + 1); the new test_handler_turn.py::test_the_slack_messages_sink_redacts_what_its_render_let_through goes red when delivery's final credential pass is dropped, which no other test in the slack, posture and credential suites noticed; the 65 recorded golden Slack, SEL and session-manager transcripts replay byte-identical.
  • Tools still work: the native Slack turn, approval clicks and keyword commands run the same code through the facade's shared compose helper, covered by the unchanged handler, interaction and transport suites.
  • Backward compatible: every name kiro_crew.slack.handler bound before is still bound there as the same object, pinned by the composition contract and the facade inventory.
  • Existing tests: assertions unchanged apart from path, row and join re-points (each proven by a mutation) and the composition contract's own owner rows, all listed in the PR body.
  • How to undo: revert this one commit; the registry rows and the owner files go together, and no stored data or config depends on them.

@bolichen97

Copy link
Copy Markdown
Contributor Author

Refresh push: b7b3590a57 supersedes 93511ca12d. It is still one commit, now on main 9d088c85ad, and has no code change. Its -U0 patch matches the one at 93511ca12d, except that three row conflicts were resolved by keeping both sides' rows.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: passed Eligible automated validation passed for the current revision labels Oct 18, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author
  • PASS punchline: the golden Slack/SEL/session-manager transcripts were recorded at base and this diff leaves them unchanged — confirmed (byte-identical to base; mutation-proven)

In test/test_slack_handler_composition_contract.py, the region from # ── golden scenarios through assert sorted(_GOLDEN_DIGESTS) == sorted(SCENARIOS) (1,039 lines: the scenarios, the 65 _GOLDEN_DIGESTS entries and test_golden_transcript) is byte-identical to base 213339f671. The only edit above it in the file is one import line. All other edits sit below it, in the owner tables.
The 65 goldens pass at this head and drive the moved code through the facade's public callbacks. Each phase owner was mutated once on real code: dispatch's "Permission denied." text fails 1 scenario, _run_turn's error text fails 1, and delivery's final answer text fails 38 of 65. The unmutated tree passes all 65.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • PASS punchline: the permit _run_turn defers on a clean completion is always released by _deliver_answer's finally, with no await between the two phases — confirmed (by construction and by test; mutation-proven)

The defer and its release. _run_turn's finally defers the release only when _acquired and _turn_completed_ok and _body_completed. Every other exit releases there. The facade then runs if await _dispatch_before_turn(turn) and await _run_turn(turn): await _deliver_answer(turn).
No await in the gap. Between that finally and _deliver_answer's outer try:, the code does only three things:

  • plain attribute sets on _SlackTurn, which has no __slots__ or __setattr__;
  • the synchronous status_ctrl.finalize;
  • return True and entry into the coroutine.
    No line there is an await. A task cancellation lands only at an await, so none can arrive before the try whose finally calls turn.release_permit(). On the deferred-OPTIONS path, the tail's own finally releases the permit instead.
    The tests. test_slack_success_after_delivery_10050.py::test_cancelled_after_completion_still_releases_permit cancels at stop_stream, and ::test_native_cancel_at_predelivery_yield_releases_permit cancels at delivery's first asyncio.sleep(0). Both are unchanged tests. With the structural release removed from that finally, both fail at this head ("permit stranded ..."). ::test_native_permit_released_only_after_accounting pins the deferral itself.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • PASS punchline: check the return False / return True rewrites, since one wrong value makes handle_message skip delivery or the model with no error — confirmed (13 of 13 mutations killed, each by a behavioural test)

The sweep. On real code at b7b3590a57 (same patch as this head), each early-exit return False and each closing return True of _dispatch_before_turn and _run_turn was flipped, one per run. Each run used the 43 test files that drive handle_message (-n 3). The unmutated baseline: 2,327 passed.
Runs that include test_handler_turn.py. All 13 fail. For 9 of them the first failure is the static guard test_no_phase_leaves_a_stale_value_on_the_turn, which reports an early return True before the hand-off.
Without that file, a behavioural test still kills each of those 9. The unchanged tests named below raise UnboundLocalError or InvalidTransition, or fail a golden digest.

site flip first behavioural failure
dispatch.py:116 (link intercept) False→True test_handler_link_intercept.py::TestLinkedThreadIntercept::test_redact_for_ui_original_for_llm
dispatch.py:146 (auto-reply) False→True test_slack_handler.py::TestHookIntegration::test_auto_reply_skips_acp
dispatch.py:154 (stats) False→True golden cmd_status
dispatch.py:189 (unauthorized) False→True test_handler_link_intercept.py::TestSessionsKeywordFallThrough::test_handle_message_reaches_sessions_command_when_linked
dispatch.py:201 (modifier only) False→True golden privacy_modifiers
dispatch.py:217 (keyword command) False→True test_slack_handler.py::TestAgentCommand::test_agent_full_filename_resolves
dispatch.py:241 (spawn/run/cron) False→True test_slack_handler.py::TestHookIntegration::test_spawn_command_records_agent_in_first_turn
dispatch.py:272 (enter the turn) True→False test_channel_activation.py::TestHandlerChannelAgent::test_channel_agent_passed_to_session
turn.py:731 (cancelled before the model) False→True golden cancelled_messages
turn.py:746 (replay stopped) False→True golden replay_stopped_before_prompt
turn.py:792 / :796 (gateway shutting down) False→True golden turn_ceiling_and_shutdown
turn.py:1212 (deliver) True→False test_credential_redaction_notice.py::TestSlackRedactionNotice::test_redacted_answer_posts_a_warning_and_keeps_redaction

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Oct 18, 2026
slack/handler.py is 3,789 lines and handle_message alone is 2,187, so
moving whole definitions cannot bring the file under the repository's
2,000-line cap. handle_message keeps its entry and inbound admission,
then runs its turn as three phases over one _SlackTurn:
_dispatch_before_turn (dispatch.py), _run_turn (turn.py) and
_deliver_answer (delivery.py). The stream loop hands each tool call and
permission request to permission_ladder.py, which also takes the
approval prompt and the click that answers it, and four agent-name
helpers move to agent_names.py. The facade's compose() runs every owner
on its globals, so a patch of kiro_crew.slack.handler.<name> still
reaches the moved code. handler.py is now 1,063 lines.

Each phase body keeps its text: it opens with aliases of the turn
values it reads and ends by copying onto the turn what the next phase
reads, and the delivery's permit and verdict closures become the turn's
methods. Guards that read the turn's code by path now read the owner
that holds each construct, and the composition contract maps every
guarded construct to the exact files that hold it.

Part of #20192
@bolichen97
bolichen97 force-pushed the refactor/linecap-g22-handler branch from b7b3590 to 35dc7e2 Compare October 18, 2026 11:57
@bolichen97

Copy link
Copy Markdown
Contributor Author

Sensitive change review

  • Head commit: 35dc7e2
  • What rule changed: no redaction rule changes. The "Slack messages" row of security_posture._REDACTION_SINKS names slack/handler_runtime/delivery.py, which now holds that sink's final redaction pass; NON_EGRESS_REDACTION_MODULES gains slack/handler.py (it keeps only _display_redactor, the canonical-order pair the delivery's fallback egress uses) and the dispatch, permission_ladder and turn owners, and delivery.py is no longer in it.
  • Before -> after: the same redactor calls run on the same inputs in the same handler process; the security posture panel shows the "Slack messages" sink at slack/handler_runtime/delivery.py instead of slack/handler.py, and the Ops Mission Control row's detail says "a separate egress boundary from the Slack messages sink" instead of naming slack/handler.py.
  • Worst case if wrong: a module would be misclassified and the drift guards in test/test_security_posture.py would go red, or the panel would show a path that does not hold the pass; nothing reaches Slack differently, because the code that redacts is unchanged.
  • Evidence checked: test/test_security_posture.py passes (sink-redacts, prose-claim, both-buckets and omission checks, the log-site census split 3 -> 2 + 1); the new test_handler_turn.py::test_the_slack_messages_sink_redacts_what_its_render_let_through goes red when delivery's final credential pass is dropped, which no other test in the slack, posture and credential suites noticed; the 65 recorded golden Slack, SEL and session-manager transcripts replay byte-identical.
  • Tools still work: the native Slack turn, approval clicks and keyword commands run the same code through the facade's shared compose helper, covered by the unchanged handler, interaction and transport suites.
  • Backward compatible: every name kiro_crew.slack.handler bound before is still bound there as the same object, pinned by the composition contract and the facade inventory.
  • Existing tests: assertions unchanged apart from path, row and join re-points (each proven by a mutation) and the composition contract's own owner rows, all listed in the PR body.
  • How to undo: revert this one commit; the registry rows and the owner files go together, and no stored data or config depends on them.

@bolichen97

bolichen97 commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor Author

MAIN_RED #5 refresh: 35dc7e2326 supersedes b7b3590a57. It is still one commit, now on main 196ab16e6d, which carries #21792. There is no code change: the -U0 patch is byte-identical to b7b3590a57's.

The reds at b7b3590a57 were not this PR's:

  • Backend Tests (3.12, 1) and Backend Tests (Windows) (1): test/test_history_bindings.py::test_the_member_set_is_the_frozen_inventory was red on main itself, and test(history): list the members #21108 added in the frozen inventory #21792 fixes it. It passes at this head.
  • Coverage Gate: it fails closed behind that backend red (backend-test=failure -- failing closed).
  • Opus 5.5 Review: discovery ran 21 turns and ended success, but its final text carried no [OPUS-DISCOVERY] marker, so the lane failed closed with no verdict. This push re-runs it.

Nothing upstream since b7b3590a57's base touches slack/handler.py or slack/handler_runtime/. Upstream did change some test files that import the facade (dashboard and messaging splits, the residue report, the paragraph-break fix), but none of their changed lines names the handler, its owners or a moved name.

Gates on the rebased head (pytest -n 3): those changed importers (test_aws_control_app, test_handlers_messaging_composition_contract, test_host_isolation_floor, test_messaging_driver, test_agent_spec_hardened_reads, test_security_posture) plus the handler, contract, facade-inventory, mirrored-owner and session-not-found suites: 1,346 passed. test_history_bindings.py passed in the earlier gate on 5699d4b. Line cap: 0 failures.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Oct 18, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author
  • PASS punchline: the permit and verdict closures, now _SlackTurn methods, release and book in the same order as before — confirmed (statement-identical to base; mutation-proven at the method and at the call sites)

The methods. _SlackTurn.release_permit, book_success and book_failure are base's _release_permit, _book_success and _book_failure closures statement for statement, in the same order. The only changes are nonlocal x becoming self.x, plus one comment pointer ("the finally above" now reads "_run_turn's finally").
test_handler_turn.py records each method's calls against a double, in the closures' order: test_release_permit_releases_then_closes_the_gap_once, test_book_success_books_once_in_the_closures_order, test_book_failure_books_once_and_marks_the_error and test_a_booked_verdict_is_never_booked_again. Each order is mutation-proven on real code:

  • closing the replay gap before the release fails the release test;
  • moving record_success after the stats bump fails 3 tests.
    The call sites. The 30 rewritten leaf statements are those calls, each in its base position (_release_permit() → turn.release_permit(), _book_success() → turn.book_success(), await _book_failure() → await turn.book_failure()). The golden session-manager transcripts record that order. Releasing before the verdict on delivery's main path fails 27 of the 65 goldens.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • PASS punchline: the golden transcripts reach the hand-off-heavy edges (compaction replay, session-not-found retry, an orphan reject mid-stream) — mostly confirmed; the one edge they miss is covered by the static guard

Which edges the goldens drive.

  • Compaction replay: compaction_failed_transient_replay, compaction_failed_permanent, cmd_compact and replay_stopped_before_prompt.
  • A reject mid-stream: tool_then_rejected_while_streaming.
  • The error arms: error_acp, error_after_partial_text, error_from_trusted_bot and the rest.
  • The session-not-found retry has no golden. The five Slack cases in test_session_not_found_surfaces.py drive it instead (replay once, a second loss, no replay after output, the stale credential, the credential give-up).
    A stale copy, per field. On real code, each field was copied onto the turn right after its first binding and the closing copy was dropped. Only the 42 behavioural handler suites ran; the static guard was left out:
  • _replayed: 4 fail (the compaction-replay goldens and TestTransientCompactionRetry);
  • _had_error: 8 fail (the error-arm goldens);
  • routed_link_key: 0 fail. Its only later change is the claim loop re-reading the thread owner (turn.py:523/:548), a race where the thread is relinked while the claim waits. No behavioural test drives that race, at base either.
    test_no_phase_leaves_a_stale_value_on_the_turn fails on all three and names the line ("_run_turn:407 rebinds linked_session_key ..."). A dropped copy with no early copy fails loudly: 285 tests raise UnboundLocalError, because a declared value that was never set raises when read.

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Oct 18, 2026

@KiroCrewCaptain KiroCrewCaptain left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved on the watch holder's request. Every check on the head passes; the triage cron held it on a size, path, checklist or lane-note rule. Any standing lane note stays on the record.

@bolichen97
bolichen97 merged commit 8204775 into main Oct 18, 2026
157 of 158 checks passed
@bolichen97
bolichen97 deleted the refactor/linecap-g22-handler branch October 18, 2026 21:53
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Oct 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants