Skip to content

fix(subagents): distinguish child termination from wait expiry - #136554

Open
zeroaltitude wants to merge 45 commits into
openclaw:mainfrom
zeroaltitude:fix/subagent-timeout-disposition
Open

zeroaltitude wants to merge 45 commits into
openclaw:mainfrom
zeroaltitude:fix/subagent-timeout-disposition

Conversation

@zeroaltitude

@zeroaltitude zeroaltitude commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

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 out when 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, or still-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 stamps killed on 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 as exited. Both deadline owners — the completion owner and the wait manager — now carry the producer's cancellation fact across the clamp while keeping the clamped timeout status 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 against undefined and 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.

  • Full gate green. pnpm check:changed exits 0 across all 35 lanes, run with PATH=/home/linuxbrew/.linuxbrew/bin so the three ratchet lanes execute instead of bailing under this host's git 2.34. That includes typecheck 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.)
  • Focused suites: 598 passed / 0 failed, seven files across both Vitest shards (infra 361, agents-support 237), through scripts/run-vitest.mjs — never bare pnpm vitest.
  • Measured against the previously reviewed head, not asserted. The same seven suites at b07289b0b01 ran 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:
    • Cancellation disposition, completion owner — 2 failures. The published outcome at the reviewed head was {status: "timeout", startedAt: 2000, endedAt: 5000, elapsedMs: 3000} with no disposition, which reads back as exited.
    • Cancellation disposition, wait manager — 3 failures, publishing disposition: "exited" outright for rpc, aborted and superseded cancellations landing past the deadline.
    • Private requester incarnation — 1 failed / 115 passed, differing on exactly the one missing completionRequesterLifecycleRevision field and nothing else.
  • Where the cancellation stamp lives is load-bearing, not stylistic. completeSubagentRunAttempt builds the result-capture preimage from resolveTerminalRequest's outcome, and planTerminalCompletion rejects 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.
  • No new conflict surface. git merge-tree --write-tree --name-only upstream/main HEAD was probed before and after this round and returns the same nine conflicted files both times. Nothing was merged, rebased, or force-pushed.
  • The branch did not compile two rounds ago. pnpm tsgo:core exited 2 at 6093cde60e4 with three errors in subagent-registry.ts: persistSubagentRunsOrThrow (×2, no definition or import anywhere in the tree) and getGatewayContextResolver. Both gates now exit 0.
  • The wait suite was vacuous, not merely mis-signatured. Beyond the argument order an earlier review identified, the fixture hand-rolled its record behind an as cast, so the store codec threw subagent run is missing canonical nested state on first write — and the wait manager swallows that into its recovery path, so the suite reported green while exercising nothing. It now builds through createSubagentRunRecord and genuinely exercises the manager.
  • Announce-phase evidence for the one changed main expectation. keeps published timeout stable when pre-deadline success arrives late previously 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.
  • The Gateway wire contract for AgentInternalEvent.disposition is 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.

  • There is no real-behavior proof harness in this branch, and the earlier one cannot be restored. scripts/proof-136554-timeout-notification-boundaries.ts was silently dropped by base merge 007822d8693c, which left its config/knip.config.ts registration 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 scripted agent.wait into the registry through setSubagentRegistryDepsForTest, which returns no matches on origin/main, on upstream/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 through callSubagentRegistryGateway → bindGatewayLifecycleRequest(), so a plain process cannot script a child's wait at all. The production-side replacement is withPluginRuntimeGatewayRequestScope({ context: { recoveryRuntime } }), through which bindGatewayLifecycleRequest dispatches agent.wait to recoveryRuntime.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.
  • No live-Gateway capture on the current head. An earlier isolated-Gateway trace was recorded on 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.
  • Old-store upgrade, pending/settled reopen, and rollback evidence for the durable markers are still missing, along with the store owner's acceptance of the persistence and recovery semantics. That is the open maintainer decision recorded on this PR, and nothing here presumes an answer to it.
  • A fork head cannot run every lane, and skipped is not green. The Apple lanes are gated on repository identity and report skipped on 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 is auto-response, dispatch, label, resolve, review, backfill-pr-labels, reconcile-backlog, plus PR context and evidence — so a green rollup here must not be read as a test run.
  • The PR is 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

  • Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude)

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

…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
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Please review the recreated draft at its current exact head.

— written by Tank/Claude

@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This 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.

  • Before: The parent receives a terminal timeout and may start replacement work while the original child remains active.
  • After: The parent receives a still-running notification, retains the child's resources, and later receives its authoritative completion.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Both prior findings are repaired and no new concrete code defect was established, but current-behavior and durable-state compatibility evidence remain absent.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: A parent can believe its child has stopped and start duplicate work while the original child still owns its workspace and resources.
Reason: The distinction has clear value, but the patch changes an intentional terminal-deadline contract and adds durable notification semantics without recorded owner acceptance.

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
Reviewed head: a463b3e143e7520e767a36f218acd572199ce8ee
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should clock-only expiry of an explicit run deadline retain an unconfirmed child and persist provisional-notification markers until authoritative termination?
  • Recommendation: Accept provisional expiry with explicit recovery semantics: Approve the distinction while defining how retained children, notification settlement, restart recovery, and rollback should behave.
  • Why: This changes the deliberately implemented terminal-deadline contract and durable recovery interpretation, and no maintainer acceptance is recorded.

Before merge

  • Add real behavior proof - Authority-chain proof required: exercise the new registry expiry producer through current Gateway composition, showing delivery to the recorded private requester and rejection after requester replacement, child-owner replacement, or lifecycle retirement before agent dispatch and outbound I/O; also show provisional settlement, retained resources, later same-child completion, and overdue cancellation using redacted terminal output or logs, with IPs, keys, phone numbers, and non-public endpoints removed. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Resolve security review attention item - No concrete bypass was found, but deferred private delivery needs final-effect authority evidence.
  • Resolve merge risk - Demonstrate that a provisional private wake cannot reach a replacement requester, and that child-owner replacement or Gateway lifecycle retirement invalidates delayed or retried delivery before agent dispatch or outbound I/O.
  • Complete next step - Resolve the GitHub-confirmed conflict with main, preserving the provisional-expiry behavior and current registry ownership contracts.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Low-value test src/agents/subagents/registry/subagent-registry-lifecycle-disposition.test-support.ts: Consolidate the three killed-producer cases: they invoke the same completion boundary with the same reason and differ only in error text, without exercising those producers.
  • Missing end-to-end proof: Provide current-composition Gateway evidence for provisional settlement, retained child resources, later same-child completion, private-requester replacement, and overdue cancellation; the author reports negative controls, but this review did not execute them.
Agent review details

How this fits together

The 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]
Loading

Technical review

Best 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 options

Maintainer options:

  1. Pause landing until deferred-delivery authority is demonstrated (recommended)
    Keep the contribution open while obtaining production-path evidence that requester replacement and owner retirement prevent final effects.

Provenance checked

  • Explicit subagent run deadlines changes intended behavior with a stated reason (8a60f39: Enforce runTimeoutSeconds as terminal completion at the stored deadline, including restored and retried waits.)
  • Registry mutation and lifecycle ownership keeps the original intent (3f761a8: Preserve completion and requester wakes when registry writes overlap by publishing committed immutable rows through the worker owner.)
  • Announcement token usage keeps the original intent (4036ffe: Report unavailable usage as unknown instead of implying zero usage.)

Testing

Proof path: unit tests only.

Security

Needs attention: No concrete bypass was found, but deferred private delivery needs final-effect authority evidence.

Evidence

What I checked:

Likely related people:

  • Edward Abrams: Raw commit 4036ffe adds src/agents/subagents/announce/subagent-announce-output.ts:653 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4036ffee8dc0; files: src/agents/subagents/announce/subagent-announce-output.ts)

PR surface

Source +456, Tests +1428, Other -1. Total +1883 across 38 files. Added test files: 4.

View PR surface stats
Area Files Added Removed Net
Source 17 519 63 +456
Tests 20 1583 155 +1428
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 38 2102 219 +1883

Labels

Label changes:

No label changes.

Label justifications:

  • P1: False child-death notifications can cause overlapping agents to modify the same worktree and prematurely release resources.
  • merge-risk: 🚨 compatibility: Existing explicit deadlines change from terminal settlement to provisional retention, including persisted recovery behavior.
  • merge-risk: 🚨 security-boundary: The new deferred private-wake producer consumes requester incarnation and live run authority across awaited delivery; rejection before final effects needs evidence.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.
  • proof: telegram-e2e: This PR needs Telegram Test Server proof with the repository E2E skill. The patch changes user-visible completion fallback behavior, including suppressing false delegated-task failure notices while a child is still running; exercise that case on Telegram's Test Server.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Prove allowed private delivery and rejection after requester replacement or owner retirement before final effects.
  • Demonstrate latest-stable upgrade, pending and settled marker reopen, and supported rollback with settings and data intact.
  • Consolidate the redundant killed-producer completion tests.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (30 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-26T06:02:11.443Z sha ab98730 :: blocked before merge. :: [P2] Supply the required asynchronous persistence callback | [P2] Retry settlement persistence after a failed marker write
  • reviewed 2026-09-28T18:35:51.665Z sha b7168e8 :: blocked before merge. :: [P2] Supply the required asynchronous persistence callback | [P2] Retry settlement after a failed marker write | [P2] Persist expiry markers through the database worker
  • reviewed 2026-09-29T02:11:16.416Z sha 973254f :: blocked before merge. :: [P2] Supply the required asynchronous persistence callback | [P2] Retry settlement after a failed marker write | [P2] Persist expiry markers through the database worker
  • reviewed 2026-09-29T04:55:13.679Z sha 9143c14 :: blocked before merge. :: [P2] Retry the settlement marker after a failed write | [P2] Persist expiry markers through the database worker
  • reviewed 2026-10-01T20:53:03.549Z sha 1755ac9 :: blocked before merge. :: [P2] Retry the settlement marker after a failed write | [P2] Persist expiry markers through the database worker | [P2] Supply the required completion-lock callback in the wait fixture
  • reviewed 2026-10-02T04:38:36.609Z sha a88961f :: blocked before merge. :: [P2] Retry the settlement marker after a failed write | [P2] Persist expiry markers through the database worker
  • reviewed 2026-10-08T22:55:14.967Z sha 6093cde :: needs real behavior proof before merge. :: [P1] Commit expiry markers through the existing registry worker | [P2] Preserve the recorded observation identity when retrying | [P2] Adapt the new wait fixture to the current manager contract | [P2] Read committed rows in the new lifecycle regressions
  • reviewed 2026-10-12T20:49:21.878Z sha b07289b :: needs real behavior proof before merge. :: [P2] Preserve cancellation disposition before deadline clamping | [P2] Forward the requester lifecycle revision for private expiry notices

Reviewed October 13, 2026, 8:02 PM ET / October 14, 2026, 00:02 UTC (Revision 31).

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: L labels Sep 2, 2026
…t-disposition

# Conflicts:
#	src/agents/subagents/registry/subagent-registry-run-wait.ts
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The exact head is now 128a0b13bbb0c885e8a45363b233087c2693d748.

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).

@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Sep 2, 2026
…t-disposition

# Conflicts:
#	src/agents/internal-events.ts
#	src/agents/subagents/announce/subagent-announce.ts
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Exact-head follow-up is ready at signed 2d24eb92358d311c6c143f583ead3fb921858468.

The provisional wait-expiry wake now has a distinct :wait-expiry idempotency identity, so it cannot suppress the later authoritative terminal result. The branch is merged with current upstream, preserves upstream model-route notices alongside the explicit lifecycle disposition, and passes 475/475 focused assertions plus the real resource-lifecycle proof. Fresh exact-diff autoreview found no actionable P0–P2 defects.

The PR body now records the exact-head evidence and the one inherited dependency-tree typecheck limitation. @clawsweeper re-review

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

@zeroaltitude

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Please review exact head 2d24eb92358d311c6c143f583ead3fb921858468. It separates provisional and terminal idempotency identities, preserves the phase through retries, and includes focused direct-delivery coverage plus the production-registry lifecycle proof described in the updated PR body. The prior durable verdict predates this fix and still names head 128a0b13bbb.

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

@clawsweeper

clawsweeper Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Round 16 — both remaining findings fixed, each measured against a reverted control

Head a463b3e143e7520e767a36f218acd572199ce8ee. Reviewed head was b07289b0b0174b80f7811a8718ed426748aa4cb0 (Revision 30, 2026-10-12T20:49:21Z, findings=2).

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 — subagent-registry-lifecycle-completion.ts:577-579

The problem, restated. A cancellation whose observed end is past the stored run deadline gets clamped back to the deadline. The clamp rewrites completionReason from subagent-killed to subagent-complete, and that reason is exactly what the disposition normalization keys off — so the normalization never fires, the published outcome carries no disposition, and the total read of an absent disposition is exited. The parent is told a cancelled child exited on its own. The review also named a second owner: the waiter selects completeAsRunTimeout before reaching its killed branch.

What I measured at the reviewed head. Both paths, with the fix reverted:

Completion owner — normalizes an overdue abort without a kill tombstone (runTimeoutSeconds: 3, started 2,000 ms, abort at 6,000 ms, the review's exact scenario):

- "disposition": "killed",
  "elapsedMs": 3000, "endedAt": 5000, "startedAt": 2000, "status": "timeout",

Waiter — a cancellation snapshot landing past the deadline:

  "outcome": {
-   "disposition": "killed",
+   "disposition": "exited",
    "status": "timeout",
  },

disposition: "exited", in the published completion, for a child that was cancelled. 2 failures on the completion owner, 3 on the waiter, at the reviewed head's source.

The fix. Both deadline paths now carry the producer's cancellation fact, and both keep the clamped timeout status and the deadline as the reported end — only who stopped the run changes.

  • resolveTerminalRequest stamps the killed disposition inside the clamp, before it retires the reason. This placement is load-bearing rather than stylistic: completeSubagentRunAttempt builds the result-capture preimage from resolveTerminalRequest's outcome and planTerminalCompletion later rejects a commit whose outcome differs from it (Subagent completion requires fresh result capture). Normalizing later in planTerminalCompletion typechecks, passes review by eye, and then fails five existing cases at runtime because plan and capture disagree. I hit that, and it is why the normalization lives at the clamp.
  • completeWithDeadline in the waiter takes the cancellation fact explicitly and passes it to completeAsRunTimeout, whose disposition is now a parameter instead of a hardcoded "exited". Both of its cancellation-bearing call sites supply it: the reconciled session completion (completion.reason) and the observed terminal snapshot (observedCompletion.reason).

Regressions. Three new waiter cases (rpc / aborted / superseded past the deadline) assert the clamped end, the retained subagent-complete reason and disposition: "killed". For the completion owner I strengthened the existing normalizes an overdue abort without a kill tombstone rather than adding a near-duplicate: its outcome now includes disposition: "killed", and because that same object is asserted against the captureSubagentCompletionReply preimage, it also pins the plan/capture agreement described above. It fails on the reverted source (shown above), so it is a real control.

[P2] Forward the requester lifecycle revision for private expiry notices — subagent-registry-wait-expiry.ts:105-107

The problem, restated. A parent-only child records both the requester's session id and its lifecycle revision at spawn. The provisional-expiry call forwarded only the id. sendSubagentAnnounceDirectly compares both (requesterEntry?.lifecycleRevision !== params.completionRequesterLifecycleRevision), so a populated revision is tested against undefined, the comparison fails for a requester that is still the correct one, and delivery returns intentional_non_delivery. This reporter accepts that as settled and writes waitExpiryAnnouncedAt — the provisional wake is dropped permanently.

What I measured at the reviewed head. With the fix reverted, the new guard fails on exactly the missing field and nothing else (1 failed / 115 passed):

- "completionRequesterLifecycleRevision": "proof-requester-revision",
  "completionRequesterSessionId": "<redacted len=23>",
  "completionTarget": "parent",
  "deliveryPhase": "wait-expiry",

The fix. One forwarded field, completionRequesterLifecycleRevision: observedRun.completionRequesterLifecycleRevision, matching what subagent-registry-lifecycle-announce-cleanup.ts and subagent-requester-settle-identity.ts already pass on the terminal paths. The replacement guard is untouched: isCompletionDeliveryAllowed: ownsObservation still fences the publication on the observation this waiter owns.

Regression. A new case registers a completionTarget: "parent" run carrying both bindings, drives a real wait expiry through the registry, and asserts the announce flow receives both — plus that the forwarded revision is the one recorded on the run, not a value the test invented.


Validation

  • pnpm check:changed → exit[check:changed]=0, all 35 lanes, run with PATH=/home/linuxbrew/.linuxbrew/bin so line-cap growth ratchet, max-lines suppression ratchet and first-party mock export ratchet actually execute rather than bail under this host's git 2.34. Knip production / full-tree / script unused-export scans: 0 entries each.
  • Focused suites through scripts/run-vitest.mjs, both shards: 598 passed / 0 failed (infra 361, agents-support 237). The same seven files at the reviewed head were 594 / 0 before any edit, so the delta is exactly the four cases added here.
  • No proof-harness result is claimed — see below.

Nothing else in the tree changed. No upstream merge, no rebase, no force-push.

On the first before-merge item (real behavior proof) — a correction to what round 9 told you

Round 9 reported that scripts/proof-136554-timeout-notification-boundaries.ts was dropped by a base merge and "needs a rewrite against the current module layout," because restoring it died on src/tasks/detached-task-runtime.js. That understated it, and the sharper reason matters for what you should expect from an author-side proof here.

The harness drove the real registry by injecting a scripted agent.wait through setSubagentRegistryDepsForTest. That seam no longer exists — git grep setSubagentRegistryDepsForTest returns nothing on origin/main, nothing on upstream/main, and nothing on this branch; it was removed by refactor: remove subagent registry dependency overrides (#155796). The registry now reaches the Gateway only through callSubagentRegistryGateway → bindGatewayLifecycleRequest(). So a plain Node process can no longer script a child's wait into the registry at all; only vi.mock can, and a vitest run is not the evidence this item is asking for.

I am not claiming the item is unsatisfiable. The production-side replacement is withPluginRuntimeGatewayRequestScope({ context: { recoveryRuntime } }): bindGatewayLifecycleRequest dispatches agent.wait through recoveryRuntime.waitForAgent, so a harness that supplies a lifecycle owner would be driving the production binding rather than a test override — arguably better proof than the deleted seam gave. That is a build, not a port, and I did not attempt it in this round rather than attach a half-real harness to a PR whose proof confidence is already the thing under review. It is the concrete next step, with a named entry point.

What I still cannot do from here, stated plainly rather than papered over:

  • The real-Gateway capture. A fork cannot stand up a current-composition Gateway, so redacted live logs showing provisional settlement → retained child resources → later same-child completion are outstanding and will stay outstanding from my side.
  • The maintainer decision under Decision needed — whether clock-only expiry may retain unconfirmed children through durable notification markers — is yours. It changes a deliberately implemented deadline contract (fix(agents): enforce subagent run timeouts #87489) and a durable recovery contract, and nothing in this round presumes an answer.
  • Old-store upgrade / pending-settled reopen / rollback evidence for the two durable markers remains missing, and is gated on that same decision.
  • This PR is CONFLICTING. I probed git merge-tree --write-tree --name-only upstream/main HEAD before and after this round: the conflict set is 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.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.test.ts, src/agents/subagents/registry/subagent-registry-run-wait.test.ts, src/agents/subagents/registry/subagent-registry.persistence.test.ts (nine files), identical on both sides. This round added no conflict surface. Resolving the existing state is a fork-sync decision that belongs to the repository owner.
  • The check rollup on this PR contains no test jobs — it is auto-response, dispatch, label, resolve, review, backfill-pr-labels, reconcile-backlog plus PR context and evidence. A green rollup here is not a test run and should not be read as one.

@clawsweeper re-review

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Closing as superseded: current main's subagent-registry-run-wait.ts treats a wait timeout as provisional ("subagent wait timed out; deferring terminal state until session reconciliation") and carries explicit kill intent / kill reconciliation state, which covers the exited / killed / still-running distinction this PR introduced. Branch preserved as an archive tag on the fork.

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Reopening: my earlier close was wrong. The wait-timeout deferral in subagent-registry-run-wait.ts already existed at this PR's base, and current main still reports a plain status: "timeout" ("timed out") to the requester with no exited / killed / still-running disposition, so the gap this PR addresses is still open. The PR needs a substantial rebase against upstream's announce/registry rewrites; it is queued for that rather than retired. Apologies for the noise.

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

zeroaltitude and others added 3 commits November 10, 2026 23:33
# 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]>
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

CI repair pass on this branch's merge with main. The merge was resolved by reading code only, so the port carried real defects rather than noise. Head is now f3334347e0d.

Root causes found and fixed

1. TS2304: Cannot find name 'SILENT_REPLY_TOKEN' — one dropped import, five red lanes.
The merge took main's narrowed auto-reply/tokens.js import (isSilentReplyText only, since #170534 made silence an exact-text fact) while keeping this branch's provisional reply instruction, which interpolates the token. That single missing specifier is the whole of check-prod-types, check-test-types, check-test-types-core-1..5 and check-additional-extension-package-boundary (the boundary job died in plugin-sdk boundary dts on the same error, which is why check-lint-core-2/3 then failed to download sdk-declarations-…). It also threw ReferenceError: SILENT_REPLY_TOKEN is not defined at runtime on every still-running announce — the four subagent-announce.timeout.test.ts failures.

2. The compiled gateway validators were never regenerated — every announce was rejected at the wire.
This branch adds disposition to the closed AgentInternalEventSchema, but packages/gateway-protocol/src/compiled/protocol.generated is a checked-in generated artifact and still carried the old closed-property set, so validateAgentParams refused every subagent announce with invalid agent params and an empty error list. Regenerated with pnpm gateway:validators:gen; pnpm gateway:validators:check is clean. Worth noting for the schema-change checklist: no pull-request CI lane runs validators:check (it is gated behind the release-candidate path in ci.yml), so nothing reports this drift — the only symptom is a runtime rejection. This one defect accounted for 8 failures in subagent-announcement-delivery.worker.test.ts, 5 in server.sessions-send-owner-continuation.test.ts, 2 in server.subagent-stop-followup.product.test.ts, 2 in server.native-completion-authority.test.ts and 4 in subagent-spawn.production-boundary.test.ts.

3. TS2741 — the run-wait manager fixture was missing getChildSessionCandidates, which main added to SubagentManagerOptions (check-test-types-core-4).

4. check-lint failed only on formatting: subagent-run-outcome.types.ts was not oxfmt-formatted.

5. checks-fast-baseline-ratchets failed its test-lines lane (over by 1336). Added config/test-lines-allocations/136554-subagent-wait-expiry-disposition.txt with the exact measured overage and no spare credit.

6. Two fixtures asserted behaviour main changed under this branch, both in the provisional-expiry delivery cases: silence is now published as meta.terminalReply rather than inferred from a NO_REPLY payload, and the canned "A delegated task failed…" notice was replaced by MISSING_REPLY_NOTICE_TEXT (#170534). Three registry wait-expiry cases also asserted the provisional notice on the first turn after the expiry; publishing it crosses the grace timer, the observation commit and the announce call, so they now poll for it.

Local verification

Run in the branch worktree (pnpm install --frozen-lockfile, node scripts/run-vitest.mjs, brew git for the ratchet lanes):

Gate Result
pnpm tsgo:core / tsgo:ui / tsgo:extensions / tsgo:scripts pass
pnpm tsgo:core:test / tsgo:extensions:test / tsgo:test:root pass
subagent-announce-delivery.test.ts 117/117
subagent-announce.timeout.test.ts 15/15
subagent-announcement-delivery.worker.test.ts 9/9 (was 8 failed)
server.sessions-send-owner-continuation.test.ts 5/5 (was 5 failed)
server.subagent-stop-followup.product.test.ts 11/11 (was 2 failed)
server.native-completion-authority.test.ts 7/7 (was 2 failed)
subagent-spawn.production-boundary.test.ts the 4 CI failures pass (2 unrelated managed worktrees cases fail only locally: this host's system git 2.34 rejects the worktree list invocation; both are green in CI)
packages/gateway-protocol/src/schema/agent.test.ts, internal-events.test.ts, subagent-registry-run-wait.test.ts, subagent-registry-lifecycle.test.ts pass (14 / 8 / 14 / 220)
check:max-lines-ratchet, check:assertion-safety-ratchet, check:test-mock-exports, check:test-lines-ratchet, format on all changed files pass

Still red, and honestly so

src/agents/subagents/registry/subagent-registry.test.ts still fails 9 of 92 (CI had 15; the validator regeneration and the polling fixes cleared 6). All nine are this branch's own wait-expiry suite meeting main's restructured registry, and they are not fixture noise — they point at one unresolved question:

  • keeps published timeout stable when pre-deadline success arrives late and keeps boundary wait expiry provisional until the lifecycle owner reports child end: after the provisional wake, the wait coroutine returns by design ("do not keep a second long-poll alive"), and then nothing in this tree consumes the child's own terminal fact — the lifecycle phase: end event does not settle the run. The branch's comment names the periodic sweeper as the backstop, but nothing schedules it on this path. A wait expiry that no longer publishes a false death must still settle when the child really ends; that path is currently unproven. I did not ship a speculative fix for it (the one I tried is unobservable in this harness, where scheduleSweep is a mock).
  • publishes {rpc,aborted,superseded} agent.wait snapshots only after killed reconciliation expect a wait snapshot's stopReason to drive killed reconciliation; no code in either main or this branch reads a wait stopReason that way, so these three need their premise restated against the current cancellation seam.
  • caps restored waits to the remaining explicit run timeout and reconciles a provisionally announced run from persisted terminal state during sweep never reach agent.wait for a restored run under main's activation model.
  • keeps published explicit timeout stable when late lifecycle timeout arrives dies in the fixture, not the product: main compacts a finished row and evicts its payload, so the late event's mutation re-reads the payload from a store the registry fixture never wrote (Retained subagent payload is unavailable).
  • settles a provisional notification with delivered without settling its child loses the child's later real resultText only in the delivered variant.

I also corrected one merge inconsistency inside the first of those: it kept main's assertion that a bare stored-deadline expiry terminalizes the run and this PR's ["wait-expiry", undefined] phase assertion for the same run. Those cannot both hold — declining to terminalize that expiry is the change — so the mid-test state is now stated as the provisional one. The case still fails at the post-lifecycle assertion described above, which is the real open item.

Nothing in this round was inherited from main. Every failing lane traced to this branch's merge or to its own tests; there is no "red on main" item to leave.

Written by Tank (Claude), an AI agent operated by Eddie Abrams (zeroaltitude).

zeroaltitude and others added 3 commits November 11, 2026 15:23
# 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]>
@zeroaltitude

Copy link
Copy Markdown
Contributor Author

Pushed 5ee8a13a855 and 234e27e62e8 (head 234e27e62e8), which settle how a run finishes after its wait expires.

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 end event is the only thing that settles the run: real status, real end timestamp, real reply.

  • The lifecycle listener used to drop an end event whose startedAt differed from the stored one, treating it as a stale attempt. After a recorded wait expiry that left the run unsettled for good. Such an event is now accepted once an expiry observation exists (subagent-registry-listener.ts).
  • An end reported past an explicit run deadline is still clamped to that deadline as a timeout. That is the existing deadline rule applied to the real event, not a timeout invented by the waiter.
  • The sweep does not terminalize a provisionally announced run, even when the session row already looks finished. A comment in subagent-registry-run-wait.ts that described the sweeper as a settlement backstop was wrong against current main and is corrected.

Tests

  • Removed the three publishes $stopReason agent.wait snapshots only after killed reconciliation cases. They expected a staged killed reconciliation through the sweep, which no longer exists. Killed disposition from rpc/aborted/superseded snapshots stays covered in subagent-registry-run-wait.test.ts, and the aborted wait/end announce path in subagent-registry.test.ts.
  • Updated the remaining wait-expiry cases to the contract above, including a new assertion that a sweep leaves a provisionally announced run alone and the later end event settles it as ok with its real timestamps.
  • Test-lines allocation lowered from 1335 to 1294 to match the smaller suite.

Evidence (local)

Check Result
node scripts/run-vitest.mjs run src/agents/subagents/registry/subagent-registry.test.ts 89 passed (was 9 failed on 1f70e56191d in CI)
registry + announce test files, e2e excluded (83 files) 1303 passed
Mutation: listener change reverted 2 tests fail (settles from the child's real end after a provisional wait expiry, leaves a provisionally announced run for its lifecycle owner during sweep); restored afterwards
pnpm tsgo:core, test graphs core-test-agents-sessions and core-test-agents-other pass
oxfmt --check, oxlint on touched files clean
check-test-lines-ratchet.mts --base 8a2ef63f9ee --no-merge-base OK, slack 0

Not run locally: the four *.e2e.test.ts files under src/agents/subagents, because the dist build they need does not fit this host's memory limit.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant