Repository navigation
refactor(dashboard): compose the chat turn runtime from chat_turn owners - #16224
Conversation
First Principles Review (Opus 5.5) — 🟡 CONCERNSPremise-level review of First-Principles-Verdict: CONCERNS
Not justified as shipped
What this change shipsInventory (8 items) — 7 justifiedIntent: 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)
[FIRST-PRINCIPLES-REVIEWED] c4d439a Description read[DESCRIPTION-READ] f19bf412942d80ec6fdcfd7a20798558b90ead75ac28de7bb116a76be61007d6 That sha256 names the PR description this verdict read. Recompute it with |
GPT 6.1 Review — ✅ no blocking findingsGPT 6.1 completed its review of This comment is updated in place on each push. Review detailsNo findings. False positive or not applicable? A repository writer can comment: |
Design Review (Opus 5.5) — ✅ PASSDesign-level review of Design-Verdict: PASS Check that the conflict hotspot actually moved: Suggestions
[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 |
Opus 5.5 Review — ✅ no blocking findingsReviewed Review detailsNo findings that block the merge; one advisory finding below. FINDING — src/kiro_crew/dashboard/chat_turn/recovery.py:520 — the refusal-replay abort broadcasts [OPUS-REVIEWED] c4d439a Verdict parsed from the review's SHA-scoped output markers for commit False positive or not applicable? A repository writer can comment: |
4aca2c2 to
fae38c3
Compare
|
|
|
|
mechanism: contract-test bytecode pin (_AWAIT_FREE_PHASES) plus a where-new-code-goes rule
|
|
|
|
|
|
Merge probe against current
|
buluoray
left a comment
There was a problem hiding this comment.
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.pyhas 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_contextdiffers by one docstring word ("historically"), and_run_chatand_start_next_queued_turnare 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_chat11,061 → 10,456 lines,_start_next_queued_turn919 → 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
returnvalues, 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_verdictand_report_unclaimed_directives. One trailing# else:comment after_recover_posttoken_transientwas dropped; it was comment only. The one other change inside_run_chatis a# noqa: F811on an existing inline import. - Liveness and control flow. None of the removed blocks contained a
return,break,continue,nonlocalordelaimed at the enclosing function, apart from the drain'sreturn False, which is kept asif 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 onlynonlocalamong 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 anawaitinside an owner are either callables or locals nothing else mutates. - Compose. Every
LOAD_GLOBALin every owner code object, nested code included, resolves inchat_runner's namespace. I also walked every value reachable from the runner and owner globals: dicts, tuples, partials, defaults, closures and class members. Aftergc.collect(), nochat_turnfunction bound to an owner's globals is reachable from any module, under four import orders (runner directly, viachat_handlers/chat, viadashboard.server). The only stragglers before collection are held bycompose's own_swapreference 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 arechat_utilsconstants (steer_queue) anddeny_guidanceconstants (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 patchchat_runner.<name>, and owner functions read the runner's globals, so the mutations below show those patches still reach moved code.chat_runner.pyhas no upstream change since the base, andgit merge-treeagainst 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):
- Replaced the
compose(...)call with a no-op → 260 failures, includingtest_every_owner_function_runs_on_the_runner_globals,test_a_patch_of_the_runner_reaches_an_owner_functionandtest_a_second_runner_import_recomposes_the_owners_onto_it, plus behaviour tests intest_dashboard_chat.py. - Skipped rebinding of class members in
compose→test_compose_rebinds_functions_and_class_membersandtest_every_owner_function_runs_on_the_runner_globalsfailed. - Changed the cancellation reason in
_drop_superseded_refusal_replay→TestRunChatRefusalFallback::test_drain_purges_replay_when_binding_changesfailed. - Removed the latch consume in
_refresh_genuine_turn_allowances→ three tests intest_model_access_fallback_interactive.pyfailed, includingtest_swap_recovery_replay_preserves_the_one_shot_flag. - Removed the
_poisoned_reset_usedrefund in_image_recovery_vetoed_at_consume→TestRunChatTransientRetry::test_stop_after_image_recovery_dispatch_aborts_before_providerfailed. - Reverted the
stall_attributionowner row (G3) →test_a_stalled_owner_frame_still_reads_as_a_dashboard_chat_turnfailed.
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_payloadin_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.composeduplicatesslack.gateway_runtime.compose. Holds, non-gating._rebindreally is a copy,__type_params__handling included. Sharing it requires editingslack/gateway_runtime/__init__.py, which is outside this PR's scope. Tracked in #16231 (open). - First Principles —
turn-stats-footer.mdsignature 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)
- #16230: add the
awaitonchat_done_payloadin_refusal_replay_vetoed_at_consume, add a regression test, and remove it from_AWAIT_FREE_PHASES. - #16231: hoist a single
compose/_rebindthat both facades call. - 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< 3retry 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. - 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.
977b2fb to
91786cf
Compare
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.
91786cf to
c4d439a
Compare
|
|
|
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.pyheld 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_chatalone 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
chat_handlers.pyor any other production importer; every name they import or patch still resolves fromchat_runneras the same object.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._run_chatthat tests read from its own source: those arms stay in_run_chat.DashboardState,_ChatSlot, History, Session, Memory, ACP or the provider.What changed (motivation → approach → change)
chat_runner.py_run_chat_start_next_queued_turndashboard/chat_turn/, largest 960 linesEach 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_turnkeep 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.composere-runs every owner function onchat_runner's module globals, the techniqueslack.gateway_runtime.composealready uses. A test that patcheschat_runner.<name>therefore still reaches moved code, module state stays on the runner, and__module__still readskiro_crew.dashboard.chat_runner. Owners import the runner and their siblings only underTYPE_CHECKING, and import load-time project constants plainly (steer_queuefromchat_utils,tool_approvalfromdeny_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_chatarm 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 onlychat_runner.py(see the integration-owner edits below).learn-cron-dashboard.mdgains a "Chat runner composition" section with the owner map and where new code goes;turn-stats-footer.mdnames the new owner and brings its_attach_turn_statssignature up to date (ttft_ms, the bool return).Backwards compatibility
Compatible: every module-level name
chat_runnerbound at the base still resolves there as the same object with the same signature,dashboard.chat's re-exports andchat_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.pyinto owners and stay bound onchat_runneras the same objects. Their readers onorigin/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_contextby name from its own globals, where the owner's object is bound -- test_chat_runner_coverage.py::TestDrainPendingContextReader: src/kiro_crew/dashboard/chat_runner.py:_run_chat -- chat -- reads
cross_surface_withheldthe same way -- test_session_control.py::test_a_changed_audience_withholds_the_cross_surface_replyReader: src/kiro_crew/dashboard/chat_runner.py:_run_chat -- chat -- reads
unverified_directive_outcomeandunverified_directive_noticethe same way -- test_session_directive_input_digest.py::test_unverified_notice_leads_with_a_human_outcome_for_every_directive_toolReader: 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.pyReader: test/test_thread_backfill.py:drain_pending_context -- chat -- imports it from
chat_runner-- test_thread_backfill.pyReader: test/test_slack_mirror_context_leak.py:drain_pending_context -- chat -- imports it from
chat_runner-- test_slack_mirror_context_leak.pyReader: 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_recordsTests
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_handlersandchatsee 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, anawaitadded to an await-free phase).Local gate:
scripts/local-gate.py --dry-runselects 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_turnfiles and importsdashboard.chat_runneranddashboard.chatin 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:
test/test_no_config_dir_in_async.py(G1)_ASYNC_CHECKED_FILESrow per owner that holds a coroutinetest/test_prompts.py,test/test_redaction_allow.py,test/test_name_grant_surfaces.py,test/test_discord_empty_turn.py(G2)chat_turnowner modules (non-empty asserted)src/kiro_crew/stall_attribution.py(G3)dashboard chatsurface row also matches/kiro_crew/dashboard/chat_turn/src/kiro_crew/autonudge_service/model.py(G4),test/test_autonudge.py(G5)AUTOSDE.yaml(G6)memory-store-seamrule's file patterns addsrc/kiro_crew/dashboard/chat_turn/**/*.pytest/test_source_corpus.py(G7)blocking-on-loopprefilter'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 containasyncadd 9Accepted 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_RUNNERplacement 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:229test/test_subagent_stop_reason_consistency.py:712-717test/test_turn_duration_recorded.py:161-162test/test_post_compaction_continuation.py:400test/test_credential_redaction_switch.py:268test/test_turn_ceiling.py:1047test/test_agent_sdk_provider_identity.py:52test/test_agent_sdk_capabilities.py:57test/test_core_path_redact_before_bound.py:190test/test_chat_turn_timeout_consistency.py:38test/test_chat_hooks.py:131test/test_mcp_session_report.py:444Known follow-up cite (not granted,
website/**):website/src/pages/chat/groupDisplayItems.ts:87nameschat_runner.py; the call site it describes is still there.Checklist
feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)