Skip to content

refactor(dashboard): hoist the chat turn's closures into chat_turn - #22057

Merged
bolichen97 merged 1 commit into
mainfrom
refactor/linecap-g01-chat-runner-p6
Oct 19, 2026
Merged

bolichen97 merged 1 commit into
mainfrom
refactor/linecap-g01-chat-runner-p6

Conversation

@bolichen97

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: Turn the dashboard chat runner's in-function closures into functions that take the turn, each in the chat_turn owner of its responsibility, so chat_runner.py sheds another 1,000 lines with no change to what a turn does.

src/kiro_crew/dashboard/chat_runner.py is about 13,700 lines after the previous PR of this series, and almost all of it is one function, _run_chat. The campaign rule is that no hand-written file goes over 2,000 lines. _run_chat defines 31 helper closures inline (the live Stop signal, the reply flushes, the recovery ledgers, the owner check, the refusal fallback retry), and they hold the turn's state in closure cells. Nothing in that body can move until those helpers stop being closures.

Why it matters

The next PRs of this series move _run_chat's phases out by responsibility. A phase can only leave the function when the helpers it calls are reachable from outside it, which is what turning each closure into a function of the turn does. Keeping them as closures keeps the runner far over the cap and keeps every phase pinned inside it.

Not a goal

  • No change to what a turn does: each closure's body moves verbatim; only its reach to the turn's state is re-plumbed.
  • _run_chat's phases stay where they are; they move in later PRs of the series.
  • _claim_session stays a closure until the next PR, which moves the phase that defines it.

What changed (motivation → approach → change)

Thirty of _run_chat's closures become functions whose first argument is the turn (turn_locals._ChatTurn), and each moves to the owner of its responsibility. A value the closure wrote is spelled turn.<name> at every site; a value it read that _run_chat rebinds is copied onto the turn right after each store and read off it. A call passes the turn (_flush_text_stream(turn)), a callback is functools.partial(<function>, turn), and an off-loop call passes it to asyncio.to_thread. The three helpers main added beside the previous PR's owners move with them.

Owner New What moved in
turn_entry yes the live Stop signal (_stop_pressed), the session's Stop count, the directive provenance a channel steer narrows
turn_admission yes the session binding a turn may run on: the current binding and its requirement, the app owner check, the dispatch lock's release
turn_reply_seams yes the partial reply a dying turn persists, the abnormal end's usage row, the text and thinking stream flushes, the steer's segment cut, the watchdog error rows
turn_ledgers yes the consumption reports, the recovery a turn queues and the completion it owes, the terminal directive, the coding-activity cadence
turn_context, turn_spec_hooks, slash_commands, model_fallback, acp_recovery no the skills restore after compaction, the spec-hook _fire, the blocked-slash refusal, the refused-cycle record and refusal fallback retry, the binding-rebuild gate
eager_spawn, app_agent_binding no stop_eager_spawns (#21552); the app-agent host gates _app_agent_host_allowed, _app_agent_turn_host_allowed (#21673)

turn_entry (65 lines) and turn_admission (69 lines) are small here because they hold only the helpers so far; the next PR moves the turn's entry and admission phases into them.

Repository guards that read a moved construct by path read its new home: the composition contract's owner set and homes, the base surface, the turn plumbing and shared-state inventories, security_posture.py's non-egress registry for the three owners that now hold redactor calls (turn_reply_seams, turn_ledgers, model_fallback), the redact-before-bound floor and the config-dir guard. Three source pins follow the closures to the turn spelling, and the two async-path guards (no config_dir() call, no inline mention resolve) read a function that takes the turn as they read a coroutine, the reach they had over the closures (see Claim).

Backwards compatibility

Compatible: every name chat_runner bound at the base is still bound, as the same object (the base-names contract test); every patch target still reaches the code it reached.

The one public def that moved, stop_eager_spawns, still resolves on chat_runner (imported there by name for its production importer and bound by compose):

Reader: src/kiro_crew/slack/gateway_runtime/exit_path.py:stop_eager_spawns -- release -- imports it from the runner at gateway shutdown; test_eager_spawn_shutdown.py

Tests

  • Collected nodes over the ten test files whose tests change (two more get comment-only edits): 707 at the base, 715 at the head, none removed. The new nodes are the three moved helpers' base-surface rows and five plumbing tests: two self-tests of the turn rules (test_an_owner_function_never_rebinds_a_name_it_read_off_the_turn, test_the_closure_rule_reads_an_owner_functions_writes) and the convention pin (test_every_function_cut_from_run_chat_takes_the_turn_first, test_the_async_guards_reach_every_function_cut_from_run_chat, test_the_config_dir_guard_reads_a_function_that_takes_the_turn). Each new test passes 5 runs at -n0 and one at -n 3.
  • Closure fidelity: each of the 30 closures at the base and the function it became, compared as syntax trees after undoing only the re-plumbing (the turn parameter, the entry aliases, the turn.<name> spellings, the (turn, ...) / partial / to_thread call forms), is identical, and so is _run_chat itself apart from its _ChatTurn(...) line, which gains the 15 inputs the moved functions read.
  • Every guard that reads a construct by path has a mutation of that construct, in the file that holds it now, that turns it red: 144 mutants, every one killed. That is the earlier PRs' 115 re-aimed at where their constructs live, 8 for the turn plumbing and the source pins, 16 for this PR's rows (the config-dir guard and non-egress row of each owner that gained redactor calls, the redact floor, the owner set, two homes rows, the moved helpers' base-surface rows, the leaked-toolcall reach) and 5 for the async-guard reach (config_dir() planted in _queue_recovery and in _stop_pressed, an inline mention resolve in a turn function, a renamed turn parameter, a guard that stops reading turn functions). The same plants with the guard change reverted stay green.
  • 525 test files that import, patch or read chat_runner, chat_turn or a moved name, plus the guards that scan them: 30,984 passed (-n 3 --dist loadgroup). The only reds came from running in a git-less export (two line-cap checkout tests and the harness-parity git ls-files test), all of which pass in a checkout. CI runs the full suite.
  • Per-file coverage of each owner this PR adds or extends, over the 525 test files above: turn_entry 100%, turn_admission 100%, turn_reply_seams 97%, turn_ledgers 91%, turn_context 95%, turn_spec_hooks 93%, slash_commands 96%, model_fallback 94%, acp_recovery 93%, eager_spawn 92%, app_agent_binding 91%, turn_locals 99%; each clears the 80% floor on its own.
  • mypy over src/kiro_crew: clean. semgrep 1.78 (CI configs, baseline at the base): 0 findings. black, isort, flake8, comment-history, brand, docs-lint, feature-map, harness-parity, agent-sdk boundary and line-cap gates: clean; the flake-pattern ratchet passes. Installed-mode smoke: a wheel built from the head imports the runner and the four new owners from the installed copy under an isolated HOME.

Move audit: chat_runner.py 13,738 → 12,742 lines. The three helpers move unchanged; _run_chat shows as one changed unit because its closures leave it, which the closure-fidelity check above accounts for.

Manual verification

N/A — a structural move; the turn-level characterization suite, the closure-fidelity check and the mutation-proven guards are the verification.

Related Issues

Part of #20192

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

Move audit

src/kiro_crew/dashboard/chat_runner.py: 13738 -> 12742 lines; moved 2.75% (python-ast)
   changed: _run_chat [AsyncFunctionDef] 12359 lines
test/test_chat_runner_composition_contract.py: 1417 -> 1428 lines; moved 90.4% (python-ast)

_run_chat is the one changed unit: its 30 closures leave it, and the closure-fidelity check shows the rest of its body and every closure unchanged apart from the re-plumbing. The contract's changed units are its owner set and homes table.

Claim

Granted edits outside the claim:

  • test/test_refusal_inband_notice.py and test/test_post_compaction_continuation.py: the (turn) spelling of _stop_pressed / _session_stop_generation and of _flush_text_stream, granted for this step (L30).
  • test/test_no_config_dir_in_async.py and test/test_prompts.py: one-off grant for this PR, to restore BASE reach after hoisting _run_chat closures. The config_dir() scan reads a function whose first parameter is turn (_takes_the_turn) as it reads a coroutine, and lists the owners that hold one; the inline mention-resolve scan does the same. No other line changes.
  • test/test_leaked_toolcall_notice.py: one-off grant for this PR, for the same reason (restore BASE reach after hoisting _run_chat closures). The bare-reset sweep reads every function whose first parameter is turn as well as _run_chat; its assertion text is unchanged.
  • Comment-only citations (DOC_GRANT): src/kiro_crew/dashboard/chat_delivery.py, src/kiro_crew/dashboard/chat_utils_turn_recovery.py, test/test_stderr_redact_then_tail.py and test/test_crew_log_order.py name where _queue_recovery, _refusal_fallback_retry, _fire and the steer cut live now.

Baselined growth (L56 addendum 1, 1b): src/kiro_crew/security_posture.py (line-cap baseline row 3,181) goes from 3,413 lines on main to 3,416, the three NON_EGRESS_REDACTION_MODULES rows (1b); its reason comment keeps its seven lines.

The 30 closures _run_chat defines become functions that take the turn
(the per-turn state object), each moved into the chat_turn owner of its
responsibility. A closure that read a local of _run_chat reads it off
the turn, or as an alias bound from it at entry; its call sites pass the
turn. Four owners are new: turn_entry (the live Stop signal and the
entry state), turn_admission (the session binding a turn may run on),
turn_reply_seams (what a turn writes as its reply) and turn_ledgers
(what a turn records about itself). The rest join existing owners.

The three helpers main added beside the previous step's owners move
with them: stop_eager_spawns to eager_spawn, and the app-agent host
gates to app_agent_binding. compose binds every moved name on the
runner, so chat_runner.<name> still resolves and a patch of it still
reaches the moved code.

The guards that read a moved construct by path read its new home: the
composition contract's owner set and homes, the base surface, the
turn plumbing and shared-state inventories, the security posture
non-egress registry, the redact-before-bound floor and the config-dir
guard. Three source pins follow the closures to the turn spelling, and
the two async-path guards (no config_dir() call, no inline mention
resolve) read a function that takes the turn as they read a coroutine,
the reach they had over the closures.

Part of #20192
@bolichen97
bolichen97 requested review from a team and KiroCrewCaptain as code owners October 19, 2026 04:13
@bolichen97
bolichen97 requested a review from buluoray October 19, 2026 04:13
@github-actions

github-actions Bot commented Oct 19, 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 fa282d1.

@bolichen97

Copy link
Copy Markdown
Contributor Author

Sensitive change review

  • Head commit: fa282d1
  • What rule changed: no rule. security_posture.py's NON_EGRESS_REDACTION_MODULES gains dashboard/chat_turn/turn_ledgers.py, turn_reply_seams.py and model_fallback.py, and its comment lists the families they hold. The redactor calls in _run_chat's closures moved there verbatim as functions that take the turn: the partial reply's _redact_segment and the stream flushes (turn_reply_seams), the terminal directive's _redact_tool_field (turn_ledgers), the refusal fallback hop's model-id redaction (model_fallback). The registry follows them to their new files.
  • Before -> after (what was allowed/blocked, now): before, those calls ran inside _run_chat in chat_runner.py; after, the same calls in the same order run in the owners on the runner's globals (compose), called with the turn. Nothing is allowed or blocked differently, and no sink, egress path or classification changes; the file grows only by the three rows.
  • Worst case if wrong (breaks commands / leaks secret / locks user out): the posture drift guard would miscount a redactor site and fail its test; the redaction itself is the moved code, unchanged, so a reply, a directive id and a fallback model id are scrubbed exactly as they were.
  • Evidence checked (which sandbox result proves it): test_security_posture.py::TestOmissionDetection::test_every_redactor_call_site_is_a_registered_sink_or_allowlisted is green on this head and turns red when any of the three rows is removed (mutants PR6-non-egress-turn-ledgers, -turn-reply-seams, -model-fallback). The redact-before-bound floor turns red when turn_reply_seams stops redacting. The closure-fidelity audit shows every moved closure identical after undoing the turn re-plumbing.
  • No regression:
    • Tools still work (which tools/commands were run, result): the 532 test files that import, patch or read chat_runner, chat_turn or a moved name passed on this patch (30,963 passed), mypy over src/kiro_crew/ clean.
    • Backward compatible (old config / old data / old callers still work, how checked): no config, data or caller changes; every chat_runner.<name> still resolves to the same object (test_chat_runner_base_surface.py) and the registry only gains rows.
    • Existing tests (which suites passed on this head): test_security_posture.py, test_core_path_redact_before_bound.py, test_no_config_dir_in_async.py, the runner composition contract, base-surface, compose-binding and turn plumbing tests.
  • How to undo: revert this PR's single commit; the calls return to _run_chat with the registry rows removed in the same revert.

@github-actions

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — ⏭️ skipped

Revision fa282d194447317e100b782ca5fccfebb08124a0 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 added the readiness: checking Automated validation is still running label Oct 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — ✅ PASS

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

Design-Verdict: PASS

Check that the existing copy-after-store rule in test_chat_runner_turn_shared_state.py still covers every name _run_chat rebinds that the 30 moved functions now read off the turn.

[DESIGN-REVIEWED] fa282d1

Description read

[DESCRIPTION-READ] 9d8fc85b3e10d13e6941a0b2059daff15ecc4ebcbd69a44163e729b573bc54e6

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

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — ✅ PASS

Premise-level review of fa282d194447317e100b782ca5fccfebb08124a0 — 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 merge, check that every place _run_chat rebinds a value also copies it onto the turn. One missed copy is a stale read that the syntax-tree comparison cannot catch.

What this change ships

Inventory (9 items) — 9 justified

Intent: shrink chat_runner.py toward the 2,000-line cap that AGENTS.md requires, with no change to what a chat turn does. This is an ADDITION (a structural move), not a FIX.

  1. Thirty _run_chat closures become functions that take the turn as their first argument. Each sits in its responsibility's chat_turn owner. — justified
  2. A new turn_entry owner holds the Stop signal, the Stop count and the steer provenance. — justified
  3. A new turn_admission owner holds the session binding, the owner check and the dispatch-lock release. — justified
  4. New turn_reply_seams and turn_ledgers owners hold the reply flushes, the recovery ledgers and the terminal directive. — justified
  5. _ChatTurn gains 15 constructor inputs and the shared-state attributes that the moved functions read. — justified
  6. The security_posture non-egress registry lists three owners that now hold redactor calls. — justified
  7. The composition, base-surface, plumbing, redact-floor and config-dir guards are re-aimed at the moved code's new homes. — justified
  8. Five new plumbing tests pin the turn-first convention and how far the async guards reach. — justified
  9. Docstring and comment references to the moved code are updated, along with four spec docs. — justified

[FIRST-PRINCIPLES-REVIEWED] fa282d1

Description read

[DESCRIPTION-READ] 990139f3bb6a2fb9ef33dc36bd6743eaccedc5ddb6bf9b2c1c8608dcfa736371

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

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

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

Review details

No findings.

[OPUS-REVIEWED] fa282d1

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

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

@github-actions

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — ✅ no blocking findings

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

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] fa282d1

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

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • Copy-after-store coverage of the moved functions (Design PASS punchline)

Outcome: rebutted. Confirmed as asked; no change is needed. The rule is test_every_store_of_a_shared_name_is_copied_onto_the_turn in test_chat_runner_turn_plumbing.py, not shared_state. It needs no hand list: read_off_the_turn collects every turn.<name> load in _run_chat and in every owner function whose first parameter is the turn (the entry aliases x = turn.x included). It then requires each store of such a name to be followed at once by turn.x = x.
So the 30 moved functions are covered by construction: a name one of them reads joins the set the moment it is spelled. test_every_function_cut_from_run_chat_takes_the_turn_first pins that all 30 take the turn first, so none drops out of _functions().
Mutation on this head: dropping the copy turn._wsred = _wsred in _run_chat turns this rule red, and test_chat_runner_turn_sequence.py red behaviourally (PR6-a-shared-value-is-not-copied-onto-the-turn).

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • A missed copy as a stale read (First Principles PASS punchline)

Outcome: rebutted. That case is checked, by a rule rather than by the syntax-tree comparison. test_every_store_of_a_shared_name_is_copied_onto_the_turn (test_chat_runner_turn_plumbing.py) takes every name any function reads off the turn, _run_chat and the 30 moved functions alike. It fails on any store of one in _run_chat or an owner that is not followed at once by turn.x = x.
test_an_owner_function_never_rebinds_a_name_it_read_off_the_turn and test_a_name_a_closure_writes_is_never_held_under_its_own_name close the other two ways a value could go stale: a rebound alias, and a bare local of a name the turn owns.
Mutation on this head: removing one copy (turn._wsred = _wsred) turns the rule red, and the turn-sequence suite red behaviourally (PR6-a-shared-value-is-not-copied-onto-the-turn). All 146 PR6 mutants are red.

@bolichen97
bolichen97 enabled auto-merge (squash) October 19, 2026 04:35
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Oct 19, 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.

Every review lane on the head is clean (only runner notices); held by the triage cron on the 20-file cap alone. Approved on the watch holder's request.

@bolichen97
bolichen97 merged commit 20fcbd5 into main Oct 19, 2026
151 of 153 checks passed
@bolichen97
bolichen97 deleted the refactor/linecap-g01-chat-runner-p6 branch October 19, 2026 07:09
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Oct 19, 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.

2 participants