Skip to content

refactor(dashboard): compose the chat turn runtime from chat_turn owners - #16224

Merged
bolichen97 merged 1 commit into
mainfrom
refactor/d01-chat-runner
Oct 3, 2026
Merged

bolichen97 merged 1 commit into
mainfrom
refactor/d01-chat-runner

Conversation

@bolichen97

@bolichen97 bolichen97 commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: The dashboard chat turn runtime lives in named owners under dashboard/chat_turn/, so a contributor changing one turn policy (fallback, recovery, approval, recipient fencing, file-change chips, the turn marker) edits one cohesive module instead of a 21,000-line file, while every chat turn behaves exactly as before.

src/kiro_crew/dashboard/chat_runner.py held every policy of a dashboard chat turn in one 21,471-line module: model fallback and restore, retry and replay revalidation, tool-approval policy, recipient authorization, file-change snapshots, the in-flight turn marker, steer settlement, directive backstops and the turn-stats footer. Its turn entry _run_chat alone was 11,061 lines. About 60 open PRs touch the file, so every change to one policy collides with unrelated work on the others.

Why it matters

Changes to the chat runtime are the most conflict-prone in the repository. A reviewer has to page through unrelated state machines to judge one rule, and a fix to one policy routinely lands next to another policy's code because there is no owner to put it in. Splitting by responsibility gives each policy one place to change and one place to review, without changing a byte of behaviour.

Not a goal

  • No behaviour change: no new feature, no bug fix, no changed wording, payload, ordering, timeout or retry budget.
  • No change to chat_handlers.py or any other production importer; every name they import or patch still resolves from chat_runner as the same object.
  • No change to security_posture.py, the agent-sdk-boundary/docs-lint baselines or the QF2 registry; the only guard edits are the granted G1-G6 tightenings below.
  • Not decomposing the parts of _run_chat that tests read from its own source: those arms stay in _run_chat.
  • No change to DashboardState, _ChatSlot, History, Session, Memory, ACP or the provider.

What changed (motivation → approach → change)

Before After
chat_runner.py 21,724 lines, 200 top-level definitions 17,728 lines, 115 definitions: the turn entry, every task coroutine, every guarded construct
_run_chat 11,152 lines 10,546 lines; unpinned phases call owners
_start_next_queued_turn 963 lines 700 lines
Owners none 13 modules under dashboard/chat_turn/, largest 960 lines

Each owner holds one responsibility: turn context, prompt assembly, model fallback, tool approval, MCP session, file changes, turn stats, recipient, steer queue, recovery, ACP recovery, turn marker, directives. Top-level helpers moved verbatim: of 200 base top-level definitions, 197 are AST-identical, one is docstring-only (_detach_appended_context), and _run_chat/_start_next_queued_turn keep their statements but call owner phases; all 67 module assignments are identical. Those phase blocks became owner functions that keep the original statements and take the original locals as same-named parameters.

chat_turn.compose re-runs every owner function on chat_runner's module globals, the technique slack.gateway_runtime.compose already uses. A test that patches chat_runner.<name> therefore still reaches moved code, module state stays on the runner, and __module__ still reads kiro_crew.dashboard.chat_runner. Owners import the runner and their siblings only under TYPE_CHECKING, and import load-time project constants plainly (steer_queue from chat_utils, tool_approval from deny_guidance); nothing but the runner imports an owner.

What repository guards read by path stays in chat_runner.py: redactor call sites, deny and approve sites, task entry coroutines, the memory-store seam, the decisions hooks and the Jev routing family, and every _run_chat arm a test reads from its source. The config_dir guard (G1) and four absence pins (G2) now scan the owners too; the pins listed under Accepted residual still read only chat_runner.py (see the integration-owner edits below). learn-cron-dashboard.md gains a "Chat runner composition" section with the owner map and where new code goes; turn-stats-footer.md names the new owner and brings its _attach_turn_stats signature up to date (ttft_ms, the bool return).

Backwards compatibility

Compatible: every module-level name chat_runner bound at the base still resolves there as the same object with the same signature, dashboard.chat's re-exports and chat_handlers' six seams are unchanged. Every existing test passes; five were widened under G1/G2 (scan sets only, node IDs unchanged), one corpus-cost ceiling was re-pinned to its true value under G7, and one docstring was repointed under G5.

Four public defs move from chat_runner.py into owners and stay bound on chat_runner as the same objects. Their readers on origin/main (every entry point, app bundles and release branches searched; the only non-test readers are the runner's own call sites):

Reader: src/kiro_crew/dashboard/chat_runner.py:_run_chat -- chat -- reads drain_pending_context by name from its own globals, where the owner's object is bound -- test_chat_runner_coverage.py::TestDrainPendingContext
Reader: src/kiro_crew/dashboard/chat_runner.py:_run_chat -- chat -- reads cross_surface_withheld the same way -- test_session_control.py::test_a_changed_audience_withholds_the_cross_surface_reply
Reader: src/kiro_crew/dashboard/chat_runner.py:_run_chat -- chat -- reads unverified_directive_outcome and unverified_directive_notice the same way -- test_session_directive_input_digest.py::test_unverified_notice_leads_with_a_human_outcome_for_every_directive_tool
Reader: test/test_gateway_appkit_endpoints.py:drain_pending_context -- app -- imports it from chat_runner, which re-exports the owner's object -- test_gateway_appkit_endpoints.py
Reader: test/test_thread_backfill.py:drain_pending_context -- chat -- imports it from chat_runner -- test_thread_backfill.py
Reader: test/test_slack_mirror_context_leak.py:drain_pending_context -- chat -- imports it from chat_runner -- test_slack_mirror_context_leak.py
Reader: test/test_discord_resumed_busy.py:cross_surface_withheld -- chat -- reads cr.cross_surface_withheld -- test_a_landed_steer_records_the_audience_fence_the_peer_path_records

Tests

  • test/test_chat_runner_composition_contract.py (new) pins: all 686 base names still resolve; each moved name keeps its base kind, signature and owner and is one object at both paths; chat_handlers and chat see the runner objects; task entries stay defined in the runner file; every owner function runs on the runner's globals and every global it reads is bound there; a patch of the runner reaches moved code end to end; owners capture no name a test rebinds (corpus-derived patch scan with self-tests, fails closed on an unresolved target); owners import the runner and siblings only for type checking, and no other module imports an owner; constructs path-keyed guards read stay in the runner; an owner frame reads as the dashboard chat surface; the phases cut from await-free blocks still never suspend (bytecode sweep with a self-test); star import, fresh import and re-import behaviour.

  • Twelve mutation proofs turn these and the widened guards red and green again (compose removed, a base name dropped, a captured patch target, a runtime sibling import, a task creation in an owner, config_dir() in an owner coroutine, an inline prompt-mention call, an allow-list read, a name-grant thread, a respelled remedy, the stall fragment dropped, an await added to an await-free phase).

  • Local gate: scripts/local-gate.py --dry-run selects 1,809 backend and 696 frontend related files, too many for the shared host, so a 286-file set ran instead (every test that names the runner or an owner, every guard this diff touches or depends on, and the tests of the upstream commits ported here): 23,082 passed, 5 skipped. The static floor, semgrep in baseline mode and a built-wheel import ran green; CI owns the broad suite.

Manual verification

N/A — no user-visible change. A built wheel contains all 14 chat_turn files and imports dashboard.chat_runner and dashboard.chat in installed mode.

Related Issues

no linked issue: KC27 campaign scope D01 (chat turn runtime composition).

Integration-owner edits, each a coordinator grant and each tightening only:

File Change
test/test_no_config_dir_in_async.py (G1) one _ASYNC_CHECKED_FILES row per owner that holds a coroutine
test/test_prompts.py, test/test_redaction_allow.py, test/test_name_grant_surfaces.py, test/test_discord_empty_turn.py (G2) the absence pin's scan set gains the chat_turn owner modules (non-empty asserted)
src/kiro_crew/stall_attribution.py (G3) the dashboard chat surface row also matches /kiro_crew/dashboard/chat_turn/
src/kiro_crew/autonudge_service/model.py (G4), test/test_autonudge.py (G5) one comment each names the recipient ladder's new home
AUTOSDE.yaml (G6) the memory-store-seam rule's file patterns add src/kiro_crew/dashboard/chat_turn/**/*.py
test/test_source_corpus.py (G7) the blocking-on-loop prefilter's corpus-cost ceiling is re-pinned to the true value (906 kept, ceiling 907): main keeps 897 files and the nine new owners that contain async add 9

Accepted residual (Master G2 ruling): these absence pins and censuses still read only chat_runner.py, because the constructs they guard stay there. The contract test's _STAYS_IN_THE_RUNNER placement pins keep each guarded positive construct in the runner; the forbidden halves of these pins are not enforced in the owners (accepted under R12).

  • test/test_native_question_card_lifecycle.py:229
  • test/test_subagent_stop_reason_consistency.py:712-717
  • test/test_turn_duration_recorded.py:161-162
  • test/test_post_compaction_continuation.py:400
  • test/test_credential_redaction_switch.py:268
  • test/test_turn_ceiling.py:1047
  • test/test_agent_sdk_provider_identity.py:52
  • test/test_agent_sdk_capabilities.py:57
  • test/test_core_path_redact_before_bound.py:190
  • test/test_chat_turn_timeout_consistency.py:38
  • test/test_chat_hooks.py:131
  • test/test_mcp_session_report.py:444

Known follow-up cite (not granted, website/**): website/src/pages/chat/groupDisplayItems.ts:87 names chat_runner.py; the call site it describes is still there.

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 a review from a team as a code owner October 2, 2026 18:30
@bolichen97
bolichen97 requested a review from buluoray October 2, 2026 18:30
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Oct 2, 2026
@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — 🟡 CONCERNS

Premise-level review of c4d439a10fd7db9e0f1281bae5fadc7944cf27d8 — 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: CONCERNS

chat_turn.compose re-implements the Slack composer: _rebind and _functions_of are copied byte-for-byte from slack/gateway_runtime/__init__.py.

Not justified as shipped

  • Item 2 — duplicate of src/kiro_crew/slack/gateway_runtime/__init__.py: the description says it is "the technique slack.gateway_runtime.compose already uses". The diff copies that module's _rebind (lines 132–142) and _functions_of (lines 117–129) unchanged. compose itself matches lines 53–106 with only the host arm and the requalify pass removed. That makes 2 copies of each helper in src/ (checked by reading both files after grepping for def compose and def _rebind). A fix to how a function is rebound now has to land twice, and the copies will drift apart.
    Subtraction: delete _rebind and _functions_of from dashboard/chat_turn/__init__.py and import them from kiro_crew.slack.gateway_runtime. Keep only the host-less compose loop.
    Clears when: the two helpers exist once in src/kiro_crew, or the PR names a behaviour where the dashboard copy must differ from the Slack copy.

What this change ships

Inventory (8 items) — 7 justified

Intent: let a contributor change one dashboard chat-turn policy in one small module instead of a 21k-line file, with no behaviour change — ADDITION (refactor)

  1. The chat turn runtime is split into 13 owner modules under dashboard/chat_turn/ — justified
  2. A new composer runs the owner functions on the runner's globals so patches still reach them — duplicate of slack/gateway_runtime/__init__.py
  3. Stall attribution still labels frames from owner files as "dashboard chat" — justified
  4. The memory-store-seam rule now covers the chat_turn/ files — justified
  5. Five guard tests now scan the owner files as well as the runner — justified
  6. The blocking-on-loop corpus ceiling goes from 900 to 907 — justified
  7. A new composition-contract test pins name resolution, signatures and globals — justified
  8. Spec docs and two comments now point at the owner files — justified

[FIRST-PRINCIPLES-REVIEWED] c4d439a

Description read

[DESCRIPTION-READ] f19bf412942d80ec6fdcfd7a20798558b90ead75ac28de7bb116a76be61007d6

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 2, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — ✅ no blocking findings

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

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] c4d439a

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

@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — ✅ PASS

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

Design-Verdict: PASS

Check that the conflict hotspot actually moved: _run_chat only goes from 11,152 to 10,546 lines, so most of the ~60 colliding PRs still collide there.

Suggestions

  • chat_turn.compose is a near-copy of slack.gateway_runtime.compose, without the host-class half. Make it one shared helper so the rebinding rules (properties, static/class methods, re-import) live in one place instead of two that drift apart.

[DESIGN-REVIEWED] c4d439a

Description read

[DESCRIPTION-READ] d834c7777ae1b5aacb1ba2dac898b7b824f16ef2b864b0e982be8be1a3828299

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 added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Oct 2, 2026
@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

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

Review details

No findings that block the merge; one advisory finding below.

FINDING — src/kiro_crew/dashboard/chat_turn/recovery.py:520 — the refusal-replay abort broadcasts chat_done_payload(state, slot) without awaiting it, but that function is async def (chat_utils.py:1310). So websocket_hub.broadcast_ws gets a coroutine, json.dumps raises TypeError, the except Exception swallows it, and the cancelled replay never sends a chat_done frame, which can leave the dashboard tab stuck busy. The PR moved this line unchanged from the base chat_runner.py:11628, so it did not introduce the bug → Fix: state.broadcast_ws("chat_done", await chat_done_payload(state, slot)), the same as the sibling vetoes at lines 353 and 458.

[OPUS-REVIEWED] c4d439a

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

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

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=16746014cd7d accepted-and-deferred: un-awaited chat_done_payload in the refusal consume-seam veto

Outcome: accepted-and-deferred to #16230 (deferred-finding, owner bolichen97, Due 2026-10-09).
The defect is real and pre-existing: the same un-awaited call is in the base runner's _run_chat (e1a9584), byte-identical, and this PR only moved the block into chat_turn/recovery.py.
This PR is a behaviour-preserving split (frozen Not a goal: no bug fix), so the one-line await fix ships as its own PR with a regression test right after #16224 merges.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=627a5745088e accepted-and-deferred: chat_turn.compose duplicates slack.gateway_runtime.compose

Outcome: accepted-and-deferred to #16231 (deferred-finding, owner bolichen97, Due 2026-10-16).
The subtraction needs one neutral compose helper outside both packages and an edit to slack/gateway_runtime/__init__.py; both are outside this PR's file claim, and importing a slack/ internal into the dashboard runner is the coupling the finding itself rejects.
#16231 hoists compose(namespace, owners, host=None) into one module both facades call, after this PR merges.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=39fb4ccbfb7a rebutted: turn-stats-footer.md signature catch-up is an undeclared rider

Outcome: rebutted, and the body now declares it under What changed.
The edited Backend sentence is the one this PR rewrites to name the new owner (chat_turn/turn_stats.py); leaving its stale signature would ship a wrong owner row, and the repo rule is that the owning spec stays accurate in the same commit.
It documents the signature the moved function already has on main (#15750); no behaviour or surface is added.

@bolichen97

Copy link
Copy Markdown
Contributor Author

mechanism: contract-test bytecode pin (_AWAIT_FREE_PHASES) plus a where-new-code-goes rule

  • span=8e9d2d4aef7b fixed: await-free drain and consume phases can silently gain a suspension point

Outcome: fixed in fae38c3.
test_chat_runner_composition_contract.py pins the 11 phases cut from await-free blocks (_AWAIT_FREE_PHASES): a bytecode sweep asserts none has GET_AWAITABLE, SEND, YIELD_VALUE, GET_AITER, GET_ANEXT or BEFORE_ASYNC_WITH, with a self-test and a mutation proof (an await planted in _rearm_turn_episode turns it red).
learn-cron-dashboard.md's where-new-code-goes paragraph states the rule: a phase cut from a block that never awaited stays await-free.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=16746014cd7d accepted-and-deferred: un-awaited chat_done_payload in the refusal consume-seam veto

Outcome: accepted-and-deferred to #16230 (deferred-finding, owner bolichen97, Due 2026-10-09); same disposition as on 4aca2c2.
The un-awaited call is byte-identical to the base runner's _run_chat (e1a9584); this behaviour-preserving split only moved it into chat_turn/recovery.py.
The fix PR adds the await, a regression test, and drops _refusal_replay_vetoed_at_consume from _AWAIT_FREE_PHASES in the same commit, since the broadcast is the last statement before return True.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=ee9b2e8badcf accepted-and-deferred: chat_turn.compose duplicates slack.gateway_runtime.compose

Outcome: accepted-and-deferred to #16231 (deferred-finding, owner bolichen97, Due 2026-10-16); same disposition as on 4aca2c2.
Named constraint: slack.gateway_runtime.compose(namespace, host, owners) requires a host class, and making it optional means editing slack/gateway_runtime/__init__.py, a file outside this PR's claim; calling it with a stand-in host class would encode an orchestrator that does not exist.
#16231 makes host optional in one neutral helper both facades call, after this PR merges.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=7a7aeac0981a rebutted: turn-stats-footer.md signature catch-up rides along

Outcome: rebutted; the body declares it under What changed.
The edited Backend sentence is the one this PR rewrites to name the new owner (chat_turn/turn_stats.py); keeping its stale signature would ship a wrong owner row, and the owning spec stays accurate in the same commit.
It documents the signature the moved function already has on main (#15750); no behaviour or surface is added.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=10c71fc5a961 accepted-and-deferred: extract the shared rebinding core before a third copy

Outcome: accepted-and-deferred to #16231 (deferred-finding, owner bolichen97, Due 2026-10-16).
The shared core needs slack/gateway_runtime/__init__.py's required host parameter made optional, a file outside this PR's claim; #16231 hoists one helper both facades call after this PR merges.

@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 2, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author

Merge probe against current main (no refresh push needed):

  • base af162847d (13 commits past this head's parent e1a9584a0); git merge-tree --write-tree origin/main fae38c3c4 is clean (tree 833f2cc8e)
  • the only upstream change to a file this PR touches is learn-cron-dashboard.md L258 (cron editor rows, fix: resolve each cron agent_sequence step as its own crew (#15139) #16047), outside the rows this PR edits; no upstream change to dashboard/chat_runner.py or dashboard/chat_turn/
  • on the merged tree: test_chat_runner_composition_contract.py, test_source_corpus.py, test_resume_retired_agent_names.py, test_subagent_stop_reason_consistency.py — 283 passed; scripts/docs-lint.sh exit 0

buluoray
buluoray previously approved these changes Oct 2, 2026

@buluoray buluoray left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Summary

I checked this split on its own instead of relying on the contract test, and nothing was lost. Every top-level name in the base runner still resolves. Moved helpers and assignments are AST-identical. The 19 phase blocks cut out of _run_chat and _start_next_queued_turn are the original statements; the only additions are the trailing returns their call sites need. compose leaves no owner function on the owner's own globals, whether the runner is imported directly or through chat_handlers, chat or dashboard.server. I found no blocking defects. The one real bug the bots raised (the un-awaited chat_done_payload) exists byte-for-byte on the base and is tracked in #16230.

What I verified

Inventory (my own AST scripts, base e1a9584a01 vs head fae38c3c44)

  • Base chat_runner.py has 260 named top-level bindings (196 defs/classes plus 64 assignments). After this PR, 257 are AST-identical: 163 still in the runner and 94 in owners (tool_approval 13, recovery 12, file_changes 12, model_fallback 11, recipient 11, steer_queue 8, turn_marker 8, directives 7, mcp_session 5, turn_stats 4, turn_context 3). Of the rest, _detach_appended_context differs by one docstring word ("historically"), and _run_chat and _start_next_queued_turn are the two functions that were cut into phases. Nothing is missing.
  • Every base import and every other module-level statement is still in the runner. The head adds one module-level statement, the compose(...) call. The PR body's counts (21,471 → 17,470 lines, 196 → 111 defs, _run_chat 11,061 → 10,456 lines, _start_next_queued_turn 919 → 656 lines) match.
  • Phase extraction. I paired each removed hunk with its owner function and diffed them after normalizing whitespace. The only differences are added return values, reflowed lines and comments that now say "in _run_chat" where they used to say "above/below". Checked: the 4 drain gates, the 3 consume vetoes, _refresh_genuine_turn_allowances, _rearm_turn_episode, _settle_session_model, _session_replay_history, _scrub_dashboard_prefix, _checklist_resync, _requeue_auth_retry, _requeue_after_prompt_busy, _recover_posttoken_transient, _poisoned_conversation_verdict and _report_unclaimed_directives. One trailing # else: comment after _recover_posttoken_transient was dropped; it was comment only. The one other change inside _run_chat is a # noqa: F811 on an existing inline import.
  • Liveness and control flow. None of the removed blocks contained a return, break, continue, nonlocal or del aimed at the enclosing function, apart from the drain's return False, which is kept as if await gate(...): return False. Every local a removed block assigned and the runner reads later is either returned and rebound at the call site (_is_model_access_replay_turn, withheld_pin, compressed, full_message, _todo_sync_rendered, _todo_recovery_carried) or is assigned again on its own branch before that read (_requeue_text/_requeue_payload/_retry_msg). symtable shows no free name in either cut function that is not a module global or a builtin. The only nonlocal among the passed-in locals is _consumed_reported, and it goes to _requeue_auth_retry, which is await-free and reads it once, at the same point as before. Parameters read after an await inside an owner are either callables or locals nothing else mutates.
  • Compose. Every LOAD_GLOBAL in every owner code object, nested code included, resolves in chat_runner's namespace. I also walked every value reachable from the runner and owner globals: dicts, tuples, partials, defaults, closures and class members. After gc.collect(), no chat_turn function bound to an owner's globals is reachable from any module, under four import orders (runner directly, via chat_handlers/chat, via dashboard.server). The only stragglers before collection are held by compose's own _swap reference cycle, which is harmless. The requires-python floor is 3.12, so __type_params__ is safe.
  • Import cycles. Owners import the runner and their siblings only under TYPE_CHECKING. Their only plain project imports are chat_utils constants (steer_queue) and deny_guidance constants (tool_approval), and neither of those modules imports the runner. No production module imports an owner.
  • Stale monkeypatch targets. No test patches a kiro_crew.dashboard.chat_turn.* path. Tests patch chat_runner.<name>, and owner functions read the runner's globals, so the mutations below show those patches still reach moved code. chat_runner.py has no upstream change since the base, and git merge-tree against the current main is clean.

Tests. I ran every test file that names chat_runner plus every test this PR touches (209 files): 17,043 passed, 2 skipped, 2 failed. The two failures are test_stop_hook_continuation.py::TestRealHookProcess::*; both also fail on the base commit in the same environment, because a real hook subprocess exits 1 there. The PR did not cause them.

Mutations (each restored from a backup; the worktree is clean at the end):

  1. Replaced the compose(...) call with a no-op → 260 failures, including test_every_owner_function_runs_on_the_runner_globals, test_a_patch_of_the_runner_reaches_an_owner_function and test_a_second_runner_import_recomposes_the_owners_onto_it, plus behaviour tests in test_dashboard_chat.py.
  2. Skipped rebinding of class members in compose → test_compose_rebinds_functions_and_class_members and test_every_owner_function_runs_on_the_runner_globals failed.
  3. Changed the cancellation reason in _drop_superseded_refusal_replay → TestRunChatRefusalFallback::test_drain_purges_replay_when_binding_changes failed.
  4. Removed the latch consume in _refresh_genuine_turn_allowances → three tests in test_model_access_fallback_interactive.py failed, including test_swap_recovery_replay_preserves_the_one_shot_flag.
  5. Removed the _poisoned_reset_used refund in _image_recovery_vetoed_at_consume → TestRunChatTransientRetry::test_stop_after_image_recovery_dispatch_aborts_before_provider failed.
  6. Reverted the stall_attribution owner row (G3) → test_a_stalled_owner_frame_still_reads_as_a_dashboard_chat_turn failed.

Mutations 3–5 show that the moved phases are actually exercised by existing behaviour tests through the runner's namespace.

Fail-open vs fail-closed. The PR adds no new runtime error paths. compose runs once at import. If it were wrong, the result would be a NameError the first time an owner function ran, or a runner patch that silently stops applying in tests. Both failure modes are fail-closed in production and pinned by the contract test.

Specs and docs. The new "Chat runner composition" section in learn-cron-dashboard.md matches the code: the owner map, the constructs that stay in the runner, and the _snapshot_write_target call sites (still two to_thread sites in _run_chat). The turn-stats-footer.md signature (..., model, ttft_ms) -> bool matches the code. The other specs that still cite chat_runner._name for moved helpers remain accurate, because the runner is the documented import and patch surface. The commit message and PR body match the diff.

Bot-claim dispositions

  • Opus — un-awaited chat_done_payload in _refusal_replay_vetoed_at_consume (chat_turn/recovery.py:520). Holds, but does not gate this PR. The call is byte-identical in base _run_chat, so this PR introduces nothing. The fix belongs in its own behaviour-change PR, tracked in #16230 (open). That fix must also drop the name from _AWAIT_FREE_PHASES (test_chat_runner_composition_contract.py:732), as the disposition says.
  • First Principles — chat_turn.compose duplicates slack.gateway_runtime.compose. Holds, non-gating. _rebind really is a copy, __type_params__ handling included. Sharing it requires editing slack/gateway_runtime/__init__.py, which is outside this PR's scope. Tracked in #16231 (open).
  • First Principles — turn-stats-footer.md signature catch-up rides along. Does not hold. That sentence is the one this PR has to rewrite to name the new owner, and the PR body declares the change.
  • Design — run the full CI. Non-gating. My 209-file run covers every test that names the runner; CI owns the rest.
  • GPT — no findings. I agree.

Blocking findings

None.

Follow-ups (non-blocking)

  1. #16230: add the await on chat_done_payload in _refusal_replay_vetoed_at_consume, add a regression test, and remove it from _AWAIT_FREE_PHASES.
  2. #16231: hoist a single compose/_rebind that both facades call.
  3. Accepted residual. The 12 absence pins listed in the PR body still scan only chat_runner.py. I grepped the owners for each forbidden construct ("question_card", owner_view, turn_ceiling.gate(, stats = Stats(), startswith("error:"), the < 3 retry literals, compaction_settled=saw_compaction, spool_refused_turn) and none is present today. A future edit could still reintroduce one in an owner without any test noticing. A shared helper that returns "runner plus owner sources" would close that gap the next time one of those tests is touched.
  4. The commit message cites coordinator labels (G1–G7) that have no meaning in the main branch's history. Consider removing them from the squash body.

@bolichen97
bolichen97 added this pull request to the merge queue Oct 2, 2026
@bolichen97
bolichen97 removed this pull request from the merge queue due to a manual request Oct 2, 2026
@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 3, 2026
@bolichen97
bolichen97 force-pushed the refactor/d01-chat-runner branch from 977b2fb to 91786cf Compare October 3, 2026 03:49
@github-actions github-actions Bot added readiness: checking Automated validation is still running merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: passed Eligible automated validation passed for the current revision and removed readiness: passed Eligible automated validation passed for the current revision readiness: checking Automated validation is still running labels Oct 3, 2026
chat_runner.py held every policy of a dashboard chat turn in one
21,724-line module. Split the responsibilities that no repository
guard pins to that file into thirteen owners under
dashboard/chat_turn/: turn context, prompt assembly, model fallback,
tool approval, MCP session, file changes, turn stats, recipient,
steer queue, recovery, ACP recovery, the turn marker and directives.

Top-level helpers move verbatim. Unpinned phase blocks of _run_chat
and _start_next_queued_turn become owner functions that keep their
statements and take the original locals as same-named parameters.
chat_turn.compose re-runs every owner function on chat_runner's
globals, so a patch of chat_runner.<name> still reaches moved code,
module state stays on the runner and every base name resolves there
as the same object. Task entries, redactor sites, deny and approve
chokepoints, the decisions hooks and every _run_chat arm a test reads
from source stay in chat_runner.py.

The guards granted for this (G1-G6) now read the owners too:
stall_attribution names an owner frame as the dashboard chat surface,
the config_dir, prompt-mention, allow-list, name-grant and
empty-turn remedy pins scan the owner modules, and the memory-store
seam rule in AUTOSDE.yaml covers them. Comments in
autonudge_service/model.py and test_autonudge.py name the ladder's
new home.

The blocking-on-loop prefilter's corpus-cost ceiling in
test_source_corpus.py is re-pinned to its true value (G7): 906 kept,
ceiling 907, the nine new owner files that contain "async".

test_chat_runner_composition_contract.py pins the surface, the
composition and the patch reach. learn-cron-dashboard.md records the
owner map and where new code goes.
@bolichen97
bolichen97 force-pushed the refactor/d01-chat-runner branch from 91786cf to c4d439a Compare October 3, 2026 04:58
@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 merge conflict Branch has merge conflicts with its base — author must resolve before merge labels Oct 3, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=16746014cd7d accepted-and-deferred: un-awaited chat_done_payload in the refusal consume-seam veto

Outcome: accepted-and-deferred to #16230 (deferred-finding, owner bolichen97, Due 2026-10-09); same disposition as on the earlier heads.
The un-awaited call is byte-identical to the base runner's _run_chat; this behaviour-preserving split only moved it into chat_turn/recovery.py.
The fix PR adds the await and a regression test, and drops _refusal_replay_vetoed_at_consume from _AWAIT_FREE_PHASES in the same commit.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=7447bc5e6adb accepted-and-deferred: chat_turn.compose duplicates slack.gateway_runtime.compose

Outcome: accepted-and-deferred to #16231 (deferred-finding, owner bolichen97, Due 2026-10-16); same disposition as on the earlier heads.
Named constraint: slack.gateway_runtime.compose(namespace, host, owners) requires a host class, and making it optional means editing slack/gateway_runtime/__init__.py, outside this PR's claim; a stand-in host would encode an orchestrator that does not exist.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=81c1954f80f4 accepted-and-deferred: extract the shared rebinding core before a third copy

Outcome: accepted-and-deferred to #16231 (deferred-finding, owner bolichen97, Due 2026-10-16).
The shared core needs slack/gateway_runtime/__init__.py's required host parameter made optional, a file outside this PR's claim; #16231 hoists one helper both facades call after this PR merges.

@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 3, 2026
@bolichen97
bolichen97 merged commit 139de6e into main Oct 3, 2026
97 checks passed
@bolichen97
bolichen97 deleted the refactor/d01-chat-runner branch October 3, 2026 06:37
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Oct 3, 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