Skip to content

fix(session): a parent that ends takes its sub-agents with it - #11966

Merged
bolichen97 merged 1 commit into
mainfrom
fix/cancel-children-on-parent-end
Sep 20, 2026
Merged

bolichen97 merged 1 commit into
mainfrom
fix/cancel-children-on-parent-end

Conversation

@iamwhatever

@iamwhatever iamwhatever commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

When a conversation ends, the sub-agent runs it spawned keep going.

Only one backend hides it. ACP_BACKENDS_SESSION_SHARING = frozenset({ACP_BACKEND_KIRO}), so a kiro child dies because the shared process it lives on is reaped — a side effect, not a decision. The other seven give each child its own process, so closing a tab leaves those processes and their MCP fleets running until each run's timeout expires. Then the child reports, and _on_done resolves the parent key through the session registry and creates a session when none is live — rebuilding the conversation the user just closed and seeding it with a dead run's output.

Why it matters

A user closes a tab and expects the work to stop. Instead an agent process keeps running with tool access, against a conversation nobody is reading, and can re-open that conversation minutes later. On seven of eight backends.

What changed (motivation → approach → change)

The teardown is two halves, deliberately split. Selection is synchronous, inside the registry lock hold that retires the key — every await after that is a window in which a cold start can register a successor under the same key, and a selection made later names the successor's runs. Cancellation awaits, so it runs after.

piece where
snapshot_teardown_children(key) -> ids subagent_manager/cancellation.py
cancel_for_teardown(ids) -> stopped subagent_manager/cancellation.py
_teardown_cancelled_ids (_AgingIdSet, 24h) subagent.py
delivery gate subagent_manager/terminal.py
DELIVERY_ROUTING_FIELDS + producer-side AST trap subagent.py, test_session.py
end_children_for(key) session_lifecycle.py
_snapshot_parent_children / _cancel_parent_children session_lifecycle.py
one INFO audit line per teardown, naming its verb subagent_manager/cancellation.py
handler registration slack/gateway.py, session.py
allow_admitted=False: a CLAIMED-but-unstarted durable row is left to its claimer subagent_manager/admission/taskq_bridge.py

A stopped run is marked, then stopped through the ordinary cancel — no second reap path, which would drift. The mark separates this from cancel_for_parent (Stop all), where reporting home is the point.

Four things the mark gates, each found by a failure rather than by design: the _on_done injection; the failure announce, at the one choke point every undeliverable report funnels through; the wave digest's synthetic flush record, whose fresh id an id-keyed gate can never recognise, so it is disarmed at its source; and a run's follow-up watcher, same fresh-id problem.

Six parent-end sites call both halves: reset (conditionally), remove, destroy, discard_conversation, remove_if_unclaimed, retire_kiro_identity_sessions. Each cancel sits in a finally, so a provider shutdown that raises cannot orphan children, and runs before the runtime release, so a child stops through its own teardown rather than by having the process pulled from under a live turn. close_all and _retire_kiro_subagent_runtimes are exempt, each on a fact about itself.

reset is the hard case and the reason for a new keyword. It is the verb every evict-and-retry path reaches for — wedged prompt, failed auto-compaction, provider switch, idle expiry, watchdog — where the children have a conversation to deliver into. So ends_conversation defaults to False, and all 46 callers were audited. Four pass True:

caller why the conversation ends
src/kiro_crew/dashboard/handlers_channel.py — api_channel_clear_context the user asked the agent to forget it (scope=all also wipes the channel buffer)
src/kiro_crew/cron.py — cancel / _force_reap the job is cancelled or reaped
src/kiro_crew/taskrunner.py — _cleanup_run_sessions cancel cleanup ends every step conversation
src/kiro_crew/workflows/agent_pool.py — reset the pool starts a NEW conversation on a pooled key

A fifth is src/kiro_crew/session_compaction.py's still-critical reset, the only clear_conversation=True caller in src/: that keyword clears the resume sid and suppresses replay, so the conversation is over. src/kiro_crew/session_cleanup.py (idle expiry) keeps the default.

A missed flag costs more than an orphan — it arms no delivery gate either, so the report reaches _on_done's session-creating get_or_create and re-opens the ended conversation. No ratchet sees a keyword, so callers are pinned by PATH plus the implication that discarding a conversation ends its children.

Two children are NOT cancelled, and both were learned the hard way: one parked on an unanswered spawn approval (cancelling answers a person's question for them; the request then reads as "not found"), and one finished but undelivered (nothing to cancel, everything to gate).

Residual — two halves

The mark and the snapshot are both taken at the one synchronous point available, so anything already in flight sees neither:

half what escapes bound
admitted late a spawn between its row write and its registration is in neither the queue nor _agents, so no snapshot names it, and it starts into whatever the key serves next its own run timeout
reporting late a report already past the delivery gate and suspended in _on_done is not stopped by marking its id afterwards — the injector resolves the parent through get_or_create, which creates a session when none is live, and never re-reads the mark, so it can deliver its own run timeout

Neither closes with another recheck at one end; they are the same defect at opposite ends of one window. The answer is one identity every path can test, and it does not exist: session_generation counts allocation reservations — get_or_create advances it twice per call, and reset advances it on a recycle — so fencing on it refuses ordinary queued work. Tracked in #12069, which carries both halves, the counter design and its cost.

Backwards compatibility

Compatible. ends_conversation is a new keyword; every existing reset caller keeps today's behaviour, which is the recycle. Nothing main accepts is rejected, renamed or removed.

Tests

All in test/test_session.py unless noted.

test locks in
test_{remove,destroy,discard_conversation,remove_if_unclaimed,identity_retire}_cancels_children each site ends its children
test_a_reset_leaves_a_healthy_child_running / ..._that_ends_the_conversation_stops_the_children the recycle does not; the flag does
test_the_conversation_ending_reset_callers_say_so the four True callers, by path
test_every_parent_end_release_site_ends_its_children AST ratchet over release sites
test_every_parent_end_verb_names_itself_in_the_audit the audit line and each site's verb, no exemption
test_a_failing_provider_shutdown_still_ends_the_children the finally, per site
test_an_ending_reset_cancels_before_it_releases_the_runtime cancel before release
test_teardown_does_not_report_the_run_into_the_retired_parent the delivery gate
test_the_delivery_parked_states_are_enumerated_from_the_producers the table matches its producers' AST
test_a_teardown_cancelled_member_arms_no_digest_flush ¹ the synthetic flush record
test_a_teardown_disarms_its_runs_follow_up_watchers the watcher
test_a_child_parked_on_a_spawn_approval_is_not_cancelled the approval exclusion
test_a_finished_but_undelivered_child_is_gated_without_being_cancelled gate, not cancel
test_the_teardown_gate_forgets_by_age_and_never_by_count ¹ age bound, not capacity
test_a_teardown_leaves_a_claimed_but_unstarted_row_to_its_claimer allow_admitted=False
test_a_child_that_finished_mid_teardown_never_reaches_the_sync_store_call liveness, not presence
test_the_cheap_reuse_path_still_ends_the_previous_conversations_children ² the pool's warm path

¹ test_subagent_coverage.py · ² test_workflows_agent_pool.py

Manual verification

E2E (stub ACP backend, offline) exercises the real gateway with nested spawns and an owner approval over projected MCP; it is green on this head. This host cannot run that lane locally (unshare(CLONE_NEWUSER) is EPERM).

Related Issues

Pattern harvest

Rule candidate: review-prompt

Pattern: a cross-cutting invariant that one backend satisfies as a side effect is untested everywhere else. ACP_BACKENDS_SESSION_SHARING had one member and every teardown expectation was written against it, so seven backends had no coverage and no code expressing the intent. Worth asking of any frozenset({ONE_THING}) that gates behaviour.

Second, narrower: a counter advanced by more than one kind of event cannot fence on one of them. _ownership_generations answers "is this the same reservation"; three review rounds here read it as "is this the same conversation".

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|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

@iamwhatever
iamwhatever requested review from a team and buluoray September 19, 2026 06:58
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Sep 19, 2026
@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ no blocking findings

GPT 5.6 completed its review of 6ff0f92244f29639e2e1e89b6d266206d70edbfc and found no blocking issues.

This comment is updated in place on each push.

Review details

FINDING -- src/kiro_crew/session_lifecycle.py:70 -- "cancel after the provider teardown awaits" contradicts remove(), which cancels before shutdown -> Fix: document the actual ordering.
FINDING -- src/kiro_crew/session.py:2451 -- "the idle sweep" does not end conversations or cancel children -> Fix: remove that example.
[GPT-REVIEWED] 6ff0f92

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

@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5) — ✅ PASS

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

Design-Verdict: PASS

Verify the 46-caller reset audit is complete — a conversation-ending caller that omits ends_conversation=True silently keeps the headline defect on that path, and no ratchet sees a keyword.

[DESIGN-REVIEWED] 6ff0f92

@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5) — ✅ PASS

Premise-level review of 6ff0f92244f29639e2e1e89b6d266206d70edbfc — 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

Verify the 46-caller reset audit: a conversation-ending caller left on the default is the headline defect surviving, and only the path pin guards it.

What this change ships

Inventory (10 items) — 10 justified

Intent: FIX — ending a conversation must stop the sub-agent runs it spawned and keep their late reports from re-opening it (today they run on and _on_done's get_or_create rebuilds the closed conversation on 7 of 8 backends). Provenance is derived: the added tests (e.g. test_remove_cancels_children) fail on base, where set_child_teardown_handler does not exist.

  1. Closing, removing, destroying, discarding or identity-retiring a conversation now stops its sub-agent runs — justified
  2. A stopped run's report, failure notice, digest flush and follow-up watcher no longer re-open the ended conversation — justified
  3. reset(ends_conversation=True): channel clear-context, cron cancel/reap, taskrunner cleanup, pool hard-reset, compaction critical reset now end children — justified
  4. Workflow pool warm reuse ends the previous task's children (end_children_for; 1 consumer: workflows/agent_pool.py:207) — justified
  5. A child parked on an unanswered spawn approval is not cancelled, only delivery-gated (reproduced: pooled destroy made the approval POST answer 404) — justified
  6. A claimed-but-unstarted durable row is left to its claimer (allow_admitted=False) — justified
  7. One INFO audit line per teardown, naming its verb — justified
  8. A provider shutdown that raises can no longer skip the child cancel, at every site — justified
  9. The delivery gate forgets cancelled ids by age (24h), never by count — justified
  10. DELIVERY_ROUTING_FIELDS plus AST ratchets pinning producers, release sites and the True callers by path — justified

Not a duplicate: cancel_for_parent (Stop-all, subagent.py:3601) reports home by design; the teardown verb exists to suppress that, and both share one reap path. Root cause (no conversation-incarnation identity; two in-flight escapes) is declared, argued and tracked in #12069 — accepted-and-deferred. Docs updated in the same commit per AGENTS.md.

[FIRST-PRINCIPLES-REVIEWED] 6ff0f92

@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review — ✅ no blocking findings

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

Review details

Based on my analysis, let me verify the one candidate's mechanism against the actual asyncio semantics and the surrounding code.

The candidate claims that catching CancelledError from the reaper's wait_for timeout at await session.provider.shutdown() (line 691) defers it, running the trailing teardown before re-raising. I traced this:

  • asyncio.wait_for on timeout cancels the awaited coroutine exactly once; the injected CancelledError is caught by except BaseException, stored, and _must_cancel is cleared, so subsequent awaits proceed. wait_for then blocks in _cancel_and_wait until the coroutine truly completes. Mechanism confirmed across the 3.8–3.10 and 3.11+ (asyncio.timeout) implementations.

However, evaluating (c) — an observable wrong outcome — strictly:

  • The timeout landing inside shutdown() is reachable (a hung shutdown is exactly what the reaper guards). But the trailing code immediately force-kills the PID (kill_process_tree_async), so the process death itself is not delayed — the reaper's _sigkill_session fallback fires afterward on an already-dead process (redundant).
  • The only added delay comes from _cancel_parent_children, and only when the session actually has slow-to-cancel sub-agents (it is bounded to _CHILD_CANCEL_TIMEOUT_SECS = 20.0, and returns promptly for the common empty-snapshot case). With no slow children — the overwhelming majority of cron jobs — there is no observable delay at all.

So the outcome reduces to "the redundant SIGKILL could be delayed up to ~20s if the session happens to have slow-to-cancel children" — a contingent "could," with the process killed and the job reaped regardless. That does not clear the bar for a concrete, observable wrong outcome. The candidate's own confidence was LOW, and my independent re-derivation does not raise it above the 80 threshold.

No findings.

[OPUS-REVIEWED] 6ff0f92

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

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

@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 Sep 19, 2026
@iamwhatever
iamwhatever force-pushed the fix/cancel-children-on-parent-end branch from 8ae2c31 to 9768887 Compare September 19, 2026 07:48
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 19, 2026
@iamwhatever
iamwhatever force-pushed the fix/cancel-children-on-parent-end branch from 9768887 to 6870cc6 Compare September 19, 2026 07:59
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 19, 2026
@iamwhatever
iamwhatever force-pushed the fix/cancel-children-on-parent-end branch from 6870cc6 to 2c9cc44 Compare September 19, 2026 08:18
@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 Sep 19, 2026
@iamwhatever
iamwhatever force-pushed the fix/cancel-children-on-parent-end branch 4 times, most recently from 497a683 to 0d29f00 Compare September 19, 2026 09:06
@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 Sep 19, 2026
@iamwhatever
iamwhatever force-pushed the fix/cancel-children-on-parent-end branch from 0d29f00 to 0e27972 Compare September 19, 2026 09:25
@github-actions github-actions Bot removed the readiness: action required A blocking check or review needs attention label Sep 19, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: end_children_for loses its verb parameter and hardcodes its own name; the verb-naming ratchet loses the exemption that parameter required

  • end_children_for(*, verb=) is generalized for callers that don't exist (span=15b8ace4c754) — subtracted in 96dfec51aa21cd00ac94ddf5a7f3bf89ac8b9b19.

Accepted as stated. One consumer, one value, so the parameter carried nothing the method
name did not — and the second half of the observation is the part that decided it: the
parameter also bought the verb-naming ratchet a named exemption whose own correctness then
needed its own assertion. That is machinery standing in for a rule, added to support a
caller that does not exist.

Subtracted as prescribed. end_children_for(key) now hardcodes verb="end_children_for",
which is what every other site does — each names itself — so the ratchet checks one rule
with no carve-out. The exemption block and its forwarded assertion are gone; in their
place the ratchet asserts the primitive still appears among the call sites it found, so the
primitive silently ceasing to reach the teardown is still caught.

The one thing I checked before agreeing, because it is what the parameter was for: whether
the audit line loses information. It does not. The verb identifies the code path that ended
the conversation and the line's key identifies the conversation, so the pool's call reads
verb=end_children_for key=wf-pool:run-1:0 — the pool is named by the key. Losing
verb=workflow_pool_reuse costs nothing a reader of that line needs.

Item 7 in the same review — the claimed-but-unstarted rule being invisible because the
description truncated at 8000 bytes — is fixed rather than subtracted: allow_admitted=False
now has its own row in the piece table at byte ~2100 and its test in the test table, both
well inside the window. Its own subtraction question was already settled earlier in this PR:
the rule exists because an admitted row's claimer would otherwise register and run work
the teardown believed it stopped, and because such a row may carry a person's approval
decision.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: no
mechanism: the delivery gate at terminal.py — one id test before _on_done, with _teardown_cancelled_ids armed synchronously in snapshot_teardown_children_impl

Accepted, not rebutted. I confirmed it in the tree rather than from the diff: the gate is a
single id test before _on_done; _on_done is the gateway's _subagent_done, which
resolves the parent through get_or_create — the call that CREATES a session when none is
live — and never re-reads the mark; and the mark is armed synchronously in
snapshot_teardown_children_impl, described there as the last synchronous point before the
teardown's awaits. So a report suspended between the gate and that resolution can have its
id marked and its parent key retired afterwards, and it then rebuilds the conversation the
teardown took down and seeds it with the retired run's text. The adjudicator's
UPHOLD-FENCED reasoning matches what the code does.

self-added: no — and this is the load-bearing fact for the deferral. The window is in
slack/gateway.py's injection path, which this PR does not modify beyond registering the
teardown handler. _subagent_done resolves its parent through the session-creating
get_or_create on main today, and has since before this branch. What this PR adds is a
mark that COULD be rechecked there — it does not add the resurrection path.

Deferred rather than patched because the prescribed recheck would be the FIFTH recheck on
this one delivery path in this PR. The previous four each closed a real instance — the
_on_done injection, the failure announce, the wave digest's synthetic flush record, the
follow-up watcher — and none closed the class. That is the same shape as the admission
fence this PR ultimately removed after four rounds: an instance closed per round while the
class stayed open.

The reason a fifth recheck cannot close it is in the finding's own shape. This is the
REPORT-SIDE TWIN of the residual this PR already documents on the spawn side. Both halves
have one cause — the mark and the snapshot are taken at the only synchronous point
available, and anything already in flight does not see them — so a recheck at either end
leaves the other end open:

half escapes bound
admitted late a spawn between its row write and its registration is in neither the queue nor _agents, so no snapshot names it, and it STARTS its own run timeout
reporting late a report already past the gate and suspended in _on_done is not stopped by marking its id afterwards, so it DELIVERS its own run timeout

What closes both is one identity every path can test cheaply, which does not exist today:
session_generation counts allocation reservations — get_or_create advances it twice per
call and reset advances it on a recycle — so fencing on it refuses ordinary queued work,
which is why the fence built on it was removed rather than fixed.

Tracked in #12069 (open, deferred-finding, assigned, Due: 2026-10-17), which now
carries this half with the terminal.py:236 / _subagent_done get_or_create evidence
written out, plus acceptance criteria that require a test driving the interleaving rather
than asserting on the gate alone.

The residual text now names BOTH halves in three places, so the next reader is not told the
delivery gate is a backstop it is not: the PR description (§ Residual — two halves),
docs/system-specs/modules/subagent.md § RESIDUAL, and the audit-line comment in
cancellation.py where a reader meets the teardown in code. The earlier wording claimed a
missed run's report is dropped by the gate; it now says that holds only for a run the
snapshot did name.

This record does not clear the gate and is not an override. A fenced security-class finding
needs a repository writer's SHA-scoped /ai-review override, which an agent must never
self-authorize; that decision is with the repository owner.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

Rebased: ee521b0dbf -> 891e6de8da, head e74fe68e20 -> d7207d69e8; CI re-running.

Not a green-age re-sync. The previous head's CI was stale red through no fault of this
branch
: main's tip at the time (1c7f963706, #11947) imported
require_private_memory_execution from kiro_crew.member_memory_auth, which did not define
it, so every lane that boots a gateway off the merge ref failed at import — E2E (stub ACP backend, offline), Real Adapter Contract Tests, Windows Fail-Closed Sandbox Contract.
Reproduced on a clean detached main worktree with this branch not involved. #12091 has
since reverted it and the name is gone from main entirely.

The rebase moved nothing. Sorted -U0 line sets against the pre-rebase head are
byte-identical — 2787 added, 42 removed, 25 files, comm empty in all four directions —
and the rebase applied with no conflicts.

Re-verified on the new base: 1418 passed, 1 skipped over the affected files; isort, flake8,
mypy, comment-history, docs-lint, harness-parity and agent-sdk-boundary all pass. black --check flags four files (test_cron_cancel.py, test_cron_reaper.py,
test_session_coverage.py, test_handlers_channel_clear_context.py) that a clean
git archive origin/main extract flags identically, so they are the baselined set rather
than this change.

Note for any pending /ai-review override: the head SHA changed, so an override must name
d7207d69e8.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

/ai-review override gpt d7207d6: authorised by zejiangg on 2026-09-19: report-side twin of documented residual, pre-existing on main, deferred to #12069

@github-actions

Copy link
Copy Markdown
Contributor

Human judgment recorded

@iamwhatever marked the gpt AI finding as false positive, not applicable, or explicitly accepted for d7207d69e87a1381bb85a6f3019268e931a84d6f.

authorised by zejiangg on 2026-09-19: report-side twin of documented residual, pre-existing on main, deferred to #12069

This decision applies only to this commit. A new push requires a new judgment.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

mechanism: KIROCREW_HOME reserved; fetch-family boundary recorded by test

  • the strip reserves 2 names of a >=4-member family; job.env still redirects the ceiling (span=b86df4ca1b8f) — fixed in cefd85a1e201

Half upheld, half rebutted, and the counted siblings split cleanly.
KIROCREW_HOME was real and is now reserved: config/paths.py:261 reads it,
governance._policy_home_path resolves the ceiling file under it, and no spawn
scrub carries it. Pinned by test_cron_job_env_must_not_deliver_the_data_home.
The other three counted names — KIROCREW_POLICY_URL,
KIROCREW_POLICY_CACHE_ONLY, KIROCREW_POLICY_MAX_CACHE_AGE_SECS — cannot reach
the scheduled child today. All seven KIROCREW_POLICY_* names are in
sandbox._AGENT_DENIED_ENV_KEYS by exact spelling, and the ACP spawn applies
scrub_agent_subprocess_env AFTER overlaying extra_env, so a job-supplied value
is dropped before any governance read. That is the "shown unreadable by the
scheduled child" arm, and
test_the_policy_fetch_family_is_stopped_by_the_spawn_scrub records it.
The description now states which names the seam reserves and which the spawn
scrub owns, instead of claiming the whole family.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

mechanism: KIROCREW_HOME added to _CRON_RESERVED_ENV_KEYS

  • the deny-list covers two members of the family it defines; KIROCREW_HOME subsumes both (span=eadfb887244b) — fixed in cefd85a1e201

Upheld, and the clearing condition is met by reservation rather than by argument.
Verified from code: config/paths.py:261 reads KIROCREW_HOME,
governance._policy_home_path resolves security_policy.json through
config_dir(), and the name appears in no spawn scrub or deny list — so a
job-supplied home did point the ceiling read at a directory the job controls.
KIROCREW_HOME is now in _CRON_RESERVED_ENV_KEYS, and
test_cron_job_env_must_not_deliver_the_data_home pins it in both spellings,
failing when the entry is removed. The comment states the property the same way
the other members do.
Not reserved here, deliberately: the KIROCREW_POLICY_* fetch family, which
sandbox._AGENT_DENIED_ENV_KEYS already drops at the spawn. A second test
records that boundary so this seam is not widened to duplicate it.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: the reset docstring's and the spec's cost model now name delivery-resurrection as the miss cost, and say a keyword is invisible to the AST ratchet

  • A future conversation-ending reset caller that omits the flag silently reproduces the resurrection bug (span=fc1ad9c7b530) — fixed in a8892cd731b8652b05d33f25404ae85c2fd05441.

Taken on the Watch item's own terms, and the second of its two "clears when" options is the
one I could do here: the cost model now names delivery-resurrection.

The item is right that the old wording understated the miss. It said a missed cancel "leaves
a bounded child running to its own timeout" — but a missed flag also arms no delivery gate,
so the child's report still reaches _on_done, which resolves the parent through
get_or_create, the call that CREATES a session when none is live. The conversation the
caller ended re-opens, seeded with that report. That is the headline defect in full, not a
milder orphan, and a future caller weighing "bounded process" against "destroys live work"
would reasonably choose wrong.

Corrected in both places a caller reads: the reset docstring in
src/kiro_crew/session_lifecycle.py and the caller table's argument in
docs/system-specs/modules/session.md. Both now also say plainly that nothing structural
catches an omission, because a keyword is invisible to the AST ratchet, and that the
path pin exists for exactly that reason.

This round also proved the seam is not hypothetical, which is worth recording next to the
Watch item: the First Principles lane found a REAL instance of it on this same head —
session_compaction.py's still-critical reset discards the conversation
(clear_conversation=True) and was keeping its children. That is fixed in the same commit,
and the fix carries a test that asserts the implication rather than a path, so the next
forgotten flag of that shape fails instead of shipping.

The fail-open default itself is unchanged and the item agrees it is defensible: 42 of the
~46 callers are recycles, and a wrong True destroys live work. #12069's
conversation-incarnation identity is the thing that would make a forgotten flag harmless,
which is the item's first "clears when" and is out of scope here.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: no
mechanism: snapshot_teardown_children_impl selects from _agents and _queue, both in-memory, because it must be synchronous inside the registry lock hold that retires the key

Accepted, and the adjudication says the decisive thing better than the finding does: this
residual is "exactly the residual the code documents at cancellation.py:456-477". It is
the ADMITTED-LATE half of the two-halves residual this PR writes down, reached from the
selection side rather than the admission side. The prescribed fix — "bind durable rows to a
conversation incarnation and reject or cancel rows from retired incarnations"
— is
word-for-word what #12069 is for.

So this is not a new defect, it is the documented one, found again from a third direction.
Three lanes have now independently arrived at the same missing primitive:

span seen from prescribed fix
acd7a71d948d the report already past the delivery gate recheck a stable conversation-incarnation identity
d5ac4f1e6ea4 the accepted row not yet in _agents or _queue bind durable rows to a conversation incarnation
earlier, gate.py the admission in flight compare a conversation-incarnation counter

Not patched, and the reason is this PR's own history rather than a general preference. The
previous attempt to close this exact half is what the fence WAS: a generation captured at
accept, persisted on the row, compared at registration. It went four rounds, and it was
removed — not because it was unfinished, but because session_generation counts allocation
reservations. get_or_create advances it twice per call and reset advances it on a
recycle, so fencing on it refused ordinary queued work and killed children the
ends_conversation default exists to protect. Re-adding a fence on the same counter under a
new name would reproduce that, and no other counter exists.

The E2E evidence from that attempt is why the selection is not simply widened instead.
Widening it is what produced the wrong cancel: E2E (stub ACP backend, offline) failed with
the audit line verb=destroy key=wf-pool:wf_000008:0 snapshot_ids=861623e0 and, on the same
id, approvals/spawn:861623e0/approve -> HTTP 404. A child the widened snapshot swept was
one carrying a person's unanswered approval, and cancelling it answered that request for
them. That is what forced the split this PR ships — approval-parked children are delivery-
GATED, never cancelled — and it is objective evidence that "select more" is not the safe
direction here. The lane is right that the narrow selection leaves a residual; the split
exists because the wide one caused a worse, demonstrated failure.

Tracked in #12069 (open, deferred-finding, assigned, Due: 2026-10-17), which carries the
counter design, its ~550–640 LOC estimate, the four named risks, and both halves of the
residual. The residual text names both halves in the PR description, subagent.md
§ RESIDUAL, a pointer in session.md, and the audit-line comment in cancellation.py.

This record does not clear the gate and is not an override. A fenced security-class finding
needs a repository writer's SHA-scoped /ai-review override; the one already authorised on
this PR was reasoned about the REPORT-side half, so it does not carry to this span, and the
decision on this one is with the repository owner.

The lane's advisory item is fixed rather than deferred and is not covered by this rationale:
the one-off from kiro_crew.taskq.model import ADMITTED now uses the same deferred package
alias as the other 28 store calls in that module, so the line has its siblings' shape and
introduces no new import pattern. Module scope was the finding's suggestion; that file is on
the gateway boot path where deferred imports are the convention, so matching the convention
is the smaller change.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: the teardown's queued-retraction path — taskq_cancel_queued_async(allow_admitted=False), then _unqueue(stored=params, store_cancelled=True), then _report_queued_stop

  • Refused cancellation is published as stopped (span=d5ac4f1e6ea4) — accepted as advisory, no fix in this head.

Downgraded on adjudication, and recorded rather than patched because this PR is frozen at
readiness. The finding is real in shape and its chain is longer than the headline says — the
adjudicator's own trace is the useful part, so I am keeping it here rather than restating
the claim:

The allow_admitted=False call returns None for an ADMITTED row, the row is still in the
in-memory _queue, so _unqueue_impl pops it and returns it — bypassing the
claimed_unstarted branch — and the entry is reported stopped. But with stored=None
and a store attached, that same _unqueue re-posts the cancel as a retry using the default
allow_admitted=True, which WOULD cancel the admitted row on the writer thread. So the
child only survives to boot reconciliation if that retry ALSO fails — a persistent store
outage, not a transient one.

That is why the remedy is disproportionate here, and it is the same shape already judged so
on this PR: "await a successful admitted-row cancellation before unqueueing" means awaiting
a store commit inside a path whose whole design is that the loop never holds the SQLite
lock. The earlier gate.py:1081 finding on this PR was downgraded for exactly that reason.

Worth separating from the residual family, because it is NOT the same defect: the two
documented residual halves are about work the teardown never SELECTED. This one is about
work it selected, refused, and then mis-reported. The mis-report is the part with teeth —
_report_queued_stop publishes a neutral stopped terminal for a row the store declined —
and it is bounded by the retry above.

Left as advisory with the boundary written down rather than closed: a persistent store
outage during a parent end already degrades this path in several directions the code states
(the durable-read exhaustion warning, the live-reap fallback), and adding a fifth
store-await inside the synchronous retraction is the change most likely to introduce a loop
stall. If it is taken up, the natural home is alongside #12069, where the queued-retraction
path is already being revisited.

No push: pr_status reports readiness passed on this head, and the standing rule is that
advisories get dispositions rather than pushes once a PR is frozen.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: the except BaseException re-raise wrapped around await session.provider.shutdown() at each parent-end site, which defers the exception past the child cancel and the runtime release

  • The BaseException catch swallows the reaper's injected CancelledError (span=9794ef0e0782) — accepted as advisory, no fix in this head.

Confirmed, and it is the sharpest reading anyone has given that finally pass. The
interaction is specific and I can follow every hop: cron.py wraps
reset(..., ends_conversation=True) in asyncio.wait_for(..., _REAPER_RESET_TIMEOUT), so a
timeout there injects CancelledError INTO the reset; the new catch is BaseException, so
it takes that cancel; the deferred re-raise then happens only after
_cancel_parent_children's own bounded wait (wait_for(shield(task), 20s)) and the runtime
release. So _cancel_and_wait blocks for up to ~20s past the deadline the tight
_REAPER_RESET_TIMEOUT exists to enforce, delaying exactly the SIGKILL escalation that a
wedged provider needs — and a wedged shutdown() is precisely when that timeout fires.

The premise is right too, which is what makes it worth recording rather than arguing: I
chose BaseException deliberately, so that a cancel could not skip the child cancel and
leave orphans. The finding shows that choice has a cost I did not weigh — it also cannot
skip the twenty-second wait, and on the reaper's path that is the wrong trade, because the
release backstop and the reaper's own SIGKILL already cover the cancel-during-shutdown case.

Not fixed here, and the reason is procedural rather than a disagreement. pr_status reports
readiness passed on this head, and the standing rule on this PR is that once readiness
passes the branch is frozen: advisories get dispositions, not pushes. Narrowing the catch to
Exception (or re-raising CancelledError before the bounded wait) is a small change, and
it touches the exception path at six teardown sites with six raising tests behind it — so it
deserves its own round rather than a push onto a green head.

Recorded with the remedy the finding names, so whoever picks it up does not re-derive it:
re-raise CancelledError before _cancel_parent_children's wait, leaving the runtime
release and the reaper's SIGKILL to handle the rare cancel-inside-shutdown case. The six
test_a_failing_provider_shutdown_still_ends_the_children parametrisations are the tests
that must keep passing across that change, and a seventh for the cancel case is what would
pin it.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

Rebased: abedd2ed15 -> c23bb8a576, head 22e31332d1 -> 06ec1613cf; CI re-running.

Green-age had reached base +8 with seven overlapping files, so this is a deliberate re-sync
rather than a content change. One conflict, in src/kiro_crew/session_cleanup.py: main
rewrote the idle-sweep block into an orphan/idle split (slot_owned_keys.discard,
expect_session=scanned, skip_if_injecting, two reset calls). This branch's change there
was a four-line comment plus one Protocol keyword, so the resolution takes main's block whole
and re-attaches both to the call they describe — the idle branch's
reset(key, skip_if_busy=True, skip_if_injecting=True).

Line-set proof against the pre-rebase head, sorted -U0:

pre post
added 2850 2851
removed 42 42
files 25 25

Removals identical, file set identical. The added-line delta is exactly the resolution: the
same four comment lines re-indented from 12 to 16 spaces (main nests them one level deeper
now), plus one new line recording that neither call on that path passes ends_conversation.
Nothing else moved.

Re-verified on the new base: 1236 passed, 1 skipped across test_session.py,
test_session_coverage.py, test_subagent_coverage.py, test_session_cleanup.py,
test_session_idle_busy_guard.py, test_process_tree.py,
test_overload_integration_glue.py, test_workflows_agent_pool.py, test_cron_cancel.py,
test_cron_reaper.py, test_handlers_channel_clear_context.py, test_taskrunner.py,
test_auto_compact_gate.py and test_post_compaction_continuation.py — the affected set plus
the tests owning every overlapping file.

isort, flake8, mypy, docs-lint, comment-history, harness-parity and agent-sdk-boundary all
pass. black --check flags the same four files a clean git archive origin/main extract
flags (test_cron_cancel.py, test_cron_reaper.py, test_session_coverage.py,
test_handlers_channel_clear_context.py), so they are the baselined set rather than this
change.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

Both GPT findings on 06ec1613cf answered; new head 59f9becf656e5afbdba43a62435a321a64722888.

cancellation.py:414 — Completed runs can retain follow-up watchers — FIXED

Real, and I reproduced it against the live CancellationCoordinator before touching anything.
A record that is done=True, _reported_to_parent=True with every delivery field clear:

done+delivered -> delivery_is_parked: False
selected            : ()
marked              : []
watcher still armed : True      <- before
watcher still armed : False     <- after

Such a run is in none of live / approval_parked / undelivered, and it is not even
MARKED — there is nothing to cancel and nothing parked to gate. So the watcher was the only
thing the teardown could still act on, and it was left armed.

The reason it is armed at that moment is not a race, it is the design: a follow-up watcher
dispatches AFTER its run finishes, which is exactly why the dispatch cannot read the asking
ordinal. Its two exits are the ones this PR closes everywhere else — dispatch the queued
continuation on the retired key, or announce a failure built as a synthetic record with
uuid.uuid4().hex[:8] for an id, which walks past any gate keyed on the original run and
reaches _on_done, where the parent is resolved through the session-creating
get_or_create.

Fix is the one line the finding prescribes — disarm on OWNERSHIP rather than on what was
selected:

for agent_id in [info.id for info in mine]:     # was [*live, *approval_parked, *undelivered]

Dropping the follow-up silently is the right outcome, and it is the argument already written
above that loop: it was a correction queued for a conversation that has ended, and announcing
it is the injection the teardown exists to prevent.

Test: test_a_teardown_disarms_the_watcher_of_a_delivered_run. It asserts the preconditions
that make the case meaningful — selected == () and the marked set empty — before asserting
the watcher is popped and stopped, so it cannot pass for the wrong reason. Mutation-verified:
restoring the three-list iterable fails it by name, and the sibling not-done test passes
either way, so the new test pins this branch specifically.

Verified: 912 passed across test_session.py, test_subagent_coverage.py,
test_continuable_followups.py, test_subagent_continuable.py, test_side_steer_queue.py,
test_mcp_followup_dispatch.py and test_overload_integration_glue.py. black, isort,
flake8, mypy and comment-history pass.

cancellation.py:386 — Store-only queued children escape teardown — accepted-and-deferred

Third appearance of this span, and the adjudication again identifies it as the documented
residual: "exactly the residual the code documents at cancel_for_teardown_impl
(cancellation.py:462-477)"
. The prescribed fix — "fence persisted rows by conversation
incarnation"
— is what #12069 exists for.

Not re-attempted here. The previous attempt to close this half WAS the admission fence, and it
was removed after four rounds because session_generation is the wrong counter:
get_or_create advances it twice per call and reset advances it on a recycle, so fencing on
it refused ordinary queued work and killed children the ends_conversation default protects.
No other counter exists, which is the whole content of #12069.

Widening the snapshot instead is the direction with objective evidence against it: the E2E lane
failed on verb=destroy key=wf-pool:wf_000008:0 snapshot_ids=861623e0 with
approvals/spawn:861623e0/approve -> HTTP 404 on the same id — a child the widened snapshot
swept was carrying a person's unanswered approval, and cancelling it answered their request for
them. That is why approval-parked children are delivery-gated rather than cancelled.

Tracked in #12069 (open, deferred-finding, assigned, Due: 2026-10-17), which carries both
halves of the residual, the counter design and its cost. The residual itself is stated in the
PR description, docs/system-specs/modules/subagent.md § RESIDUAL, a pointer from
session.md, and the audit-line comment in cancellation.py.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: yes
mechanism: _AgingIdSet.__contains__ tests membership without pruning; _prune runs only from add / update

  • Expired teardown IDs remain active (span=599ab81e58eb) — confirmed, not patched in this head.

New span, and a fair one. __contains__ returns agent_id in self._marked_at without
calling _prune, so an entry older than the TTL still answers True until some later add
or update sweeps it. I am not disputing the mechanism.

Two things make this different from the findings before it, and the adjudication established
both rather than me:

It FLAGGED rather than fenced — the first non-fenced blocking verdict on this PR. The
reasoning is that the harm needs three conditions at once: a marked run that never reaches a
terminal (so approval-parked, since the ordinary path discards the mark at terminal.py:266),
more than a full day with zero teardown-cancellation events anywhere in the process (any one
.update() prunes the expired prefix first), and a 1-in-2³² uuid4().hex[:8] collision with
that one specific stale id. It also notes the falsely-suppressed run stays dashboard-visible:
subagent_done still fires and the result file and tombstone are still written, so what is
lost is the parent injection, not the record.

The remedy is genuinely one line — prune before testing membership — and I am not
applying it, on instruction rather than on judgement. This PR is frozen; the freeze was
lifted for exactly one push this round (the cancellation.py:414 watcher disarm, which is in
59f9becf65), and the standing rule is that anything red beyond the one authorised span
stops for a decision rather than being patched. Three consecutive rounds on this PR have each
produced a new one-line finding after the previous one landed, which is the pattern the
freeze exists to interrupt.

For whoever takes the decision, the shape is: call self._prune(now) at the top of
__contains__ before the membership test, matching what add and update already do. The
test would drive a mark older than _TEARDOWN_GATE_TTL_SECS with no intervening
add/update and assert the id is absent; mutation-verified by removing the prune call.
test_the_teardown_gate_forgets_by_age_and_never_by_count and
test_the_gate_backstop_outlasts_a_human_approval_window are the two tests that must keep
passing across it, since they pin the TTL's two directions.

Recorded here so the next round does not re-derive it.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

Re-synced onto main (conflict rebase)

old new
base c23bb8a576 1fbffb1c7a
head 59f9becf65 de13c8da5b

GitHub reported mergeable=CONFLICTING / DIRTY, so this is the standing conflict rebase. No
behaviour change is included.

Conflicts: 1 file. src/kiro_crew/subagent.py — one content conflict at the module-constant
block. main (#11556's neighbourhood) added _MAX_COMPLETION_WAITERS = 64 at the same insertion
point where this branch adds the delivery-routing comment block and _AgingIdSet. Both sides are
purely additive there, so the resolution is concatenation, not a choice: main's constant first,
then this branch's block. No checkout --ours was used. All 185 lines this branch adds to that
file were then grepped back individually (0 missing), and main's two _MAX_COMPLETION_WAITERS
consumers at subagent.py:2778 and :2784 were confirmed intact.

The other 7 overlapping files auto-merged: docs/system-specs/modules/session.md, cron.py,
session.py, session_compaction.py, slack/gateway.py, taskrunner.py, test/test_session.py.

Equivalence: exact, zero delta. Sorted -U0 line sets before and after the rebase:

pre post pre-only post-only
added lines 2941 2941 0 0
removed lines 42 42 0 0

comm in both directions is empty in all four quadrants, and the 25-file change list is identical.

Tests: 1890 passed, 1 skipped (-n 2), covering the 9 test files this branch changes plus the
owners of every overlapping file: test_subagent, test_cron, test_session_cleanup,
test_slack_gateway, test_taskrunner_coverage, test_auto_compact_gate,
test_post_compaction_continuation, test_task_runner_compaction, test_compaction_wait_budget.

Caveat on that run, and it is main's, not this branch's. main at 1fbffb1c7a currently
cannot import kiro_crew.sandbox: the module-level invariant at sandbox.py:1053 is violated —
_DELEGATED_OVERLAP_LEAF_REASONS lists cloud.json and playwright-cli, while
_CREW_NOFOLLOW_READONLY_FILE_LEAVES | _CREW_NOFOLLOW_READONLY_DIR_LEAVES is those two plus
subagents, member-memory-bindings and decisions. Reproduced on a clean detached
origin/main worktree with no part of this branch present, so every collection on this base fails
at conftest.py import. The figures above were measured with that one main-side assert
neutralised locally, uncommitted; it was restored before the push and the pushed tree carries the
assert verbatim.

Gates on the pushed commit: isort, flake8, mypy (14 changed src/ files), docs-lint,
comment-history, agent-sdk-boundary and harness-parity all pass. black flags 4 test files
(test_cron_cancel, test_cron_reaper, test_session_coverage,
test_handlers_channel_clear_context) — inherited drift: black --check refuses the same four
files on a clean origin/main worktree.

Frozen again at de13c8da5b. The disposition on span d5ac4f1e6ea4 (deferred to #12069) still
stands; no new code was written for it here.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

Re-synced onto main again — off the broken base

old new
base 1fbffb1c7a 2b7d378116
head de13c8da5b 3e5c4ee6d7

The previous base could not import kiro_crew.sandbox (module assert at sandbox.py:1053), which
failed every backend, E2E and build lane at collection on this PR for a reason that was not this
PR's. #12193 landed as 2b7d378116 and supplies the missing delegated-overlap wording, so this
re-sync is purely to put CI on a base that imports. No behaviour change.

Conflicts: none. The rebase applied cleanly. main's new commit touches only
src/kiro_crew/sandbox.py, which this branch does not touch, so the overlap set between this
branch's 25 files and main's move is empty.

Equivalence: exact, zero delta. Sorted -U0 line sets before and after:

pre post pre-only post-only
added lines 2941 2941 0 0
removed lines 42 42 0 0

comm empty in all four quadrants; the 25-file change list is identical.

Tests: 1890 passed, 1 skipped (-n 2) — and this time on the real base, with no local patch of
any kind. Same selection as before: the 9 test files this branch changes plus test_subagent,
test_cron, test_session_cleanup, test_slack_gateway, test_taskrunner_coverage,
test_auto_compact_gate, test_post_compaction_continuation, test_task_runner_compaction,
test_compaction_wait_budget.

Gates on the pushed commit: isort, flake8, mypy (14 changed src/ files), docs-lint,
comment-history, agent-sdk-boundary and harness-parity all pass. black flags the same 4 test
files (test_cron_cancel, test_cron_reaper, test_session_coverage,
test_handlers_channel_clear_context) — inherited drift, black --check refuses those four on a
clean origin/main worktree too.

Review state carried over from de13c8da5b, where GPT 5.6, Opus 4.8, Design and First Principles
all passed with no blocking span: spans 599ab81e58eb and d5ac4f1e6ea4 were both absent there, so
no override was needed on that head and none is claimed here. The lanes re-run on 3e5c4ee6d7.

Frozen again at 3e5c4ee6d7.

@github-actions

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ no blocking findings

GPT 5.6 completed its review of 3e5c4ee6d7b11e5c5968ef03ed23454f917c8f46 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 3e5c4ee

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

@iamwhatever

Copy link
Copy Markdown
Contributor Author

Re-synced onto main — picks up the defer_embedding test fix

old new
base 2b7d378116 7e8f2c459f
head 3e5c4ee6d7 2cb9282ebb

On the previous base, three shards — Backend Tests (3.12, 2), Backend Tests (Windows) (2) and
macOS (3) — all failed on the same single test,
test/test_vector_memory.py::TestConflictResolution::test_replacing_a_real_value_still_retires_episodic_memory
(AssertionError: assert [] == [('pref.os', 'macos')]), and Coverage Gate then failed closed on
backend-test=failure. That test is not in this PR's 25 files. 098f07e09a
(fix(memory): defer_embedding) was already in base 2b7d378116 and left the stubs behind; the
matching test fix 7e8f2c459f landed on main afterwards. Verified by running that exact node on a
detached worktree at 2b7d378116 carrying no part of this branch: it fails there too. So this
re-sync is to pick up 7e8f2c459f. No behaviour change.

Conflicts: none. Two commits came in (7e8f2c459f test fix, b5b9c62f96 docs) and the overlap
set with this branch's 25 files is empty.

Equivalence: exact, zero delta.

pre post pre-only post-only
added lines 2941 2941 0 0
removed lines 42 42 0 0

comm empty in all four quadrants; the 25-file change list is identical.

Tests: 1997 passed, 15 skipped (-n 2) — the affected set plus all of test_vector_memory.py.
The node that failed on the old base passes on this one, run on its own as well.

Gates: isort, flake8, mypy (14 changed src/ files), docs-lint, comment-history,
agent-sdk-boundary, harness-parity all pass. black flags the same 4 test files
(test_cron_cancel, test_cron_reaper, test_session_coverage,
test_handlers_channel_clear_context) — inherited drift; black --check refuses those four on a
clean origin/main worktree too.

Review lanes were all green on 3e5c4ee6d7 (GPT 5.6, Opus 4.8, Design, First Principles, UX,
Security Scope) with no blocking span, so no /ai-review override was needed there and none is
claimed here. The lanes re-run on 2cb9282ebb.

Frozen again at 2cb9282ebb.

@github-actions

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ⚠️ review incomplete

GPT 5.6 did not produce a complete verdict for 2cb9282ebbc0550602f2158e9a6f4e04f0b8a7f3; inspect the workflow logs and re-run it.

This comment is updated in place on each push.

See the GPT 5.6 Review job logs; this commit has no completed GPT verdict.

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

@iamwhatever

Copy link
Copy Markdown
Contributor Author

Re-synced onto main (conflict rebase)

old new
base 7e8f2c459f 1e40f7f0f5
head 2cb9282ebb fab363b5a2

2cb9282ebb had reached readiness: passed with all six review lanes green, then main moved 8
commits and GitHub flipped this PR to CONFLICTING / DIRTY. This is the standing conflict rebase;
no behaviour change is included, and nothing else was touched.

Conflicts: 1 file, 1 line each side. src/kiro_crew/session_lifecycle.py, in the
identity-change retire loop. main (143a7cd8c4, "drop the native sid when the signed-in account
changes") added invalidated_keys.append(key) to the removal path; this branch adds
teardown_children_by_key[key] = self._snapshot_parent_children(key) at the same point. Two
independent statements, so the resolution keeps both — main's first, then this branch's. No
checkout --ours was used. Every line this branch adds to that file was grepped back afterwards: 0
missing.

The other 5 overlapping files auto-merged: docs/system-specs/modules/session.md,
docs/system-specs/modules/subagent.md, src/kiro_crew/session.py,
src/kiro_crew/slack/gateway.py, src/kiro_crew/subagent.py.

Equivalence: exact, zero delta.

pre post pre-only post-only
added lines 2941 2941 0 0
removed lines 42 42 0 0

comm empty in all four quadrants; the 25-file change list is identical.

Tests: 2242 passed, 15 skipped (-n 2) — the 9 test files this branch changes plus the owners of
every overlapping file (test_subagent, test_session_cleanup, test_slack_gateway,
test_session_token_identity, test_session_provider_liveness, test_session_terminated_reap,
test_session_drain, test_subagent_manager_boundaries, test_subagent_persistence,
test_vector_memory, test_cron, test_taskrunner_coverage). Then a second pass over every test
file mentioning the three symbols in the resolved hunk (invalidated_keys,
retire_on_identity_change, _snapshot_parent_children) — test_session.py and
test_external_logout_detection.py, 458 passed, which covers both sides of that resolution.

Gates: isort, flake8, mypy (14 changed src/ files), docs-lint, comment-history,
agent-sdk-boundary, harness-parity all pass. black flags the same 4 test files
(test_cron_cancel, test_cron_reaper, test_session_coverage,
test_handlers_channel_clear_context) — inherited drift; black --check refuses those four on a
clean origin/main worktree too.

Frozen again at fab363b5a2.

@github-actions

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — 🔴 changes requested (blocking)

GPT 5.6 found at least one blocking issue that must be resolved before merging fab363b5a205c20248b67bb3f6ffd569db8eb86f. Adjudication produced no [GPT-ADJUDICATED] marker for fab363b: the adjudication stage FAILED TO RUN (its raw output is in the Adjudication details block -- typically an API or setup error), so no proportionality review took place and GPT's blocking verdict stands unreviewed.

This comment is updated in place on each push.

BLOCKING -- src/kiro_crew/subagent_manager/cancellation.py:403 -- Spawn-approval rejection bypasses the teardown gate
self._manager._teardown_cancelled_ids.update(agent_id for agent_id in approval_parked if agent_id)
Parent ends during spawn approval -> rejection calls _safe_announce_impl directly -> _on_done recreates and seeds the retired conversation.
Anchor: residual/crash-data-loss-corruption
Fix: In _safe_announce_impl, discard and return when the ID is teardown-cancelled.
[BLOCK-MERGE] fab363b
[GPT-REVIEWED] fab363b
False positive or not applicable? A repository writer can comment:
/ai-review override gpt fab363b5a205c20248b67bb3f6ffd569db8eb86f: <one-sentence reason>

@iamwhatever

Copy link
Copy Markdown
Contributor Author

Fixed: span d5ac4f1e6ea4 — spawn-approval rejection bypassed the teardown gate

Fixed at cf9bcfbc1a (was fab363b5a2). The finding is real; I verified it before fixing rather
than taking the report's word for it.

Probe verdict: REAL. Driven through the real coordinator — real SubagentManager, real spawn
gate, real snapshot_teardown_children, real _spawn_with_approval_impl rejection path, with
nothing about the gate or the announce stubbed:

1. parked?            _awaiting_approval=True _exec_started=None done=False
2. teardown armed     returned_for_cancel=()
3. id in gate?        True
4. _on_done called?   True  ids=['f05b15d8']
5. id still in gate?  True
6. run state          done=True error='spawn rejected'

Lines 2 and 3 are the split the teardown intends: an approval-parked run is returned for no
cancellation (the approval is a person's to answer) but IS marked, precisely so its delivery cannot
land. Line 4 is the defect — the decline reached _on_done anyway. Line 5 shows the mark was never
consulted on that path.

Why the existing gate missed it. The delivery gate lives in _report_terminal_impl
(terminal.py:236) and in notify_injection_failed (terminal.py:744). The decline in
_spawn_with_approval_impl (pump.py:588) takes neither: it claims the finalize and calls
_safe_announce directly. _safe_announce_impl had no check, so the one representation the
teardown is certain to have marked walked straight into the injector — which resolves the parent key
through the session registry and CREATES a session when none is live.

The fix is the guard GPT named, at the top of _safe_announce_impl in
src/kiro_crew/subagent_manager/admission/gate.py: if the id is teardown-cancelled, log and return.
The id is left in the set rather than discarded, because this function is one of five announce entry
points (gate.py:1114, gate.py:1285, pump.py:422, pump.py:588, waves.py:168) and the age
backstop is what retires the mark. Gating here covers all five at once, the same way
terminal.py:744 is a single choke point for the failure-notice callers.

Test:

test/test_subagent_coverage.py::TestNotifyInjectionFailed::
  test_a_rejected_spawn_approval_after_teardown_does_not_recreate_the_conversation

It drives production code rather than a hand-built record: spawn registers, the approval callback
parks, snapshot_teardown_children("dash:1") arms the mark (asserted to return () and to mark
the id), then the prompt answers False; _on_done must never be awaited.

Mutation-verified. With the guard neutralised to if False and ... the test fails with
AssertionError: Expected mock to not have been awaited. Awaited 1 times. Restored, green again.

Diff: +15 lines in gate.py, +73 in test_subagent_coverage.py, nothing else. Regression sweep
856 passed across test_subagent_coverage, test_subagent, test_session,
test_subagent_spawn_approval_parked_6484, test_spawn_approval_no_surface_2381,
test_subagent_batch_injection, test_workflows_agent_pool, test_subagent_manager_boundaries,
test_subagent_scale.

Gates: isort, flake8, mypy (15 changed src/ files), docs-lint, comment-history,
agent-sdk-boundary, harness-parity all pass. black flags the same 4 test files
(test_cron_cancel, test_cron_reaper, test_session_coverage,
test_handlers_channel_clear_context) — inherited drift; black --check refuses those four on a
clean origin/main worktree too.

Backend Tests (Windows) (1) will stay red on this head: 4 failures in test/test_acp_runtime.py
(reap-amendment assertions), deterministic across two runs, filed upstream as #12247 and inherited
from 1e40f7f0f5. Nothing in this PR touches that file.

Frozen again at cf9bcfbc1a.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

self-added: no
mechanism: an injection ALREADY appended to slot._pending_subagent_failures before the teardown is drained later by chat_runner.py:9728 / gateway.py:8562, neither of which reads _teardown_cancelled_ids

  • Marking an already queued delivery does not retract it (span=d5ac4f1e6ea4) — confirmed, not patched in this head.

The mechanism holds and I am not disputing it. _pending_subagent_failures is a plain
list on the dashboard slot; terminal.py:744 gates at the moment of QUEUEING, so a notice
queued before the teardown is never re-examined, and both drains
(chat_runner.py:9728, slack/gateway.py:8562) copy-and-clear it with no gate test. The
adjudicator reached the same reading by grep — the membership set is consulted only at
terminal.py:236, gate.py:1140 and waves.py:310, all inside subagent_manager — and
returned UPHOLD-FENCED.

What I want on the record is that this is a THIRD mechanism, not either half of the
residual deferred to #12069, and I checked rather than assumed:

where the delivery is at teardown who fails to see the mark
#12069 half 1 still in admission, never selected the snapshot
#12069 half 2 (span acd7a71d948d) a coroutine suspended past the gate, before get_or_create the gate, already behind it
this finding already a string in the slot's pending list the drain, which is in another subsystem

Half 2's acceptance is written as "a report suspended between the delivery gate and
get_or_create". That is not this: here nothing is suspended and nothing is in flight —
the text has already landed in a queue that outlives the conversation, and the reader that
drains it lives outside subagent_manager entirely. A conversation-incarnation counter,
which is what #12069 proposes, would not close it either unless that drain learned to test
the counter, which is a change to two call sites this PR does not touch.

It is also not something this PR introduced. _pending_subagent_failures, both drains and
the queue-time gate all predate it; this diff does not contain the string
_pending_subagent_failures anywhere. What the diff adds is the marking of
finished-but-undelivered ids, and the finding's point is that marking is the wrong
instrument for a delivery that has already been handed off.

For whoever takes it: the shape is either a teardown-side sweep of the retiring key's slot
queue (cheap, but the slot lives in dashboard/state.py and the teardown is in
session_lifecycle.py, so it crosses a boundary this PR has kept clean), or a gate test
inside the two drains (one line each, but it makes the subagent gate a dependency of the
chat runner). Both are real designs and neither is a line I should pick unilaterally on a
head that is otherwise converged.

Recorded here so the next round does not re-derive it.

@iamwhatever

Copy link
Copy Markdown
Contributor Author

/ai-review override gpt cf9bcfb: Span d5ac4f1e6ea4: the slot queue and both drains (chat_runner.py:9728, slack/gateway.py:8562) are pre-existing and untouched by this diff, and the queue-time gate at terminal.py:744 predates this PR - only the marking is new. Deferred to #12069, where this third mechanism is now recorded with both candidate fixes. Opus traced the same path and rated it advisory: the stale text lands in the replacement conversation as a visible notice only, result file and tombstone intact - no data loss.

@github-actions

Copy link
Copy Markdown
Contributor

Human judgment recorded

@iamwhatever marked the gpt AI finding as false positive, not applicable, or explicitly accepted for cf9bcfbc1aaee1fef37dc6ecde93f609652a783b.

Span d5ac4f1e6ea4: the slot queue and both drains (chat_runner.py:9728, slack/gateway.py:8562) are pre-existing and untouched by this diff, and the queue-time gate at terminal.py:744 predates this PR - only the marking is new. Deferred to #12069, where this third mechanism is now recorded with both candidate fixes. Opus traced the same path and rated it advisory: the stale text lands in the replacement conversation as a visible notice only, result file and tombstone intact - no data loss.

This decision applies only to this commit. A new push requires a new judgment.

Reaping a parent's companion subagent runtime ends the children of a harness
that multiplexes them onto one process -- killing the process is what ends
them. A harness that runs one process per child has no entry in
_subagent_runtimes, so the reap reaches nothing and its children outlive the
conversation that asked for them, each holding an agent process and that
process's MCP fleet until its own run timeout expires. Seven of the eight
registered backends take that path.

Parent-end teardown gets its own verb rather than reusing cancel_for_parent.
That one is the user pressing Stop all, where reporting the outcome back into
the conversation is the point; _on_done resolves the parent key through the
session registry and injects, creating a session when none is live, so at a
parent end it would rebuild the conversation the teardown just took down and
seed it with a retired run's terminal text.

cancel_for_teardown takes IDS, and snapshot_teardown_children supplies them
synchronously in the same lock hold as the pop. Selecting by key at cancel time
matches a string a cold start may by then have registered a successor under,
and the retired generation would cancel the successor's runs.

Every lifecycle site that releases the companion runtime drives both halves, so
no surface that ends a conversation needs a call of its own and no backend is
named. close_all is exempt (cancel_all runs there and also drains follow-up
watchers); _retire_kiro_subagent_runtimes is exempt because it reaps only idle
runtimes and has no running child to end.

A ratchet matches this on the AST, and found the second exemption.

subagent.md and session.md carry the verbs, the sites and both exemptions.
@iamwhatever

Copy link
Copy Markdown
Contributor Author

Re-synced onto main — picks up the Windows reap fix

old new
base 1e40f7f0f5 954fb69185
head cf9bcfbc1a 6ff0f92244

Backend Tests (Windows) (1) was red on the previous head with 4 deterministic failures in
test/test_acp_runtime.py (the reap-amendment assertions, [returncode=<not reaped>]), filed as
#12247 and inherited from 1e40f7f0f5. #12269 — fix(acp): record the reap on the Windows teardown branch too — is now on main as 954fb69185, so this re-sync is to pick it up. No behaviour change
in this PR.

Conflicts: none. 10 commits came in and the rebase applied cleanly. The only overlapping file was
src/kiro_crew/session_lifecycle.py, which auto-merged; every line this branch adds to it was
grepped back afterwards, 0 missing.

Equivalence: exact, zero delta.

pre post pre-only post-only
added lines 3029 3029 0 0
removed lines 42 42 0 0

comm empty in all four quadrants; the 26-file change list is identical.

Tests: 2422 passed, 1 skipped (-n 2), including test/test_acp_runtime.py and
test_acp_runtime_kill.py in full — the suite that was failing on Windows — plus the affected set,
the owners of the overlapping file, and the spawn-approval suites that cover the _safe_announce
guard from this round.

Gates: isort, flake8, mypy (15 changed src/ files), docs-lint, comment-history,
agent-sdk-boundary, harness-parity all pass. black flags the same 4 test files
(test_cron_cancel, test_cron_reaper, test_session_coverage,
test_handlers_channel_clear_context) — inherited drift; black --check refuses those four on a
clean origin/main worktree too.

The push voids the /ai-review override gpt that cleared span d5ac4f1e6ea4 on cf9bcfbc1a, since
an override is SHA-scoped. It will be re-posted on this head once the GPT lane has run, under the
same condition and with the same reason: the queued-delivery mechanism is recorded as the third half
of #12069, the slot queue and both drains are untouched by this diff, and the queue-time gate
predates it.

Frozen again at 6ff0f92244.

@bolichen97 bolichen97 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.

Reviewed against the pr-triage-pipeline gates plus a full-diff concurrency and crash-safety audit.

fix(session), 26 files. Makes a conversation-ending parent take its sub-agents with it, driven as two halves at every ending verb (remove, destroy, discard_conversation, remove_if_unclaimed, retire_kiro_identity_sessions) plus reset(ends_conversation=True).

Audit findings, all in the safe direction:

Wrong-process and PID-reuse: termination is keyed by run id, never PID. cancel_for_teardown deliberately takes ids from a snapshot rather than a session key, because re-resolving a key at cancel time could match a successor that a cold start registered under the same key. The snapshot is taken synchronously inside the same lock hold as the pop, so it cannot name a successor's runs. On the shared kiro backend the per-run cancel runs before the shared-process runtime release, so a child is not killed out from under a live turn.

Premature kill: reset defaults to recycle, so children keep delivering into the resumed conversation. Spawn-approval-parked children are not cancelled, because a person's decision is not the teardown's to answer, but they are delivery-gated. A run parked on a later approval is live work and is cancelled. Queued claimed-but-unstarted rows are refused to avoid stranding an in-flight registration.

Ordering and idempotency: snapshot under lock, then provider shutdown, then cancel children, then release runtime. Shutdown exceptions are deferred in reset and wrapped in finally elsewhere, so a raising shutdown cannot skip the cancel. The reap is a shielded background task, so the timeout bounds the parent's wait rather than the kill. Delivery suppression is an age-based set read by every announce path including the synthetic digest-flush and follow-up-watcher ones.

The cancel is also correctly placed outside the 'if session' guard, since a prior recycle can leave session None while children still run.

Why I am approving despite the scope: no blocking correctness defect was found. The reasons this could not ride the automated Tier 1 path are scope and policy only, 26 files against the 20-file cap and a fix: declared over the 5-file cap, not a defect.

Two residuals are disclosed by the author rather than hidden, bounded by each run's own timeout and tracked in #12069: a spawn between row-write and registration sits in neither queue nor _agents so no snapshot names it, and a report already past the delivery gate and suspended in _on_done is not stopped by a later mark. Accepted as documented.

One latent footgun for a human to keep in view: the feature depends on every conversation-ending reset caller passing ends_conversation=True, and a keyword is invisible to the AST ratchet. A future ending path that forgets it would both orphan the children and resurrect the ended conversation via _on_done into get_or_create. Correct today, guarded only by test_the_conversation_ending_reset_callers_say_so.

Spec ride-along: docs/system-specs/modules/session.md and subagent.md changed as a minority of the diff (2 files / 263 lines against 24 files / 2808 lines) and were not reviewed as a design decision.

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