Skip to content

fix(agents): drain active runs before durable agent deletion - #168199

Merged
steipete merged 52 commits into
mainfrom
codex/stab-agent-delete-draining
Oct 12, 2026
Merged

steipete merged 52 commits into
mainfrom
codex/stab-agent-delete-draining

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Deleting an agent while one of its turns is running leaves it half deleted. On a dev Gateway (real OpenAI provider), agents.delete during a sleep 30 shell turn:

Why This Change Was Made

Deletion retired the agent's stores while work could still enter or was still running. Nothing closed ingress, active runs weren't settled through the abort owner, and background memory work could still be catching up on sessions when its database workers were revoked. So the purge failed, the journal stayed pending, and the failure detail was reduced to a boolean.

Deletion is now a durable two-phase operation:

  1. Draining. The journal records phase = "draining". Admission owners refuse new work for the agent (chat send, session create, terminal open, cron, worker placement, plugin runtime agent calls, session maintenance). Active runs are aborted and settled through the existing abort owner, and Memory Core work is drained while storage is still open.
  2. Retiring. The phase advances to retiring, stores are retired, files are trashed, and cleanup completes automatically. A restart in either phase resumes from the recorded phase.

Cleanup failures now keep the failing step, database path and underlying cause in the existing failed[] payload next to purgeFailed, so a stuck deletion says what failed.

Persisted state (maintainer-approved)

Peter approved "Add durable draining phase" on 2026-10-09. That covers restart continuation and migration-safe handling of journals written by older builds. The only persisted addition is the nullable column agent_deletion_journal.phase TEXT. New deletions advance draining → retiring; old journals with a null or absent phase keep the previous retirement semantics. State schema stays v20; no other persisted change.

User Impact

Deleting an agent mid-turn stops the turn within about 2 s, removes its sessions, workspace and databases, and lets you recreate the same name right away. Deleting an idle, freshly recreated agent also works the first time. Under heavy load the delete call takes longer (about 40 s at load ~55), because it now waits for the drain instead of returning early and leaving cleanup pending.

Evidence

  • Live A/B on a dev Gateway, fresh state dir, real OpenAI provider (agentlife4 probe: create agent, quick turn, long sleep 30 turn, delete mid-turn, recreate same name, turn, delete again):
    • main (round-6 baseline): delete ok removed 0; turn kept running about 63 s; journal pending across restart; recreate blocked.
    • this branch: delete ok, 7 paths trashed; long turn aborted about 2 s after the delete; agent unlisted; sessions 0; workspace gone; chat.send to the old session → Unknown agent id; recreate same name ok on the first attempt; recreated agent replies reborn; deleting the recreated idle agent → ok.
  • Tests: 455 passed across 27 files (affected suites), including active deletion, recreated-agent memory drain, restart during draining, old-journal recovery, deletion/retirement authority, shared-store preservation, agent RPCs, cron retention, abort/reply settlement and offline deletion. Negative controls: with the original memory-close ordering restored, the real-Gateway regression fails (agent database retirement began before its memory manager drained), and the diagnostics regression fails before the production change.
  • pnpm tsgo:core, Gateway runtime build, lint, format, schema verification (v20), Kysely generation check, 0 cycles and docs links pass. Autoreview against origin/main is scoped-clean.
  • Known log noise, not changed here: the deleted agent's skills watcher logs FsSafeError: root path changed during operation when its directory is trashed.

Follow-up after review (head 6948ee6)

The first landing attempt stopped on review findings. They're fixed on this head, with origin/main merged in:

  1. Cross-agent abort. Cancellation captures the exact run registration and its teardown before any await (src/agents/embedded-agent-runner/runs.ts), so a reused session id can't abort another agent's run or be mistaken for a finished teardown.
  2. Stale journal and protected work. The journal-aware final guard is threaded through every cancellation owner and checked right before each side effect (agents-delete.ts). That ties administrative and protected cancellation to the current journal owner, not just host liveness.
  3. Workspace relocation during the drain. Changes to storage targets are fenced while a deletion is pending, including agents already removed from the roster (src/config/agent-workspace-roster-transition.ts). Name and model edits are still allowed.
  4. Upgrade compatibility. An integration fixture writes main's phase-less v20 journal, then resumes and completes the deletion and recreates the agent. The phase column stays nullable and the schema version is unchanged.
  5. CI. Worker-owned SQL brings the main-thread SQLite ratchet back to 707. Core tests no longer import extension files. Test types and placement expectations are fixed.
  6. Terminal disposal. Disposal flushes and checks authority before disposing, so backpressure isn't lost.

A live A/B on the intermediate head found an intermittent purge failure: Agent database execution admission is closed, cleanup left pending, and recreate blocked. A straggling post-turn session-entry.patch for the deleted agent shared the agent-DB executor with the purge, and its refusal path could close the native generation the purge was using. The architectural fix: session writes check the deletion admission fence before acquiring an executor (d4dfe2274bb4), and cleanup drains the previous executor and owns an exclusive one through settlement and close retries (6948ee685197). The earlier workaround is removed.

Evidence on this head:

  • Integration fixture: 20 delete/recreate cycles with 60 late session patches across three offsets (before abort settles, between clean close and config reload, during purge) all pass. Both failure variants reproduce on the earlier code. Nine cutover suites 195/195; owner and sibling suites 170 passed (1 Linux-only skip); active, restart and legacy integration pass with long timeouts. Types, lint, boundaries, formatting, docs and cycles (0) pass; SQLite T1 707. Autoreview is scoped-clean.
  • Live, fresh state, real OpenAI provider, 5 runs (3× create, quick turn, delete during a sleep 30 turn, recreate, turn, delete idle; 2× agents A and B each mid-turn, delete A, then delete B once idle): 5/5 clean. Deletes took 2.5–4.2 s with 7 paths trashed; turns aborted; recreate worked the first time; B's concurrent turn finished B-DONE; idle deletes succeeded. The structured log has no purge failures and no failed late writes; late writes are refused before they reach the database.

Second follow-up after review (head 265fd8e)

The next landing attempt stopped on two more findings, both fixed:

  • Cross-agent admission identities. With a shared session store, deletion matched session-work admissions by bare session id across agents, so a surviving agent's replacement work on the same id could be interrupted. Admission closures and interruptions are now constrained to the deleted agent (5782beac7857), and two keys sharing one physical session are drained once while every alias is still settled (2166b90eb1dd).
  • Bounded ordinary drains. A drain timeout in plain session archive/delete waited without limit for the aborted owner. Unbounded settlement is now confined to agent deletion; ordinary operations report their bounded timeout again (5782beac7857).
  • Write fence lifetime. Review also found that a failed drain could release the session-write fence while the journal stayed pending. The fence is now owned by the journal and held until completion or rollback, and restart recovery refreshes it (f019f11ff035, 035b6ec04656, 265fd8e88af4).
  • Main merges. origin/main is merged again (069e513f6ccc, 55c237a68fc8). The admission check moved with main's extracted session creator (runtime-agent.ts, session-create-target.ts).

Evidence: every new regression fails before its fix. Nine cutover suites 199/199; delete/archive 86; owner suites 170; plugin runtime 65; active, restart and legacy integration including the 20-cycle late-patch fixture all pass. T1 stays 707 with 0 cycles. Full-branch autoreview is scoped-clean. Live on this head (fresh state, real provider, same five runs as before): 5/5 clean. Deletes took 2.7–5.3 s with 7 paths trashed; turns aborted; recreate worked the first time; B-DONE; idle deletes succeeded. The structured log has no failed purges and no failed late writes.

Third follow-up (head 25ef067)

The previous landing attempt stopped because ordinary user Stop regressed: src/gateway/server-worker-placement-cancel.test.ts failed 3/3 on the PR head (no aborted summary, no killed terminal) while passing on main. The cause was f019f11ff035: session admission had lost Stop's interruption callback. 92a5dcd9be8a restores it, so aborted receipts are kept and deletion refusals take precedence where they overlap a Stop fence. It also makes the deletion executor reject stale-owner promises consistently, which fixes the related CI shard. 25ef06704022 removes a duplicate wrapper-inventory entry and moves the unchanged wait helpers into their existing observer owner (deleting runs.wait.ts), which drops 333 unneeded inventory entries.

  • The unchanged Stop suite passes 3/3 (fails 3/3 on 265fd8e88af4); deletion registry 18/18; Stop, operator and placement siblings 207; the attributed CI replay 649 passed and 1 skipped; wrapper closure 17/17. The active, restart and legacy integration with the 20-cycle fixture passes. Full-branch autoreview is scoped-clean.
  • Live, fresh state, real provider: ordinary Stop (chat.abort during a sleep 30 shell turn) aborts in 17 ms on the built-in runtime and 32 ms on Codex, and the next turn answers on both, the same as latest main (29 ms and 5 ms). Agent deletion: 3/3 lifecycle runs clean and the cross-agent run clean, with B's concurrent turn finishing. A second cross-agent run was inconclusive: B's Codex turn hit codex app-server request timed out before its tool started, while fseventsd was using about 5.5 cores from other builds on the host. Deletion latency rose to 11–46 s under that file-system contention; agent creation and turns slowed by the same factor.
  • On the ClawSweeper P2 "[P2] Revalidate journal authority before stopping worker placement": prepareSessionLifecycleDrain passes its full params to prepareSessionWorkerPlacementStop, and in src/gateway/worker-environments/session-placement-lifecycle.ts both beforeDrain and stop call params.authorize?.() before any effect, with dispatch reclaim receiving both. Placement stop is already re-authorized against the current journal before its side effects.

Fourth follow-up (head 28f417c)

  • Legacy upgrade (also broken on current main). With a real v2026.9.9 state holding an unfinished, phase-less agent deletion, Doctor migrated schemas, hit the deletion fence, refused the whole run and skipped later repairs. This reproduces on main: maintenance discovery left out stores with pending deletions. 11d375f9d51c and 8a224f065473 include those stores in Doctor preflight and backups, prepare their schemas under deletion ownership, and stop treating WAL sidecars as databases. A committed regression uses v2026.9.9-shaped storage, and the published-driver harness (keeper agent with settings, sessions and workspace, plus a doomed agent with a pending journal) passes end to end: Doctor, recovery, keeper intact, reopen, recreate.
  • Delete stall after merging main. Main's perf(plugin-state): reuse committed observations during turns #168635 added a plugin-state observation cache that compound deletion did not update, so native binding cleanup flip-flopped between stale cached presence and actual absence. Live, agents.delete took 237 s, with the session delete-prepare run phase at 232.9 s. c3621fab51e6 makes those comparisons read authoritative state inside the existing worker transaction and removes the incomplete cache and duplicate conditional SQL (production −223 lines). A Gateway regression fails at a 10 s bound before the fix. Ordinary session deletes on main are unaffected; I checked live on 31b1db6.
  • Main merged again (28f417c0f20c). The lander's reviewed test-only fixture patch is included.
  • Evidence on this head: all 21 requested groups pass, including the v2026.9.9 harness on a hash-verified copy, the 10 s delete assertions in the active, restart and legacy integration, Doctor (154) and update guards (58). Autoreview is scoped-clean. Live, fresh state: ordinary Stop aborts in 10 ms (built-in) and 5 ms (Codex) and the next turn answers; agent deletion 2/2 lifecycle runs clean at 6.1 s and 3.8 s (7 paths trashed, turn aborted, recreate on the first try, idle delete ok); the cross-agent run is clean at 5.2 s with B's concurrent turn finishing.

Fifth follow-up (head 223616b)

Review of 4e14485 asked for runtime evidence that stale deletion authority cannot cancel protected work, an upgrade proof from the latest stable release, and found that an established connection-owned terminal escaped deletion drain. This head addresses all three.

  • Connection-owned terminals and other retained resources. A terminal opened with a connection owner released its agent admission once opening finished, so deletion's session-scoped drain never saw it and deleteFiles: true could trash the workspace while the shell kept running. Deletion now joins connected, detached, pending, and already-exiting terminals by recorded agent ID, and drains independent exec processes, retained MCP runtimes, and browser state for the deleted agent before storage is retired. Survivor-owned terminals and exact-session Stop/archive behavior are unchanged. A finalized-process retry gap found during review keeps cleanup ownership when a deletion retry follows a failed process cleanup.
  • Authority loss through the production cancellation owners. With a real deletion journal and lease, six cases (unkeyed and protected work, each with the journal replaced, completed, or revoked between two cancellations) were run through the production owners: the first accepted cancellation settles, and the later cancellation is rejected ("deletion no longer owns database cleanup" or "agent deletion ... was lost"), with the later work item never cancelled.
  • Published-writer upgrades. State genuinely produced by v2026.9.9 and by v2026.10.1 (an unfinished, phase-less deletion journal written by that release's own journal owner) was upgraded on this head through Doctor preflight, startup maintenance, and resumeAgentDeletions, closed and reopened, then the deleted ID was recreated. Keeper configuration, preferences, session entry JSON, transcript event bytes, and workspace contents survived byte-for-byte; the doomed agent was removed through safe-trash; all databases report ok. Shared schema stays 20; the agent schema is main's 25.

Validation on this head: focused deletion regressions 19/19, exec settlement 19/19, the requested matrix 1,589 passed / 1 failed / 2 skipped (the failure is the existing macOS/APFS PR-provisioning stress test hitting its default 120 s timeout; the wrapper inventory itself passes 17/17), types, lint, format, boundaries, ratchets, and import cycles green, fresh autoreview clean at P0-P2.

Live proof on a dev Gateway built from this head (real OpenAI provider, both runtimes): deleting an agent mid-shell-turn aborted that turn, removed its storage, and let the same ID be recreated and answer; deleting agent A mid-turn left agent B's concurrent shell turn to finish normally; an ordinary Stop on both runtimes aborted within 3 ms and the session accepted the next turn.

L52g main conflict integration (head 4817035)

Merged main ca5abdd341bc to resolve the confirmed conflict. The resolution keeps main's removal of Cron receipt-authority custody and its simplified admission tracking/validation, while retaining the deletion journal's recovery identity, agent-specific admission publication, accepted cancellation settlement, and shared-store survivor boundaries. No additional persistence change: nullable agent_deletion_journal.phase TEXT, shared schema 20, and null/absent legacy phases retain retirement semantics.

Five PR-only fixtures were updated to remove the Cron host that main retired. The pending-admission fixture now supplies the existing separate revalidation hook so it holds pre-writer validation, matching main's new one-check path. Its first attempted run timed out because it held the writer validator while waiting for cancellation; the repaired fixture passes all eight tests without extending deadlines.

Validation of this merge candidate: deletion/Stop/retained-resource/shared-store regressions 29/29; nine cutover suites plus session delete/archive 307/307; journal/Doctor/legacy-preparation 78/78; agent-admission 8/8; pnpm tsgo:core, changed-file lint, formatting, schema-v20 guard, and PR wrapper inventory passed. Active/restart-draining/legacy-retiring integration took 43.2/35.2/21.8 s at default deadlines, including the 10-second delete assertion. Both committed v2026.9.9 upgrade modes passed. Fresh isolated Codex autoreview is clean at P0-P2. An initial reviewer claim that the reply-cancellation loop lacked a guard was rejected by source inspection: the loop already invokes params.authorize?.() before each cancellation; the second review confirmed it.
Published-writer copied-state proofs also passed on exact committed head 4817035cf0331a4e1a027c1384871d4e2d0a9770: v2026.9.9 73.113 s runner / 13.263 s body, and v2026.10.1 72.049 s runner / 11.807 s body. Default deadlines, fresh hash-verified copies, full Doctor/startup/recovery/reopen/recreate/teardown; keeper entry, transcript bytes, workspace and preferences preserved; all four databases ok; shared schema 20 with nullable phase TEXT/no default. Original snapshots and artifacts remain hash-identical. This is offline released-writer × candidate proof; the fifth follow-up separately records real-provider Gateway evidence on the pre-merge head.

Sixth follow-up (head 69de971)

Integrates current main (including main's cold-actor append retry e65bd3be4134 and its configured-default model selection change). It also updates three tests to the surviving-owner contract that ClawSweeper flagged on 4817035: the Claw cleanup assertion now expects the surviving agent's shared-store handle to stay open, and two awaits of the now-synchronous memory fixture factory are removed. ClawSweeper revisions 13 and 15 report no findings and no security concerns.

Proof on this head: 408 deletion, Stop, retained-resource, shared-store, cutover, journal, and Doctor regressions pass; types, lint, format, schema guard (shared schema 20), and wrapper inventory pass; autoreview clean P0-P2. Published-writer upgrade proofs pass again on fresh copies: v2026.9.9 (84.5 s) and v2026.10.1 (44.0 s) complete Doctor/startup, resume of the phase-less journal, close/reopen, recreation, and final close, with keeper settings, session entry JSON, transcript bytes, and workspace preserved.

L52i conflict integrations and CI attribution (head ea9970d)

GitHub reported a new conflict on 69de9714db28, so this update merges main 537792d98c57. Journal completion retains the retiring/legacy-null guard and uses main's returned database paths. Plugin-state comparisons still read authoritative rows inside the write transaction; main's receipt-backed keyed reads and native-binding invalidation are preserved. Shared schema stays 20, and the PR's only persisted addition remains nullable agent_deletion_journal.phase TEXT.

A fresh integration check exposed a fixture race: startupSettled does not join the separately scheduled startup recovery. Recovery could legitimately resume the fixture's synthetic pending deletion while the test asserted ingress refusal. The fixture now joins the actual call-through recovery operation before creating that journal. It keeps every refusal assertion and the 10-second deletion bound. Active/restart/legacy integration passes at default deadlines (22.4/44.5/29.9 s); the final session lifecycle/Stop/archive/delete siblings, MCP/admission, journal/Doctor, and plugin-state suites pass. Types, changed-file lint/format, schema guard and wrapper inventory pass. Fresh isolated Codex autoreview is clean at P0-P2. Both corrected published-writer copies pass on exact committed head de2f50c7e3e3281077be0937683728e428dfcbb5: v2026.9.9 (43.8 s) and v2026.10.1 (47.7 s) complete Doctor/startup/recovery/reopen/recreate/teardown. Keeper configuration, preferences, entry JSON, transcript bytes and workspace are preserved; all four databases in each proof pass integrity checks. Original artifacts and snapshots remain hash-identical.

A second confirmed conflict required merging main 5d9a5ff1b44c into final head ea9970d8a7ee. Its model-close fixture follows main's simplified metadata ownership. Memory Core now owns publication in workers and a query-only manager reader, so two fixture observations follow actual durable lease IDs instead of requiring a Gateway writable handle. They retain nonempty/unchanged leases while accepted work is blocked, zero executor reopen requests, committed content, final empty leases, memory-drain-before-retirement ordering, and deletion/recreation checks. All 10 affected model-close, Memory-close, ordinary Stop, and active/restart/legacy deletion tests pass at default deadlines; types, lint/format, schema-v20 guard, wrapper inventory and fresh full-candidate P0-P2 autoreview also pass. ClawSweeper revision 17 on de2f50c7e3e3 had no findings or security concerns and requested only resolution of this conflict.

Both published-writer proofs also pass on exact final head ea9970d8a7ee74aa13047ca655d8f6df572c8858: v2026.9.9 43.8 s, v2026.10.1 43.5 s, with all five phases, default deadlines, full keeper-data preservation, four integrity checks per copy, unchanged original artifacts and completed worker teardown.

The previous exact-head CI run 38135692957 (attempt 1, head 69de9714db28, tested merge e0bfaaf0ebd3, main parent ff6f58a8c32b) had six independently attributed inherited failures, 130 successful jobs, 21 skipped jobs and no cancellations:

Failing job Attribution
checks-node-changed-compact-small-5-1 (114459332807) The sandbox test snapshots its entire temporary HOME and rejects Bun's new package-cache .pile files. The same assertion reproduces on baseline ff6f58a8c32b with the repository's checksum-pinned Bun fork; only the platform-specific cache paths differ.
checks-node-changed-compact-small-11-1 (114459332907) ACP warm-session command admission raises SessionActorStaleVersionError before the runtime turn or explicit abort. Main run 38135845314, job 114459576766, reproduces the error and consequent abort-result/timeout failures; main run 38132306883, job 114449120424, also matches.
checks-node-changed-compact-small-24-3 (114459333065) The model-auth corruption test's synthetic SQL interception does not fire. Same case and assertion on main run 38135845314, job 114459576746, and a direct baseline reproduction.
checks-node-changed-5 (114459333137) The account-model product proof is refused by Codex route compatibility preflight. The exact baseline reproduces the same synthetic-model refusal through its real fixture Gateway (1 failed, 2 passed).
checks-node-changed-extensions-bundle-3 (114459335189) Steering's accepted(true) callback remains uncalled, followed by both 180-second cleanup-hook timeouts. The exact 12-file CI group reproduces all three symptoms on baseline ff6f58a8c32b using Linux Node v24.19.0, two CPUs/two workers: 1 failed, 485 passed, settled exit 1. Testbox run 38137798043. The complete source manifest matches the baseline tree. Focused and full-group macOS passes alone were not used as attribution.
checks-node-changed-compact-large-2 (114459335228) The subagent replacement-run fixture raises SubagentRegistryVersionConflictError during setup. Same case/stack in main run 38135845314, job 114459576816, and earlier main job 114449120478.

Job-level checkout and failure logs were inspected and retained; qualifying source blobs/trees match the tested main parent. The CI gate (114461729712) is downstream of those six jobs. These are prior-head results, not a green CI claim for this integration. ClawSweeper revision 16 completed on 69de9714db28 with Findings None / Security None and asked only for this attribution. The new head requires its own CI and completed ClawSweeper review; inherited-only failures will use the explicitly authorized native admin exception after exact-head revalidation.

L52i CI disposition (historical head ea9970d)

CI 38143548993, attempt 1, on ea9970d completed with 126 successful jobs, 21 skipped jobs, seven failed roots and the downstream CI gate; no jobs were cancelled. The actual tested merge was 8325abda5fd9, with main parent 96a5e338a79d. security-fast passed. ClawSweeper revision 18 completed on this exact head with Findings None / Security None and requested CI attribution.

All seven failures are independently attributed to the baseline. Peter explicitly authorized the native inherited-failure admin exception; the failed results are retained as failures, not reported as green CI.

Failed job Independent baseline evidence
checks-ui-e2e (3/7) — 114482499347 The mocked-Gateway directory-race click timeout matches main run 38143525086, job 114482207729. The entire UI source tree is identical between the tested baseline and merge.
checks-node-changed-compact-small-3-2 — 114482501027 All four dreaming-startup admission cases match main job 114482209121; the test, admission owners and Memory Core tree are unchanged.
checks-node-changed-compact-large-9-2 — 114482501077 Both retained-reader revocation expectations match main job 114482209092. The test and retained-reader/authorization owners are unchanged; the PR's added agent scope does not establish these failures, which occur on main without it.
checks-node-changed-compact-small-9 — 114482501216 Same Bun package-cache additions in the whole-HOME snapshot. The pinned-Bun baseline reproduction and current failure have identical test, child, launcher and runtime-pin inputs.
checks-node-changed-compact-large-11-2 — 114482501225 All four durable-ACK/agent fixture failures match main job 114482209021. The abort scenario fails before receiving its initial admission/ACK, before exercising ordinary abort.
checks-node-changed-5 — 114482501344 Same Codex account-model support-preflight refusal reproduced through the baseline fixture Gateway; the test and support/selection owners are unchanged.
checks-node-changed-extensions-bundle-3 — 114482503258 A fresh Linux replay on the exact current main parent 96a5e338a79d reproduced the same accepted(true) zero-call assertion and both 180-second cleanup-hook timeouts: 1 failed, 485 passed, completed exit 1. Exact 12-file group, Node v24.19.0, two CPUs/two workers, 8 GB instance; verified source manifest matches all 53,821 tracked baseline paths and blob IDs. The earlier baseline proof was not used to waive intervening plugin-lifecycle changes.

The aggregate gate 114485141829 is downstream of these seven jobs. Exact checkout, failure, baseline and source-identity evidence is retained for native validation. The current-baseline replay used the pre-authorized AWS fallback after Testbox spent 15 minutes queued without a runner; that queue timeout was not counted as test evidence. Required review and security checks remain enforced by the native merge workflow.

L52j conflict integration and validation (head f936fa0)

GitHub reported a new conflict on 439df8bb7947, so this update merges main 4d36172e3d7d. The only textual conflict was scripts/pr-lib/wrapper-components.txt; the resolution preserves the union of the PR runtime entries and main's added session-actor-command.ts. No deletion design or schema change was added: the only PR persistence addition remains nullable agent_deletion_journal.phase TEXT, shared schema 20, with null/absent legacy phases retaining retirement semantics.

Validation on the merged candidate: deletion-drain 11/11, ordinary Stop 3/3, chat admission authority 6/6, PR provisioning 16 passed / 1 skipped (309.55 s), eager wrapper inventory 1 passed / 16 unrelated cases skipped, and pnpm tsgo:core passed. The three runtime suites took 57.34 s together; the complete focused wrapper run took 398.80 s. Fresh isolated Codex autoreview of the full candidate against the integrated main completed both passes with zero P0–P2 findings. The merge commit is f936fa017c7e7263039007b2286b68dad2b11919. Historical published-writer proofs are reused for unchanged code; no upgrade fixtures were regenerated, and no fresh live-provider result is claimed for this merge.

ClawSweeper revision 20 completed on the previous head 439df8bb7947 with Findings None / Security None, requesting only current-head CI attribution. That head's CI 38155236578 had 115 successful jobs, 21 skipped jobs, 18 failed roots plus its gate, and no cancellations. Seventeen roots were independently attributed to main. Fresh Linux baseline proof on de06364815bf reproduced steering's missing callback and both 180-second cleanup hooks: 1 failed / 485 passed, native settled exit 1, Node 24.19.0 and two CPUs/workers, with all 53,945 tracked baseline paths byte-verified. The update-campaign failure remained unqualified despite passing baseline replays; it was not waived. A queued resource-matched replay was stopped before dispatch when the new conflict required this integration.

Those are historical results, not current-head admission evidence. New-head CI 38161395288 and a completed ClawSweeper review of f936fa017c7e are required by the native landing cycle. Any current failures will receive their own job-level attribution before using the explicitly authorized inherited-failure exception. Required review and security gates remain enforced.

Final L52j integration (head 4afc414)

A second confirmed conflict required the final authorized main integration, from fd7d336ecffd. This time the conflict was additive session-creation code: main introduced readRequestedSessionCreateTarget, while the PR already owned withSessionCreateAdmission. Both helpers and imports are retained. The worker-based explicit target read executes inside the existing agent admission, whose guard and release still span creation, finalization, and rollback. No wrapper-entry relocation was necessary. Commit: 4afc4143d41e9ef65068799ca88780b66d1cba2e.

Fresh full-candidate Codex autoreview completed two passes with zero P0–P2 findings. Core types, focused lint/format and wrapper inventory passed. The required deletion-drain, ordinary Stop and chat-admission suites passed 20/20; the added target-authority tests passed 2/2. Public sessions.create durability proof passed 14 cases, including persisted first turns and recovery, with one concurrent-input timeout. The exact concurrent-input case independently fails with the same RPC timeout on main fd7d336ecffd (native exit 1); it remains a recorded pre-existing local failure. The combined runtime run was 36 passed / 1 failed in 251.61 s.

Full PR provisioning completed 15 passed / 1 skipped / 1 failed: the known macOS/APFS full cold/warm stress case hit its existing 120,000 ms deadline. Total provisioning time was 809.61 s. The provisioning test and script owners are unchanged by this PR; the only script delta is the inventory already validated separately. No timeout was increased, no test was weakened, and this failure is not counted as passing coverage. All historical upgrade fixtures remain unchanged.

ClawSweeper revision 21 reviewed previous head f936fa017c7e with Findings None / Security None, requesting only conflict resolution and current CI attribution. Its CI run 38161395288 had 129 successful jobs, 21 skips, four failed roots and the downstream gate. Three roots were independently qualified; steering required fresh baseline proof and was not waived. All auxiliary workflows passed. These remain prior-head results: the final head requires its own completed CI, ClawSweeper review, and native admission.

L52k reload-isolation integration (head e5ed235)

A confirmed conflict required merging main 7ec434a7bac62be8f1e749bd50467ccd6292e58f. The two conflict resolutions retain both lifecycle contracts: targeted registry-removal publication keeps unchanged agents' admission and plugin generations intact, and new-agent database preparation completes before roster publication. The durable deletion journal continues owning its admission fence through draining and retirement; only the deleted agent's own stores receive exclusive cleanup executors. Fresh destructive registry reads, publication-driven discovery, queued lease cleanup, local deletion-open refusals, shared-store survivors, and ordinary Stop semantics remain intact. The only PR schema addition remains nullable agent_deletion_journal.phase TEXT; shared schema stays 20, and null/absent legacy phases mean retirement.

Validation on this integration: 135/135 tests across deletion drain, ordinary Stop, chat admission, Claw removal approvals, registry snapshots, lifecycle registry, and the corrected sticky-model suite (399.63 s). Active/restart-draining/legacy-retiring integration passed 3/3 at default deadlines, with test bodies 78.316 s / 59.539 s / 39.877 s (261.21 s total runner). Wrapper inventory, pnpm tsgo:core, lint and formatting passed. Fresh full-candidate isolated Codex autoreview completed two passes with no P0–P2 findings. No upgrade fixture was regenerated; earlier published-writer proof remains historical evidence for its named head, and no fresh live-provider result is claimed here.

Exact-head CI is 38175916895. Current-head ClawSweeper completion and any failed-job attribution remain required before native preparation and landing; previous-head failures are not treated as green CI.

L52k completed-process correction (head 1e7680a)

ClawSweeper's completed review of e5ed235e0a4e3 found one P2: successful exec settlement removed the retained agentId, undoing main's completed-process visibility fix in #169302. CI confirmed all four existing routing variants failed. This three-line correction removes that deletion, restoring main's settlement owner exactly. Temporary notification routing is still released; completed records remain visible only to their owning agent. Deletion still cancels only live processes, joins accepted finalization, and rejects uncertain cleanup; its existing exact-record selection also includes queued completion notifications.

The unchanged regression reproduced locally before correction: 4 failed / 12 passed. Afterward, exec cleanup, process observation, deletion-exec, deletion-drain and ordinary Stop all passed: 39 tests (130.02 s + 29.11 s across two scoped commands), with lint, diff sanity and fresh isolated P0–P2 autoreview clean. No schema, admission/abort policy, or upgrade fixture changed. The broader 138-test integration proof above remains applicable to unchanged source.

Prior CI 38175916895 completed with 125 successful jobs, 21 skipped jobs, seven failed roots and its downstream gate, no cancellations. The exec-cleanup root 114578621836 was PR-caused and is fixed in this head. The other six roots were independently attributed to the baseline:

  • UI jobs 114578620350, 114578620269, 114578620363: six cases match main CI 38172718771 verbatim. The seventh, retained board draft loss, is isolated to identical UI/static-sandbox fixtures with mocked Gateway RPCs; no changed deletion or runtime code executes. This is inspected causal isolation, not a claimed main replay of that board case.
  • Bun SDK-state snapshot 114578621631: the same six package-cache .pile additions reproduced in the retained baseline proof; test, child, launcher and runtime-pin inputs match.
  • Doctor update-owner fixture 114578621811: the exact case independently fails on main 072f977edd46c with the same retired update owner error. Twenty-two causal inputs match the tested main parent aef528ff45ef; baseline probe 1 failed / 23 skipped, 41.452 s. This is retained as a failure, with no weakened assertion or schema repair.
  • Account-model route 114578624370: the same synthetic-model compatibility-preflight refusal from the retained baseline Gateway reproduction, before model execution; causal inputs match.

SQLite retirement and steering passed in this attempt. These dispositions belong only to the historical integration head. Corrected-head CI 38177694561, a completed ClawSweeper review of 1e7680ae1227, and exact-head native preparation remain required. Peter's authorized inherited-failure admin route will be used only for fully attributed current failures; no failed or skipped result is represented as green.

Current CI blocker on 1e7680a

CI 38177694561, attempt 1, completed before product coverage: UI job 114583891301 failed bundling because domain-board.ts and domain-keyed.ts are missing. Its tested merge 022c3538d23d3 has main parent 0e998aa0985cc; its entire UI tree is identical to that parent. Main #168871 added active consumers and main #169368 subsequently removed the adapters without updating them. The same missing files and importer blobs remain on observed main 84a834e23340. This is an inherited main build break, not a deletion change.

The successful fail-fast monitor cancelled 118 jobs, including security-fast 114583890889 during Checkout. Totals: 2 successful, 21 skipped, 118 cancelled, 1 failed root plus the failed CI gate. Other security review checks passed, but native inherited-failure admission separately requires security-fast to pass; this attempt cannot use that exception. No cancelled coverage is counted as success. A newer-main repair must be established before another stale-base integration is justified; no rerun or push has been made solely to obtain green.

Final L52k integration (head bea9bb2)

Main fixed the inherited missing-adapter build break in da8802bc54ef0. This clean merge integrates main e0e9b6b668fef for that named failing gate; it is not a CI-only rerun. The affected pnpm ui:build now succeeds. Deletion-drain, ordinary Stop, chat admission and completed-process cleanup all pass (36 tests, 138.69 s), as do wrapper inventory and pnpm tsgo:core. Fresh full-candidate isolated autoreview completed two passes with no P0–P2 findings. The completed-process ownership correction remains intact. ClawSweeper reviewed prior head 1e7680ae1227 with Findings None / Security None / Before merge None.

Both saved published-writer harnesses were rerun on fresh copies for this exact final head, without regenerating fixtures or changing assertions/default deadlines: v2026.9.9 107.761 s; v2026.10.1 69.023 s, native exit 0 including teardown. All five upgrade/deletion/recreation phases, exact keeper data, and four integrity checks per copy passed. Original artifact/snapshot hashes and path-relocated harness bytes remained unchanged. Shared schema stays 20 with the approved nullable phase; final agent schema 26 is inherited from the newly integrated main baseline, with no additional PR schema change. New exact-head CI and a completed ClawSweeper review remain required before native landing.

L52k final conflict retry (head b624177)

GitHub confirmed another conflict after main advanced. This merge incorporates e9d8770489b6b and resolves only runtime-agent.test.ts: retain main's real worker-snapshot latch and callback-not-called assertion, plus the deletion branch's finally cleanup that releases and joins both pending operations. Main's asynchronous reads remain inside the retained admission flow; journal phases, authority guards, survivor ownership, and completed-process ownership remain intact.

The merged candidate passed 40 tests across runtime-agent, deletion-drain, ordinary Stop and chat admission in 163.61 s, plus core types, wrapper inventory, resolved-test lint, diff sanity and fresh two-pass full-candidate P0–P2 autoreview. Published-writer proof on parent bea9bb26328c remains historical, with no fixture regeneration or new-head live claim; deletion journal/migration owners are unchanged by this conflict resolution.

ClawSweeper completed bea9bb26328c with Findings None / Security None, requesting the confirmed conflict repair and qualified current CI disposition. Its CI 38180526828 completed 129 successful / 21 skipped / 8 failed roots plus gate, no cancellations, with security-fast passing. Seven roots are independently attributed to baseline UI, Bun cache, Board permissions fixture, Doctor update-owner fixture and account-model route behavior. The config.patch timeout remains unqualified: exact-main Node 24 macOS full-file replay passed 69/69, which is not an inheritance claim. A bounded Linux baseline probe is in progress. None of that prior-head CI is presented as current-head success; this head requires its own completed review and CI admission.

L52k bounded closeout: CI admission remains blocked

Final head b624177 has a completed ClawSweeper review with Findings None / Security None. CI 38183516423, attempt 1, finished 129 successful / 21 skipped / 10 failed roots plus the aggregate gate, no cancellations; security-fast passed. No merge request was dispatched.

Seven failed roots have independent main-failure or isolated-fixture evidence. Three remain unqualified for the native exception:

  • 114601248134, optional connection identity: Alice and Bob have correct metadata, but the entire third anonymous user event is absent. The exact main baseline's cold case passed (Node 26/macOS), so that pass is not inheritance or fix evidence.
  • 114601248469, session wire speed: the first sessions.list omits the canonical main row, before speed/reset/cancel assertions. Exact-main full-file replay passed 7/7 on Node 24.21/macOS; it does not qualify the Linux CI failure.
  • 114601436264, test types: UI mcp-app-unmount.test.ts:40 reports SourceAccessor<Node[]> versus Element; mcp-app-view.test.ts:801,804,815 reports missing updateComplete. Job-level output is captured, but independent qualification is unfinished.

The inbound-maintenance root was independently reproduced on exact main: its worker-read await permits scheduled maintenance before dispatch. The prior-head config timeout did not reproduce in either macOS or bounded Linux main probes and remains unqualified for that earlier attempt; it is absent from this head's failed roots. No deadline, assertion, or fixture was weakened. Native review remains NEEDS WORK; preparation and merge are held until every current failure has a qualified disposition.

Record a durable draining phase, close agent work admission, and settle existing run owners before retiring databases. Resume exact pending deletions after restart while preserving legacy journals and Claw removal ownership. Release config custody during settlement and roll back fresh deletion intent when final preconditions refuse removal.
Preserve config-application receipts after durable draining and return UNAVAILABLE with existing cleanup details for incomplete purge or Trash. Exercise native session cleanup, real Gateway RPCs and real Trash before same-name recreation. The coordinator-reported residual live stall remains unconfirmed by the local regression.
Keep the deletion journal in draining while the existing memory owner settles
accepted session catch-up and sync work. Retire storage only after that owner
closes, preserving cancellation writes and restart recovery.

Report the failed session-store cleanup step, database path, and underlying
cause through the existing failed/purgeFailed response fields. Exercise memory
settlement after agent recreation through the real Gateway and Memory Core.
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes scripts Repository scripts commands Command implementations agents Agent runtime and tooling size: XL labels Oct 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. 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. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR drains agent-owned work before retiring storage and resumes interrupted deletion after restart.

Example: Delete agent agentlife4 during a shell turn running sleep 30, then recreate the same agent.

  • Before: Deletion returned success with no removed paths, the turn continued, and recreation remained blocked by pending cleanup.
  • After: The turn aborted, seven paths were trashed, and the recreated agent answered reborn.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful lifecycle repair supported by live Gateway behavior, authority-loss traces, and released-writer upgrade evidence, with no new blocking code finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Recorded real-provider Gateway flows exercise mid-turn deletion, recreation, surviving-agent work, and ordinary Stop; production-owner logs separately prove refusal after journal replacement, completion, and lease revocation. The later integration retains these owners, and unrelated UI parity images were not counted as deletion 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: Deleting an agent during a turn can report success while execution continues, cleanup remains pending, and recreating the agent fails.
Reason: The demonstrated lifecycle failure warrants repair, and maintainer authorship establishes direction for the durable draining phase.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this maintainer-authored PR fixes a demonstrated active-deletion failure that current main still has, and no new blocking patch defect was found.

Priority: P2
Reviewed head: b62417774a44610061fd95988ec03e12d9f0f856

Before merge

  • Complete next step - Resolve the confirmed GitHub conflict and qualify the optional-identity, session-wire-speed, and test-types failures in run 38183516423; repair demonstrated PR-caused failures and retain independently established inherited failures through the authorized native landing path.

Findings

None.

Agent review details

How this fits together

Gateway and CLI deletion enter the agent lifecycle owner, which coordinates admission, cancellation, memory settlement, database retirement, and filesystem cleanup through a durable journal.

flowchart TD
 A[Gateway or CLI deletion] --> B[Deletion journal and lease]
 B --> C[Close agent work admission]
 C --> D[Cancel and settle runtime owners]
 D --> E[Drain memory and retire storage]
 E --> F[Purge sessions and trash files]
 F --> G[Complete journal and allow recreation]
 B --> H[Restart recovery]
 H --> C
Loading

Technical review

Best possible solution:

Complete agent-scoped draining and restart recovery through the existing lifecycle and storage owners before retiring durable data.

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

Current-main source still retires storage without first draining active agent work, matching the reported real-Gateway baseline; this read-only review did not rerun it.

Is this the best way to solve the issue?

Yes: the repair uses existing cancellation and storage owners, retains accepted settlement, scopes cancellation to the deleted agent, and records restart continuation without adding configuration.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8a39ccbb2245.

Provenance checked

  • Transactional deletion and recreation fences keeps the original intent (8a5b4af: fix(gateway): make agent deletion transactional #111678 established durable deletion ownership, cleanup retries, and protection against inherited command authority on ID reuse.)
  • Memory and reader retirement ordering changes intended behavior with a stated reason (40d284f: fix(agents): release model and auth readers when deleting agents #159013 closes deleted-agent resources while preserving surviving physical owners; this PR explains why memory settlement must precede database retirement.)
  • Plugin-state comparison mutations keeps the original intent (01e1892: perf(plugin-state): reuse committed observations during turns #168635 sought fewer repeated observations while preserving TTL and quota contracts; the introduced diff reuses canonical mutation functions inside the existing comparison transaction.)
  • Ordinary Stop and session drain bounds keeps the original intent (80e18aa: The merged change made Stop reach OpenAI-compatible HTTP work; this PR retains that cancellation path and confines additional unbounded local settlement to agent deletion.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Chris Eckert: Raw commit 40d284f adds src/agents/agent-delete-databases.ts:41 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 40d284f9a6aa; files: src/agents/agent-delete-databases.ts)

PR surface

PR surface statistics unavailable: the file list is incomplete.

Review metrics

Metric Value Why it matters
Persisted contract addition One nullable journal column: phase TEXT The additive column has no default or constraints, retains shared schema version 20, and preserves legacy retirement semantics.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: Active agent deletion can leave cleanup pending and prevent same-name recreation; the failure is limited to this lifecycle operation.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • 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 (28 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-11T18:05:14.659Z sha f936fa0 :: needs changes before merge. :: none
  • reviewed 2026-10-11T19:20:05.804Z sha 4afc414 :: needs changes before merge. :: none
  • reviewed 2026-10-11T21:04:08.267Z sha f19e6bb :: needs changes before merge. :: none
  • reviewed 2026-10-11T21:30:29.945Z sha e5ed235 :: needs changes before merge. :: [P2] Preserve the agent owner on completed process records
  • reviewed 2026-10-11T22:16:22.484Z sha 1e7680a :: needs maintainer review before merge. :: none
  • reviewed 2026-10-11T22:44:58.047Z sha bea9bb2 :: needs changes before merge. :: none
  • reviewed 2026-10-11T22:53:39.404Z sha bea9bb2 :: needs changes before merge. :: none
  • reviewed 2026-10-11T23:27:37.462Z sha b624177 :: needs changes before merge. :: none

Reviewed October 11, 2026, 8:13 PM ET / October 12, 2026, 00:13 UTC (Revision 29).

Capture exact run handles and teardown before inventory, revalidate the current deletion journal at cancellation, and retain started settlement on authority loss. Fence cleanup-target relocation while allowing unrelated edits. Keep journal SQL in its worker owner, preserve terminal output and backpressure on refusal, and prove phase-less state-v20 recovery without another persisted field. Close the trusted wrapper import inventory over the new runtime owner.
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 10, 2026
Preserve a retiring-journal lease refusal through the existing worker admission channel so a straggling session patch retires only its native generation, leaving the cleanup executor valid. Certify the refusal at lease claim; retain full retirement for later native, protocol, or cleanup failures.

Regression reproduces the original admission-closed purge failure before the fix and covers both sides of cleanup capture plus config removal. Draining finalization, journal fencing, legacy cleanup, and SQLite T1 count 707 remain intact.
@openclaw-barnacle openclaw-barnacle Bot reopened this Oct 10, 2026
Reuse the agent lifecycle admission fence before selecting a session writer and after its FIFO wait. Preserve cleanup authority and logical shared-store identity without querying SQLite on the host.
@steipete
steipete merged commit be2850e into main Oct 12, 2026
42 of 43 checks passed
@steipete
steipete deleted the codex/stab-agent-delete-draining branch October 12, 2026 01:36
steipete added a commit that referenced this pull request Oct 12, 2026
#168199 re-added three source paths that #169327 had already listed in scripts/pr-lib/wrapper-components.txt, so the eager-import-closure test ("resolves wrapper package exports and workspace aliases from the extracted dependency context") fails on main. Keep the sorted-section entries and drop the re-added copies.
obviyus added a commit that referenced this pull request Oct 12, 2026
## What Problem This Solves

Fixes the PR wrapper extraction regression that makes `test/scripts/eager-import-closure.test.ts` fail on main.

## User Impact

No application behavior changes. The trusted wrapper still extracts the same source files, once each.

## Why This Change Was Made

Commit be2850e (#168199) added three inventory entries already introduced by cbc2017 (#169327): `src/chat/sender-identity.ts`, `src/sessions/input-provenance.ts`, and `src/sessions/user-turn-transcript.metadata.ts`. `copyPrWrapperSources` faithfully copies and returns this production inventory; this is duplicate inventory data, not alias resolution or a graph traversal defect.

Remove the three newly added duplicate lines while retaining their existing entries. The parent of #168199 has no duplicate inventory lines; that commit has exactly these three. The existing uniqueness assertion and extracted runtime-closure tests remain unchanged.

No overlap with Pash/Sarah changes.

## Evidence

Command: `node scripts/run-vitest.mjs run test/scripts/eager-import-closure.test.ts`

- Before, on fetched `origin/main` 6ce48cb: **1 failed, 16 passed (17)**. The failing case is `resolves wrapper package exports and workspace aliases from the extracted dependency context`, at line 173; received the three duplicate paths above instead of `[]`. This newer main reproduces one failure, not the three previously reported at 52200cf.
- After: **17 passed (17)**, including inventory closure, extracted dependency resolution, wrapper lease bootstrap, and legacy anchor cases.
- `git diff --check`: passed.
- `oxfmt --check --no-error-on-unmatched-pattern scripts/pr-lib/wrapper-components.txt`: exited successfully; plain-text inventory is not a supported formatting target (0 files).
- `check-changed --dry-run` identifies the tooling lane. No TypeScript or JavaScript changed, so oxlint and tsgo do not have an applicable changed source target.
- Searched open PRs for eager-import closure and wrapper duplication; found no existing fix for these three duplicate entries.

Two-way door: reverting restores only the duplicate inventory entries. Blast radius is limited to PR wrapper extraction and its tests; no schema, stored state, configuration, or public API changes.

Co-authored-by: Ayaan Zaidi <[email protected]>
steipete added a commit that referenced this pull request Oct 12, 2026
#168947 removed the admitted-schema-facts lookup from openclaw-state-db-schema-additive.ts in favor of tableHasColumn, while #168199 landed a new ensureAgentDeletionJournalPhaseSchema that still used getAdmittedSqliteSchemaFacts and parseSqliteTableDefinition, leaving main without those imports (tsgo:core TS2304). Use the same direct column check.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…w#168199)

Deleting an agent mid-turn returned ok with nothing removed while the turn kept running, left the deletion journal pending across restarts, and blocked recreating the name. Deletion is now two-phase: a durable draining phase (agent admission owners refuse new work for that agent; active runs, terminals, exec processes, retained MCP runtimes, browser state, and Memory Core work are drained through their owners) followed by retiring (stores retired, files trashed, cleanup auto-completes; restart resumes from the recorded phase). Persisted state: nullable agent_deletion_journal.phase TEXT (maintainer-approved); shared schema stays v20; phase-less journals from v2026.9.9 and v2026.10.1 are migrated by Doctor and resume.

Proof: deletion/Stop/admission/shared-store regressions, six-case authority-loss matrix through the production cancellation owners, v2026.9.9 and v2026.10.1 published-writer upgrade proofs, and live dev-Gateway A/B (delete mid-turn, cross-agent delete, Stop on both runtimes, overlapping agent edits). ClawSweeper revisions 19-28 report no findings and no security concerns.

Landed by maintainer instruction with CI not fully attributed; follow-up CI repair on main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
openclaw#168199 re-added three source paths that openclaw#169327 had already listed in scripts/pr-lib/wrapper-components.txt, so the eager-import-closure test ("resolves wrapper package exports and workspace aliases from the extracted dependency context") fails on main. Keep the sorted-section entries and drop the re-added copies.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
## What Problem This Solves

Fixes the PR wrapper extraction regression that makes `test/scripts/eager-import-closure.test.ts` fail on main.

## User Impact

No application behavior changes. The trusted wrapper still extracts the same source files, once each.

## Why This Change Was Made

Commit f99ca39 (openclaw#168199) added three inventory entries already introduced by 4700877 (openclaw#169327): `src/chat/sender-identity.ts`, `src/sessions/input-provenance.ts`, and `src/sessions/user-turn-transcript.metadata.ts`. `copyPrWrapperSources` faithfully copies and returns this production inventory; this is duplicate inventory data, not alias resolution or a graph traversal defect.

Remove the three newly added duplicate lines while retaining their existing entries. The parent of openclaw#168199 has no duplicate inventory lines; that commit has exactly these three. The existing uniqueness assertion and extracted runtime-closure tests remain unchanged.

No overlap with Pash/Sarah changes.

## Evidence

Command: `node scripts/run-vitest.mjs run test/scripts/eager-import-closure.test.ts`

- Before, on fetched `origin/main` 375d62b: **1 failed, 16 passed (17)**. The failing case is `resolves wrapper package exports and workspace aliases from the extracted dependency context`, at line 173; received the three duplicate paths above instead of `[]`. This newer main reproduces one failure, not the three previously reported at 7816f57.
- After: **17 passed (17)**, including inventory closure, extracted dependency resolution, wrapper lease bootstrap, and legacy anchor cases.
- `git diff --check`: passed.
- `oxfmt --check --no-error-on-unmatched-pattern scripts/pr-lib/wrapper-components.txt`: exited successfully; plain-text inventory is not a supported formatting target (0 files).
- `check-changed --dry-run` identifies the tooling lane. No TypeScript or JavaScript changed, so oxlint and tsgo do not have an applicable changed source target.
- Searched open PRs for eager-import closure and wrapper duplication; found no existing fix for these three duplicate entries.

Two-way door: reverting restores only the duplicate inventory entries. Blast radius is limited to PR wrapper extraction and its tests; no schema, stored state, configuration, or public API changes.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
openclaw#168947 removed the admitted-schema-facts lookup from openclaw-state-db-schema-additive.ts in favor of tableHasColumn, while openclaw#168199 landed a new ensureAgentDeletionJournalPhaseSchema that still used getAdmittedSqliteSchemaFacts and parseSqliteTableDefinition, leaving main without those imports (tsgo:core TS2304). Use the same direct column check.
steipete added a commit that referenced this pull request Oct 12, 2026
…169738)

Warm session admission added eight deletion-journal statements and eight worker requests per turn after #168199. Reuse committed per-agent facts through the existing database admission transport, and publish or invalidate them at every journal writer. Preserve queued-work revocation, active-run draining, persisted tombstones, and final cleanup authority.

The live comparison removes all eight statements and requests from warmed turns; whole-workload deletion-status calls fall from 124 to one. Owner regressions cover native-worker deletion, queued and next-turn refusal, commit/rollback, completion/removal, and reload. Full measurement attribution, static-check evidence, inherited CI failures, and update proof are recorded in the PR.
RomneyDa pushed a commit that referenced this pull request Oct 13, 2026
…026.10.5 backport)

Session deletion could retire reply abortability before its canonical chat
controller recorded cancellation: the lifecycle drain aborted retained reply
operations (and the embedded run) inside the queued-abort callback, which runs
before the controller loop. chat.send controllers are abortable only while
their reply run is, so the controller abort was skipped and no canonical
"aborted" terminal with stopReason was published.

Taken: the ordering fix. Queue fencing stays before controller cancellation;
exec-command cancellation moves after the controller loop; embedded and
retained-reply aborts move to the existing onCancellationStarted hook. Adds
main's "delete drain records cancellation before settling a retained reply"
regression adapted to the branch drain signature (no timeoutMs, plain session
seed); the controller case fails without the fix.

Left out: the captured embedded drain-target receipt join
(captureEmbeddedRunDrainTarget/isAborted), onAuthorizedBeforeEmbeddedAbort
and stopEmbeddedRun hooks, and agents-delete-drain test changes, which depend
on main-only #168199/#168080; and the built-CLI flip-proof assertion restore,
since the branch helper never relaxed it.

Extracted-from: 6bb8525
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…penclaw#169738)

Warm session admission added eight deletion-journal statements and eight worker requests per turn after openclaw#168199. Reuse committed per-agent facts through the existing database admission transport, and publish or invalidate them at every journal writer. Preserve queued-work revocation, active-run draining, persisted tombstones, and final cleanup authority.

The live comparison removes all eight statements and requests from warmed turns; whole-workload deletion-status calls fall from 124 to one. Owner regressions cover native-worker deletion, queued and next-turn refusal, commit/rollback, completion/removal, and reload. Full measurement attribution, static-check evidence, inherited CI failures, and update proof are recorded in the PR.
RomneyDa added a commit that referenced this pull request Oct 14, 2026
…#171531)

* fix(release-checks): Windows installer lane fails when gateway stop help is slow and hides cleanup errors (#169567)

(cherry picked from commit 84d7af2d8d43923dad86319a86d710fd217809d9)
(cherry picked from commit c9fd3c085f1167014043ca33fecd3d07b48ab0c4)

* fix(release): recover packaged Gateway port refusals (#170178) (2026.10.5 backport)

Packaged and installer release checks now retry Gateway startup once on a
freshly reserved, persisted port when the exited child's current-launch log
shows the busy-without-listener-PID refusal for that launch's port
(issue #169669). Unrelated exits, stale log lines, a failed config write,
and a second refusal still fail; the startup-migration restart shares the
same single-retry bound.

Adapted: main moved Gateway readiness into gateway-readiness.ts
(#168331, a main-only refactor) with one caller. The branch keeps the
recovery owner in process.ts, renamed waitForGatewayWithStartupRecovery to
match main, and adds configureReplacementGatewayPort there so both branch
callers (runtime.ts waitForGateway and installed.ts waitForInstalledGateway)
share the same port-replacement step. The regression test is taken verbatim.

Extracted-from: 350b86fd97ceea990f738c106c43298b6083a49b

(cherry picked from commit 658dde7d9b5d8ac9fb8d594251feb7a1e9323390)

Backport adaptation: keep September's existing startup-migration tests and retarget them to
waitForGatewayWithStartupRecovery with a gatewayPort; the donor's rewritten scenario table
depends on October test fixtures. Port-refusal recovery is covered by the new
cross-os-release-gateway-startup test.

* test(gateway): await unrelated inbound worktree writes

The inbound restore fixture used a one-second polling deadline to prove
that unrelated session writes can complete while a real allocation lease
is held. Both variants exhausted that deadline in full CI while their
later persisted-session, worktree, and transcript assertions passed.

Await the unrelated request under the held lease using the test signal.
Cancellation still enters finally and releases the lease. Use explicit
entry gates so early settlement cannot masquerade as reaching the owner.

Formatting, basic lint, and Codex review cover this fixture-only change.
Exact-file runtime proof is queued with the campaign coordinator.

(cherry picked from commit 2f6273f2b8af2c1cade3fb434416fda99f64de12)
(cherry picked from commit 760b3b3e78dda886f1bdac2fde703b0ab573d7d9)

* ci: give the extension package boundary check room on hosted release runners (#170702)

* ci: give the extension package boundary check room on hosted release runners

Full release validation for 2026.10.5-beta.3 cancelled check-additional-extension-package-boundary at its 30-minute limit twice (runs 38333371459, 38350592860) after both boundary checks had passed: hosted ubuntu-24.04 spent 366s preparing and 1374s compiling 128 plugins, finishing at ~30.5 minutes. A concurrent release run took 26.7 minutes on the same runner label, so the job routinely sits at the edge of its budget. Raise only this group to 40 minutes; plugin-sdk-api-diff keeps 30 and other additional checks keep 20.

* docs(ci): document the 40-minute package-boundary budget

(cherry picked from commit e88c11c8b20ee7ba31c2c6f85dcf35e1ebb8f203)
(cherry picked from commit 5cf57706f04049125c2f10ba0e78154af397cdcd)

* fix(update): retain Doctor child identities after failed custody binding (#169665) (extracted hotfix)

Publish the owned child identity before fallible native binding and let the original cleanup owner retire its reservation after confirming process-group extinction. Failed admission still refuses input; unknown launches, live groups, and failed settlement remain protected.

Extraction notes: taken the child-binding half of #169665 (update-doctor-process-custody.ts, exec-spawn.ts, their regressions, and the docs/cli/update.md note). Left out the bounded-ancestry half (restart-stale-pids.ts throughPid, update-run-activity.ts, update-command-handoff.ts, legacy-parent handoff, their tests and the repair-and-recovery doc line): on 2026.10.5 continuation and handoff checks still use the /proc/ps ancestor set without a completeness gate, so an unreadable supervisor above the verified driver does not refuse Doctor; that defect arrived with main's native proc-safe ancestry walker after the cut.

Extracted-from: 2a6ffca7f37bfe745f459bd79da8cd30b2e20fa6
(cherry picked from commit 30e3d8131b808383f66864ba7e6c3f48f6591ea9)

Backport adaptation: createManagedCommandProcessCustody is synchronous on 2026.9.33, so the new failed-bind regression wraps the native factory with a synchronous mock implementation instead of awaiting it. Production hunks are unchanged.

* fix(update): Windows update rolls back when Doctor re-checks ancestry after verifying its driver (#169563) (2026.10.5 backport)

Retain identity-verified ancestor drivers for the process lifetime so a later
transient process-inspection failure cannot revoke a continuation this
process already verified, and report unreadable ancestry as a
process-inspection failure instead of a conflicting live update.

Backport notes: production change applied as on main, using the branch's
existing inspectSelfAndAncestorPidsSync() (PowerShell Get-CimInstance path on
Windows) in place of getSelfAndAncestorPidsSync(), which also makes an
incomplete ancestry walk an explicit "ancestry-unverified" result. The three
new regressions were rewritten against the branch's spawnSync/PowerShell
mocks; main's versions mock the native proc-safe ancestry reader that is not
on 2026.10.5 (#168942).

Extracted-from: 830b3ea72dab162ae689f850448ff62073b0b590
(cherry picked from commit 06f5b6a3c3a718003a646455f3b23c177b231248)

* fix(update): accept a found driver from an incomplete Windows ancestry walk after the #169563 backport

The #169563 backport carried main's rule that an incomplete ancestry walk never
grants continuation. 2026.10.5 still reads Windows ancestry through PowerShell
Get-CimInstance, and that walk reports complete only when the chain reaches PID
0, so ordinary Windows chains that end at an exited parent were always
incomplete. Candidate Doctor then refused its own update ("this host could not
read this process's ancestry") and the Windows packaged 2026.10.2 -> beta.3
upgrade rolled back in Full Release Validation run 38332766825 (Release Checks
child 38334632811, both Node lanes).

Every PID the walk collects is a creation-ordered verified ancestor, so a found
driver proves the continuation, as beta.2 already accepted. Completeness now only
decides between not-continuation and ancestry-unverified when the driver is not
found. The retained verified-ancestor proof from #169563 is unchanged.

(cherry picked from commit 34dcc1ae572f2c14bd68cf0d653929e1fcfdc1e8)

* fix(update): preserve reported install refusals (#169658) (2026.10.5 backport)

Keep completed operation ExitErrors intact so clean pre-write service refusals remain recoverable by published update drivers. Carry the native-authority marker in genuine service authority errors, including failures reported through daemon JSON output.

Backport notes: production changes (update-executor.ts, service-update-authority.ts), docs, and the install-wrapper and service-integration regressions are taken unchanged. Left out the new cases in update-command-service-command.timing.test.ts: that file was introduced on main by #168409 after the 2026.10.5 cut and does not exist on this branch; the driver-side classification it exercises is unchanged here and the remaining regressions cover the executor and end-to-end restart behavior. The install-wrapper test also adopts main's hoisted runtime-capture mock (spreading the real runtime module) so the new cases can import ExitError and the executor; this branch's eager capture fails module mocking once those imports are added.

Extracted-from: f12cb2e333852f265c8137fd7ec3693c406367f7
(cherry picked from commit bc281f391f824c97d98abe6d2d0e1a63d94652e7)

Backport adaptation: docs keep only the service-refresh refusal paragraph (the Windows handoff and channel-health paragraphs are not part of this line's history). The service integration test adds only the UpdateServiceDefinitionRecovery type import and keeps 2026.9.33's signal/killed/termination command result fields around the donor's clean-refusal ternary. The install-wrapper test keeps the runtimePins import; ServiceStartRefusalError does not exist on 2026.9.33, so the pre-write refusal case rejects inspection with a plain SERVICE_DEFINITION_UNKNOWN Error and expects the sanitized SERVICE_DEFINITION_UNKNOWN refusal, which the executor now reports unchanged instead of rewrapping as UPDATE_NATIVE_AUTHORITY.

* test(update): expect classified native authority refusals after the #169658 backport

The #169658 backport (bc281f391f82) makes GatewayServiceAuthorityError carry
the UPDATE_NATIVE_AUTHORITY: marker, but left out main's companion test
update 2a21fcd2f97, so the composed native/config authority cases still
expected the unprefixed message and failed (reproduced locally on macOS).

(cherry picked from commit 2a21fcd2f9733c060886f24e9b25524267b2817b)
(cherry picked from commit 0ae0e8154d7c52298af52d8fd16fd1d715821147)

* fix(update): update history writes stall Gateway cron and cleanup during validation (#169283) (2026.10.5 backport)

Update history producers (step/phase/finish records, reconciliation,
interruption settlement) asked the host for their initial grant after
BEGIN IMMEDIATE. The host answers on its event loop, so any updater
main-thread latency became shared-state writer hold time and starved the
serving Gateway's ordinary writers (#169260).

Request the initial grant before the write transaction. Rows are still
reread inside the transaction and the commit grant still revalidates live
authority immediately before COMMIT.

Backport notes: moved assertCurrent("transaction") ahead of the writer in the
mutation worker, reconciliation worker and interruption store, and took the
interruption-store accept() commit-grant fix. Left out the
update-run-admission.ts hunk and its "run creation" regression case: on
2026.10.5 run creation takes no host admission grant (main threads
assertCurrent through createUpdateRun later), so there is nothing to move.
Adapted to the branch's writer object (writer.run, not writer().run).

Extracted-from: 053dbe94df70aef67aa4e7c790933f8742869b35

Backport adaptation: 2026.9.33 has no update-run mutation worker, so only the reconciliation worker and interruption store move their transaction grant ahead of the write transaction, together with the interruption-store accept(current) commit grant and the sqlite-worker-store comment. The donor's update-run-contention regression file does not exist on this line; an equivalent lock-observation regression for the reconciliation and interruption writers was added to update-run-reconciliation.worker.test.ts.

Co-authored-by: Donnie Fiander <[email protected]>
(cherry picked from commit 92f11220cdc3e3273c179b3805e305a4a834e8e6)

* fix(update): keep candidate bookkeeping out of old updaters' config comparison (#170195) (2026.10.5 backport)

During candidate validation the new version's Doctor wrote bookkeeping-only config changes (meta, wizard) into the copied config; older updaters such as 2026.9.4 then reported a required config change and their repair refused it, a dead end. The config writer and Doctor now defer bookkeeping-only changes during rehearsal, preserving real migrations and normal metadata writes after activation. Released 9.4 validator now reports changedKeys=[]. Refs #169953 (the config.auth hang in that report is not reproduced).

Backport notes: production changes apply unchanged apart from an import conflict in src/config/io.meta.ts (this branch still uses the synchronous config machine-state writer). The new rehearsal-bookkeeping regression uses a plain `const` context because this branch's prepareDoctorContext test helper is not AsyncDisposable. The TransactionRecipes visibility cleanup in database-engine/contract.ts is left out; that file does not exist on this branch.

Extracted-from: 529b4d75b7030592d7e0718fa63fb9db16ce8ec3
(cherry picked from commit 8f8af3e42fa0c3dc4935e107ad30f5e69172dcff)

Backport adaptation: 2026.9.33's stampConfigWriteMetadata keeps its positional `_now` parameter, so the new `env` parameter is fifth and io.write-safety.ts passes (parsed, undefined, override, undefined, params.env); io.meta.ts adds only the isDeepStrictEqual and resolveUpdateRehearsalRoot imports. The legacy webhook-pin hunks, their regression, and the docs sentence about webhook completion are dropped because webhook listener migration does not exist on this line. The rehearsal-bookkeeping regression is kept unchanged.

* fix(update): keep pnpm 12 Gateway service commands on the durable install link (#170003)

On pnpm 12 (global/v11), the Gateway service unit recorded the versioned .pnpm/openclaw@<ver> entrypoint, which the next update deleted, so every update left the Gateway stopped; the same mis-detection made in-Gateway /update refuse as unmanaged-package-install. The pnpm install owner now recognizes nested .pnpm roots and persists paths under the durable project hash link. Production net -6 LOC. Fixes #169059.

(cherry picked from commit d0dbb628ca4ca5c3198336d55b6f7cff36ac7ea8)
(cherry picked from commit 7b29c21a2b71049f811cb133b3d3dc6385579284)

Backport adaptation: production changes apply unchanged. In the pnpm11 guard test, 2026.9.33's it.each alias matrix is kept and its package roots move to <root>/hash-openclaw/node_modules/openclaw; the line-only shared-store replacement case expects the same durable hash link. 2026.9.33 keeps pnpm discovery in update-global.pnpm11-discovery.test.ts, so the donor's nested-store case and hash-link expectations land there and update-global.bun-owner.test.ts stays unchanged. The new systemd regression in program-args.pnpm.test.ts drives the entrypoint through process.argv because 2026.9.33's resolveGatewayProgramArguments has no cliEntrypoint parameter.

* fix(update): relocate pnpm 12 basedir_abs launcher shims after native updates (#170131) (2026.10.5 backport)

pnpm 12 command shims use $basedir_abs/, which the launcher relocation did not match, so after a native update the openclaw bin shim pointed at the deleted .openclaw-update-native-* staging directory and every CLI call failed with MODULE_NOT_FOUND. Relocation now handles basedir_abs, physical bin paths and new package groups, and activation checks each published launcher target, warning with repair guidance instead of reporting silent success. Already-broken shims still need a reinstall. Fixes #169244. Supersedes #169388, thanks @goutamadwant.

Backport notes: code and tests apply unchanged. Resolved a docs/install/updating.md conflict by keeping only the pnpm 12 launcher paragraph; the neighboring private-candidate verification paragraph documents a main-only change that is not on this branch.

Extracted-from: 51211ac26ca0ab42837dab765713cf4d41d2ad87
(cherry picked from commit 60b5138d807e5a2c74c21c3a63f8bd54ea1a4da9)

Backport adaptation: 2026.9.33 has no Bun CLI launcher, so the bunLauncher branches are dropped from verifyRuntimeLauncher and relocateRuntimeLauncher; the shared launcherRelativePath pattern and the donor's sourceDir/destinationDir/shellBase relocation replace this line's inline regex replacement. package-update-swap-results.ts takes only verifyLaunchers (keeping invalidLayout and importing formatErrorMessage), and package-update-swap.ts awaits verifyLaunchers(shims) after the activation if/else, before post-install verification. The native-stage test iterates bun, pnpm10, pnpm11, and pnpm12; the new launcher-publication test defines its pnpm target locally because this line's test support has no createPnpmTarget.

* fix(update): reclaim retained updater runtimes outside node_modules and never link recovery files (#170170)

On npm-prefix installs the retained updater runtime was created in lib/, but Doctor and updater cleanup only searched node_modules, so it was never reclaimed; it could also hard-link the package-activation recovery database, leaving nlink=2 and blocking recovery as unsafe. Cleanup now derives its search roots from the producer's own boundary, recovery artifacts are excluded from retention, and the strict nlink guard points to openclaw doctor --fix. Production net -2 LOC. Fixes #169463. Supersedes #169518, thanks @SunnyShu0925.

(cherry picked from commit 60cfa39850052a1779c116b447586e47a783cdba)
(cherry picked from commit e4af2a56b58a9470dc23812462f647755bf4b8ad)

Backport adaptation: partial. Takes resolveRetainedUpdateRuntimeParents and the flatMap discovery in maintainRetainedUpdateRuntimes; update-retained-runtime.ts keeps 2026.9.33's native packageOwner boundary, adds it to the mutation boundaries, and takes its scratch parent from resolveRetainedUpdateRuntimeParents(...).at(-1). Keeps 2026.9.33's package-update-activation-paths.ts (including its unsafe-recovery message), update-candidate-plugin-tree.ts, and the activation-journal and retained-runtime tests; drops the diagnostic-support redaction hunk and the absent package-update-backup-paths.ts. The npm-prefix reclaim regression is appended to doctor-retained-runtime.test.ts beside this line's existing cases.

* fix(doctor): never delete an OAuth profile because the legacy auth store is unreadable (#170256)

Doctor's OAuth-shadow cleanup treated any failure to read or parse the legacy auth store as 'no sidecar reference' and deleted the sidecar-backed canonical OAuth profile, silent credential loss. Only a missing file (ENOENT) now counts as absence; other read or parse failures keep the profile and warn with the file path, and a canonical oauthRef also prevents deletion. Production net -8 LOC. Fixes #168959. Supersedes #169047, thanks to its author.

Backport note: the unrelated ui/src/components/session-group-defaults-dialog.tsx
lint hunk is omitted; that file does not exist on the release branch.

(cherry picked from commit 11a12460482f7790aca049243de04cb9193e87c2)
(cherry picked from commit 5961d8a62aeafec919444a9209ae2126997036de)

Backport adaptation: builds on 2026.9.33's repairStaleOAuthProfilesForAgent instead of inlining it. In stale-oauth-profile-shadows.ts only ENOENT returns null and other read or parse errors throw with the file path; shouldRemoveLocalOAuthShadow refuses a local isLegacyOAuthRef(oauthRef); the scan returns {hits, warnings} and repair starts from the scan's warnings, while a store that becomes unreadable before removal reports through the existing per-agent repair warning. preview-warnings.ts surfaces scan warnings. Keeps this line's hasLegacyOAuthSidecarRef, stale-oauth-profile-shadows.test-support.ts, its test-API publication, and its locked-store recheck tests; the mock-exports baseline hunk is skipped (no such file here) and the assertion-safety baseline is unchanged because the ratchet passes as is. The donor's sidecar (legacy JSON and canonical store, the latter with the legacy file absent), unreadable legacy file, and post-scan corruption cases are added, wrapping credentials in this line's oauthCredential helper.

* feat(meta): support Muse Wonder (#170232)

* feat(meta): support Muse Wonder

* test(meta): honor protected egress in live proof

(cherry picked from commit 9b998e9d23d8b04d0ac5474a0a54e41bd6e7a253)
(cherry picked from commit 61d5e6c86f6a2e997d4869139787fdf74478bb37)

Backport adaptation: dropped the authenticated-catalog projection test because
buildOpenAICompatibleLiveModels is not exported from
openclaw/plugin-sdk/provider-catalog-live-runtime on this line, and the public
SDK surface stays unchanged for the backport.

* fix(minimax): honor M3.1 thinking effort levels (#160089)

* fix(minimax): honor M3.1 thinking effort levels

* ci: apply existing package-boundary job budget for landing

Carry forward the workflow-only correction already on main in
5e5e50e842c52431d82f7163fea83b998178ec17. PR 160089's exact-head run
36407519621 exceeded the former 20-minute whole-job deadline after
all 125 plugin compiles and the canary passed. Keep complete validation,
compiler concurrency, runner selection, and every required gate unchanged.
Only this row gets the existing measured 30-minute budget.

No MiniMax runtime or test changes in this preparation commit.

Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Tak Hoffman <[email protected]>
Co-authored-by: Takhoffman <[email protected]>

* ci: prepare conflict-free main workflow refresh

The isolated timeout hunk conflicts with adjacent scheduling and runner
updates already on main. Remove the copied workflow hunk so the PR can
inherit the complete reviewed main workflow through a normal base refresh,
rather than mixing workflow fragments or changing any required gate.

No MiniMax source or test changes. Preserve requested landing credit.

Co-authored-by: Tak Hoffman <[email protected]>
Co-authored-by: Takhoffman <[email protected]>

* fix(minimax): preserve signed replay without output-cap metadata

* fix(minimax): retain mandatory replay with small output caps

* fix(minimax): ignore manual budgets for adaptive replay

---------

Co-authored-by: NianJiuZst <[email protected]>
Co-authored-by: RoboClaw <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: Tak Hoffman <[email protected]>
Co-authored-by: Dallin Romney <[email protected]>
(cherry picked from commit 8cedf203e34af009708af0ccfaaa43f2ff7c0987)
(cherry picked from commit 900722b03484e86686d3cabb41cd389681810b9b)

Backport adaptation: kept the September replay hook constant and the
resolveMinimaxThinkingProfile hook in provider-registration.ts; replaced only
the minimax-fast-mode stream family spread with wrapMinimaxProviderStream for
wrapStreamFn and wrapSimpleCompletionStreamFn. stream.ts still composes the
same minimax-fast-mode family wrapper underneath, so fast mode is preserved.

* fix(minimax): OAuth sign-in stops working about two hours after login because expired tokens are never refreshed (#160459)

* fix(minimax): refresh expired portal OAuth tokens

* fix(minimax): bind portal OAuth refresh to the issuing region

* refactor(plugins): keep OAuth dispatch with runtime auth ownership

* test(minimax): retire obsolete OAuth mock exception

* fix(minimax): recognize the current CN inference host during refresh

* fix(plugins): keep Chutes refresh test options out of caller config

* test(chutes): verify refresh through registered provider hook

---------

Co-authored-by: Dallin Romney <[email protected]>
Co-authored-by: Masato Hoshino <[email protected]>
(cherry picked from commit 9e28ade6814511ea9670040620d78ae699f5d2db)
(cherry picked from commit 463017d7dfa5fcbcb6fff97f32c17e09267c2b5a)

Backport adaptation: plugin-only. The September refreshOAuth hook keeps its
one-argument SDK signature, so the portal provider reads
models.providers.minimax-portal.baseUrl from api.runtime.config.current() for
the region check. Kept the existing oauth.ts token payload cast, added refresh
token reuse when MiniMax does not rotate it, and recorded tokenEndpoint at
login. Dropped the provider-runtime-auth relocation, the provider-runtime
refactor and two-argument hook type, the Chutes test edit, the SDK hook doc,
and the retired mock-exports baseline. The refresh tests drop the config
argument and set the base URL through the runtime config instead.

* fix(models): honor live thinking levels in agent runs (#168566)

Fixes agent runs that reject a thinking level the provider now supports, or accept a level the provider has removed, when an older model row already declares `reasoning`.

Agent commands, replies, and scheduled runs use the thinking levels in their admitted provider catalog. This reads the catalog already held in memory; it does not fetch a model list during a turn. Explicit configured level maps and effort lists still win. Missing observations do not mean that thinking is unsupported.

xAI sign-in no longer saves provider-owned effort lists or thinking maps as operator overrides. Sign in again to replace rows saved by an older sign-in. Other model fields and credentials retain their existing behavior.

A defined `reasoning` boolean does not prove that the supported level list is current. Remove that short circuit from command selection and fallback execution, and from these five consumers:

- `src/auto-reply/reply/model-selection.ts`
- `src/auto-reply/reply/model-runtime-normalization.ts`
- `src/auto-reply/reply/agent-runner-utils.ts`
- `src/cron/isolated-agent/model-selection.ts`
- `src/cron/isolated-agent/run-executor.ts`

The existing catalog owner still controls observation, route selection, and lifetime. Re-sign-in persistence is owned by `extensions/xai/onboard.ts::applyXaiOAuthConfig`. The shared ID-keyed auth merge preserves omitted model fields, so merely leaving out the old effort list did not delete it from saved config. xAI now supplies explicit `undefined` deletion markers for its thinking map and effort list. Other providers keep their existing merge behavior; no config migration is needed.

- Command and reply regressions both fail with the old guard for an added level and a removed level. They pass with this change.
- The full `runModelsAuthLoginFlowCore` regression fails on the prior head because copied thinking fields survive the disk write. It passes with the xAI deletion markers and confirms another provider's explicit map and effort list remain unchanged.
- 268 tests passed across the two reported failure files and the focused command, reply, cron, catalog-owner, and xAI suites. Coverage includes explicit overrides, missing observations, native runtime selection, and no-network catalog reads.
- The source build completed through the normal CLI wrapper.
- An isolated Anthropic API-key profile refreshed its catalog, then completed `agent --local --thinking max` and returned `OK` with HTTP 200. Its configured model row had only the reasoning boolean, not a level map. The live listing supplied `max`. The redacted outgoing request contained:

```json
{
  "model": "<live-listed Anthropic model>",
  "thinking": { "type": "adaptive", "display": "summarized" },
  "output_config": { "effort": "max" }
}
```

`npm view openclaw version` reported **2026.9.9**. The proof executed that published package's `applyXaiOAuthConfig` and saved its JSON output, including the copied `["low", "high"]` effort list. No real xAI account was used: a local HTTP server supplied synthetic OAuth credentials, a model listing, and streamed API responses.

The candidate loaded those bytes through the normal config loader. An embedded `--thinking high` turn returned `OK`. The real `runModelsAuthLoginFlowCore` then completed sign-in against the stub, and a fresh read of the saved file contained neither `thinkingLevelMap` nor `compat.supportedReasoningEfforts`. The config still validated. After catalog refresh, `--thinking xhigh` returned `OK`.

Redacted trace:

```json
[
  {"stage":"stable-config","version":"2026.9.9","supportedReasoningEfforts":["low","high"]},
  {"stage":"candidate-load","valid":true},
  {"request":"/v1/responses","model":"grok-4.6","reasoning":{"effort":"high","summary":"auto"},"reply":"OK"},
  {"oauth":["/.well-known/openid-configuration","/oauth2/device/code","/oauth2/token","/v1/models"]},
  {"stage":"saved-config-readback","thinkingLevelMap":"absent","supportedReasoningEfforts":"absent","reasoning":true,"valid":true},
  {"request":"/v1/responses","model":"grok-4.6","reasoning":{"effort":"xhigh","summary":"auto"},"reply":"OK"}
]
```

This profile had no Gateway. Sign-in reported the local Gateway refresh warning, but the saved-config readback and both embedded turns succeeded without a restart.

- Keyless host selection with plugins disabled must remain available after an explicit runtime reset. That is a real contract: runtime preparation now skips the provider-catalog lookup when plugins are disabled. It does not grant explicit model availability.
- The fallback test's ban on a scoped read pinned the old guard, not a network boundary. It now returns no observation for the fallback provider and still checks that the prepared fallback metadata selects `xhigh`. It also checks the scope of all three in-memory reads.

Core behavior can be reverted. Re-signing into xAI removes copied capability fields from saved rows; reverting does not restore those removed values. The affected surface is thinking selection for agent runs and xAI sign-in, not transport routing or credentials.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 1a6d781104c6c0bb97c2f618717b96e3b438658a)
(cherry picked from commit cf399af0c224baea6e8cf85043ffc9d6d3af9b6f)

Backport adaptation: the retired mock-exports baseline stays deleted. In
reply model-selection.ts only the needsThinkHydration wrapper is removed, so
the provider-scoped catalog load is unconditional. September's
prepareModelSelectionRuntime has no hydrateThinkingCatalog option, so the
removed guard becomes an early "ready" return only when plugins are disabled.
agent-runner-utils.ts keeps September's base-params structure, which had no
hydration guard there. Tests keep September structure: xai-oauth.test.ts
renames the stale row to grok-4.6 and adds the stale thinking fields and
assertions; the configured and reply selection tests add only the new it.each
cases (with the scoped thinking catalog mock), and two existing September
reply tests drop their pins on the old guard as upstream did. The cron
admitted-catalog fast path is restored by the following backport of
5558b6063f4.

* fix(models): reuse admitted thinking catalogs after the #168566 backport

The #168566 backport (cf399af0c224) removed the reasoning short circuit, so
cron fallback candidates and idle native model selections reloaded provider
thinking catalogs on the turn path: FRV run 38333371459 failed
run.cron-model-override-forwarding (4 catalog loads, expected 2) and
get-reply-native-slash-fast-path (rediscovery, expected none). This is a perf
regression main repaired in production code; takes main's follow-up
unchanged. Cron reuses matching host rows from its captured catalog, and
idle model-only host selection skips thinking-policy observation; stored
levels, pending followups, native runtimes, and missing rows still get
scoped metadata.

Extracted-from: dd4b258a3cfa6fdef41535e5518fe260f5665a9c
Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit 5558b6063f4f6514a6fe84a319d321d8ebad2e33)

Backport adaptation: September's prepareModelSelectionRuntime has no
hydrateThinkingCatalog option, so it gains only the optional
thinkingPolicyRequired flag and returns the admitted catalog as "ready" when
plugins are disabled or no thinking observation is needed. The September-only
cron runtime-only override test now expects the executor's per-candidate
capability load (three scoped catalog reads instead of two); upstream main has
the same executor behavior and had already retired that test.

* fix(lmstudio): discover new models when refreshing saved inventory (#168039)

* fix(lmstudio): discover new models when refreshing saved inventory

* fix(lmstudio): expose local auth before catalog activation

* fix(models): preserve manifest auth during deferred catalog refresh

* fix(models): resolve local auth markers without saved model rows

* test(models): reuse default rows in local marker cases

(cherry picked from commit 30c1dabc5e40aff07c27410c10d51aa26f3069af)
(cherry picked from commit e4eb3a33812932a368789adcdc3de01d718f55a6)

Backport adaptation: index.ts takes the provider-discovery.ts spread and drops
September's inline catalog and resolveSyntheticAuth hooks, which that module
now supplies. The model-auth local-marker cases are rewritten as the upstream
it.each([0, 1]) pair on September's resolveApiKeyForProviderCore helper. The
worker scope integration test keeps September's structure, omits the
credential-only synthetic auth case, and does not pass wait: true, which this
line's loadFullModelCatalog does not take.

* fix(llama-cpp): select aliased models and fail when credentials cannot be saved (#168232)

* fix(llama-cpp): preserve aliased models during managed setup

Resolve configured model aliases and auth-profile suffixes through the canonical model owner before ordering setup candidates. Keep the resolver lazy.

Current-main regression: three supported references selected the first model instead of the selected GGUF. Remote before/after and CI changed-lane selection: 80 passing tests after the fix. Remote formatting passed; local formatter version is unavailable. Content scans ran separately.

* fix(llama-cpp): fail setup when credentials cannot be saved

Use the existing throwing auth-store writer before publishing the profile and default model. Previously a failed write was ignored and setup logged success.

The regression uses a loopback discovery server and a blocked auth-store directory. It fails on current main and passes with the repair. Remote formatting and changed-lane tests passed; content scanners ran separately because the local formatter version is unavailable.

(cherry picked from commit f160a6921ecd577fe4f6edce553f959f2c61f9fd)
(cherry picked from commit 94ba626229333fa81a81039c239348f5133bdd2c)

Backport adaptation: setup.ts keeps September's configuredCandidates body
(managed inventory scope) but makes it async and resolves the primary through
a lazy resolveDefaultModelForAgent call with manifest and plugin normalization
disabled, so aliases and auth-profile suffixes select the configured model.
Both callers await it. The docs paragraph about authored-model setup is not
ported because that feature is not on this line, and the retired
setup-authored-model.test.ts stays deleted; its alias cases move into
setup.test.ts using cached local models. The auth-persistence test drops the
compiled-subprocess-testing import, which this line does not export and the
in-process test does not need.

* fix(deepseek): recover calls markup instead of leaking tool payloads (#169728)

* fix(deepseek): recover calls markup instead of leaking tool payloads

Share recognized DSML wrappers across recovery and visible-text filtering, including the reported separator space. Preserve matched closing tags and existing tool authority. Related: #159665; thanks @TOMUIV for the reproduction.

* fix(deepseek): hide DSML during direct finalization

Keep the shared text filter active in direct provider calls without enabling textual tool recovery there. Cover compact and spaced tool wrappers across streamed chunks. Related: #159665.

Backport adaptation: the September stream has no Gemma tool-call recoverer, so only the DeepSeek recoverer gating (`!directMode && shouldFilterDeepSeekDsmlText`) is applied. The donor test context included a DSML `__proto__` scalar-argument it.each that is not on this line; only the three new DeepSeek tests are taken.

(cherry picked from commit 910a2c1b30857b3b96a456da86a1e72d69d3ebba)
(cherry picked from commit 25f5232102a027d84dbcff9e478af01c9a78bd22)

* fix(openai): turn fails when the ChatGPT WebSocket closes with 1000 mid-stream (#167512)

When the ChatGPT Responses WebSocket closed with code 1000 in the middle of a stream, before response.completed, OpenClaw treated the close as non-retryable and failed the turn. An unexpected mid-stream 1000 close is now retryable through the existing bounded retry. A 1000 close after a completed response still does not retry, and policy and protocol closes (1008, 1002) stay non-retryable. Proof: the shipped local-agent CLI against a loopback WebSocket server. On main the turn failed after one request; with the PR it retried once (1 of 8 allowed) and returned exactly one final answer with no duplicated partial output. The completed-1000, 1008 and 1002 controls behaved the same on both. Excerpts are in the PR description. Fixes #167345. Thanks @ericcurtin.

Backport adaptation: the source change applies cleanly. The donor test block lives in a test layout this line does not have, so it is dropped; the 1000 close case is added to the existing retry-directed close it.each in openai-chatgpt-responses.websocket-errors.test.ts instead. The donor docs paragraph does not exist on this line; one sentence about a normal (1000) close before the terminal event is added to the existing recovery paragraph in docs/concepts/model-failover.md.

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

* fix(agents): enforce provider response-header deadlines (#168282)

* fix(agents): enforce provider response-header deadlines

Carry the first-event deadline through synchronous and asynchronous stream
creation until provider acceptance or activity. Keep provider timeout
overrides, local post-acceptance gap behavior, and transport first-SSE
deadlines under their existing owners.

Exercise missing response headers through the real Responses, Completions,
Anthropic, and Ollama transports, plus asynchronous factory deadline
carryover. Detach synthetic recovery fixtures from durable session lookup
so their fake retry clocks remain deterministic.

Release-note context: stalled local provider requests now recover at the
first-event deadline rather than waiting for longer transport defaults.

* fix(agents): retain idle watchdog across accepted stream setup

Keep the request deadline alive on the idle budget after cloud provider
acceptance until the iterator watchdog takes over. Creation-only local
streams still stop gap policing at acceptance. Preserve timeout rejection
when activity arrives synchronously before an async factory returns.

Regressions cover pending accepted factories, distinct header and idle
budgets, local gap opt-out, and stream-to-iterator deadline hand-offs.
The negative control fails on the incoming head; the five-file timeout,
transport, progress, policy, and recovery suite passes all 122 tests.

* fix(agents): release retired request deadline promises

Drop the pending request timeout promise when its deadline retires so long
streams do not accumulate one promise reaction per event. Preserve a fired
deadline's rejection for late consumers by recording expiry before abort
callbacks can reenter cleanup.

The real-owner GC probe retains 1 promise after 1000 events instead of 1001.
Extend the hand-off regression to consume after expiry and verify the same
error. The five-file timeout and recovery suite passes all 122 tests.

Backport adaptation: hand-ported into the September llm-idle-timeout.ts.
The request deadline, finishCreation, withRequestTimeout, provider
acceptance observer, and stream-level producer-completion cleanup are
applied on top of this line's abortStream and firstArmPending structure.
The model-progress timer branch is omitted because #165983 is not on this
line; the request deadline uses a dedicated timer helper and the iterator
idle timer retires the request deadline when it fires, matching the donor's
shared startTimer behavior. The async-factory branch becomes
withSourceAbort(withRequestTimeout(source)) and the now-unused
createTimeoutPromise is removed. Tests: the three new deadline regressions
are taken; existing September tests whose synchronous streams never signal
provider acceptance now report acceptance (the donor made the same change
to its tool-activity test), and the pass-through assertions allow the
private acceptance observer key. The new regressions and the adapted
creation-only test live in llm-idle-timeout.request-deadline.test.ts so
llm-idle-timeout.test.ts stays within its max-lines limit. The donor's real-loopback transport test
and its attempt-recovery fixture tweak are not taken: the transport test
passes with this port and fails 5 of 10 cases on the prior head, but costs
about 22 s warm and 61 s cold wall time. The custom-providers.md sentence
matches this line's 120 s cloud and 300 s local/self-hosted first-event
budgets.

(cherry picked from commit 5554f7c81ff60357855e2b80aa4ecf07cada01a0)
(cherry picked from commit 4bc8f7b82c2033e517c0107b3feba8bdc43ce75e)

* fix(codex): stream the completed answer tail that deltas dropped (#168400)

Codex app-server agentMessage deltas are best-effort; item/completed text is
authoritative (codex-rs TUI streaming.rs consolidates from the completed item
so dropped deltas cannot truncate the transcript). The Codex projector stored
the completed text for results/transcripts but never reconciled the streamed
buffer, so when a provider stream omitted its final delta the gateway chat
final (built from streamed assistant events) silently lost the last tokens,
e.g. the Luna steering live test received CODEX-STEER-...45 for ...45AB.

On completion, stream any tail the completed text adds to an already-started
stream through the existing delta path, so live previews, channel partials,
HTTP streams, and the chat final all end on the authoritative text. Also drop
a dead pending-echo reset in recordItemCompleted that the next branch always
overwrote, and make the live steering assertion report the transcript answer
on mismatch.

Backport adaptation: the donor's recordCompletedItemContent helper comes
from refactor #166704, which is not on this line. The tail reconciliation
is a small streamCompletedTextTail method on CodexAssistantProjection
(keeping assistantTextByItem private), called before recordItemCompleted in
the item/completed handler and before recordSnapshotItem in the
completed-turn snapshot loop. The regression test covers both completion
paths. The dead pending-echo reset is not part of this cherry-pick's diff
and is left unchanged.

(cherry picked from commit 4fcac11846800494f7b25f795d039be1ed505a62)
(cherry picked from commit 40b8f5dfb972cf5187cb9d00f69bedb86b5a8abb)

* fix(codex): recover follow-up requests after failed thread preparation (#169431) (2026.10.5 backport)

Failed Codex warm preparation (binding publication or enclosing lease
settlement failing after warm reuse transferred its claim) could leave the
thread "claimed by active work", rejecting compatible follow-ups until a
native background command ended.

Taken: the full extensions/codex production fix (client-runtime.ts,
thread-lifecycle-run.ts, thread-lifecycle-warm.ts), both regression suites
(thread-lifecycle.warm-cleanup.test.ts and .native.test.ts), their
registration in the database-worker extension path list (required for the
suites to run under their canonical extension-database-workers owner), the
release-only runtime inventory entry for the native suite, and the matching
CI planner test updates that keep that inventory consistent.

Left out: the .github/workflows/ci.yml fork failure-reporter checkout change
and test/scripts/ci-pr-failure-report.test.ts. They are an unrelated CI repair
bundled into the PR; the reporter script and its test do not exist on the
release branch.

Backport adaptation: thread-lifecycle-run.ts keeps this line's
withCodexThreadLifecycleBinding callback signature (assert, no authority
object) and wraps its result with the donor cleanupWarmBinding /
AggregateError recovery. In thread-lifecycle-warm.ts, releaseCodexBoundLiveThread
gains the protected-thread guard on both the refusal check and the retired
client release, without the donor's abort race on the retired exit. The
hoisted liveThreadEphemeralPolicy keeps this line's skillsInstructions field.
The cleanup(retainSubscription, ownership) closure is built from this
line's finally body (assertWarmOwner plus same-owner recheck, then
retainCodexAppServerBindingSubscription) rather than authority.withCurrent.
The donor's rotate-path preserveSubscription hunk is not taken: this line
clears the binding immediately on rotation instead of staging a replacement
that later releases the predecessor, so retaining the subscription there
would orphan it. For the same reason the protected-rotation test and
scenario are dropped. Both suites inject the failure by making the binding
store's withLease throw after the lifecycle published its warm binding,
since this line's resolveCodexSessionBinding has no authority.withCurrent
seam. The vitest database-worker path list gains only the two warm-cleanup
entries. To keep client-runtime.ts within its max-lines limit, the claimed
and protected predicates share one live-runtime mark helper; the claimed
predicate's behavior is unchanged.

Extracted-from: 31f23a54ecaa27012a78e5bfc3d9b54db83fe733
Co-authored-by: Dallin Romney <[email protected]>
(cherry picked from commit 7a37b9eeec47006c77f81e93191286be4460312f)

* fix(outbound): preserve live sends during recovery inspection (#169010) (2026.10.5 backport)

Startup and recurring delivery recovery took the in-memory per-entry claim
before reloading a row, so a live producer still awaiting its committed
enqueue reply lost its claim and failed with "Delivery intent is already
claimed", leaving the row stranded until its lease expired. Recovery now
skips rows with an active delivery owner before claiming them.

Backport: import-only conflicts in delivery-queue-recovery-policy.ts and
delivery-queue-recovery.ts because main's ambiguous-final-text replay
helpers (#168738) are not on the release branch; they were left out. The
onPending hook context from #169717 is also absent and not needed. The
shouldInspectQueuedDelivery policy and all three call sites are taken
verbatim, plus the regression test. Verified the new test fails on the
release branch without the fix ("Delivery intent is already claimed").

Extracted-from: f56818ae76ac1f4e0165b7fd78e7d25cf149236a
(cherry picked from commit f56818ae76ac1f4e0165b7fd78e7d25cf149236a)
(cherry picked from commit 949df7760ec5fbab21e2365a39a9cfa08809935e)

Backport adaptation: delivery-queue-recovery.ts keeps the extended-stable
resolveAttemptCount import alongside shouldInspectQueuedDelivery. The
integration test keeps the existing raw/prepared media custody test, adds
the startup/recurring live-producer regression, and adds the donor's
deliveryParams helper that the extended-stable test file lacked.

* fix(outbound): drop the unused storage re-export of hasActiveDeliveryOwner after the #169010 backport

(cherry picked from commit e83b02d2992ad31b7bce058ab4ba2d5d2f5b8827)

* fix(gateway): retain tool history details and channel startup context (#164848)

* fix(gateway): preserve tool history and channel startup context

* test(gateway): cover tool metadata and detached channel requests

---------

Co-authored-by: Sarah Fortune <[email protected]>
(cherry picked from commit b1880a04d182f9f719b7aaf3b9fb2da2c610be27)

Backport adaptation: prerequisite for #159396. Only the channel-startup
Gateway context binding (server-channels.ts, server-runtime-state-prepare.ts)
is taken; the tool-history display projection, its docs, and its tests are
left out. The channel-startup regression is carried by the #159396
backport's server-channels.request-scope.test.ts ("operator client" case).

* fix(gateway): channel tools fail with stale caller authority after a config write restarts the account (#159396)

* fix(gateway): channel tools fail with stale caller authority after a config write restarts the account

A channel account restarted by a config.patch/config.apply RPC inherited that
request's plugin runtime scope (client, hasCurrentClientAuthority, signal)
through AsyncLocalStorage. Every later inbound turn on that account then failed
its in-process Gateway tool dispatch with "Gateway caller authority is no longer
active." once the RPC connection closed.

Channel account monitors now keep the Gateway binding and plugin facts but drop
the request-owned authority and tool caller identity, matching how scheduled
work is detached.


* test(gateway): queue the request-scope inbound event without a real timer


* fix(gateway): preserve channel startup authority on current main

* test(gateway): prove channel authority expires with its caller

* fix: keep channel ingress independent of completed operator tools

* fix(gateway): detach account startup at its native owner

* test(gateway): isolate channel request authority regression

* test(gateway): remove extracted request fixture imports

---------

Co-authored-by: Dallin Romney <[email protected]>
(cherry picked from commit a4d915f206e196b35d89fc420fba89b571516be5)
(cherry picked from commit 0e78bb9d7303aa97221f4c6c58e691bcb418dd1d)

Backport adaptation: relies on the preceding #164848 channel-startup
context binding backport. server-channels.test.ts keeps the extended-stable
tests; the donor-only test it moved was never on this line. The new
request-scope test defines its registry/manager/abort helpers locally
because the extended-stable test-support lacks them, and imports
withOperatorToolGatewayAuthority from server-plugin-in-process-dispatch.js
(this line has no server-plugin-in-process-authority.js). Without the
server-channel-startup.ts change, the agent-run and operator-tool cases fail.

* fix(nodes): node requests fail with "pairing changed" after unrelated pairing activity (#169486)

* fix(nodes): keep unrelated node bindings across missed pairing revisions

A pairing lookup, pending read, or commit receipt that arrived with a
revision the publication cache had not seen cleared every cached device
binding. Every other node then failed its authority check with "Device
pairing authority requires a current worker publication", surfacing as
"node pairing changed before request dispatch" and as dropped
Gateway-to-node events.

Bindings are per-device facts refreshed by that device's own reads and by
commit receipts, so a missed revision now only marks the set incomplete;
full lists still replace it. Real unpair and token changes still install
their receipt row and retire the node connection.

Refs #166652

* test(nodes): keep pairing publication regression free of shared helper imports

* test(gateway): prove node delivery and refusal across missed pairing revisions

Drive the real Gateway and node WebSocket transport: an unrelated
missed-revision publication landing between a node's pairing lookup and
the synchronous re-check no longer blocks node.invoke delivery or the
node's own requests, while token revoke, token rotate, and unpair during
dispatch preparation still refuse the node before any invoke frame is
sent.

Refs #166652

(cherry picked from commit 2bb3dac0102688d6a8401fa15443baf7bdd21fc5)
(cherry picked from commit d794175485bbaa2e69d70566179f70291182d06b)

Backport adaptation: this line has no captured.nodes snapshot cache, so the
publication change drops those lines and keeps only the incomplete-marking
and receipt behavior. The unit regression seeds bindings with
listDevicePairing (readDevicePairingNodeSnapshot is absent here). The
Gateway regression matches the node-request authorization path by
server-methods.ts, which owns that check on this line instead of
server-methods/request-authorization.ts. Verified the Gateway regression
fails without the publication change.

* fix(nodes): node requests and events fail while another device's pairing is being written (#169575)

* fix(nodes): keep node authority readable during unrelated pairing writes

Any pairing mutation except three metadata types made
getPublishedPairedDeviceBinding throw for every device for the whole worker
round trip, so one device's token verification, reconnect, presence, or
metadata write failed every other node's dispatch and send-time checks.

Stored rows stay authoritative until COMMIT, and the first binding read after
COMMIT drains and installs the worker's receipt, so the in-flight fence
protected nothing. Drop it and the invalidatesAuthority distinction. Blocked,
epoch, and incomplete-row checks stay; Gateway revocations still retire live
transports through invalidateClientsForDevice.

* test(nodes): satisfy pairing mutation return checks

* test(nodes): prove node delivery during unrelated pending pairing writes

(cherry picked from commit e158fc392cc9ee13a8b71dbf7642ef6739283230)
(cherry picked from commit af004af351bf59f8fe04a742e51a2830f3dbf66f)

Backport adaptation: this line fences in-flight mutations with
captured.blocked ||= invalidatesAuthority instead of a mutation-scoped
flag, so beginMutation() takes no arguments and that line is dropped;
the worker still captures a publication for every mutation (no join-code
or bootstrap.prune exemption here) and calls beginMutation() with no
arguments. The donor prepareNodes snapshot cache is absent and left out.
The unit regression seeds bindings with listDevicePairing and holds the
writer through a runOpenClawStateWorkerOperation spy (no owner-probe
helper here). The Gateway regression's request leg cannot spy on
authorizeGatewayRequestPreDispatch (an intra-module call in
server-methods.ts here), so it instead proves the request reaches its
handler's pairing lookup while the unrelated write is held. Verified both
Gateway legs fail without the publication change.

* fix(acpx): ACP agents lose plugin and OpenClaw tools when acpx is installed as a separate package (#164272)

When ACPX was installed as a separate package rather than bundled with OpenClaw, it guessed the OpenClaw host root from its own location, which is outside the host tree. Both managed MCP bridges then failed with ERR_MODULE_NOT_FOUND and agents lost their bridge tools. For that external layout only, ACPX now locates the host by walking up from the real path of the running openclaw launcher to the package named openclaw. Bundled and source-checkout layouts resolve exactly as before. Proof: a real npm-installed packed OpenClaw, a separately packed ACPX, a symlinked launcher, an isolated Gateway and a fake ACP agent. On main the bridges exited with ERR_MODULE_NOT_FOUND; with the PR they completed stdio initialize and tools/list, and the agent received the bridge tools. Source and bundled root controls were unchanged. Fixes #164211. Thanks @jayzhou2309.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit 22d6c639c169ea8d4f77126c03dd5281a4720e18)
(cherry picked from commit e41b38e12c9ac360524e035263b41ab9dc541b38)

* fix(talk): prevent immediate consultation aborts after connecting (#170083) (2026.10.5 backport)

Talk consultations now take a detached independent root-work admission so a
later spoken request no longer inherits the completed voice-offer work scope
and its aborted signal.

Taken: src/gateway/talk/client-agent-consult.ts, the detachedWork option on
tryBeginGatewayIndependentRootWorkAdmission, and the regression in
src/gateway/talk/handlers/client-native-control.test.ts.

Left out: fixture realignments in server.talk-consult-history.test.ts,
openclaw-agent-worker-store.test.ts and the UI child-session e2e test. They
target main-only owners (runWithRetainedGatewayRootWork, paced session
refresh) that do not exist on the release branch and are not part of the fix.

Extracted-from: 90b37dff1523d3ad6eb00743df024747b35e63cb

Co-authored-by: Martin Cleary <[email protected]>
(cherry picked from commit fb14d0dd5ed0f8723c1f569780b735ef3c40a3e8)

Backport adaptation: client-native-control.test.ts takes only the new
consult-after-offer regression and its imports; the donor-only
transcript-close it.for block is not on this line.

* test(gateway): run Talk consult history publications outside the producer scope after the #170083 backport

(cherry picked from commit f0670cb8720b1b6ff01c2dbf4ca869ee2bd31cf5)

* test(gateway): publish native Talk transcript updates outside the producer scope after the #170083 backport

The #170083 backport (fb14d0dd5ed) moved Talk consultation onto detached Gateway-independent root work admission. client-native-actions.test.ts published committed transcript updates inside the consultation producer scope, so the producer drain aborted them (AbortError from AsyncWorkScope.beginClose; FRV run 38333371459, job 115088201415). Production already detaches these publications (src/gateway/server-runtime-subscriptions.ts, runOutsideAsyncWorkScope).

Port main's fixture fix from #170359 (a55e956fe36): wrap the listener publication in runOutsideAsyncWorkScope, keeping the explicit publication drain and rejection checks. Same root class as f0670cb8720.

(cherry picked from commit 9442ab7bd3673e9355915b288eb2a5a5f9afc977)

* fix(gateway): record cancellation before draining retained replies (2026.10.5 backport)

Session deletion could retire reply abortability before its canonical chat
controller recorded cancellation: the lifecycle drain aborted retained reply
operations (and the embedded run) inside the queued-abort callback, which runs
before the controller loop. chat.send controllers are abortable only while
their reply run is, so the controller abort was skipped and no canonical
"aborted" terminal with stopReason was published.

Taken: the ordering fix. Queue fencing stays before controller cancellation;
exec-command cancellation moves after the controller loop; embedded and
retained-reply aborts move to the existing onCancellationStarted hook. Adds
main's "delete drain records cancellation before settling a retained reply"
regression adapted to the branch drain signature (no timeoutMs, plain session
seed); the controller case fails without the fix.

Left out: the captured embedded drain-target receipt join
(captureEmbeddedRunDrainTarget/isAborted), onAuthorizedBeforeEmbeddedAbort
and stopEmbeddedRun hooks, and agents-delete-drain test changes, which depend
on main-only #168199/#168080; and the built-CLI flip-proof assertion restore,
since the branch helper never relaxed it.

Extracted-from: 6bb8525d548881f86d550f5476a4f804b77daed6
(cherry picked from commit 9564061ab79c433d2d0c9f3fc902e3ccd579a8cb)

Backport adaptation: chat-abort-runtime.ts is unchanged; this line's
prepareChatSessionAbort has no exec-command (commands.cancel) cancellation
to reorder. In sessions-lifecycle-drain.ts the queued-abort callback keeps
only clearSessionQueues; the embedded abort and this line's retained reply
aborts (replyRunRegistry.abort per key, abortReplyRunBySessionId) move into
the existing onCancellationStarted hook, each after authorize?.(). Verified
the controller regression fails without the drain change.

* fix(agents): deliver blocking questions from routed turns (#170039)

* fix(agents): deliver questions from routed agent turns

* docs(agents): explain question delivery for routed turns

(cherry picked from commit e163d81940e34518eac3ce7d52338a38a1fc640c)
(cherry picked from commit 856e0353eca3ab565de50b3d634ebd83c3b4784f)

Backport adaptation: run-attempt-dispatch.ts keeps this line's progress
controller wrapper but passes it only when the caller supplied
onToolResult, so routed turns without a reply sink no longer reserve a
prompt nobody delivers. openclaw-tools.ts creates ask_user and secrets
separately here, so both creators take the originating-channel sender
(options.questionPrompt override first) from one local resolver built from
the existing delivery options; tool-resolution.ts drops its
Gateway-only sender. The extended-stable tool-resolution test that
asserted that sender now asserts the delivery facts handed to the tool
surface.

* test(agents): prove routed turns deliver blocking questions after the #170039 backport

Routed turns (Gateway agent method with a channel target) carry no reply
sink, so ask_user must publish its own prompt to the originating
conversation. The regression builds the real OpenClaw tool surface with
routed-turn delivery options and executes ask_user against a stubbed
question Gateway and durable channel sender. It fails without the
#170039 backport (no prompt is sent).

* fix(cron): failed one-shot automations are never silent (#169102) (extracted hotfix)

A one-shot that failed terminally (permanent failure or exhausted retries)
was disabled without any notice: failure alerts waited for the
consecutive-failure threshold and the owner-conversation repair skipped
disabled jobs. A terminal one-shot now notifies on that failure: owned jobs
get a repair turn in the owner conversation with a terminal brief, falling
back to the normal failure alert if that turn cannot start; unowned jobs get
the normal alert. Opt-outs, best-effort, and cooldown policy are unchanged;
recurring jobs keep their threshold.

Taken: failure-alerts.ts, failure-repair-brief.ts, notification-dispatch.ts,
notification-intents.ts, their regressions (service.failure-repair.test.ts,
failure-alert test helper, one-shot lifecycle test) and the matching
delivery.md paragraphs. The branch already carries the cron error
classification part as 568fec865a2c. Left out: validator message rewrites,
CLI add/edit validator delegation, automations/github_publish model-facing
description changes, prompt snapshots, and payloads.md guidance; the
one-shot lifecycle test keeps the branch's existing validator messages.

Extracted-from: 78d72c97a85c9e16a0ac17edb7a91b5f246a12fc
Co-authored-by: Peter Steinberger <[email protected]>

(cherry picked from commit 8c73c69b5ff8f502e83e84955477a4ddd04465cb)

Backport adaptation: the owner-conversation failure-repair feature is absent
on 2026.9.33, so every repair hunk is dropped (failure-repair-brief.ts,
service.failure-repair.test.ts, the failure-repair notification intent and
dispatch, the repair test-helper wiring, and the repair docs). Only the
alert path is kept: a one-shot that is disabled after a terminal error now
bypasses the consecutive-failure threshold (default 2) in
maybeEmitFailureAlert, so it is never silent. Routes, opt-outs, best-effort,
and cooldown policy are unchanged; recurring jobs keep their threshold. The
one-shot lifecycle regression is taken unchanged; delivery.md gets an
alert-only paragraph.

* test(cron): distinguish cancellation output from failure alerts after the #169102 backport

The #169102 backport (8c73c69b5ff8) makes a terminally failed one-shot send a
failure alert. server-cron's cancelled-command test runs such a one-shot, so
it now sees the cancelled completion plus that intended alert (2 sends, not
1); bisect over 467e83dea27..e83b02d2992 lands on 8c73c69b5ff8. Takes main's
companion test change unchanged: assert the aborted completion and the
independent alert separately, keeping the no-retry guarantee and the disabled
error state. No production change.

Extracted-from: ddea57545b784eab1c5498754bc6254f293fe8d5
Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit a27197f6bc7a4540fc2917cc3d3082b0eedb93a6)

Backport adaptation: 2026.9.33 still carries the "one-shot retry" case in
timer.pacing.test.ts (the source line removed it earlier), and that case is
another terminally failed one-shot. It now expects the auto-disabled notice
plus the intended failure alert (two system events, one coalesced
heartbeat); the recurring scenarios keep a single notice.

* fix(cron): stop holding the state writer while waiting on host admission (#168291) (2026.10.5 backport)

Cron runtime mutations made synchronous host-admission round-trips inside their SQLite write transactions; with a busy Gateway main thread the cron startup catch-up held the shared-state writer for 107 s, so a concurrent update failed with database is locked. Cron's in-transaction prepare and commit admissions now opt into a 1,000 ms deadline: on timeout the transaction rolls back and releases the writer, late host grants are rejected atomically, and cron retries through its existing scheduler with a warning. All other worker admission callers keep their unbounded wait. Refs #168072. Reported by @jlapenna.

Backport: taken are the opt-in deadlineMs admission request field, the
TIMED_OUT decision with host-side expiry checks and late-port closing, the
deadline-bounded worker wait loop, SqliteWorkerAdmissionTimeoutError in the
worker contract plus its broker reply decoding, cron's 1,000 ms opt-in in
runtime-mutation.worker.ts, the onTimer and startup retry handling, both
regression suites, and the worker-access doc paragraph. Left out: main's
mechanical move of the database-facts relay into
sqlite-worker-database-admission-relay.ts (and its import-only caller
updates, wrapper-components and max-lines baseline entries); the branch
keeps the relay in sqlite-worker-operation-admission.ts. The refusal type
widening lands on the branch's SqliteWorkerOperationContext, which still
lives in the admission module, and the timeout test imports
settleSqliteWorkerOperationContext from there.

Extracted-from: 8b677154aef03278c14100a8dca7c629a8b1b4cb
Co-authored-by: Peter Steinberger <[email protected]>

(cherry picked from commit 854be9f060958cedfbd69156b021cd9196bb1ba8)

Backport adaptation: 2026.9.33 has no cron schedulerScope, no
currentSqliteOperationTiming, and no cron receipt-authority helper. The
startup retry schedules through state.deps.scheduler and startOnce drops
the scope renewal; runInDetachedAsyncContext comes from
shared/async-work-scope.js; the commit-stage request keeps T's
deferSqliteWorkerCommitReceipt(db, { nonce }) and only adds deadlineMs.
In the a…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui cli CLI command changes commands Command implementations 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. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant