Skip to content

fix: preserve restarted child results and gateway test ownership - #203839

Merged
vincentkoc merged 18 commits into
mainfrom
fix/ci-windows-owner-20261123
Nov 23, 2026
Merged

vincentkoc merged 18 commits into
mainfrom
fix/ci-windows-owner-20261123

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

What Problem This Solves

Restarting the Gateway while a child result is being prepared can send that internal result through human-chat recovery and rebuild different input under its original idempotency key. The result can be cancelled or conflict with its accepted receipt.

Gateway test fixtures also duplicated Windows process ownership and contained outdated lifecycle assumptions, creating failed cleanup and misleading CI failures.

User Impact

Child completion recovery keeps its original input and current owner across a restart. Human queued messages retain their existing principal, device and scope checks.

The raw-payload field already shipped for private completions now also retains public attempts, with an explicit non-private marker. Upgrades preserve old private semantics. Older binaries do not understand that marker: downgrading with outstanding public completion attempts is not covered by this change.

Why This Change Was Made

  • The freshly recovered, exact completion cohort owns its queued input; human replay neither dispatches nor cancels it. Unmatched, refused, browser-bound and explicitly ended inputs retain their existing handling.
  • The completion owner retains pre-hook raw bytes for every attempt. Recovery reuses them only for the same run identity; a new retry still builds a fresh prompt. Strict full-message idempotency and authority checks remain.
  • All platforms use the canonical Gateway process owner, preserving the absolute startup deadline and first cancellation error. Failed cleanup retains ownership.
  • Lifecycle fixtures now follow the existing hook budget, Telegram replay, model admission, direct-chat restart, Gateway acquisition, retention maintenance, role enforcement and ready-child partition contracts.

Production +63 lines adds the missing completion ownership and raw-input preservation. Shared test infrastructure -104; tests +353; retired mock baseline -3; total +309. The duplicate Windows stopper and obsolete implementation-specific test are removed. No SQLite schema version or table changes. The two unmarked/stale-requester fixtures use the existing preparation hold to preserve the intended unconsumed result before marker edits; zero-input, pending-delivery and exactly-once assertions remain unchanged.

Evidence

  • Targeted formatting, Node syntax checks and git diff --check passed.
  • Independent owner review and scoped P0–P2 autoreview found no actionable issue. Runtime validation of final head 7b35f40cb7745e24483ce739a5853a1e5777b496 passed: 58 jobs succeeded, 29 skipped, zero failed, including the aggregate gate. The final static delta reviews were P0–P2 scoped-clean (0.88 and 0.85).
  • Raw-input unit proof: 30/30 passed, including public/private/yielded retry payloads. Custody and released-payload proof: 16/16 passed, including both literal v2026.11.7 queued-private cases. Both executed under Bun on the final-head test merge f8b08432f846e5a72c4c363a15c58bb23b7c1450.
  • Completion restart proof: 13/13 passed under Bun, including preparing-announcing (40.445s), unmarked-requester (42.612s), and stale-settle-requester (42.595s). Those last two fixtures failed before restart on the prior head and now preserve their intended pending state. The original preparing-announcing failure is recorded in CI45102016431; its strict idempotency assertion remains intact.
  • Added regressions cover public/private/yielded completion bytes after a sibling changes, actual queued input ownership, explicit cancellation, replaced-session/run/agent/source rejection, and public/private failure-notice visibility. The custody test loads literal v2026.11.7 private registry/pending-row payloads, closes and reopens SQLite, then preserves the flagless private input and exact queued bytes/hash under recovered ownership. This proves payload compatibility, not execution of the old binary or a full historical schema migration.
  • Native Windows proof: 72 passed, 5 skipped at 4442d2af622d2866394f325e5bf674d9429befd2; later changes preserve that execution path.
  • Published 2e01cd9 CI finished with 46 passed, 28 skipped and 13 failed. The original preparing-announcing case passed (27.678s); eleven of thirteen completion cases passed, and all six restart-resume cases passed. Unmarked/stale-requester cases failed because graceful shutdown had already delivered the supposedly pending result; the final fixture holds preparation before consumption. Custody/wake unit tests were selected, but their exact execution result was not verified in that run.
  • The same CI exposed an Iterable/array type mismatch and redundant session identity pin. Both are fixed in the final delta; the queue reader owns replaced-transcript exclusion.
  • Local runtime testing remains unqualified because the shared dependency installation has a broken workspace link. Earlier task-owned Testbox allocations did not execute; the exact-head hosted run above supplied runtime proof.

Limits and Follow-up

The original November 21 empty-attempt Windows failure did not reproduce; this PR does not claim to repair that historical incident. The native runner retained one temporary namespace without aggregate descendant-settlement proof.

Follow-up: preserve the specific missing-model refusal in session-event acceptance errors; that production path currently emits a generic admission failure.

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

clawsweeper Bot commented Nov 23, 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.

@vincentkoc
vincentkoc marked this pull request as ready for review November 23, 2026 00:25
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 23, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 23, 2026
@clawsweeper

clawsweeper Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR preserves child-completion input across Gateway restarts and consolidates Gateway test-process ownership.

Example: The Gateway restarts while CAPTURED_CUSTODY_RESULT is waiting for requester input preparation.

  • Before: Human-message recovery can cancel the internal input, or reconstructed input can conflict with its accepted idempotency receipt.
  • After: The recovered completion owner retains the queued input and reuses its original raw message for that attempt.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful owner-level repair with focused restart evidence, released-payload compatibility coverage and no open finding.
Proof confidence 🐚 platinum hermit (4/6) ✨ media proof bonus Sufficient (linked_artifact): Supplied evidence exercises actual Gateway processes, persisted completion input, preparation interruption and repeated restart through the real transport path; GitHub confirms successful execution for the pinned head, while direct log inspection was blocked by the review host.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A completed child result can be cancelled or stranded when the Gateway restarts during delivery preparation.
Reason: Restores existing delivery guarantees under maintainer-approved direction without a new option, API, table or alternate runtime owner.

Merge readiness

✅ Ready for maintainer review

This PR repairs a concrete restart-delivery defect using existing owners; the compatibility follow-up resolves the previous blocker, and no actionable correctness finding remains.

Priority: P2
Reviewed head: 7b35f40cb7745e24483ce739a5853a1e5777b496

Before merge

None.

Findings

None.

Agent review details

How this fits together

Child results enter requester-settle delivery, which persists input and receipts; Gateway startup restores completion custody before queued-message replay and resumes delivery into the requester session.

flowchart TD
  A[Child result] --> B[Requester settle owner]
  B --> C[Persisted raw input and receipt]
  C --> D[Gateway restart recovery]
  D --> E[Recovered completion custody]
  D --> F[Human queued message replay]
  E --> G[Requester session]
  F --> G
Loading

Technical review

Best possible solution:

Keep exact attempt bytes with the existing completion owner and let freshly recovered custody resume its queued input.

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

Current-main source retains raw bytes only for parent-only attempts and routes unmatched internal queued input through human-principal recovery; the supplied earlier CI failure identifies the corresponding strict-idempotency failure, without a new local execution.

Is this the best way to solve the issue?

The repair belongs in the existing settle and restart-custody owners, preserves strict receipts and human admission checks, and removes competing test-process cleanup machinery.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 7d0cc1ec8157.

Provenance checked

  • Requester-settle raw input changes intended behavior with a stated reason (36e277d: The controller refactor retained raw private input under its exact dispatch identity; the released writer confirms that private-only scope.)
  • Restart completion custody keeps the original intent (fix: deliver retained child results after Gateway restart #198905: Retained child obligations require fresh requester admission after process-bound authority is retired.)
  • Private consumption classification keeps the original intent (fix: report subagent requester waiting and consumption truthfully #199695: Committed private input can settle delivery independently of a requester continuation interrupted by restart.)
  • Gateway fixture process custody keeps the original intent (ebdc7d5: The existing process owner joins output closure and certified extinction before releasing fixture state or admitting restart.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit ebdc7d5 adds test/helpers/openclaw-test-process.ts:5 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ebdc7d54c084; files: test/helpers/openclaw-test-process.ts)
  • Ayaan Zaidi: Raw commit 09d956b adds src/agents/subagents/announce/subagent-announce.requester-settle-wake.ts:466 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 09d956bee838; files: src/agents/subagents/announce/subagent-announce.requester-settle-wake.ts)
  • Vincent Koc: Raw commit 2db3431 adds src/agents/subagent-announce.requester-settle-wake.ts:240 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2db3431f4aa1; files: src/agents/subagent-announce.requester-settle-wake.ts)

PR surface

Source +63, Tests +249, Other -3. Total +309 across 23 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 6 85 22 +63
Tests 16 797 548 +249
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 3 -3
Total 23 882 573 +309

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 test growth Production +63 net lines; test infrastructure −104; tests +353. Focused recovery logic and compatibility coverage accompany removal of the duplicate Windows process owner.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: Repairs child-result recovery during Gateway restart with a limited lifecycle trigger.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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 (7 earlier review cycles)
  • reviewed 2026-11-23T01:18:16.850Z sha 54e464b :: needs changes before merge. :: [P2] [P2] Migrate acquisition tests to the new instance-creation boundary
  • reviewed 2026-11-23T01:30:31.538Z sha 7213290 :: needs changes before merge. :: [P2] [P2] Explain isolation for both changed factory mocks
  • reviewed 2026-11-23T01:48:34.755Z sha 94d6eec :: needs maintainer review before merge. :: none
  • reviewed 2026-11-23T02:06:23.920Z sha a3046b1 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-23T02:25:53.985Z sha 95500f6 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-23T02:50:58.452Z sha 0a2b6ee :: needs maintainer review before merge. :: none
  • reviewed 2026-11-23T03:14:39.233Z sha 2e01cd9 :: blocked before merge. :: none

Reviewed November 22, 2026, 11:03 PM ET / November 23, 2026, 04:03 UTC (Revision 8).

@vincentkoc vincentkoc changed the title fix(ci): unify gateway fixture process ownership fix(ci): unify gateway ownership and repair lifecycle fixtures Nov 23, 2026
@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

Please review exact head 7213290. The acquisition suite now injects distinct instances through createOpenClawTestInstance and joins the captured suite cleanup on early failures. The original cleanup order, retained state, and late-acquisition assertions remain. The direct-chat restart fixture also checks the current restart contract without issuing another exec. Final-head CI: https://github.com/openclaw/openclaw/actions/runs/45094172583

@clawsweeper

clawsweeper Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

Exact head 94d6eec addresses the sole finding: both instance-factory mocks now state their isolation boundary immediately above the call, and both obsolete baseline identities are removed. This last delta is comments plus baseline deletions only. All five targeted runtime groups and lint passed on prior head 7213290: https://github.com/openclaw/openclaw/actions/runs/45094172583 .

@clawsweeper

clawsweeper Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling labels Nov 23, 2026
@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

Please review exact head 7b35f40cb7745e24483ce739a5853a1e5777b496. The prior data-model compatibility move is implemented and now exercised: literal v2026.11.7 private registry and queued-input payloads are loaded through real SQLite close/reopen, then retain their private classification and unchanged queued bytes/hash under recovered ownership. This is payload compatibility, not a claim of historical-binary/schema-migration or downgrade support.

Exact-head CI passed: https://github.com/openclaw/openclaw/actions/runs/45106405982 — 58 successful jobs, 29 skipped, zero failures. Completed consumer manifests and Bun logs verify requester-wake 30/30 (job137469170477), custody 16/16 including both released-payload cases (job137469170546), and completion restart 13/13 (job137469170401). Preparing-announcing, unmarked-requester and stale-settle-requester all passed. The original preparing-announcing strict-idempotency failure is in CI45102016431; the assertion remains intact. Latest PR body contains direct proof links and the explicit older-binary downgrade limitation.

The final follow-ups also fix the Iterable type error, rely on the canonical queue reader for replaced-transcript exclusion, and hold the two pending-incident fixtures before input consumption without weakening their assertions or increasing timeouts. No further source changes are pending.

@clawsweeper

clawsweeper Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Nov 23, 2026
@vincentkoc
vincentkoc merged commit 92e92d7 into main Nov 23, 2026
166 of 167 checks passed
@vincentkoc
vincentkoc deleted the fix/ci-windows-owner-20261123 branch November 23, 2026 04:07
@vincentkoc

Copy link
Copy Markdown
Member Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 23, 2026
…nclaw#203839)

* fix(ci): unify gateway fixture process ownership

* test(ci): verify cancelled gateway descendant cleanup

* fix(ci): satisfy gateway fixture lint rules

* test(ci): respect process group scope and expose hook failures

* test(ci): separate hook capacity from the shared cron budget

* test(ci): locate child requests across gateway restart phases

* test(telegram): verify the single crash recovery replay

* test(ci): configure agent admission for gateway wake fixtures

* test(ci): separate chat restart from stopped child delivery

* test(ci): align acquisition mocks with the gateway factory

* test(ci): declare acquisition mock isolation

* test(ci): wait for retention startup before shutdown

* test(telegram): accept every completed recovery drain

* test(ci): align restart fixtures with role and completion owners

* fix(gateway): preserve completion input ownership across restart

* fix(gateway): materialize recovered run iterator

* test(gateway): preserve released completion records across recovery

* test(gateway): hold pending completion before requester recovery
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…203102)

(cherry picked from commit 2e1d67c)

Release adaptation: Stable merged read owner retained; terminal-delivery filtering moved to its query; main-only benchmark and helper omitted.

Companion audit: #203176 and #203222 selected in lane; #204260, #204178 and #203839 not selected (not a prerequisite).

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…203176)

## Problem

A requester that calls `sessions_yield` after spawning several completion-mode subagents was woken only when every member of the frozen yield batch was ready. A sibling that keeps running, or that pauses on its own `sessions_yield` while a background command runs, held every finished result back.

Production incident (2026-11-21): a dashboard parent spawned 3 children and yielded at 16:20 IST. Two children finished at 16:26:58 and 16:29:41 with reports that needed a decision. The third kept cycling through exec-yield and resume. The Gateway log has no `announce:requester-settle:…` run for that parent. The parent ran again only at 18:32, when the user typed into the chat. A copy of the state database shows why: both finished rows were `terminal`/`ok` with `delivery.status: pending` and a pending `requesterSettleWake` (`batchRunIds` = all 3, `rearmGeneration: 1`). The third row was still `running`. The gate in `subagent-announce.requester-settle-wake.ts` returned `false` unless every frozen member passed `isRequesterSettleMemberReady`. #200967 had already made an exception for siblings that wait for a message. An exec-yielded or running sibling is the same bug class.

## Change

Rule: every ready result wakes the yielded parent. Siblings that are still working keep their wake, with the same `rearmGeneration`, and wake the parent again when they finish. Each result is delivered once.

- **Settle wake:** removed the all-or-nothing gate and the message-wait exception (`isEndedSubagentMessageWait` is deleted). The wake delivers the ready members of the frozen batch as one partition, and lists the members that are still working. A member whose partition has already started dispatch records its own batch, so a later partition never offers it again. When a partition holds only results that were already delivered and siblings are still pending, it settles without a redundant wake.
- **Wake message:** a partition that leaves members pending no longer says "every subagent has settled… do not call sessions_yield again". It names the siblings that are still working (label, task name or run ID, at most 5, each truncated) and tells the parent: if the request needs those results, call `sessions_yield` to wait; otherwise act on the ready results without reporting the batch as finished.
- **Lifecycle failure path:** `offeredBatch` now offers only ready members, so failure settlement can never consume the wake of a sibling that is still running or exec-yielded.
- **Yield transfer:** when a child ended before the yield and a sibling is still running, `afterRelease` now schedules the settle for the finished child. Before, nothing woke the parent until the sibling ended.
- **Followup owners** (`sessions_send` wait-for-reply, `agent-step`, nested `agent-run-subagent`): the caller is waiting for a single reply. Only the partition that leaves no member pending continues the followup. Earlier partitions wake the session as ordinary settle turns. `successor()` accepts that last partition as a subset of its cohort, so it no longer throws and records the result as a permanent failure.
- **Automation authority:** a yield that carried cron-management authority keeps it for the partition that leaves no member pending. Earlier partitions run without borrowing it, and settling them shrinks the retained cohort instead of discarding the authority.
- **Silent waits:** while siblings are still working, the parent may stay silent (`NO_REPLY`) and wait. Such a turn is not treated as a missing visible reply, so it is not retried.
- **Goal return:** an earlier partition leaves the Goal cohort when it settles. The partition that settles the cohort last resumes the Goal once.
- `isRequesterSettleMemberReady` moved to `subagent-run-liveness.ts`, its only owner, and replaces the deleted message-wait predicate.
- Docs: `tools/subagents/announce.md` and `concepts/subagent-yield-handoff.md`.

Product decisions, under the rules "no stranded user" and "no false done":
- A stopped child is a settled outcome, so its report now wakes the parent right away instead of waiting for its siblings.
- A followup caller gets one reply, after all results are in. The session itself is still woken for each result.

## Evidence

**Regression test** (`subagent-registry.requester-wake.e2e.test.ts`, real registry, lifecycle, yield tool and wake entry point): spawn 2 children, yield, finish one, keep the other exec-yielded. The parent is woken with the finished result, and the wake names the working sibling. The sibling's continuation then wakes the parent again with only its own result. A sweep adds no third wake. A second case covers a child that ended before the yield, while the requester's turn held it.
- Base `eb7ca3d33375`: both cases red (`expected [] to have a length of 1`: no wake).
- Head: both cases green.

**Owner tests:** cron authority (`requester-cron-authority.test.ts`: the early partition neither borrows nor consumes the authority, and the last partition is admitted with it), followup partition (`subagent-announce.requester-settle-followup.test.ts`: early partition runs with no followup successor, last partition carries it). Goal partition (`goal-continuation.test.ts`: early partition does not resume the Goal, last partition resumes it once).

**Updated tests that asserted the all-at-once rule:** `requester-settle-cross-turn` (paused member), `subagent-control.worker` progress card (one wake per result; the card retires once), `requester-wake-settlement` (stopped child).

**Real-Gateway E2E**, incident shape. Scratch `ocx src` Gateway under `env -i`, OpenAI `gpt-5.5` on the OpenClaw runtime. Parent spawns `alpha` (replies at once) and `beta` (`exec` with `background: true` running `sleep 90`, then `sessions_yield`), then yields.

| | alpha ended | first parent wake | beta yielded | beta ended | second parent wake |
|---|---|---|---|---|---|
| base | 19:47:10 | **19:48:53** (one combined run, after beta) | 19:47:13 | 19:48:50 | none |
| head | 19:40:08 | **19:40:11** (`announce:requester-settle:…:<alpha>:yield-1`) | 19:40:12 | 19:41:55 | 19:41:59 (`…:<beta>:yield-1`) |

The parent's replies on head were `alpha: ALPHA-RESULT-7`, then `alpha: ALPHA-RESULT-7 / beta: BETA-RESULT-9`. The live Peanutto launchd pid and `openclaw.json` hash did not change.

**Live sibling suites** (`subagent-yield-pause`, `subagent-followup-yield`, `subagent-yield-resume`, real OpenAI `gpt-5.5`): the same tests fail on base `eb7ca3d33375` and on this branch, with the same assertions (missing `completion.resultText` after a resumed or paused child completes, a Gateway shutdown timeout, an interim reply in the follow-up watch case; follow-up-yield failed 2 of 2 on base). One run of this branch showed a parent that wrote its final report as soon as the first result arrived; the wake message now says to keep waiting when the request needs the remaining results, and that failure no longer appears. The real-Gateway restart e2e files (`test/gateway-*-restart*.e2e.test.ts`) fail locally on base too (11 of 26 on base, 9 of 26 here, same assertions).

**Gates:** `pnpm tsgo:core`, `pnpm check:test-types`, oxlint and oxfmt on the changed files. Every test file in `src/agents/subagents` and `goal-continuation.test.ts` was run across the unit-fast, infra, agents-support, spawn-boundary, core-isolated and e2e projects. Two infra tests failed once under host load and passed when run alone, on head and on base.

## Size

Production code is +96 / −56. The gate, the message-wait exception and its predicate are deleted. The added lines are the partition support the old gate did not need: pending members in the message, the followup last-partition rule, Goal cohort shrink, and pre-yield scheduling, and cron-authority cohort shrink. A census of `batchRunIds`, `requesterYieldBatch`, the frozen branch and `selectConnectedSettledSubagentWave` found every remaining reader still in use. v8 coverage could not attribute lines under the compiled-worker test runner (0 files collected in two attempts), so the census was done by reading the code.

## Accepted edge cases

- If a Goal cohort's last partition is rejected for an unrelated reason (for example, a rearm-generation mismatch), the Goal return stays retained until Stop or a lifecycle rotation. That is the same outcome as a failed final delivery today.
- A nested requester whose early partition answers without yielding reports that answer to its parent. The later result wakes it again as a separate completion.

## Merge danger

- **Two-way door.** No schema, stored-row or config change: the wake rows keep their existing fields and generation. A revert restores the all-at-once wake for every cohort, including rows written while this change ran.
- **Blast radius:** requesters that yield on two or more completion children (dashboard, chat and nested subagent requesters). A defect here would show as an extra or a missing wake for the parent, not as a lost child result: every result stays saved in its child session.

Co-authored-by: Ayaan Zaidi <[email protected]>

(cherry picked from commit 09d956b)

Release adaptation: Kept stable QA Gateway fixture lifecycle; filtered intentionally silent partial-result wakes.

Companion audit: #203222 selected. #204249, #204069, #204048, #203892, #202513, #198960 not applicable (refactors/test cleanup); #204260, #204178, #204098, #204089, #203839, #203271 missing in lane and not prerequisites.

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

* fix(gateway): shutdown never first-imports chunks an in-place update replaced

* test(gateway): guard built shutdown against late first-imports

* fix(gateway): keep broker close functions visible to dead-export scan

* fix(process): supervisor shutdown warnings never first-import their logger; guard tracks pre-signal modules

* test(ci): watch supervisor shutdown owners for the late-import guard

* test(gateway): readable late-import entry parsing

* test(gateway): stop the guard Gateway after startup maintenance settles

* test(gateway): guard only hashed dist chunks that a swap removes

* test(gateway): skip the SIGTERM guard where taskkill stops the Gateway

* fix(gateway): prime supervisor shutdown logger from the shutdown runtime; add restart worker to PR wrapper inventory

* fix(memory-core): own the manager runtime loader in a leaf module so closing never loads the provider

* fix(state): agent lease cleanup handler loads with the state worker; guard stop budget and watch paths

* fix(cron): claimed runs load their finalization before shutdown can need it; watch memory loader owners

* fix(cron): scheduled runs also load finalization with their scheduler

(cherry picked from commit 78a6ca1)

Release adaptation: Preserve the stable cron dispatch preamble and command set, without main-only cron.importLegacyMemberSources; scheduler and queue still prepare finalization together. The shutdown-runtime overlap is supplied by the preceding #203185 backport.

Companions: #203185 selected and applied first. #203839 replaces test process ownership separately and is not required for this guard: the stable fixture supports the same child, entrypoint and stop APIs. #203790, #202507, #202495 startup/resource changes, #201024 cgroup sizing, #197395 cron backoff, and #204210/#203458/#203271 wrapper-only overlaps are not dependencies.
Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot added a commit that referenced this pull request Nov 24, 2026
Backport only the test/gateway-yield-restart.e2e.test.ts changes from 92e92d7 (#203839).

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot added a commit that referenced this pull request Nov 24, 2026
Backport only the fixture wait from #203839; keep the stable custody assertions intact.

(cherry picked from commit 92e92d7)

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
Backport only the settle-wake implementation, same-key regression, and two required registry hunks from #203839. Leave captured completion and unrelated Gateway changes out.

Legacy receipt compatibility checked by code inspection: the registry codec reparses the nested payload without filling this flag. Only explicit privateOnly: false changes classification. Both shipped versions write the field only for private/parent-only settle inputs, so missing flags retain their meaning. The existing parent and yielded-final-deliverable checks are unchanged.

(cherry picked from commit 92e92d7)

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot added a commit that referenced this pull request Nov 24, 2026
A clear requester marker between delivery partitions is not a settled checkpoint. Wait for the stopped child receipt before exercising the unchanged second-restart assertions. Adapt the stale-settle join from upstream 92e92d7 (#203839) without changing completion assertions.

Co-authored-by: RomneyDa <[email protected]>
obviyus added a commit that referenced this pull request Nov 24, 2026
…#204609)

## Problem
When the Gateway restarts, restart recovery tries to deliver finished subagent results that are still owed to their requesting chat. It re-admits the saved requester first. When that admission is refused because the requester's access has ended, `session-restart-resume-custody.ts` only logged a warning. The result was never settled, so it was retried and refused again at every restart. The user saw nothing, not even that a result was lost.

On one production deployment this showed as 88 refusal lines over 6 restart bursts, for 38 child results in 20 chats. 36 of those rows are in `subagent_runs`, created 10-29 to 11-23, and most are weeks old. The same rows were refused at every restart.

The refusal itself is correct and does not change: one-time admission says replayed work checks its requester again when it starts.

## Fix
`session-restart-resume-custody.ts` settles a definitely refused completion once:

- **Closed refusal list.** Only an explicit ended-access marker settles: a `GatewayOperatorRecoveryAuthorizationError` whose cause is `GatewayOperatorAccessDeniedError` with `grant-revoked` or `access-record-inactive` (the saved plugin grant or access record ended or was replaced), or `UserProfileNotFoundError` (the saved profile is gone). Everything else stays pending and retries at the next restart, as before. That includes refusals without a cause (listed below), thrown policy errors (`policy-check-failed`), an unavailable access owner, timeouts and database errors.
- **Settle.** The run record keeps the completion and its delivery payload. Delivery becomes `discarded` with `lastError` naming the reason, `suppressCompletionDelivery` retires the obligation and the pending requester wake is cleared, so the row leaves the restart pending set. Nothing is deleted.
- **Notice.** The original requesting chat, and only that chat (the session ID of the chat whose pending results recovery holds), gets one `openclaw.system-note`: "A background task's result couldn't be delivered because the access it ran under has ended." It names no requester, grant or result. Several results settled in the same chat in one pass produce one notice. The notice is written before the rows settle, so a failed notice leaves them pending. A repeated notice for the same results is not written twice. The row's `details` hold only `source` and a SHA-256 digest of the settled run IDs (the dedupe key), so no run, child or requester ID enters the chat row.
- **7-day cutoff.** A result whose latest recorded time is more than 7 days before the settle settles without a chat notice. Each recovery pass logs one count-only line for them. The latest recorded time is the maximum of `completion.capturedAt`, `completion.fallbackCapturedAt`, `execution.endedAt` (stored rows keep it under `parentCompletion.execution.endedAt`), `delivery.payload.endedAt`, `delivery.createdAt`, `delivery.enqueuedAt`, `delivery.lastAttemptAt` and `delivery.suspendedAt`. The row's `createdAt` is used only when none of these exist. This errs toward notifying. `requesterSettleWake.nextAttemptAt` is a future schedule and is not used.

Docs: `docs/gateway/restart-recovery.md` describes the settle, the notice and the cutoff.

## Expected effect on first deploy (production counts as of 2026-11-24, by the latest recorded time per row)
- 7 days or newer: 9 rows in 6 chats, so 6 chats get one notice each.
- Older than 7 days: 27 rows in 15 chats settle silently, with one summary log line per recovery pass. One chat is in both groups.
- 2 of the 38 refused ids are not in `subagent_runs` and are unaffected.
- After that, those rows are no longer retried at restart.

Related: #204551 (weeks-old pending child results are the same "results without a settled owner" class).

## No-cause refusal sites (classified; none settle)
Every `GatewayOperatorRecoveryAuthorizationError` thrown without a cause, at head:
- `src/gateway/operator-admission.ts:264`: OpenClaw ID disabled in config (policy).
- `src/gateway/operator-admission.ts:271`: tunnel principal not found while OpenClaw ID is not enabled (config state).
- `src/gateway/operator-admission.ts:274`: tunnel principal no longer current (membership).
- `src/gateway/operator-admission.ts:291` (`refuse()`): profile id changed, shared session generation mismatch, auth method disabled, password fallback generation changed, device token or key not current. Mixed. The shared generation is compared against state the new process rebuilds, so it cannot be certified as a policy-only decision.
- `src/gateway/operator-admission.ts:310`: channel identity missing or not current (identity).
- `src/gateway/operator-admission.ts:422`: live ingress binding aborted or profile changed (live sources only).
- `src/gateway/operator-admission.ts:439`, `:474`, `:479`: person-principal auth error, role excludes the agent, no scopes left (policy).
- `src/gateway/operator-run-recovery.ts:91`: role no longer grants the start (policy).
- `src/gateway/remote-ingress-principal-recovery.ts:88`, `:114`: ingress grant missing, ingress identity or scope changed.

Because `:291` mixes policy with rebuilt process state, no-cause refusals are excluded rather than marked; they keep today's retry. Every refusal seen in production carries `grant-revoked` (88 log lines) or `access-record-inactive` (3 log lines), so this exclusion does not change the expected counts. A revoked device keeps being refused at every restart (test below), as before this change.

## Which change made weeks-old rows eligible (investigation only)
Neither candidate changes eligibility. #203839 (92e92d7) changes how a recovered cohort owns its queued settle input. #203901 (e58ca10) changes only yielded children that wait for a message. The pending-child filter in `recoverRequesterCompletionCustody` is identical at 648619c and e2973f9. So these rows were already eligible before the deploy.

The refusal path is #202513 (3ad2cce). For a role-enforced person, the legacy session-principal wake used to take its scopes from the current role. It now uses the recorded session source as the authority, and that source's saved plugin grant is checked. Not bisected end to end.

These old results should be settled, not delivered: their requester's access has ended, and one-time admission re-checks replayed work at start.

## Evidence
- `src/gateway/session-restart-resume-custody.refusal.test.ts` uses real custody, the real SQLite registry and real chat transcripts, and replaces only requester admission to choose the exact refusal:
  - refused children settle once across two restarts, one notice in the requesting chat, none in another chat (`grant-revoked` and `access-record-inactive`);
  - a result older than 7 days settles with no notice and with the summary line; a fresh one notifies;
  - an old row (created and ended 30 days ago) whose result was captured yesterday notifies;
  - a refusal without an ended-access cause, a thrown policy error, an unavailable owner and a database error each stay pending across two restarts, with no notice;
  - the notice row contains no run ID or child session key;
  - when the notice cannot be written, the refused child stays pending, the failure stays inside that chat's recovery (recovered siblings keep custody; local review finding), and the next restart settles it with one notice.
  - On merge base a3443e9 the settle cases fail (`expected 2 to be 1`: the refused child is re-admitted at the second restart; `expected 'pending' to be 'discarded'`). The recent-capture case fails the same way (`expected 'pending' to be 'discarded'`); base 4 failed, 4 passed. On the head, 9/9 pass; with `session-restart-resume-custody.test.ts`, 26/26.
- `session-restart-resume-custody.test.ts`, new case: a requester whose paired device token was revoked after the spawn is still refused by the real admission at both restarts, and its result stays pending.
- `test/gateway-restart-resume.e2e.test.ts` on the head: 5/6 pass. The remaining case, `restart markers survive graceful shutdown (blocked store: false)`, also fails on main. It is a shutdown-ordering assertion (`[close-backfill-proof]` after the clean-close receipt), and in the earlier main run an `Unexpected end of JSON input` from the mock provider harness. No completion refusal is logged in either run. Filed as #204596.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot added a commit that referenced this pull request Nov 24, 2026
The built shutdown guard can signal while the independently scheduled cron
retention reader is still linking its startup imports. Wait for its
completion without changing the shutdown assertion or timeout.

Backport only the shutdown test hunk from 92e92d7 (#203839).

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: jalehman <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 25, 2026
…#204609)

## Problem
When the Gateway restarts, restart recovery tries to deliver finished subagent results that are still owed to their requesting chat. It re-admits the saved requester first. When that admission is refused because the requester's access has ended, `session-restart-resume-custody.ts` only logged a warning. The result was never settled, so it was retried and refused again at every restart. The user saw nothing, not even that a result was lost.

On one production deployment this showed as 88 refusal lines over 6 restart bursts, for 38 child results in 20 chats. 36 of those rows are in `subagent_runs`, created 10-29 to 11-23, and most are weeks old. The same rows were refused at every restart.

The refusal itself is correct and does not change: one-time admission says replayed work checks its requester again when it starts.

## Fix
`session-restart-resume-custody.ts` settles a definitely refused completion once:

- **Closed refusal list.** Only an explicit ended-access marker settles: a `GatewayOperatorRecoveryAuthorizationError` whose cause is `GatewayOperatorAccessDeniedError` with `grant-revoked` or `access-record-inactive` (the saved plugin grant or access record ended or was replaced), or `UserProfileNotFoundError` (the saved profile is gone). Everything else stays pending and retries at the next restart, as before. That includes refusals without a cause (listed below), thrown policy errors (`policy-check-failed`), an unavailable access owner, timeouts and database errors.
- **Settle.** The run record keeps the completion and its delivery payload. Delivery becomes `discarded` with `lastError` naming the reason, `suppressCompletionDelivery` retires the obligation and the pending requester wake is cleared, so the row leaves the restart pending set. Nothing is deleted.
- **Notice.** The original requesting chat, and only that chat (the session ID of the chat whose pending results recovery holds), gets one `openclaw.system-note`: "A background task's result couldn't be delivered because the access it ran under has ended." It names no requester, grant or result. Several results settled in the same chat in one pass produce one notice. The notice is written before the rows settle, so a failed notice leaves them pending. A repeated notice for the same results is not written twice. The row's `details` hold only `source` and a SHA-256 digest of the settled run IDs (the dedupe key), so no run, child or requester ID enters the chat row.
- **7-day cutoff.** A result whose latest recorded time is more than 7 days before the settle settles without a chat notice. Each recovery pass logs one count-only line for them. The latest recorded time is the maximum of `completion.capturedAt`, `completion.fallbackCapturedAt`, `execution.endedAt` (stored rows keep it under `parentCompletion.execution.endedAt`), `delivery.payload.endedAt`, `delivery.createdAt`, `delivery.enqueuedAt`, `delivery.lastAttemptAt` and `delivery.suspendedAt`. The row's `createdAt` is used only when none of these exist. This errs toward notifying. `requesterSettleWake.nextAttemptAt` is a future schedule and is not used.

Docs: `docs/gateway/restart-recovery.md` describes the settle, the notice and the cutoff.

## Expected effect on first deploy (production counts as of 2026-11-24, by the latest recorded time per row)
- 7 days or newer: 9 rows in 6 chats, so 6 chats get one notice each.
- Older than 7 days: 27 rows in 15 chats settle silently, with one summary log line per recovery pass. One chat is in both groups.
- 2 of the 38 refused ids are not in `subagent_runs` and are unaffected.
- After that, those rows are no longer retried at restart.

Related: #204551 (weeks-old pending child results are the same "results without a settled owner" class).

## No-cause refusal sites (classified; none settle)
Every `GatewayOperatorRecoveryAuthorizationError` thrown without a cause, at head:
- `src/gateway/operator-admission.ts:264`: OpenClaw ID disabled in config (policy).
- `src/gateway/operator-admission.ts:271`: tunnel principal not found while OpenClaw ID is not enabled (config state).
- `src/gateway/operator-admission.ts:274`: tunnel principal no longer current (membership).
- `src/gateway/operator-admission.ts:291` (`refuse()`): profile id changed, shared session generation mismatch, auth method disabled, password fallback generation changed, device token or key not current. Mixed. The shared generation is compared against state the new process rebuilds, so it cannot be certified as a policy-only decision.
- `src/gateway/operator-admission.ts:310`: channel identity missing or not current (identity).
- `src/gateway/operator-admission.ts:422`: live ingress binding aborted or profile changed (live sources only).
- `src/gateway/operator-admission.ts:439`, `:474`, `:479`: person-principal auth error, role excludes the agent, no scopes left (policy).
- `src/gateway/operator-run-recovery.ts:91`: role no longer grants the start (policy).
- `src/gateway/remote-ingress-principal-recovery.ts:88`, `:114`: ingress grant missing, ingress identity or scope changed.

Because `:291` mixes policy with rebuilt process state, no-cause refusals are excluded rather than marked; they keep today's retry. Every refusal seen in production carries `grant-revoked` (88 log lines) or `access-record-inactive` (3 log lines), so this exclusion does not change the expected counts. A revoked device keeps being refused at every restart (test below), as before this change.

## Which change made weeks-old rows eligible (investigation only)
Neither candidate changes eligibility. #203839 (92e92d7) changes how a recovered cohort owns its queued settle input. #203901 (e58ca10) changes only yielded children that wait for a message. The pending-child filter in `recoverRequesterCompletionCustody` is identical at 648619c and e2973f9. So these rows were already eligible before the deploy.

The refusal path is #202513 (3ad2cce). For a role-enforced person, the legacy session-principal wake used to take its scopes from the current role. It now uses the recorded session source as the authority, and that source's saved plugin grant is checked. Not bisected end to end.

These old results should be settled, not delivered: their requester's access has ended, and one-time admission re-checks replayed work at start.

## Evidence
- `src/gateway/session-restart-resume-custody.refusal.test.ts` uses real custody, the real SQLite registry and real chat transcripts, and replaces only requester admission to choose the exact refusal:
  - refused children settle once across two restarts, one notice in the requesting chat, none in another chat (`grant-revoked` and `access-record-inactive`);
  - a result older than 7 days settles with no notice and with the summary line; a fresh one notifies;
  - an old row (created and ended 30 days ago) whose result was captured yesterday notifies;
  - a refusal without an ended-access cause, a thrown policy error, an unavailable owner and a database error each stay pending across two restarts, with no notice;
  - the notice row contains no run ID or child session key;
  - when the notice cannot be written, the refused child stays pending, the failure stays inside that chat's recovery (recovered siblings keep custody; local review finding), and the next restart settles it with one notice.
  - On merge base a3443e9 the settle cases fail (`expected 2 to be 1`: the refused child is re-admitted at the second restart; `expected 'pending' to be 'discarded'`). The recent-capture case fails the same way (`expected 'pending' to be 'discarded'`); base 4 failed, 4 passed. On the head, 9/9 pass; with `session-restart-resume-custody.test.ts`, 26/26.
- `session-restart-resume-custody.test.ts`, new case: a requester whose paired device token was revoked after the spawn is still refused by the real admission at both restarts, and its result stays pending.
- `test/gateway-restart-resume.e2e.test.ts` on the head: 5/6 pass. The remaining case, `restart markers survive graceful shutdown (blocked store: false)`, also fails on main. It is a shutdown-ordering assertion (`[close-backfill-proof]` after the clean-close receipt), and in the earlier main run an `Unexpected end of JSON input` from the mock provider harness. No completion refusal is logged in either run. Filed as #204596.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit b3dfd35)
Co-authored-by: RomneyDa <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 25, 2026
…openclaw#204609)

## Problem
When the Gateway restarts, restart recovery tries to deliver finished subagent results that are still owed to their requesting chat. It re-admits the saved requester first. When that admission is refused because the requester's access has ended, `session-restart-resume-custody.ts` only logged a warning. The result was never settled, so it was retried and refused again at every restart. The user saw nothing, not even that a result was lost.

On one production deployment this showed as 88 refusal lines over 6 restart bursts, for 38 child results in 20 chats. 36 of those rows are in `subagent_runs`, created 10-29 to 11-23, and most are weeks old. The same rows were refused at every restart.

The refusal itself is correct and does not change: one-time admission says replayed work checks its requester again when it starts.

## Fix
`session-restart-resume-custody.ts` settles a definitely refused completion once:

- **Closed refusal list.** Only an explicit ended-access marker settles: a `GatewayOperatorRecoveryAuthorizationError` whose cause is `GatewayOperatorAccessDeniedError` with `grant-revoked` or `access-record-inactive` (the saved plugin grant or access record ended or was replaced), or `UserProfileNotFoundError` (the saved profile is gone). Everything else stays pending and retries at the next restart, as before. That includes refusals without a cause (listed below), thrown policy errors (`policy-check-failed`), an unavailable access owner, timeouts and database errors.
- **Settle.** The run record keeps the completion and its delivery payload. Delivery becomes `discarded` with `lastError` naming the reason, `suppressCompletionDelivery` retires the obligation and the pending requester wake is cleared, so the row leaves the restart pending set. Nothing is deleted.
- **Notice.** The original requesting chat, and only that chat (the session ID of the chat whose pending results recovery holds), gets one `openclaw.system-note`: "A background task's result couldn't be delivered because the access it ran under has ended." It names no requester, grant or result. Several results settled in the same chat in one pass produce one notice. The notice is written before the rows settle, so a failed notice leaves them pending. A repeated notice for the same results is not written twice. The row's `details` hold only `source` and a SHA-256 digest of the settled run IDs (the dedupe key), so no run, child or requester ID enters the chat row.
- **7-day cutoff.** A result whose latest recorded time is more than 7 days before the settle settles without a chat notice. Each recovery pass logs one count-only line for them. The latest recorded time is the maximum of `completion.capturedAt`, `completion.fallbackCapturedAt`, `execution.endedAt` (stored rows keep it under `parentCompletion.execution.endedAt`), `delivery.payload.endedAt`, `delivery.createdAt`, `delivery.enqueuedAt`, `delivery.lastAttemptAt` and `delivery.suspendedAt`. The row's `createdAt` is used only when none of these exist. This errs toward notifying. `requesterSettleWake.nextAttemptAt` is a future schedule and is not used.

Docs: `docs/gateway/restart-recovery.md` describes the settle, the notice and the cutoff.

## Expected effect on first deploy (production counts as of 2026-11-24, by the latest recorded time per row)
- 7 days or newer: 9 rows in 6 chats, so 6 chats get one notice each.
- Older than 7 days: 27 rows in 15 chats settle silently, with one summary log line per recovery pass. One chat is in both groups.
- 2 of the 38 refused ids are not in `subagent_runs` and are unaffected.
- After that, those rows are no longer retried at restart.

Related: openclaw#204551 (weeks-old pending child results are the same "results without a settled owner" class).

## No-cause refusal sites (classified; none settle)
Every `GatewayOperatorRecoveryAuthorizationError` thrown without a cause, at head:
- `src/gateway/operator-admission.ts:264`: OpenClaw ID disabled in config (policy).
- `src/gateway/operator-admission.ts:271`: tunnel principal not found while OpenClaw ID is not enabled (config state).
- `src/gateway/operator-admission.ts:274`: tunnel principal no longer current (membership).
- `src/gateway/operator-admission.ts:291` (`refuse()`): profile id changed, shared session generation mismatch, auth method disabled, password fallback generation changed, device token or key not current. Mixed. The shared generation is compared against state the new process rebuilds, so it cannot be certified as a policy-only decision.
- `src/gateway/operator-admission.ts:310`: channel identity missing or not current (identity).
- `src/gateway/operator-admission.ts:422`: live ingress binding aborted or profile changed (live sources only).
- `src/gateway/operator-admission.ts:439`, `:474`, `:479`: person-principal auth error, role excludes the agent, no scopes left (policy).
- `src/gateway/operator-run-recovery.ts:91`: role no longer grants the start (policy).
- `src/gateway/remote-ingress-principal-recovery.ts:88`, `:114`: ingress grant missing, ingress identity or scope changed.

Because `:291` mixes policy with rebuilt process state, no-cause refusals are excluded rather than marked; they keep today's retry. Every refusal seen in production carries `grant-revoked` (88 log lines) or `access-record-inactive` (3 log lines), so this exclusion does not change the expected counts. A revoked device keeps being refused at every restart (test below), as before this change.

## Which change made weeks-old rows eligible (investigation only)
Neither candidate changes eligibility. openclaw#203839 (7b99025) changes how a recovered cohort owns its queued settle input. openclaw#203901 (9e3b3a0) changes only yielded children that wait for a message. The pending-child filter in `recoverRequesterCompletionCustody` is identical at edcaafd and 954c6f8. So these rows were already eligible before the deploy.

The refusal path is openclaw#202513 (f1b2b4a). For a role-enforced person, the legacy session-principal wake used to take its scopes from the current role. It now uses the recorded session source as the authority, and that source's saved plugin grant is checked. Not bisected end to end.

These old results should be settled, not delivered: their requester's access has ended, and one-time admission re-checks replayed work at start.

## Evidence
- `src/gateway/session-restart-resume-custody.refusal.test.ts` uses real custody, the real SQLite registry and real chat transcripts, and replaces only requester admission to choose the exact refusal:
  - refused children settle once across two restarts, one notice in the requesting chat, none in another chat (`grant-revoked` and `access-record-inactive`);
  - a result older than 7 days settles with no notice and with the summary line; a fresh one notifies;
  - an old row (created and ended 30 days ago) whose result was captured yesterday notifies;
  - a refusal without an ended-access cause, a thrown policy error, an unavailable owner and a database error each stay pending across two restarts, with no notice;
  - the notice row contains no run ID or child session key;
  - when the notice cannot be written, the refused child stays pending, the failure stays inside that chat's recovery (recovered siblings keep custody; local review finding), and the next restart settles it with one notice.
  - On merge base ad80d6c the settle cases fail (`expected 2 to be 1`: the refused child is re-admitted at the second restart; `expected 'pending' to be 'discarded'`). The recent-capture case fails the same way (`expected 'pending' to be 'discarded'`); base 4 failed, 4 passed. On the head, 9/9 pass; with `session-restart-resume-custody.test.ts`, 26/26.
- `session-restart-resume-custody.test.ts`, new case: a requester whose paired device token was revoked after the spawn is still refused by the real admission at both restarts, and its result stays pending.
- `test/gateway-restart-resume.e2e.test.ts` on the head: 5/6 pass. The remaining case, `restart markers survive graceful shutdown (blocked store: false)`, also fails on main. It is a shutdown-ordering assertion (`[close-backfill-proof]` after the clean-close receipt), and in the earlier main run an `Unexpected end of JSON input` from the mock provider harness. No completion refusal is logged in either run. Filed as openclaw#204596.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
Preserve the existing requester restart reason in announce classification so unconsumed completed results remain pending for startup custody. Existing consumption receipts prevent replay; permanent refusals, explicit cancellation, and ambiguous sends retain their policies.

(cherry picked from commit b8b06c4)

Follow-ups: fca5133 fix: preserve child completion inputs across Gateway restarts (#208367) [not selected for this narrow backport]; b7967b2 fix: deliver a saved child answer after a Gateway crash (#207706) [not selected for this narrow backport]; 17e2ec9 fix: tell the user when a finished subagent's report can't start in their chat (#207194) [not selected for this narrow backport]; 811f999 refactor(subagents): centralize completion delivery decisions (#206383) [not selected for this narrow backport]; 50a6774 fix: retain channel requester when child completion resumes parent [separately ordered lane row]; d2699a8 chore: carry and enforce participant limits on admitted runs (#204847) [not selected for this narrow backport]; 57dd84b fix(agents): settle every undelivered child completion into history; drop delivery dispositions (#204260) [separately ordered lane row]; cded11f fix(agents): deliver a child's end state as parent history, not a turn obligation (#204178) [not selected for this narrow backport]; 92e92d7 fix: preserve restarted child results and gateway test ownership (#203839) [not selected for this narrow backport]; 09d956b fix(subagents): wake a yielded requester for each ready child result (#203176) [not selected for this narrow backport]; 9f35510 fix: retain child results behind live requester turns (#203198) [separately ordered lane row]; c23cd7f fix: preserve private child results during restart (#203156) [separately ordered lane row]

Release adaptation: Keep stable requester fixture setup and insert the two consumed/unconsumed restart cases without moving its existing lost-yield test.

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 30, 2026
(cherry picked from commit 9f35510)

Companion audit: #203222 fixes yield settlement after cleanup, #203176 wake scheduling, #203839 restart fixtures, #208469 newer perf harness; remaining same-path commits change orchestration or history delivery and are not inputs to stable expiry ownership.

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

Labels

agents Agent runtime and tooling 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: XL 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