Repository navigation
fix(subagents): distinguish child termination from wait expiry - #136554
zeroaltitude wants to merge 45 commits into
Conversation
…ired
A visible subagent spawned with runTimeoutSeconds=5400 delivered this to its
parent at the 90-minute mark:
status: timed out
Child result: (no output)
Stats: runtime 1h30m - tokens 0 (in 0 / out 0)
The child had not stopped. It ran ~15 more minutes, committed, pushed, and
sealed a report. Three independent signals in one event all said "dead", so the
parent reasonably spawned a successor into the live child's git worktree; two
agents then worked one branch for ~12 minutes with two near-miss tree
corruptions that git cannot detect (a half-reverted tree moments before a
confident commit, and one agent's unreviewed commit sitting on the other's
shared HEAD).
Root cause, two halves.
First, subagent-registry-run-wait.ts gated the terminal publication on
`isTerminalWaitTimeout || hardRunTimeoutEndedAt !== undefined`. Those disjuncts
carry unrelated evidence: the first means agent.wait returned a terminal
snapshot (endedAt/stopReason/livenessState) and the run really stopped; the
second is clock arithmetic on our own stored deadline and says nothing about the
run. Both collapsed into `outcome: { status: "timeout" }`, the only signal
downstream, so the announce rendered "timed out", the result fell back to
"(no output)", and the stats line read the child's not-yet-flushed usage
counters as "tokens 0". agent-run-terminal-outcome.ts already separates these
("hard_timeout" vs wait-layer "timed_out"); the subagent projection discarded
the distinction.
Second, having published that, shouldPreservePublishedExplicitRunTimeout in
subagent-registry-lifecycle-completion.ts made it an immovable terminal winner.
The child's real completion 15 minutes later was dropped on the floor, which is
why no corrected event ever arrived.
Records the disposition as a fact at each producer that owns it, rather than
leaving parents to reconstruct liveness from journalctl provenance lines and a
worktree reflog. AgentRunDisposition ("exited" | "killed" | "still-running")
rides on the run outcome and on the completion event, written only where
something other than a plain terminal state was observed:
- the wait manager, when the stored deadline expired with no snapshot;
- applySubagentWaitOutcome, splitting hard_timeout (exited) from a bare wait
timeout (still-running) and cancellation (killed);
- the announce flow, when this process can still see the run executing;
- the kill path in completeSubagentRunAttempt.
A still-running event now says "still running; the wait for it expired, it did
not", carries a machine-readable `disposition:` line, reports "(no result yet;
child still running)" instead of "(no output)", labels its stats "waited 1h30m"
with "child tokens not yet reported" instead of a zeroed total, and instructs
the parent not to start a replacement or touch the state the child still owns.
The child's session is no longer deleted under it, and the publication is
treated as provisional: when the run's own terminal callback finally lands, the
delivery and cleanup bookkeeping is released so the parent hears the real
ending. A second expiry cannot re-announce, so it converges.
Production LOC +119. The growth is the recorded fact itself and its comments;
there is no way to express "the child is alive" through a shape whose only
liveness channel was a four-value status enum.
Two existing tests encoded the old behavior and were retargeted, not weakened:
"keeps published explicit timeout stable when late lifecycle timeout arrives"
now supplies a real terminal snapshot so it still guards duplicate-callback
idempotency, and a new sibling proves a wait-expiry publication yields to the
child's own ending.
Validation (topic worktree):
pnpm tsgo:core exit 0
pnpm tsgo:core:test exit 0
pnpm vitest run src/agents/subagents 40 files, 1110 passed
pnpm vitest run src/agents/internal-events.test.ts 3 passed
pnpm vitest run src/agents/tools/media-generate-background-shared.test.ts
27 passed
pnpm vitest run src/agents/command/attempt-execution.shared.test.ts
10 passed
pnpm plugin-sdk:surface:check exit 0
pnpm oxlint <touched files> exit 0
oxfmt --check <touched files> clean
git diff --check clean
Every new regression test was verified to fail on pre-fix code for the intended
reason (production files stashed): 3 wait-manager, 5 announce-event, 1
lifecycle-supersede, 1 event-rendering.
Empirical re-validation on a live gateway is deliberately not done here: this
wording is visible to every agent and the rollout is the operator's call.
Beads: openclaw-kkv1
Two import-block conflicts, both from main moving the subagent classifier into its own module (classifySubagentTerminalOutcome in subagents/subagent-terminal-outcome.ts, openclaw#125407) so the base classifier is no longer imported at these sites. Resolved by usage rather than by preference. For each file the conflict block was excised before counting, so the counts reflect real call sites and not the markers themselves: subagent-announce-output.ts base classifier called: no AgentRunDisposition: yes subagent-registry-run-wait.ts base classifier called: no AgentRunDisposition: yes So both files take main's narrowed import of buildAgentRunTerminalOutcomeFromWaitResult, drop classifyAgentRunTerminalOutcome as genuinely unused after main's refactor, and keep this branch's `AgentRunDisposition` type import, which has real usages and carries the branch's disposition tracking. Accepting main's refactor while preserving branch utility, per instruction. NOT YET VALIDATED: pnpm install still running in this worktree; no typecheck yet.
# Conflicts: # src/agents/subagents/announce/subagent-announce-output.ts
|
@clawsweeper re-review Please review the recreated draft at its current exact head. — written by Tank/Claude |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Codex review: needs real behavior proof before merge. What this changesThis PR distinguishes a subagent wait expiring from the child terminating and publishes provisional and terminal notifications separately. Example: A child with runTimeoutSeconds=5400 continues working after its parent's 90-minute wait expires.
Review scores
ProductKind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete Merge readiness⛔ Blocked before merge - 6 items remain Keep open: this PR contains meaningful lifecycle work absent from current main, and both previous findings are fixed; its changed deadline contract still needs an owner decision. Priority: P1 Decision needed
Before merge
FindingsNone. Tests
Agent review detailsHow this fits togetherThe subagent registry consumes Gateway wait results, lifecycle callbacks, and persisted session facts, then owns completion state, parent notifications, recovery, and resource cleanup. flowchart TD
A[Gateway wait result] --> C[Subagent registry]
B[Child lifecycle callback] --> C
C --> D[Registry worker and SQLite]
C --> E[Provisional parent notification]
C --> F[Terminal completion]
F --> G[Parent result and cleanup]
Technical reviewBest possible solution: Use the existing registry lifecycle owner to distinguish wait expiry from observed termination under an accepted deadline and durable-recovery contract. Do we have a high-confidence way to reproduce the issue? Current-main source shows a bare wait timeout at the stored deadline entering terminal completion without a child-stop snapshot; this read-only review ran no target code. Is this the best way to solve the issue? Separating producer-owned termination evidence from wait expiry addresses the reported confusion, but changing explicit deadlines and persisted recovery semantics requires an owner-approved contract. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 6cdd20ae2d0a. Merge-risk optionsMaintainer options:
Provenance checked
TestingProof path: unit tests only. SecurityNeeds attention: No concrete bypass was found, but deferred private delivery needs final-effect authority evidence. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +456, Tests +1428, Other -1. Total +1883 across 38 files. Added test files: 4. View PR surface stats
LabelsLabel changes: No label changes. Label justifications:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (30 earlier review cycles; latest 8 shown)
Reviewed October 13, 2026, 8:02 PM ET / October 14, 2026, 00:02 UTC (Revision 31). |
…t-disposition # Conflicts: # src/agents/subagents/registry/subagent-registry-run-wait.ts
|
@clawsweeper re-review The exact head is now The prior P1 is resolved at the lifecycle boundary: provisional expiry no longer invokes terminal completion or cleanup. A controlled production-registry E2E proves a live resource survives expiry and is cleaned exactly once only after authoritative lifecycle completion. Publication is now two-phase and retryable failures re-arm the wait; focused coverage passes 180/180, the real lifecycle proof passes 1/1, both relevant TypeScript gates pass, and the structured P0–P2 exact-diff review is clean. Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
…t-disposition # Conflicts: # src/agents/internal-events.ts # src/agents/subagents/announce/subagent-announce.ts
|
Exact-head follow-up is ready at signed The provisional wait-expiry wake now has a distinct The PR body now records the exact-head evidence and the one inherited dependency-tree typecheck limitation. Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
|
@clawsweeper re-review Please review exact head Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Round 16 — both remaining findings fixed, each measured against a reverted controlHead Both findings were real and both are now fixed with production changes. Each one has a negative control: I reverted only that finding's own source hunks, re-ran its guards, and recorded what the reviewed head actually published. Neither assertion is a tautology. [P2] Preserve cancellation disposition before deadline clamping —
|
|
🦞👀 Re-review progress:
|
|
Closing as superseded: current main's Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
|
Reopening: my earlier close was wrong. The wait-timeout deferral in Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
# Conflicts: # config/test-mock-exports-baseline.txt # packages/gateway-protocol/src/schema/agent.test.ts # src/agents/internal-events.test.ts # src/agents/subagents/announce/subagent-announce-completion-delivery.test.ts # src/agents/subagents/announce/subagent-announce-delivery.test-support.ts # src/agents/subagents/announce/subagent-announce-delivery.test.ts # src/agents/subagents/announce/subagent-announce-direct-delivery.ts # src/agents/subagents/announce/subagent-announce-direct-response.ts # src/agents/subagents/announce/subagent-announce-output.ts # src/agents/subagents/announce/subagent-announce.timeout.test.ts # src/agents/subagents/announce/subagent-announce.ts # src/agents/subagents/registry/subagent-registry-lifecycle-completion.ts # src/agents/subagents/registry/subagent-registry-lifecycle-controller.test-support.ts # src/agents/subagents/registry/subagent-registry-lifecycle.test.ts # src/agents/subagents/registry/subagent-registry-queued-recovery.test.ts # src/agents/subagents/registry/subagent-registry-queued-registration.test-support.ts # src/agents/subagents/registry/subagent-registry-run-wait.test.ts # src/agents/subagents/registry/subagent-registry-run-wait.ts # src/agents/subagents/registry/subagent-registry-worker.test.ts # src/agents/subagents/registry/subagent-registry.persistence.orphan.test-support.ts # src/agents/subagents/registry/subagent-registry.persistence.test.ts # src/agents/subagents/registry/subagent-registry.test.ts # src/agents/subagents/registry/subagent-session-reconciliation.ts # src/agents/subagents/subagent-run-outcome.types.ts
…ain (review feedback) The merge with main was resolved by reading code only, so the port carried four real defects plus two stale fixtures: - `subagent-announce.ts` took main's narrowed `auto-reply/tokens.js` import while keeping the branch's provisional instruction, so every prod/test type lane failed `TS2304: Cannot find name 'SILENT_REPLY_TOKEN'` and the still-running announce threw `ReferenceError` at runtime. - `packages/gateway-protocol/src/compiled/protocol.generated` was never regenerated after `disposition` joined the closed `AgentInternalEventSchema`, so the compiled validator rejected every subagent announce with `invalid agent params` and an empty error list. Regenerated with `pnpm gateway:validators:gen`. No pull-request CI lane runs `validators:check`, so nothing reported the drift. - the run-wait manager fixture was missing `getChildSessionCandidates` (TS2741). - `subagent-run-outcome.types.ts` was not oxfmt-formatted. Fixture corrections for behaviour main changed under the branch: - the provisional-expiry delivery cases now state the parent's silence as `meta.terminalReply` and expect `MISSING_REPLY_NOTICE_TEXT`: openclaw#170534 stopped inferring silence from a `NO_REPLY` payload and replaced the canned failed-child notice. - the registry wait-expiry cases that asserted the provisional notice on the first turn after the expiry now poll for it; publishing it crosses the grace timer, the observation commit and the announce call. Also adds the `config/test-lines-allocations` entry this change's test growth needs. Co-Authored-By: Claude <[email protected]>
…main's terminal one `keeps published timeout stable when pre-deadline success arrives late` kept main's mid-test assertion that a bare stored-deadline expiry terminalizes the run, while also carrying this PR's `["wait-expiry", undefined]` phase assertion for the same run. Those two cannot both hold: declining to terminalize a deadline expiry that carries no child-stop evidence is the change. Re-express the mid-test state as the provisional one (running, no `endedAt`, `waitExpiryObservedAt` recorded). The case still fails afterwards, on its post-lifecycle assertion: once the provisional wake returns the wait coroutine, nothing in this tree consumes the child's own terminal fact, so the run does not settle when its lifecycle owner reports the end. That is tracked as open work, not fixed here. Co-Authored-By: Claude <[email protected]>
|
CI repair pass on this branch's merge with Root causes found and fixed1. 2. The compiled gateway validators were never regenerated — every announce was rejected at the wire. 3. 4. 5. 6. Two fixtures asserted behaviour Local verificationRun in the branch worktree (
Still red, and honestly so
I also corrected one merge inconsistency inside the first of those: it kept Nothing in this round was inherited from Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
# Conflicts: # packages/gateway-protocol/src/compiled/protocol.generated/predicates.js
…t expiry A lifecycle end that reports a corrected startedAt was dropped as a stale attempt, so a run whose wait had expired provisionally never settled from its real outcome. Once a wait-expiry observation is recorded the end event is the settlement authority for that run. Co-Authored-By: Claude <[email protected]>
…d event After a wait expires the run stays live and settles only from its own lifecycle end. Drop the three cases that expected stopReason-driven killed reconciliation through the sweep, and restate the remaining wait-expiry cases against that contract: the sweep leaves a provisionally announced run alone, a restored wait resumes only for a live execution owner, and the child's real reply is read from its terminal announcement. Co-Authored-By: Claude <[email protected]>
|
Pushed Behaviour When a wait on a child expires with no terminal snapshot, the child is marked provisionally as still running and the parent is woken once. From then on the child's own lifecycle
Tests
Evidence (local)
Not run locally: the four Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude). |
Move disposition normalization into subagent-terminal-transition; keep current requester-consumption and delivery policy instead of resurrecting deleted response classifiers. Update stale source fixtures to current outcome values, preserve provisional/terminal delivery identity and cancellation liveness facts. LOCAL ONLY: protocol schema now includes disposition but main generated predicates retained unchanged. Required protocol generation is deferred by explicit user no-build/no-generation instruction; this commit is not ready for publication. openclaw-zhal code-only refresh: no tests, builds, lints, typechecks, installs, proofs, generators, or validation hooks run. Test allocation has not been remeasured.
Recreates #135491 after the repository author-PR ceiling was corrected and portfolio slots were deliberately reprioritized.
What Problem This Solves
A parent can receive
status: timed outwhen only its wait expired and the child is still running. In the incident behind this change, the child continued for another 15 minutes, committed, and pushed while the parent—reasonably believing it dead—started a replacement in the same worktree.Approach
The subagent outcome now carries an explicit disposition (
exited,killed, orstill-running) from the producer that owns the evidence, including across the Gateway protocol boundary. Clock-only wait expiry remains provisional: it preserves the child session and owned resources, publishes a bounded warning to the parent, and yields to the child's later authoritative terminal callback. Genuine hard timeouts and kills remain terminal.Publication is two-phase. An expiry is marked announced only after delivery settles; retryable publication failures re-arm the wait instead of losing the wake. Provisional and terminal announcements use distinct idempotency identities, so a successful wait-expiry notice cannot deduplicate the later authoritative result. The authoritative terminal snapshot also remains the disposition owner even if the process-active map lags during teardown. The normal sweeper remains the persisted-state backstop.
The same recorded fact also decides whether a provisional notification is owed a visible reply at all: a parent that follows the instruction and stays silent settles the notification instead of leaving it to be re-announced every few seconds while the child works. That holds on every delivery route — message-tool-only and automatic alike — through one shared predicate rather than a per-branch special case.
Because the disposition is the fact that distinguishes the two cases, every consumer that used to infer failure from
status !== "ok"now reads it. A single predicate,isFailedTerminalSubagentCompletion, owns that classification for the direct-delivery fallbacks, so a provisional expiry can no longer be rendered as a terminal failure notice. Symmetrically, the cancellation producer stampskilledon the outcome it builds, so the killed reason and the killed disposition can no longer disagree.Two deadline-shaped gaps in that symmetry are closed in the latest round. A cancellation observed past the stored run deadline is clamped back to the deadline, and the clamp rewrites the reason to
subagent-complete; because that reason is what the disposition normalization keys off, such a cancellation published no disposition at all and read back asexited. Both deadline owners — the completion owner and the wait manager — now carry the producer's cancellation fact across the clamp while keeping the clampedtimeoutstatus and deadline end. Separately, a private (parent-only) provisional notice now forwards the requester's recorded lifecycle revision alongside its session id, so direct delivery compares two recorded values instead of testing a populated revision againstundefinedand intentionally dropping a valid parent's wake.User Impact
Parents stop treating a patience deadline as child death, preventing duplicate agents from editing one worktree. A direct-message requester no longer receives "A delegated task failed before it could report a result. Please retry the task." for a child that is still working. A cancelled child is reported to its parent as killed rather than as having exited on its own — including when the cancellation lands after the run's deadline. A private parent still receives its provisional wake instead of having it silently settled. Live-child browser/MCP resources remain available until the execution owner reports actual termination, and the parent still receives the real final completion.
Evidence
Validated on exact head
a463b3e143e7520e767a36f218acd572199ce8ee.pnpm check:changedexits 0 across all 35 lanes, run withPATH=/home/linuxbrew/.linuxbrew/binso the three ratchet lanes execute instead of bailing under this host's git 2.34. That includestypecheck core,typecheck core tests,lint core changed files,lint scripts,dead export scan,runtime import cycles, and every ratchet (line-cap growth,max-lines suppression,assertion SAFETY,SQLite worker,test timeout race,first-party mock export). Knip's production, full-tree and script unused-export scans each report 0 entries. (Correction: an earlier revision of this section said "all 36 lanes"; the measured lane count in that same round's log was 35. The count, not the result, was wrong.)infra361,agents-support237), throughscripts/run-vitest.mjs— never barepnpm vitest.b07289b0b01ran 594 passed / 0 failed before any edit, so the delta is exactly the four cases this round adds. Each finding then got its own negative control, reverting only that finding's source hunks:{status: "timeout", startedAt: 2000, endedAt: 5000, elapsedMs: 3000}with no disposition, which reads back asexited.disposition: "exited"outright forrpc,abortedandsupersededcancellations landing past the deadline.completionRequesterLifecycleRevisionfield and nothing else.completeSubagentRunAttemptbuilds the result-capture preimage fromresolveTerminalRequest's outcome, andplanTerminalCompletionrejects any commit whose outcome differs from that preimage (Subagent completion requires fresh result capture). Normalizing the disposition later instead typechecks cleanly and then fails five existing cases at runtime; stamping it inside the clamp keeps plan and capture in agreement. This was found by running the gate, not by reading.git merge-tree --write-tree --name-only upstream/main HEADwas probed before and after this round and returns the same nine conflicted files both times. Nothing was merged, rebased, or force-pushed.pnpm tsgo:coreexited 2 at6093cde60e4with three errors insubagent-registry.ts:persistSubagentRunsOrThrow(×2, no definition or import anywhere in the tree) andgetGatewayContextResolver. Both gates now exit 0.ascast, so the store codec threwsubagent run is missing canonical nested stateon first write — and the wait manager swallows that into its recovery path, so the suite reported green while exercising nothing. It now builds throughcreateSubagentRunRecordand genuinely exercises the manager.mainexpectation.keeps published timeout stable when pre-deadline success arrives latepreviously asserted exactly one announcement. Instrumenting the run shows the actual sequence is["wait-expiry", undefined]— one provisional wake, then the terminal publication — which is this PR's intended behavior and was unreachable before, because the expiry callback threw before it could announce. The expectation now asserts that phase sequence rather than a count, so two terminal publications would still fail it.AgentInternalEvent.dispositionis covered by strict protocol tests that accept the three known values and reject unknown values.Stated limitations
These are gaps, not results, and are listed so they are not mistaken for proven claims.
scripts/proof-136554-timeout-notification-boundaries.tswas silently dropped by base merge007822d8693c, which left itsconfig/knip.config.tsregistration behind; no gate catches that direction, because the deadcode check passes--no-config-hints. The dangling registration was removed, so the tree is honest about what it carries. A previous round reported that the harness "needs a rewrite against the current module layout" because it imports a moved module; the sharper reason is that the seam it used is gone. It injected a scriptedagent.waitinto the registry throughsetSubagentRegistryDepsForTest, which returns no matches onorigin/main, onupstream/main, or on this branch — it was removed by refactor: remove subagent registry dependency overrides (refactor: remove subagent registry dependency overrides #155796). The registry now reaches the Gateway only throughcallSubagentRegistryGateway→bindGatewayLifecycleRequest(), so a plain process cannot script a child's wait at all. The production-side replacement iswithPluginRuntimeGatewayRequestScope({ context: { recoveryRuntime } }), through whichbindGatewayLifecycleRequestdispatchesagent.waittorecoveryRuntime.waitForAgent— a harness built on that would drive the production binding rather than a test override. That is a build rather than a port, and it has not been attempted; no harness result is claimed here.73d9ffdfc5bcbf20c5a54f441cf97cfb180807af, which predates the immutable worker-owner cutover (fix(agents): finished subagents fail to wake their parent when registry writes overlap #163195) this branch now follows. It is not evidence for the current publication path and is not claimed as such. A fork cannot stand up a current-composition Gateway, so redacted live logs showing provisional settlement, retained child resources, and later same-child completion remain outstanding and will stay outstanding from the author side.skippedis not green. The Apple lanes are gated on repository identity and reportskippedon any fork; draft-gated lanes defer. Treat those as unproven rather than passing. The check rollup on this PR currently contains no test jobs at all — it isauto-response,dispatch,label,resolve,review,backfill-pr-labels,reconcile-backlog, plusPR context and evidence— so a green rollup here must not be read as a test run.CONFLICTING. It is reported as-is; resolving it is a fork-sync decision that belongs to the repository owner, not to a review round.Worked on by
Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).