Skip to content

fix: deliver retained child results after Gateway restart - #198905

Merged
steipete merged 4 commits into
mainfrom
steipete/fix-yield-restart-completion-custody-2489
Nov 14, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/fix-yield-restart-completion-custody-2489

Conversation

@steipete

@steipete steipete commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes delegated child results being stranded after a Gateway restart while their requester is still present, including nested yielded sessions and results already captured before shutdown.

User Impact

Pending child results can reach the parked or resumed requester once across restart. Archived, reset, replaced, or unauthorized requester incarnations remain closed. No configuration or database schema changes are required.

Why This Change Was Made

Hydration correctly retires process-bound completion authority, but startup had no fresh admission path for the retained obligation. Restart preparation now validates the current requester principal and exact session incarnation before recovering the outstanding cohort. A paused child's admitted successor retains that current requester custody instead of splitting its parent's cohort across different execution authorities. Delivery resumes after startup has admitted or parked the requester; another restart drain keeps it parked.

Related: #198729, #198807. Gateway diagnostics landed separately in #198843.

Evidence

Two real Gateway restart regressions use publicly created sessions, retained owned children, and sessions_send so the durable rows match spawnMode: session, completionTarget: parent. Both fail on main 18892937f80232a5f7159092e264fb9e44ad6a10. They verify nested yielded work, a captured result pending after shutdown, exactly one internal input in the raw persisted requester transcript, a delivered receipt, and no duplicate delivery after another restart. Stale archived/replaced/reset requester snapshots fail closed through real admission owners.

All nine real restart/continuation cases pass in 164.91 s Vitest; the two new cases take 17.710 and 15.966 s. Six admission/stale-requester controls and 203 focused owner tests also pass. A deterministic external HTTP provider supplies model responses; Gateway processes, registry persistence and restart recovery are real. No live model-provider proof is claimed.

Production grows by 162 lines for the missing fresh-admission bridge using existing owners. No additional cache or persisted authority is introduced. The 470 net test lines include a 70-line proof-budget allocation for the multi-restart scenarios and stale requester controls.

SIGKILL failure qualification

Ordinary PR CI job 132505409303 failed the SIGKILL/incomplete-shutdown case in gateway-restart-resume.e2e.test.ts: principal admission reported SessionMutationFactsUnavailableError, and the unmarked requester never received RESUMED_10_idle. It tested merge commit 127998fd43203f7ad4eff9b944f0c0d87ae4bc41, whose exact main parent is 5ed2b57f17adc9f016d90a74f57fbee34e5edcf9. The same test passed in the separate pinned-head hosted job.

The maintainer requested a bounded 20-run comparison per revision. All 40 cases completed serially in alternating AB/BA order on the same Darwin arm64 machine, using pinned Bun 1.4.4-canary.1+191755ec1, identical test bytes and unchanged assertions/timeouts:

Revision Passed Failed Setup failures
Reviewed PR head d38f7e93d13b10f204f8d3b32e065d74f03e03cb 20 0 0
Exact CI main parent 5ed2b57f17adc9f016d90a74f57fbee34e5edcf9 16 4 0

Parent iterations 1, 5, 6 and 9 all reproduced the exact requester, principal-admission error and missing-result signature. No outcome was retried away or excluded. This establishes a pre-existing main defect, with fewer failures observed on this head; it does not prove this PR repairs the separate flake or removes the original Linux/Bun failure. The generic exception does not identify the invalidating publication, and a small safe owner fix has not been established. The maintainer authorized documenting a demonstrated pre-existing flake and landing. No retry, sleep, timeout extension, assertion weakening or authority bypass was added.

UI qualification and integration

The prior pinned-head hosted CI run 43614023102 passed all Node jobs and had four UI failures. Their independent evidence is:

Failure Qualification
Missing streamed assistant avatar Reproduced on exact main parent 89f744b1; passed immediately before db1708fc90887d0d2f4b899cc6ffa327d165d6dc (#198858), failed on that introducing commit. Fixed by merged #199015 / 976a4fb8784a326579108e03d0df4356dad501a3, now integrated. The exact failing avatar case passes locally after integration (15.50 s Vitest).
UI shard 1: 20-minute step timeout Scheduled-main job 132447703504, main 0640d3995c5c9a2b4d68d377c5a08532409b7a22, has the same outer timeout. That main job also contains a separate WebKit history assertion.
UI shard 5: 20-minute step timeout Scheduled-main job 132390019719, main adb8a2b71871cc987e74dcc0aea5a5b06e988683, has the same outer timeout while progressing through cases.
Rejected-key feedback: 2458 ms versus <2000 ms Scheduled-main job 132331197529, main 94cc426fb0b412746f83715b80093faaa5a0fd43, fails the identical test and line 155 assertion at 2145 ms.

The timeout and latency defects remain open. They are not passing checks, and no UI deadline or runner setting was changed. Earlier unused-export and benchmark type failures were repaired by integrated #198863 and #198912. An earlier Boat quota failure occurred before checkout; the documented hosted fallback used the existing workflow without runner or billing changes.

Integration base is 976a4fb8784a326579108e03d0df4356dad501a3. All nine owned base/result files are byte-identical to the previously reviewed patch. Fresh Codex autoreview of the integrated candidate is scoped-clean through P2. The integrated reviewed head is e1ad9bd40da93407a14a1c7e587108c2f81a8524 (tree 26dc44b7b423cb6ce49a62866ac1bd27eeb91729). pnpm check:changed --staged --base 976a4fb8784a326579108e03d0df4356dad501a3 completed with every check passing except the independently reproduced main dead-export regression below. Final-head ClawSweeper review revision 4 reports zero findings and zero open items on this exact head (review). Final-head CI run 43623731181 completed successfully: 52 jobs passed, 27 skipped, zero failed. All selected Node tests and UI end-to-end tests pass on this head; security checks pass. The bounded SIGKILL qualification and the separately reproduced local main dead-export regression remain recorded above/below; a green selected CI run does not repair those independent defects.

The integrated main revision also introduces an independent dead-export regression: all eight production unused-export findings (four in the full-tree scan) reproduce identically with this PR removed on exact main 976a4fb8784a326579108e03d0df4356dad501a3. All eight symbols were added by c9ee2646f8c6a8869a2a1ae7629e7615204cf9fc (#196550), and were absent in its immediate parent. The failed owner command is node --import tsx scripts/check-deadcode-exports.mts. The findings cover the new compaction source helpers and SessionCompactionSourcePlan; no file in this nine-file custody patch owns them. This is a newly observed main regression, not noise or a passing gate. Exact parent evidence is retained in 2489-avatar-main976-deadcode-red.log; candidate evidence is in 2489-avatar-integrated-check.log.

@clawsweeper

clawsweeper Bot commented Nov 14, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: L labels Nov 14, 2026
@steipete
steipete marked this pull request as ready for review November 14, 2026 14:19
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-14T17:59:22.617118Z e1ad9bd New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

Please review final head e14c948, focusing on fresh requester admission after restart, retained cohort custody during paused-child adoption, and exactly-once delivery receipts. The real restart regressions and stale requester controls pass locally; the PR body records the inherited main export failure.

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 14, 2026
@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR freshly admits retained child-result delivery after Gateway restart and preserves requester custody when paused children continue.

Example: A yielded requester has CAPTURED_CUSTODY_RESULT pending when the Gateway restarts.

  • Before: The saved result loses its process-bound delivery authority and can remain stranded.
  • After: Current requester admission permits delivery once, and the persisted receipt prevents repetition after another restart.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Strong shipped-entry-point recovery evidence and no actionable findings; broad validation of the exact integrated head remains in progress. Existing serialized session and subagent formats are unchanged, so no data migration is required.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Public terminal output exercises compiled Gateway subprocesses with a deterministic external HTTP provider, public session creation and delegation, real SQLite persistence, nested and captured completion recovery, delivered receipts, and no duplicate requester input after another restart; inspected images concern related UI work and do not supply this proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Delegated results retained across a Gateway restart can fail to reach their surviving requester.
Reason: The feature-history owner's direction is established, and the focused repair restores delivery without replaying old execution authority.

Merge readiness

✅ Ready for maintainer review

This PR addresses a remaining restart-delivery bug and has no actionable correctness or security findings; exact-head CI is still running.

Priority: P2
Reviewed head: e1ad9bd40da93407a14a1c7e587108c2f81a8524

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway startup reads retained session and subagent records, admits eligible requester custody through existing authority owners, and hands pending results to ordinary completion delivery.

flowchart TD
  A[Retained session and child records] --> B[Gateway restart recovery]
  B --> C[Current principal admission]
  C --> D[Exact session identity check]
  D --> E[Existing completion custody owner]
  E --> F[Requester delivery and durable receipt]
Loading

Technical review

Best possible solution:

Use the existing admission and completion owners to deliver retained results under current requester custody, preserving ordinary restart ordering and durable delivery receipts.

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

Current source retires hydrated completion authority without the fresh admission bridge; contributor-provided subprocess results demonstrate both regressions failing on the pre-fix revision and passing with this patch.

Is this the best way to solve the issue?

The patch repairs the missing admission handoff through existing owners, preserves valid cohort custody during adoption, and adds no parallel delivery mechanism or persisted authority.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 118eb292b6b2.

Provenance checked

  • Restart completion-authority retirement and yielded-parent recovery changes intended behavior with a stated reason (9344233: refactor: resume running sessions after graceful restarts #185730 deliberately replaced restart reconstruction with ordinary fresh inputs and retired old requester authority; fix(agents): resume yielded parents after restart retires completion #198640 subsequently treated retired completion authority as an unreachable wait.)
  • Paused-child completion-authority refresh changes intended behavior with a stated reason (9344233: Explicitly admitted follow-ups acquired fresh custody after predecessor authority retired; this PR explains why already-valid requester custody must instead remain shared across the outstanding cohort.)
  • Restart drain and workspace-admission custody keeps the original intent (ea3eb71: Restart markers remain owned until admission transfers custody, including workspace waits and another shutdown; the patch preserves that ordering and leaves recovered delivery parked while draining.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 9464adb adds src/gateway/session-restart-resume.ts:638 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 9464adbe6253; files: src/gateway/session-restart-resume.ts)
  • Josh Avant: Raw commit bc3092f adds src/agents/subagents/registry/subagent-registry-run-recovery.ts:201 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: bc3092fceb5d; files: src/agents/subagents/registry/subagent-registry-run-recovery.ts)

PR surface

Source +162, Tests +471, Docs +4, Other +2. Total +639 across 9 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 3 174 12 +162
Tests 4 481 10 +471
Docs 1 9 5 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 1 2 0 +2
Total 9 666 27 +639

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.

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +162 net lines; tests +470 net lines The production bridge reuses existing authority and custody owners; tests cover nested and captured results across process restarts, duplicate prevention, and stale requester rejection.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Retained delegated results can be stranded after restart, with a focused repair and concrete recovery evidence.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 (3 earlier review cycles)
  • reviewed 2026-11-14T14:28:28.935Z sha e14c948 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-14T15:43:16.122Z sha 6f2afe2 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-14T16:13:56.477Z sha d38f7e9 :: needs maintainer review before merge. :: none

Reviewed November 14, 2026, 1:02 PM ET / 18:02 UTC (Revision 4).

@steipete

Copy link
Copy Markdown
Contributor Author

The final-head review has no findings or open checklist items. For its execution-evidence note: these tests start the compiled Gateway in separate processes, create retained sessions through public RPCs, delegate through sessions_send, stop/restart the process, and inspect the real registry/agent databases. Only the external model responses are synthetic; this is not a mocked registry or an in-process restart simulation.

Existing local execution output on this patch:

$ OPENCLAW_E2E_USE_PREBUILT_DIST=1 pnpm exec node scripts/test-projects.mts test/gateway-subagent-completion-restart.e2e.test.ts
✓ recovers session completion custody through a real Gateway restart (nested) 18003ms
✓ recovers session completion custody through a real Gateway restart (captured) 17330ms
Test Files 1 passed (1)
Tests 2 passed (2)
Duration 43.28s
[test] passed 1 Vitest shard in 45.98s

$ OPENCLAW_E2E_USE_PREBUILT_DIST=1 pnpm exec node scripts/test-projects.mts test/gateway-yield-restart.e2e.test.ts
Test Files 1 passed (1)
Tests 7 passed (7)
Duration 114.18s
[test] passed 1 Vitest shard in 116.62s

The regression assertions at the reviewed head require the captured result to remain pending after shutdown, then require a delivered receipt and exactly one internal input in the raw persisted requester transcript. A second restart must preserve both the receipt and the one-input count. Both scenarios failed on exact parent 18892937f80232a5f7159092e264fb9e44ad6a10 before the production change. No live model-provider coverage is claimed.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The final head is 6f2afe225910cab39f1e293d6cb601e221ca735b. CI caught the existing admission consumer for a second restart during recovery: the post-admission callback threw after durable custody had already been preserved. The callback now retains abort rejection and leaves completion delivery parked while restart admission is draining.

The existing failing test was reproduced locally before the correction. Afterward, all six admission/stale-requester cases and all nine real Gateway restart cases pass (164.91 s Vitest). Fresh Codex review is clean through P2. pnpm check:changed again reports only the previously attributed main Knip export. The first CI attempt also hit provider sandbox-start quota exhaustion; the documented exact-head hosted fallback will supply the new head's CI evidence.

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 14, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Final head: d38f7e9. This integrates main to resolve the UI performance baseline mismatch; the nine-file recovery patch is unchanged. The latest review had zero open items. The exact integrated candidate has a fresh clean Codex review through P2 and passes the clean UI performance comparison. The relevant restart owners and dependency lockfile are unchanged by integration, so the nine real Gateway restart tests and six admission/stale requester controls remain applicable. Final-head CI is being qualified through the existing hosted fallback after the diagnosed Boat quota failure.

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 14, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Final integration head: e1ad9bd. The previous review had zero open findings. All nine owned files are byte-identical after integrating merged #199015; its previously failing avatar case now passes. Fresh Codex review is clean through P2.

The requested bounded SIGKILL comparison is complete on one machine and the same pinned Bun runtime: reviewed head d38f7e9 passed 20/20; exact CI main parent 5ed2b57 failed 4/20 and passed 16/20. All four failures match the original principal-admission SessionMutationFactsUnavailableError and missing RESUMED_10_idle. This establishes the failure as pre-existing, not repaired by a retry or weakened assertion. Full counts, method, original CI links and limitations are in the updated PR body.

The integrated changed checks pass except eight compaction unused exports, reproduced identically on exact main parent 976a4fb and introduced by c9ee264 (#196550). That newly observed main regression is explicitly recorded. CI run 43623731181 is in progress on this published head.

@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 14, 2026
@steipete
steipete merged commit ad6738d into main Nov 14, 2026
146 checks passed
@steipete
steipete deleted the steipete/fix-yield-restart-completion-custody-2489 branch November 14, 2026 18:16
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 15, 2026
…98905)

* fix: deliver retained child results after Gateway restart

* fix: park recovered completion delivery during restart draining
obviyus added a commit that referenced this pull request Nov 22, 2026
…tead of admin (#203466)

Related: #198905

## What Problem This Solves

When the Gateway restarts while a parent chat still owes a subagent result, restart recovery rebinds that result so the parent chat is woken to receive it. If the parent chat has no saved requester and no profile owner, recovery gave the woken settlement turn `operator.admin`. The normal System baseline is `operator.write`, so a child result from a non-admin requester could wake its parent with more authority than anyone had before the restart.

## User Impact

After a restart, a woken settlement turn for an unattributed parent chat runs with `operator.write`, never admin. The child result is still delivered.

Accepted edge case (no stored field, per the inherit-never-widen rule): a requester whose live custody had admin, for example a configured owner whose chat has no profile source, can get a narrower woken turn after a restart. If that turn needs admin, the refusal is visible in its transcript. Saving the requester source on the child run would close this gap, but that is a schema change and is not part of this PR.

## Why This Change Was Made

`recoverRequesterCompletionCustody` falls back to fixed scopes when `prepareSessionSystemTurnAuthority` finds no recorded or profile source. That fallback now uses the same System write baseline as other synthetic Gateway clients. Parent chats with a recorded or profile source are unchanged: they are still admitted as that person. The custody bind stays, so the child result is not lost.

## Evidence

- `src/gateway/session-restart-resume-custody.test.ts`, new case "delivers a restored interrupted child's owed notice after its unattributed requester settled". It drives restart store discovery and custody recovery (`prepareRestartStores` → `prepareRestartCompletionCustody`, the step `resumeRestartStore` runs), then settles the interrupted child through the real lifecycle controller.
  - Base `31c9a9a90f`: red, `expected [ 'operator.admin' ] to deeply equal [ 'operator.write' ]`.
  - Head: green. The woken turn has `operator.write`, and the result is delivered (`delivery.status === "delivered"`).
- Touched test and importer tests pass: `session-restart-resume-custody.test.ts` (11/11), `subagent-registry-sweeper-owed-batches.test.ts` (1/1).

<details><summary>One-admission E2E on head <code>f4d33ac9d4</code> (isolated Gateway, real model)</summary>

| Check | Result |
|---|---|
| R: revoke while a turn runs → the turn finishes | pass |
| S: Stop → the run is cancelled | pass |
| Q: revoke while input is queued → refused visibly | fail. This also fails on `main` and is owned by a separate fix (a queued `/followup` starts without admission). This PR does not touch that path. |

</details>

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 22, 2026
…ccess (#203479)

Related: #203466, #198905

## What Problem This Solves

When the Gateway restarts while a parent chat still owes a subagent result, restart recovery rebinds the result so that the parent chat is woken to receive it. Since #203466, a parent chat with no recorded owner wakes with the System write baseline, so an admin requester can lose admin after a restart. A parent chat whose owner profile has no current role-based grant (for example, someone who connected with a device token) fails recovery completely: the log shows "Session principal has no current run authority", and the child result is not delivered.

## User Impact

After a restart, the woken settlement turn has the access of the person who spawned the subagent, checked against current policy: an owner keeps admin, a writer gets write and never admin. The child result is delivered. Subagent runs started before this change keep the earlier behavior (the session owner's access, else the System write baseline, never admin).

## Why This Change Was Made

Subagent spawn now saves the requester's operator recovery source (`requesterOperatorSource`) on the subagent run. This is the same bounded codec and the same capture (`captureQueuedOperatorRecoverySource`) that queued inputs use. Unavailable sources are not stored. At restart, `recoverRequesterCompletionCustody` re-admits that source through `restoreGatewayQueuedOperatorRecovery`, the one admission that queued work also uses. The woken turn's own admission still checks session access when it starts. A refused source leaves the result unbound, as any failed recovery does.

Storage (schema change approved by Ayaan): one optional property inside the existing `subagent_runs.payload_json`. No table, column, index, schema version or backfill. Older builds ignore the property and use their own fallback (`docs/reference/database-schemas/storage-changes.md` has the entry).

## Evidence

- `session-restart-resume-custody.test.ts`, "wakes the parent with the saved owner/writer requester's scopes after a restart". These tests drive restart store discovery and custody recovery, then settle the interrupted child through the real lifecycle controller.
  - Base `e9f29990130b`: red. Recovery fails with "Session principal has no current run authority", and the result is not delivered.
  - Head: green. The owner wakes with `operator.admin`. The writer wakes with `operator.write` and without admin. The result is delivered (`delivery.status === "delivered"`).
- Older rows: "delivers a restored ... child's owed notice after its legacy profile/unattributed requester settled" (session owner, else `[operator.write]`).
- Spawn: `subagent-registry.requester-source.test.ts`. `registerSubagentRun` persists the requester's `gateway` source in the SQLite row.
- Touched and importer tests: 17 files, 226 tests pass.

Production code grows by about 25 lines: one capture at spawn and per-child re-admission at restart. This is the approved stored-source design. It removes the single session-principal admission that every restored child shared.

Each restored child re-admits its own saved requester. A refused source (for example, a revoked device) is logged and leaves only that child unbound. Its siblings are still recovered and resumed (test: "recovers a sibling child when another child's saved requester is refused"). Shutdown or a changed requester chat still stops recovery for every child.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…tead of admin (openclaw#203466)

Related: openclaw#198905

## What Problem This Solves

When the Gateway restarts while a parent chat still owes a subagent result, restart recovery rebinds that result so the parent chat is woken to receive it. If the parent chat has no saved requester and no profile owner, recovery gave the woken settlement turn `operator.admin`. The normal System baseline is `operator.write`, so a child result from a non-admin requester could wake its parent with more authority than anyone had before the restart.

## User Impact

After a restart, a woken settlement turn for an unattributed parent chat runs with `operator.write`, never admin. The child result is still delivered.

Accepted edge case (no stored field, per the inherit-never-widen rule): a requester whose live custody had admin, for example a configured owner whose chat has no profile source, can get a narrower woken turn after a restart. If that turn needs admin, the refusal is visible in its transcript. Saving the requester source on the child run would close this gap, but that is a schema change and is not part of this PR.

## Why This Change Was Made

`recoverRequesterCompletionCustody` falls back to fixed scopes when `prepareSessionSystemTurnAuthority` finds no recorded or profile source. That fallback now uses the same System write baseline as other synthetic Gateway clients. Parent chats with a recorded or profile source are unchanged: they are still admitted as that person. The custody bind stays, so the child result is not lost.

## Evidence

- `src/gateway/session-restart-resume-custody.test.ts`, new case "delivers a restored interrupted child's owed notice after its unattributed requester settled". It drives restart store discovery and custody recovery (`prepareRestartStores` → `prepareRestartCompletionCustody`, the step `resumeRestartStore` runs), then settles the interrupted child through the real lifecycle controller.
  - Base `c99d69c47b`: red, `expected [ 'operator.admin' ] to deeply equal [ 'operator.write' ]`.
  - Head: green. The woken turn has `operator.write`, and the result is delivered (`delivery.status === "delivered"`).
- Touched test and importer tests pass: `session-restart-resume-custody.test.ts` (11/11), `subagent-registry-sweeper-owed-batches.test.ts` (1/1).

<details><summary>One-admission E2E on head <code>f4d33ac9d4</code> (isolated Gateway, real model)</summary>

| Check | Result |
|---|---|
| R: revoke while a turn runs → the turn finishes | pass |
| S: Stop → the run is cancelled | pass |
| Q: revoke while input is queued → refused visibly | fail. This also fails on `main` and is owned by a separate fix (a queued `/followup` starts without admission). This PR does not touch that path. |

</details>

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…ccess (openclaw#203479)

Related: openclaw#203466, openclaw#198905

## What Problem This Solves

When the Gateway restarts while a parent chat still owes a subagent result, restart recovery rebinds the result so that the parent chat is woken to receive it. Since openclaw#203466, a parent chat with no recorded owner wakes with the System write baseline, so an admin requester can lose admin after a restart. A parent chat whose owner profile has no current role-based grant (for example, someone who connected with a device token) fails recovery completely: the log shows "Session principal has no current run authority", and the child result is not delivered.

## User Impact

After a restart, the woken settlement turn has the access of the person who spawned the subagent, checked against current policy: an owner keeps admin, a writer gets write and never admin. The child result is delivered. Subagent runs started before this change keep the earlier behavior (the session owner's access, else the System write baseline, never admin).

## Why This Change Was Made

Subagent spawn now saves the requester's operator recovery source (`requesterOperatorSource`) on the subagent run. This is the same bounded codec and the same capture (`captureQueuedOperatorRecoverySource`) that queued inputs use. Unavailable sources are not stored. At restart, `recoverRequesterCompletionCustody` re-admits that source through `restoreGatewayQueuedOperatorRecovery`, the one admission that queued work also uses. The woken turn's own admission still checks session access when it starts. A refused source leaves the result unbound, as any failed recovery does.

Storage (schema change approved by Ayaan): one optional property inside the existing `subagent_runs.payload_json`. No table, column, index, schema version or backfill. Older builds ignore the property and use their own fallback (`docs/reference/database-schemas/storage-changes.md` has the entry).

## Evidence

- `session-restart-resume-custody.test.ts`, "wakes the parent with the saved owner/writer requester's scopes after a restart". These tests drive restart store discovery and custody recovery, then settle the interrupted child through the real lifecycle controller.
  - Base `7a9ad62bfc9e`: red. Recovery fails with "Session principal has no current run authority", and the result is not delivered.
  - Head: green. The owner wakes with `operator.admin`. The writer wakes with `operator.write` and without admin. The result is delivered (`delivery.status === "delivered"`).
- Older rows: "delivers a restored ... child's owed notice after its legacy profile/unattributed requester settled" (session owner, else `[operator.write]`).
- Spawn: `subagent-registry.requester-source.test.ts`. `registerSubagentRun` persists the requester's `gateway` source in the SQLite row.
- Touched and importer tests: 17 files, 226 tests pass.

Production code grows by about 25 lines: one capture at spawn and per-child re-admission at restart. This is the approved stored-source design. It removes the single session-principal admission that every restored child shared.

Each restored child re-admits its own saved requester. A refused source (for example, a revoked device) is logged and leaves only that child unbound. Its siblings are still recovered and resumed (test: "recovers a sibling child when another child's saved requester is refused"). Shutdown or a changed requester chat still stops recovery for every child.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…ccess (#203479)

Related: #203466, #198905

When the Gateway restarts while a parent chat still owes a subagent result, restart recovery rebinds the result so that the parent chat is woken to receive it. Since #203466, a parent chat with no recorded owner wakes with the System write baseline, so an admin requester can lose admin after a restart. A parent chat whose owner profile has no current role-based grant (for example, someone who connected with a device token) fails recovery completely: the log shows "Session principal has no current run authority", and the child result is not delivered.

After a restart, the woken settlement turn has the access of the person who spawned the subagent, checked against current policy: an owner keeps admin, a writer gets write and never admin. The child result is delivered. Subagent runs started before this change keep the earlier behavior (the session owner's access, else the System write baseline, never admin).

Subagent spawn now saves the requester's operator recovery source (`requesterOperatorSource`) on the subagent run. This is the same bounded codec and the same capture (`captureQueuedOperatorRecoverySource`) that queued inputs use. Unavailable sources are not stored. At restart, `recoverRequesterCompletionCustody` re-admits that source through `restoreGatewayQueuedOperatorRecovery`, the one admission that queued work also uses. The woken turn's own admission still checks session access when it starts. A refused source leaves the result unbound, as any failed recovery does.

Storage (schema change approved by Ayaan): one optional property inside the existing `subagent_runs.payload_json`. No table, column, index, schema version or backfill. Older builds ignore the property and use their own fallback (`docs/reference/database-schemas/storage-changes.md` has the entry).

- `session-restart-resume-custody.test.ts`, "wakes the parent with the saved owner/writer requester's scopes after a restart". These tests drive restart store discovery and custody recovery, then settle the interrupted child through the real lifecycle controller.
  - Base `e9f29990130b`: red. Recovery fails with "Session principal has no current run authority", and the result is not delivered.
  - Head: green. The owner wakes with `operator.admin`. The writer wakes with `operator.write` and without admin. The result is delivered (`delivery.status === "delivered"`).
- Older rows: "delivers a restored ... child's owed notice after its legacy profile/unattributed requester settled" (session owner, else `[operator.write]`).
- Spawn: `subagent-registry.requester-source.test.ts`. `registerSubagentRun` persists the requester's `gateway` source in the SQLite row.
- Touched and importer tests: 17 files, 226 tests pass.

Production code grows by about 25 lines: one capture at spawn and per-child re-admission at restart. This is the approved stored-source design. It removes the single session-principal admission that every restored child shared.

Each restored child re-admits its own saved requester. A refused source (for example, a revoked device) is logged and leaves only that child unbound. Its siblings are still recovered and resumed (test: "recovers a sibling child when another child's saved requester is refused"). Shutdown or a changed requester chat still stops recovery for every child.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 450441b)

Release adaptation: restore through the stable queued-source API without the newer agentId parameter; keep stable restart-store discovery proof and omit main-only restart-scope cases because stable has no restart-scope classifier. Carry upstream least-privilege System write fallback. #203521 deliberately does not turn completion custody into a fresh chat grant check. #203222 settlement already staged; later parent-history redesign is not a prerequisite.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit b3231a69dd6ead5d34ee7cba31b58aaaea29308a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant