Skip to content

refactor(subagents): retire finished child rows by one rule instead of two handed-off flags - #205482

Merged
vincentkoc merged 4 commits into
mainfrom
refactor/subagent-retirement-rule
Nov 26, 2026
Merged

vincentkoc merged 4 commits into
mainfrom
refactor/subagent-retirement-rule

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

When a sub-agent finishes, its result must reach the agent that started it exactly once, or that agent must see why it did not. That holds across restarts too. The registry tracks this with two outboxes on one row: completion delivery and the requesterSettleWake.

Cleanup's "retire this row later" intent was kept in two places that handed off to each other: requesterSettleWake.retireAfterSettle and the row's retireAfterRequesterTurn. The wake handed off to the row when it completed while the requester turn was still open, and the row handed back to the wake when the requester yielded. A missed handoff in either direction drops the intent or leaves a row behind. Separately, five call sites repeated their own mix of the three delivery-suppression facts.

This is the most-fixed area of the registry: 403 of 788 commits in the last six months were fixes, and most of them were about delivery, wake or restart. Each fix added a guard or a handoff and rarely removed one.

User Impact

There is no intended visible change for completed runs. One behavior changes: cleanup's retire intent is no longer lost when the wake goes away without completing. Before, the intent rode on the wake, so any path that cleared the wake directly dropped it, and the row stayed until the retention sweep. Those paths are a yield-paused child's wake clearing, a pause notice consumed without a cohort, a yielded batch whose final was already delivered, and restart custody retiring the obligation. Now the row keeps the intent and retires at its next settle check, which is what cleanup asked for. A regression test covers the yield-paused case.

Why This Change Was Made

  • One retirement fact plus one rule. retireAfterSettle now lives only on the row, and isSubagentRetirementSettled checks it in one place: the row is marked, no settle wake remains, and no open requester turn awaits its result. Wake completion and requester yield both call that rule. Both handoffs are deleted, along with the branch in transitionRequesterSettleWakeState that preserved the flag and the RequesterSettleWakeBatchState = Omit<…> alias that hid it from batch transitions.
  • Named suppression rules. subagent-delivery-state owns isSubagentDeliveryClosed (an accepted closure, which a kill rollback cannot undo) and isSubagentDeliveryWithheld (closed, or a pending kill asked to withhold delivery). Five sites that matched those definitions exactly now call them. Three other sites have their own definition of "still owed", for example the batch-level rule in requester-cron-authority. Changing them would change behavior, so they are left as they are. suppressAnnounceReason stays because it records a reason other code reads, not a suppression flag.
  • Legacy rows. normalizeSubagentRunState, which already normalized the old row flag on load, now also folds requesterSettleWake.retireAfterSettle and retireAfterRequesterTurn from rows written by released builds into the new fact. This needs no Doctor migration. Remove the fold once no supported build can write those shapes.

Size against the merge base: production code +84 −73 across 13 files (tests +75 −32 across 9 files). The change adds one rule and two predicates, and removes two flags, both handoffs and one type alias. The point is fewer places that decide retirement, not fewer lines. The larger follow-up merges the settle wake into the delivery obligation, which removes the second outbox and its separate retry policy. It is left out of this PR so this cutover stays reviewable.

Open overlap: the stale draft #140956 builds on the old two-flag shape and will conflict. #199455 sets requesterSettleWake.retireAfterSettle in one test line and needs a one-line rebase change.

Evidence

  • New tests in subagent-delivery-state.test.ts:
    • legacy rows fold from both old locations
    • an open requester turn keeps the retire intent
    • a yield-paused child keeps its intent until its next settle
  • Updated the existing lifecycle, requester-yield, terminal-effects, wake-receipt, wake-settlement and completion-admission tests to the single fact.
  • Local gates on 4ecd1640b0525 (the proof test was added in 68f5284694cca) (base 0b99555d5f7dd):
    • tsgo:core and tsgo:test:src clean
    • oxfmt --check clean
    • oxlint clean on the changed files
  • src/agents/subagents suite: 2,245 passed, 1 skipped and 1 failed, across 174 files. The failure is in subagent-spawn.production-boundary.test.ts. It does not depend on this change:
    • With main's versions of the 22 changed files, the subset collector child|preserves routed native Stop authority fails 3 of 3 runs. Every run fails refuses to continue a timed-out collector child, and 2 of 3 also fail preserves routed native Stop authority … (consumed-session).
    • The branch shows the same two tests failing.
    • The failing test passes alone and within its own group.
    • Instrumenting completeRequesterSettleWakeState during the failing run showed no row carrying the retire fact and no retirement. The new rule never fires there.
  • Local autoreview (helper source-sha256:aed5c70d…, Codex default engine), branch mode 0b99555d5f7dd..4ecd1640b0525 at P0–P2, with lifecycle-wake, lifecycle-completion, requester-wake-mutation, announce-cleanup and restart-custody as source context: scoped-clean, no findings, confidence 0.88. ClawSweeper local was unavailable, so one hosted review is still to request when this is ready.
  • Upgrade from the current stable, v2026.11.10, which writes both old shapes: subagent-registry.store.sqlite.test.ts "upgrades v2026.11.10 retire intent from either location to the row fact".
    • It writes rows in the released payload shape into a real SQLite state database. One row has requesterSettleWake.retireAfterSettle, the other retireAfterRequesterTurn with an open requester turn.
    • It reopens the database and loads through the production reader and codec, then checks that both rows carry retireAfterSettle, the old fields are gone, and the pending delivery payloads are unchanged.
    • It saves and reopens again, and checks that the stored JSON is in the canonical shape.
    • It fails on base 0b99555d5f7dd (expected undefined to be true) and passes on 68f5284694cca. The whole file passes 16 of 16, and tsgo:test:src, oxfmt and oxlint are clean.
  • Not exercised: a live Gateway process restarting over a v2026.11.10 state directory. The store test covers the same reader and codec that Gateway startup uses, but not the startup itself.
  • CI on a35809cb93393 failed only src/gateway/chat-goal-created-authority.e2e.test.ts, which also failed on main. It was repaired in test(gateway): expect a revoked person's Goal retry to be hidden as not found #205698. 932fc2a6fd330 merges that main (no conflicts). On the merged head: tsgo:core and tsgo:test:src are clean, and the requester-cron-authority, registry-queries, delivery-state and SQLite store tests pass (73/73).
  • a35809cb93393 adds the // SAFETY: note that the assertion-safety ratchet requires on the legacy-fold cast.

@vincentkoc vincentkoc self-assigned this Nov 25, 2026
@clawsweeper

clawsweeper Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Nov 25, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Nov 25, 2026
@clawsweeper

clawsweeper Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR replaces two deferred-retirement flags with one registry-row fact and centralizes shared delivery-suppression predicates.

Example: A yield-paused child named run-1 has pending retirement intent when its settle wake clears.

  • Before: Clearing the wake loses its retirement flag, leaving the row until retention cleanup.
  • After: The row retains the intent and can retire after its remaining requester obligations settle.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation is focused and source review found no definite defect, but required runtime and persisted-state upgrade proof is missing.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Refactor · Worth it: Yes · Fix scope: Complete
User problem: Cleanup can forget that a finished child row should retire when its settle wake clears without completing.
Reason: The maintainer-authored direction removes competing retirement facts without introducing a new subsystem, public API, or configuration option.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this maintainer-authored draft open: it makes a coherent retirement-state cutover that current main does not provide, and source review found no definite introduced bug.

Reviewed head: 4ecd1640b0525c1bd49a3163f680af1354507723

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

  • Missing end-to-end proof: Provide redacted Gateway terminal output or logs showing the paused-child retirement path and an upgrade from v2026.11.10 with both legacy flag shapes, preserved pending results and settings, exactly-once requester delivery, and a base-failing/head-passing regression; redact IPs, keys, phone numbers, and non-public endpoints.
Agent review details

How this fits together

The subagent registry persists child execution and delivery obligations; cleanup, requester-turn settlement, and restart recovery consume those records to deliver results and retire finished rows.

flowchart TD
  A[Child execution] --> B[Cleanup bookkeeping]
  B --> C[SQLite registry row]
  C --> D[Requester settle wake]
  C --> E[Requester turn settlement]
  D --> F[Shared retirement rule]
  E --> F
  F --> G[Retain or retire row]
Loading

Technical review

Best possible solution:

Keep retirement intent on the existing registry row, preserve the current settlement owners, and qualify the cutover through Gateway recovery and released-state upgrade proof.

Do we have a high-confidence way to reproduce the issue?

Current-main completeRequesterSettleWakeState clears a yield-paused child's wake without transferring its retirement flag; this establishes the lost-intent path in source, but no shipped-entry-point reproduction was supplied or run.

Is this the best way to solve the issue?

The row-level fact removes the lossy handoffs using the existing normalization, transaction, and settlement owners; the extracted suppression predicates preserve the callers' existing conditions.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 3ce6c6c7cb12.

Provenance checked

  • Deferred child-row retirement keeps the original intent (fix(agents): wake top-level requester when its last parallel child settles #99396: Keep delete-mode child results available until their durable requester-settle obligation resolves.)
  • Requester-turn retirement handoff keeps the original intent (bf2da1c: Retain completion-producing child rows through requester-turn settlement so yielding parents resume without duplicate future-child wakes.)
  • Worker-owned wake completion and reconciliation keeps the original intent (10e951e: Move settlement writes off the Gateway thread while preserving committed work through acknowledgement and publication failures.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

PR surface

Source +11, Tests +43. Total +54 across 22 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 13 84 73 +11
Tests 9 75 32 +43
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 22 159 105 +54

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • merge-risk: 🚨 session-state: The change relocates persisted retirement intent and changes when child registry rows are deleted after wake clearing; green static checks cannot establish restart compatibility.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.

Rank-up moves

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

  • Supply the Gateway recovery and released-state upgrade evidence identified in the proof assessment.

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.

Reviewed November 25, 2026, 1:06 PM ET / 18:06 UTC.

@vincentkoc
vincentkoc marked this pull request as ready for review November 26, 2026 00:56
@github-actions

github-actions Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 932fc2a6fd330ac3c1386a09ccc2c805e6ea898c
  • Maintainer: @vincentkoc
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/subagents/requester-cron-authority.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@vincentkoc
vincentkoc enabled auto-merge (squash) November 26, 2026 01:17
…irement-rule

* origin/main: (172 commits)
  test(gateway): expect a revoked person's Goal retry to be hidden as not found (#205698)
  fix: keep browser disabled when only hardening relay authentication (#203137)
  fix: recover Linux stream automations after command-anchor crashes (#203149)
  fix(whatsapp): identify voice-note captions as text in delivery receipts (#205381)
  fix(test): unblock restart-auth plugin and worker publication qualification (#205679)
  chore(ui): refresh control ui locales (#205691)
  fix: reduce memory during SQLite usage refresh (#201064)
  fix(plugins): readmit native captures with a dangling host link
  chore(i18n): refresh native locales (#205680)
  fix(update): hash SQLite lock bytes as zeros so Windows exclusion cannot fail verification (#205668)
  fix(skill-workshop): skip the skill diet for skills with Markdown outside support directories (#204881)
  fix(plugins): clarify dated SDK migration notices (#200932)
  fix: keep the resident launcher when reinstalling Gateway (#205655)
  fix: show the whole reply when you reopen a TUI session (#200455)
  test(ui): wait for restored speech player authorization (#199502)
  feat: let agents post approved GitHub comments (#204301)
  fix(agents): honor imageMaxDimensionPx at the provider and CLI image handoffs (#205663)
  chore(ui): refresh control ui locales (#205664)
  fix(google): preserve playback when Google Live splits audio into parts (#205364)
  fix: show named characters in exported session messages (#205362)
  ...
@vincentkoc
vincentkoc merged commit 0fa3412 into main Nov 26, 2026
131 checks passed
@vincentkoc
vincentkoc deleted the refactor/subagent-retirement-rule branch November 26, 2026 02:58
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 26, 2026
…f two handed-off flags (openclaw#205482)

* refactor(subagents): one retirement fact and named delivery-suppression rules

* test(subagents): prove v2026.11.10 retire intent upgrades through the sqlite store
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash auto-merge.

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

Labels

agents Agent runtime and tooling impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. security-sensitive-changed size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant