Skip to content

fix: let Gateway updates restart without locking the state store - #204868

Merged
obviyus merged 14 commits into
mainfrom
fix/store-exclusive-custody
Nov 25, 2026
Merged

obviyus merged 14 commits into
mainfrom
fix/store-exclusive-custody

Conversation

@obviyus

@obviyus obviyus commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #204704

What Problem This Solves

A release switch can replace or restore SQLite files while the previous Gateway or initiating CLI still holds them. On Windows this can prevent every new Gateway from starting with EPERM on openclaw.sqlite-wal. A restart can also keep waiting after its trial has already committed.

User Impact

Release switches wait for the old readers to close. An adopted package's committed trial ends gateway restart without requiring an operator-scoped health RPC. A connected CLI without operator.read gets a distinct diagnostic and a clear next step, not a false startup timeout.

If an unmanaged foreground launcher dies before readiness, the old runtime exits with an error and prints openclaw gateway as the recovery command. It does not reopen a store that the launcher may have migrated. A live launcher remains the only recovery owner.

Why This Change Was Made

The existing shared-state close owner now joins native consumers and retires retained file-identity descriptors before custody transfers. The Gateway completes its boot record and closes shared state before releasing its lock; process cleanup and a final custody close precede a standalone launcher spawn. The retiring Gateway's readiness observer uses only HTTP and captured configuration; its sentinel reads/writes and in-process fallback after spawning a launcher are gone.

Restart observers use file-lock identity, native process/listener information, HTTP and RPC instead of opening the store to inspect migration and owner leases. A live file owner retains bounded startup grace during a long migration. The update CLI releases custody at its existing pre-dispatch boundary, and the adopted-result waiter consumes the terminal phase at the sole trial path: update preparation already serializes active trials under the update lock.

No schema, launcher protocol or public Plugin SDK API changes. The private QA startup collector retains its closed-fixture lease check on its existing connection.

Service-definition repair publishes its planned command/environment and effective configuration after token preparation but before activation. Start and restart observers consume those facts instead of reopening SQLite to recapture repaired credentials or arguments. Windows captures its command once before /Run, retires preflight custody through the existing caller hook, and uses bounded file/process observations afterward.

Evidence

  • On source baseline 33586124338a, regressions fail for retained identity descriptors, an early-returning one-shot reader, RPC access after a committed trial, scope denial reported as a timeout, and a retiring successor observer reopening state.
  • The reported Linux external holders and Windows native ARM64 WAL/EPERM failures are retained base evidence; they were not repeated just to confirm them.
  • Earlier affected AWS gate on c698a589b131 passed (run_8c5f0a8b1085ed134733db543b577cc2): seven Vitest shards in 189.73s, targeted types/lint and ratchets. This remains prior-head evidence, not final platform proof.
  • The first Windows head (f798ffc61fd9) was red: npm exited0, restart exited1 after728.479s and nothing served; signed Handle matched the initiating CLI to control/shared/quarantine SQLite. Final stable-path evidence is below; the separately reproduced repair-path gap is explicitly tracked.
  • Test growth after consolidation and the requested recovery regression is 848 net lines against the PR's base; the approved 448-line allocation covers the distinct contracts itemized below. No behavioral assertion is weakened.
  • Platform packages/proofs use source 21066b69471a1998505bac4ee4758e2138694d33, rebuilt after the required main merge (including inherited WAL/state-upgrade changes). Later changes are the status-test warning correction and the narrowly guarded SQL-free stale-listener recovery fix, qualified by124 focused pinned-Bun consumer tests/typed lint. The platform recordings do not claim to exercise that legacy recovery branch or byte-equivalence with the later head.
  • Linux crash/restore PASS — AWS run run_ae3ce038d7ae16a26540b0d69c956015,201.82s:10 publication and6 restore snapshots, zero external native/identity holders and zero scan errors, all four families present. RestoredT served with its exact identity, read the persisted cron sentinel over RPC, and all live integrity checks passed. Actual update row finished/failed (expected injected crash); CLI settled exit1. No harness recovery. Receipt archive SHA256 68973c89550142131208d65ca7de293b18bd9dcbfaa785a92f0e28831893766f.
  • Windows native ARM64 stable-path PASS — npm0; restart0 on its own in107.673s; exact2106 RPC version/build with connected_no_operator_scope; store read passed; complete17-file scan found no EPERM. Stable archive SHA256 260da7b92739a2444678d1bb61dbceb679f4aeae6f3400cc21a9032d52092906.
  • Borrow qualification run_ec051c902d31b5c93086dcbbfde87d1b passed Node37 tests, process4 tests (including real watchdog SIGKILL and successor), and pinned Bun77 tests/1 skip. Test types and numeric guards passed. Its two static failures were a mistakenly removed required import and a stale inline suppression; both are corrected without changing borrower behavior.
  • Both Node and pinned Bun fail the unlinked-path regression on b8ee (run_40c6e4e508e393b27716dc57072b0a88). Registry-owner fix eeee passes Node cache/lock35 tests, pinned Bun cache10 tests, and original failing files/lock114 tests with21 skips (run_2844130f72a5635dadfbce107f8cd587). None of the six Bun failures needed a fixture expectation change.
  • Final head da4ee212087163db858e1472f9052fd270d02f97 local review completed: patch correct, zero findings. The additional legacy-recovery guard/fixtures pass124 pinned-Bun consumer tests and targeted typed lint; migrating/healthy/unknown/foreign negative guards remain intact.
  • Inherited CI timing note: fix: release pressured background integrity readers #204943's Bun checkpoint assertion failed in a prior CI shard. The one identical-test/identical-pinned-Bun comparison on current main094e225 and head3c43 both passed (run run_adc41ae48859bff924ccce98fb5a2119); no expectation/source change was made for it. Maintainer owns its once-only diagnostic rerun and owner routing; passing again is not claimed as a fix.
  • The approved narrow run-loop cap is1238 counted lines: inherited1235 plus the stop-budget custody join and restored required import. The cohesive persistence/custody-release block moved to run-loop-cleanup.ts; the old inline suppression and its inventory entry are removed.

The original malformed-database report remains ground truth, but its physical corruption mechanism was not established. This change removes the proven unsafe custody handoff; it does not claim to identify a corrupt SQLite page.

Known Edge Cases

If a second update prepares in the short window after the first commits but before its CLI reads the trial, the first command can report the second outcome or wait until its deadline; both are visible, and openclaw update status shows the true runs.

Windows coverage limit, explicitly accepted for this native-install cell: its actual tree is task supervisor → job anchor → cmd → Gateway, not a converted resident release launcher. No wrong process was killed and no launcher-manager recovery is claimed. The converted-install manager-cut cell belongs to the full matrix after#204866; it is not proven here.

Open reproduced repair gap: #205035. TEMP-prefix service repair is not a pass: on source2106, npm0/346.427s, restart self-exit1/512.647s, target never ready, repeated EPERM publishing control/services.sqlite. Original archive SHA256 29be88bba446d938eebe3dd4305f5b49c3248523b2096062c9a7cc09145fac5a. A fresh diagnostic captured the restart CLI child node.exe PID1652/handle3E8 on that file104ms after the first error, while alive; live archive SHA256 161ea7d9034b0a96294f37286f9473cf054c8599cd2ab14c9325b5ca73082f23. Both source/target were non-readonly with FullControl ACLs. The post-native-install runtime-pin read (service.ts:410–420→runtime-pin-store.ts:83–98) and publication rename (state-upgrade-tree.ts:627) already exist on main; no repair fix or success is claimed here. Maintainer explicitly accepts landing this PR with that named gap, owned by the next repair-producer change.

Backport

release/2026.11.15 (f1debfde108a) needs the custody correction: Gateway/resource retirement before lock transfer, file/HTTP-only restart observation, and CLI reader release. The serving Gateway must contain its part; a candidate cannot close an older process's handles. That release has no package-adoption waiter, so the terminal-trial waiter change is not part of the smallest backport. No backport PR was opened.

Test Cost and Necessity

Compared with PR base 1bec22471ad0: 848 net test/support lines; 448 allocated above the 400-line allowance. Shared full-lock/process fixtures removed39 lines, retained child diagnostics add9. The final +33 lines are the requested stale-owner regression (+28) and verified-owner caller migration (+5), explicitly approved.

The orphan-FD case stays at the cache boundary: its native owner and admission record are already gone. The full-lock matrix instead retains a live borrower and must preserve Gateway exclusion. Combining those different states would obscure which owner failed. Repair producer, native dispatch, and caller-result tests likewise exercise different boundaries.

All changed test/support files are listed; +/- counts include helper cost and deletions:

File + / - Contract or required migration
src/cli/daemon-cli/diagnostic-readiness.test.ts 9 / 15 Existing diagnostic consumers use file/HTTP snapshots.
src/cli/daemon-cli/lifecycle-core.test.ts 51 / 22 Async drain ordering and refusal before native dispatch.
src/cli/daemon-cli/lifecycle-readiness.test.ts 92 / 2 Captured facts and pre-activation readiness ownership.
src/cli/daemon-cli/lifecycle.test.ts 40 / 17 Repaired facts reach callers without reopening stores.
src/cli/daemon-cli/restart-health-deadline.test.ts 3 / 3 Existing deadline fixture cutover.
src/cli/daemon-cli/restart-health-probe.test.ts 80 / 2 Scope denial settles distinctly without polling.
src/cli/daemon-cli/restart-health-progress.test.ts 77 / 1 Long migration remains protected; verified stale stopped-listener recovery remains reachable without SQL.
src/cli/daemon-cli/restart-health-wait.test.ts 10 / 26 Bounded waits replace DB migration polling.
src/cli/daemon-cli/restart-health.test-helpers.ts 0 / 3 Remove obsolete DB observer mock.
src/cli/daemon-cli/restart-health.test.ts 25 / 19 Existing restart fixtures consume file-only observations.
src/cli/daemon-cli/start-repair.test.ts 57 / 4 Producer publishes prepared auth/command facts before activation.
src/cli/gateway-cli/run-loop-mocks.test-support.ts 6 / 30 Remove sentinel/fallback mocks; retain launcher owner.
src/cli/gateway-cli/run-loop-natural-exit.test-support.ts 9 / 5 Lifecycle cleanup ordering fixtures.
src/cli/gateway-cli/run-loop-restart-ownership.test-support.ts 1 / 1 Existing restart owner fixture cutover.
src/cli/gateway-cli/run-loop-stop.test-support.ts 10 / 8 Stop/flush ordering fixture cutover.
src/cli/gateway-cli/run-loop-update-respawn.test-support.ts 14 / 31 Launcher failure replaces competing in-process recovery.
src/cli/gateway-cli/run-loop.direct-stop-active-work.process.test.ts 143 / 32 Existing signal cases plus real stuck-borrow watchdog exit and successor.
src/cli/gateway-cli/run-loop.test-support.ts 6 / 25 Remove retired successor sentinel behavior.
src/cli/gateway-cli/run-loop.test.ts 12 / 21 Launcher death exits visibly without reopening state.
src/cli/gateway-cli/update-successor.test.ts 36 / 0 Successor readiness never reopens shared state.
src/cli/update-cli/update-command-readiness.windows.test.ts 0 / 1 Remove obsolete observer mock.
src/cli/update-cli/update-command-verification.test.ts 11 / 6 Preserve switched-release recovery outcomes and negative guards with correct file-owner lifetimes.
src/commands/doctor-config-preflight.admission.process.test.ts 2 / 2 Offline lease-inspector migration.
src/commands/doctor-config-preflight.pending-read.test.ts 2 / 1 Offline lease-inspector migration.
src/commands/doctor-config-preflight.plugin-persistence.test.ts 3 / 2 Offline lease-inspector migration.
src/commands/doctor-config-preflight.pristine.process.test.ts 2 / 5 Offline lease-inspector migration.
src/commands/doctor-config-preflight.test.ts 2 / 2 Offline lease-inspector migration.
src/commands/health.test.ts 24 / 0 CLI reports reached/scope denial, not timeout.
src/commands/startup-config-preflight.native-bootstrap.test.ts 2 / 2 Offline lease-inspector migration.
src/commands/startup-config-preflight.recovery.test.ts 4 / 3 Offline lease-inspector migration.
src/commands/status.scan.shared.test.ts 25 / 1 Status preserves reached/no-scope capability and both warnings without another probe.
src/daemon/schtasks-runtime-definition.test.ts 54 / 5 Captured command and exact file/PID/port observations avoid SQL.
src/daemon/schtasks.start.test.ts 24 / 0 Existing effect hooks can refuse before Scheduled Task Run.
src/infra/gateway-lock.test.ts 127 / 1 Shared/control/agent physical custody; immediate/borrowed handoff matrix.
src/infra/startup-migration-checkpoint.test-support.ts 35 / 0 Offline-only inspector replaces removed production observer.
src/infra/startup-migration-checkpoint.test.ts 6 / 14 Inspector moved without losing lease assertions.
src/state/openclaw-state-db-cache.cleanup.test.ts 38 / 1 Unlinked, recordless identity FD closes physically.
src/state/openclaw-state-read-source.test.ts 50 / 2 Successful one-shot CLI reads join native worker exit.
src/update/cli.test.ts 95 / 25 File-only terminal trial/deadline and pre-dispatch custody refusal.
test/scripts/ci-workflow-guards.test.ts 5 / 4 Required healthy/crash lane selection and artifacts.
test/scripts/doctor-config-preflight-plugin-index.built-cli.e2e.test.ts 2 / 2 Remaining offline inspector caller migration.

- Join native readers and identity descriptors before state-store custody transfers.
- Observe retiring successors over HTTP and adopted outcomes from the launcher trial.
- Distinguish connected clients without operator scope from startup failures.

Closes #204704
@clawsweeper

clawsweeper Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation cli CLI command changes commands Command implementations size: XL labels Nov 24, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 24, 2026
@clawsweeper

clawsweeper Bot commented Nov 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR closes state-store readers before Gateway version switches and follows launcher trial outcomes without operator-scoped health access.

Example: Windows npm adoption activates 2026.11.11-petty.0 and commits its trial.

  • Before: The restart CLI remains alive despite the replacement Gateway serving successfully.
  • After: The restart CLI completes from the matching committed trial without requiring operator.read.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The ownership repair is useful and focused, but two diagnostic defects remain and required runtime behavior is unproven.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) 2 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: A successful Windows Gateway activation can leave restart waiting and health reporting a startup timeout.
Reason: The source-pinned report establishes user value, and the maintainer-authored direction reuses existing custody and trial owners; the ready-Gateway diagnostic remains incomplete.

Merge readiness

⛔ Needs changes before merge - 3 items remain

Keep this PR open: it addresses a confirmed Windows maintenance failure, but the ready-Gateway scope diagnostic and adopted rollback message need correction.

Priority: P2
Reviewed head: f798ffc61fd946df6a6545c6752e326464eca82f

Before merge

  • Preserve the scope diagnostic when HTTP readiness succeeds (P2) - For the reported case where hello succeeds without operator.read and /readyz returns 200 with ready=true, confirmGatewayReachable sets both operatorScopeWarning and reachable=true. The wait then returns waitOutcome='healthy' before its missing-scope branch. This condition consequently skips the new explanation, and healthCommand sends another health RPC that fails with the original raw scope error, losing the promised connected-state explanation and recovery command. Handle the recorded scope warning here even when readiness is healthy, while retaining healthy restart behavior.
  • Give adopted rollback failures an actionable next step (P2) - When an adopted candidate crashes twice or refuses configuration, the launcher records reasons such as 'new build failed to start'. This replacement now returns only 'Update failed: new build failed to start'; both lifecycle callers pass it to fail without hints. The previous formatter included the recorded outcome and recovery advice. Preserve the database-free waiter, but explain that activation rolled back and direct the user to openclaw update status for the result and recovery details; do not claim the restored Gateway is ready solely from this phase.
  • Complete next step - The PR author must resolve the GitHub-reported merge conflict while preserving current-main update behavior.

Findings

  • [P2] Preserve the scope diagnostic when HTTP readiness succeeds — src/commands/gateway-diagnostic-readiness.ts:27-30
  • [P2] Give adopted rollback failures an actionable next step — src/update/cli.ts:107-108

Tests

  • Missing end-to-end proof: Provide redacted shipped-entry-point evidence for committed-trial restart exit, readyz-200 scope denial, and crash-after-migration recovery, including the update contract's platform and latest-stable upgrade requirements.
Agent review details

How this fits together

Gateway lifecycle commands coordinate native services, database custody, and release launchers; they consume ownership and trial observations and return restart or diagnostic results.

flowchart TD
  A[Update or restart CLI] --> B[State custody close owner]
  B --> C[Native service or launcher]
  C --> D[Replacement Gateway]
  C --> E[Trial file]
  D --> F[HTTP and RPC observations]
  E --> A
  F --> A
Loading

Technical review

Best possible solution:

Keep the existing custody and launcher owners, preserve scope diagnostics across healthy readiness results, and add actionable rollback guidance without reopening SQLite.

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

The linked report pins a repeatable Windows scenario, and source inspection establishes both diagnostic findings; this read-only review executed no target code.

Is this the best way to solve the issue?

Closing readers through the existing lifecycle owner and following the launcher's trial directly address the stated boundary, but the diagnostic consumers must preserve the resulting scope warning and recovery advice.

Full review comments:

  • [P2] Preserve the scope diagnostic when HTTP readiness succeeds — src/commands/gateway-diagnostic-readiness.ts:27-30
    For the reported case where hello succeeds without operator.read and /readyz returns 200 with ready=true, confirmGatewayReachable sets both operatorScopeWarning and reachable=true. The wait then returns waitOutcome='healthy' before its missing-scope branch. This condition consequently skips the new explanation, and healthCommand sends another health RPC that fails with the original raw scope error, losing the promised connected-state explanation and recovery command. Handle the recorded scope warning here even when readiness is healthy, while retaining healthy restart behavior.
    Confidence: 0.98
  • [P2] Give adopted rollback failures an actionable next step — src/update/cli.ts:107-108
    When an adopted candidate crashes twice or refuses configuration, the launcher records reasons such as 'new build failed to start'. This replacement now returns only 'Update failed: new build failed to start'; both lifecycle callers pass it to fail without hints. The previous formatter included the recorded outcome and recovery advice. Preserve the database-free waiter, but explain that activation rolled back and direct the user to openclaw update status for the result and recovery details; do not claim the restored Gateway is ready solely from this phase.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.94

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared-state handle retirement keeps the original intent (8132c7c: Retain database handles until their native workers close.)
  • Restart ownership and startup grace keeps the original intent (5469328: Preserve verified live Gateway owners through restart and stale-process cleanup.)
  • Foreground successor observation and recovery changes intended behavior with a stated reason (9b3f350: Keep foreground updates recoverable while replacing the running runtime.)
  • Installed-package adoption outcome following changes intended behavior with a stated reason (d761611: Apply newer npm installs through managed activation and distinguish successful activation from rollback.)
  • One-shot versus retained state readers keeps the original intent (0873425: Use isolated asynchronous readers for cold CLI preparation while preserving warm Gateway reader reuse.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/commands/health.test.ts src/cli/daemon-cli/restart-health-probe.test.ts src/update/cli.test.ts --maxWorkers=1
  • pnpm check:changed --base 3358612
  • git diff --check

What I checked:

  • Confirmed Windows report: DonnieFi reports committed prepared-release and npm-adoption trials with the Gateway serving, lingering restart CLIs, and health timeouts while readyz returned 200; obviyus confirms the verification problem in the discussion.
  • Pinned custody correction: The introduced diff joins native shared-state cleanup and retires admission descriptors before releasing Gateway custody. (src/state/openclaw-state-db-cache.ts:660, f798ffc61fd9)
  • Ready-Gateway diagnostic mismatch: A missing-scope response plus readyz success sets reachability true; the wait returns healthy before its missing-scope branch, while the diagnostic adapter recognizes only the missing-scope wait outcome. (src/commands/gateway-diagnostic-readiness.ts:27, f798ffc61fd9)
  • Rollback guidance regression: The adopted-result waiter returns only the launcher reason on rollback; the launcher can supply the generic reason 'new build failed to start', and lifecycle callers emit that string without additional hints. (src/update/cli.ts:108, f798ffc61fd9)
  • Supplied proof: The PR reports baseline-failing regressions and passing affected-consumer checks, but explicitly marks Linux crash-after-migration and native Windows npm-global/restart proof pending. (f798ffc61fd9)
  • Current main still needs the repair: Fetched main retains the previous adopted-result implementation, including ledger access and RPC-based outcome following. (src/update/cli.ts:94, ffa7d7459639)

Likely related people:

  • Ayaan Zaidi: Raw commit d761611 adds src/update/cli.ts:68 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d7616118b058; files: src/update/cli.ts)
  • Peter Steinberger: Raw commit dd0d1e5 adds src/state/openclaw-state-db-cache.ts:563 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: dd0d1e5641ce; files: src/state/openclaw-state-db-cache.ts)

PR surface

Source +46, Tests +324, Docs +11. Total +381 across 59 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 27 390 344 +46
Tests 31 586 262 +324
Docs 1 11 0 +11
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 59 987 606 +381

Preflight source

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

Root-cause cluster

Relationship: same_root_cause
Canonical: #204704
Summary: This PR implements the restart-wait and scope-diagnostic repair requested by the canonical Windows report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add P2: The confirmed Windows restart and health commands stall or misreport readiness while the replacement Gateway continues serving.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: The confirmed Windows restart and health commands stall or misreport readiness while the replacement Gateway continues serving.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

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

Reviewed November 24, 2026, 3:09 PM ET / 20:09 UTC.

@THE-NAVVV THE-NAVVV left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

​

@openclaw-barnacle openclaw-barnacle Bot reopened this Nov 24, 2026
- Bind native readiness to the command captured before activation.
- Use verified file ownership for Scheduled Task observation instead of SQL leases.
- Cover shared, control and agent descriptor retirement through the canonical close owner.
- Enforce the strict crash-after-migration survivor case in CI.
- Return the planned command, environment and prepared auth configuration from service repair.
- Build observation context from those facts without post-activation SQL reads.
- Preserve generated-token and managed-environment semantics.
- Correct mock loading and file-owner observation regressions.
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime scripts Repository scripts docker Docker and sandbox tooling labels Nov 24, 2026
Thread the existing custody callback through native command capture and service repair activation; retain captured file/process observations afterward.
Normalize planned repair snapshots and wait on the sole serialized trial outcome without reopening state.
Move lifecycle options and service hints to their existing sibling owners; record the exact regression test-line allocation.
Accept synchronous or asynchronous mutation hooks consistently in the generic service guard and systemd activation contract.
Expose a verified same-profile stale listener only after a confirmed native stop and explicit stale RPC refusal; keep live migration, healthy, unknown and foreign ownership protected.
Correct stopped-process file-owner fixtures and retain all recovery/negative outcomes; add the SQL-free reachability regression.
124 pinned-Bun consumer tests and targeted typed lint pass; record the approved regression allocation.
@obviyus

obviyus commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the only red, checks-node-changed-compact-small-10 (both attempts of run 45532692545), is 2 cases of src/cli/gateway-cli/pre-bootstrap.process.test.ts ("prepares recovery safely for future backup before reset" / "... after config selection changes", expected exit 1, got 0). This PR does not touch that test or pre-bootstrap.ts. Reproduced locally with the same 2 failures on plain main 230456c, on this head alone and on this head merged with that main, so it is a main regression from #204961 in startup config recovery, owned and being fixed there. Everything else on da4ee21 is green.

@obviyus
obviyus merged commit e77d359 into main Nov 25, 2026
323 of 330 checks passed
@obviyus
obviyus deleted the fix/store-exclusive-custody branch November 25, 2026 03:35
@obviyus

obviyus commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

Landed as e77d359. Updating a Gateway no longer leaves the restart CLI or the stopped Gateway holding the state store: custody is retired before the swap, readiness is observed without SQL, and a stale listener whose verified file-lock PID matches is cleaned up again. Proof: Linux crash-after-migration run (exit 0, all 4 stores passed integrity), Windows stable restart exited 0 in 108 s, and 124 tests on the pinned Bun. Known gap: the Windows repair path with a temporary prefix, where the restart CLI itself holds control/services.sqlite during the rename, is tracked in #205035 (it exists on main before this change).

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

Closes openclaw#204704

## What Problem This Solves

A release switch can replace or restore SQLite files while the previous Gateway or initiating CLI still holds them. On Windows this can prevent every new Gateway from starting with `EPERM` on `openclaw.sqlite-wal`. A restart can also keep waiting after its trial has already committed.

## User Impact

Release switches wait for the old readers to close. An adopted package's committed trial ends `gateway restart` without requiring an operator-scoped health RPC. A connected CLI without `operator.read` gets a distinct diagnostic and a clear next step, not a false startup timeout.

If an unmanaged foreground launcher dies before readiness, the old runtime exits with an error and prints `openclaw gateway` as the recovery command. It does not reopen a store that the launcher may have migrated. A live launcher remains the only recovery owner.

## Why This Change Was Made

The existing shared-state close owner now joins native consumers and retires retained file-identity descriptors before custody transfers. The Gateway completes its boot record and closes shared state before releasing its lock; process cleanup and a final custody close precede a standalone launcher spawn. The retiring Gateway's readiness observer uses only HTTP and captured configuration; its sentinel reads/writes and in-process fallback after spawning a launcher are gone.

Restart observers use file-lock identity, native process/listener information, HTTP and RPC instead of opening the store to inspect migration and owner leases. A live file owner retains bounded startup grace during a long migration. The update CLI releases custody at its existing pre-dispatch boundary, and the adopted-result waiter consumes the terminal phase at the sole trial path: update preparation already serializes active trials under the update lock.

No schema, launcher protocol or public Plugin SDK API changes. The private QA startup collector retains its closed-fixture lease check on its existing connection.

Service-definition repair publishes its planned command/environment and effective configuration after token preparation but before activation. Start and restart observers consume those facts instead of reopening SQLite to recapture repaired credentials or arguments. Windows captures its command once before `/Run`, retires preflight custody through the existing caller hook, and uses bounded file/process observations afterward.

## Evidence

- On source baseline `e147cdfe6e38`, regressions fail for retained identity descriptors, an early-returning one-shot reader, RPC access after a committed trial, scope denial reported as a timeout, and a retiring successor observer reopening state.
- The reported Linux external holders and Windows native ARM64 WAL/`EPERM` failures are retained base evidence; they were not repeated just to confirm them.
- Earlier affected AWS gate on `c698a589b131` passed (`run_8c5f0a8b1085ed134733db543b577cc2`): seven Vitest shards in 189.73s, targeted types/lint and ratchets. This remains prior-head evidence, not final platform proof.
- The first Windows head (`f798ffc61fd9`) was **red**: npm exited0, restart exited1 after728.479s and nothing served; signed Handle matched the initiating CLI to control/shared/quarantine SQLite. Final stable-path evidence is below; the separately reproduced repair-path gap is explicitly tracked.
- Test growth after consolidation and the requested recovery regression is 848 net lines against the PR's base; the approved 448-line allocation covers the distinct contracts itemized below. No behavioral assertion is weakened.
- Platform packages/proofs use source `21066b69471a1998505bac4ee4758e2138694d33`, rebuilt after the required main merge (including inherited WAL/state-upgrade changes). Later changes are the status-test warning correction and the narrowly guarded SQL-free stale-listener recovery fix, qualified by124 focused pinned-Bun consumer tests/typed lint. The platform recordings do not claim to exercise that legacy recovery branch or byte-equivalence with the later head.
- **Linux crash/restore PASS** — [AWS run `run_ae3ce038d7ae16a26540b0d69c956015`](https://crabbox.openclaw.ai/portal/runs/run_ae3ce038d7ae16a26540b0d69c956015),201.82s:10 publication and6 restore snapshots, zero external native/identity holders and zero scan errors, all four families present. RestoredT served with its exact identity, read the persisted cron sentinel over RPC, and all live integrity checks passed. Actual update row finished/failed (expected injected crash); CLI settled exit1. No harness recovery. Receipt archive SHA256 `68973c89550142131208d65ca7de293b18bd9dcbfaa785a92f0e28831893766f`.
- **Windows native ARM64 stable-path PASS** — npm0; restart0 on its own in107.673s; exact2106 RPC version/build with `connected_no_operator_scope`; store read passed; complete17-file scan found no EPERM. Stable archive SHA256 `260da7b92739a2444678d1bb61dbceb679f4aeae6f3400cc21a9032d52092906`.
- Borrow qualification `run_ec051c902d31b5c93086dcbbfde87d1b` passed Node37 tests, process4 tests (including real watchdog SIGKILL and successor), and pinned Bun77 tests/1 skip. Test types and numeric guards passed. Its two static failures were a mistakenly removed required import and a stale inline suppression; both are corrected without changing borrower behavior.
- Both Node and pinned Bun fail the unlinked-path regression on b8ee (`run_40c6e4e508e393b27716dc57072b0a88`). Registry-owner fix eeee passes Node cache/lock35 tests, pinned Bun cache10 tests, and original failing files/lock114 tests with21 skips (`run_2844130f72a5635dadfbce107f8cd587`). None of the six Bun failures needed a fixture expectation change.
- Final head `da4ee212087163db858e1472f9052fd270d02f97` local review completed: patch correct, zero findings. The additional legacy-recovery guard/fixtures pass124 pinned-Bun consumer tests and targeted typed lint; migrating/healthy/unknown/foreign negative guards remain intact.
- Inherited CI timing note: openclaw#204943's Bun checkpoint assertion failed in a prior CI shard. The one identical-test/identical-pinned-Bun comparison on current main094e225 and head3c43 both passed ([run `run_adc41ae48859bff924ccce98fb5a2119`](https://crabbox.openclaw.ai/portal/runs/run_adc41ae48859bff924ccce98fb5a2119)); no expectation/source change was made for it. Maintainer owns its once-only diagnostic rerun and owner routing; passing again is not claimed as a fix.
- The approved narrow run-loop cap is1238 counted lines: inherited1235 plus the stop-budget custody join and restored required import. The cohesive persistence/custody-release block moved to run-loop-cleanup.ts; the old inline suppression and its inventory entry are removed.

The original malformed-database report remains ground truth, but its physical corruption mechanism was not established. This change removes the proven unsafe custody handoff; it does not claim to identify a corrupt SQLite page.

## Known Edge Cases

If a second update prepares in the short window after the first commits but before its CLI reads the trial, the first command can report the second outcome or wait until its deadline; both are visible, and `openclaw update status` shows the true runs.

Windows coverage limit, explicitly accepted for this native-install cell: its actual tree is task supervisor → job anchor → cmd → Gateway, not a converted resident release launcher. No wrong process was killed and no launcher-manager recovery is claimed. The converted-install manager-cut cell belongs to the full matrix after#204866; it is not proven here.

**Open reproduced repair gap: [openclaw#205035](openclaw#205035 TEMP-prefix service repair is not a pass: on source2106, npm0/346.427s, restart self-exit1/512.647s, target never ready, repeated EPERM publishing `control/services.sqlite`. Original archive SHA256 `29be88bba446d938eebe3dd4305f5b49c3248523b2096062c9a7cc09145fac5a`. A fresh diagnostic captured the restart CLI child node.exe PID1652/handle3E8 on that file104ms after the first error, while alive; live archive SHA256 `161ea7d9034b0a96294f37286f9473cf054c8599cd2ab14c9325b5ca73082f23`. Both source/target were non-readonly with FullControl ACLs. The post-native-install runtime-pin read (`service.ts:410–420`→`runtime-pin-store.ts:83–98`) and publication rename (`state-upgrade-tree.ts:627`) already exist on main; no repair fix or success is claimed here. Maintainer explicitly accepts landing this PR with that named gap, owned by the next repair-producer change.

### Backport

`release/2026.11.15` (`109e8ff908ae`) needs the custody correction: Gateway/resource retirement before lock transfer, file/HTTP-only restart observation, and CLI reader release. The serving Gateway must contain its part; a candidate cannot close an older process's handles. That release has no package-adoption waiter, so the terminal-trial waiter change is not part of the smallest backport. No backport PR was opened.

## Test Cost and Necessity

Compared with PR base `285567057721`: **848 net test/support lines; 448 allocated above the 400-line allowance**. Shared full-lock/process fixtures removed39 lines, retained child diagnostics add9. The final +33 lines are the requested stale-owner regression (+28) and verified-owner caller migration (+5), explicitly approved.

The orphan-FD case stays at the cache boundary: its native owner and admission record are already gone. The full-lock matrix instead retains a live borrower and must preserve Gateway exclusion. Combining those different states would obscure which owner failed. Repair producer, native dispatch, and caller-result tests likewise exercise different boundaries.

All changed test/support files are listed; `+/-` counts include helper cost and deletions:

| File | + / - | Contract or required migration |
| --- | ---: | --- |
| `src/cli/daemon-cli/diagnostic-readiness.test.ts` | 9 / 15 | Existing diagnostic consumers use file/HTTP snapshots. |
| `src/cli/daemon-cli/lifecycle-core.test.ts` | 51 / 22 | Async drain ordering and refusal before native dispatch. |
| `src/cli/daemon-cli/lifecycle-readiness.test.ts` | 92 / 2 | Captured facts and pre-activation readiness ownership. |
| `src/cli/daemon-cli/lifecycle.test.ts` | 40 / 17 | Repaired facts reach callers without reopening stores. |
| `src/cli/daemon-cli/restart-health-deadline.test.ts` | 3 / 3 | Existing deadline fixture cutover. |
| `src/cli/daemon-cli/restart-health-probe.test.ts` | 80 / 2 | Scope denial settles distinctly without polling. |
| `src/cli/daemon-cli/restart-health-progress.test.ts` | 77 / 1 | Long migration remains protected; verified stale stopped-listener recovery remains reachable without SQL. |
| `src/cli/daemon-cli/restart-health-wait.test.ts` | 10 / 26 | Bounded waits replace DB migration polling. |
| `src/cli/daemon-cli/restart-health.test-helpers.ts` | 0 / 3 | Remove obsolete DB observer mock. |
| `src/cli/daemon-cli/restart-health.test.ts` | 25 / 19 | Existing restart fixtures consume file-only observations. |
| `src/cli/daemon-cli/start-repair.test.ts` | 57 / 4 | Producer publishes prepared auth/command facts before activation. |
| `src/cli/gateway-cli/run-loop-mocks.test-support.ts` | 6 / 30 | Remove sentinel/fallback mocks; retain launcher owner. |
| `src/cli/gateway-cli/run-loop-natural-exit.test-support.ts` | 9 / 5 | Lifecycle cleanup ordering fixtures. |
| `src/cli/gateway-cli/run-loop-restart-ownership.test-support.ts` | 1 / 1 | Existing restart owner fixture cutover. |
| `src/cli/gateway-cli/run-loop-stop.test-support.ts` | 10 / 8 | Stop/flush ordering fixture cutover. |
| `src/cli/gateway-cli/run-loop-update-respawn.test-support.ts` | 14 / 31 | Launcher failure replaces competing in-process recovery. |
| `src/cli/gateway-cli/run-loop.direct-stop-active-work.process.test.ts` | 143 / 32 | Existing signal cases plus real stuck-borrow watchdog exit and successor. |
| `src/cli/gateway-cli/run-loop.test-support.ts` | 6 / 25 | Remove retired successor sentinel behavior. |
| `src/cli/gateway-cli/run-loop.test.ts` | 12 / 21 | Launcher death exits visibly without reopening state. |
| `src/cli/gateway-cli/update-successor.test.ts` | 36 / 0 | Successor readiness never reopens shared state. |
| `src/cli/update-cli/update-command-readiness.windows.test.ts` | 0 / 1 | Remove obsolete observer mock. |
| `src/cli/update-cli/update-command-verification.test.ts` | 11 / 6 | Preserve switched-release recovery outcomes and negative guards with correct file-owner lifetimes. |
| `src/commands/doctor-config-preflight.admission.process.test.ts` | 2 / 2 | Offline lease-inspector migration. |
| `src/commands/doctor-config-preflight.pending-read.test.ts` | 2 / 1 | Offline lease-inspector migration. |
| `src/commands/doctor-config-preflight.plugin-persistence.test.ts` | 3 / 2 | Offline lease-inspector migration. |
| `src/commands/doctor-config-preflight.pristine.process.test.ts` | 2 / 5 | Offline lease-inspector migration. |
| `src/commands/doctor-config-preflight.test.ts` | 2 / 2 | Offline lease-inspector migration. |
| `src/commands/health.test.ts` | 24 / 0 | CLI reports reached/scope denial, not timeout. |
| `src/commands/startup-config-preflight.native-bootstrap.test.ts` | 2 / 2 | Offline lease-inspector migration. |
| `src/commands/startup-config-preflight.recovery.test.ts` | 4 / 3 | Offline lease-inspector migration. |
| `src/commands/status.scan.shared.test.ts` | 25 / 1 | Status preserves reached/no-scope capability and both warnings without another probe. |
| `src/daemon/schtasks-runtime-definition.test.ts` | 54 / 5 | Captured command and exact file/PID/port observations avoid SQL. |
| `src/daemon/schtasks.start.test.ts` | 24 / 0 | Existing effect hooks can refuse before Scheduled Task Run. |
| `src/infra/gateway-lock.test.ts` | 127 / 1 | Shared/control/agent physical custody; immediate/borrowed handoff matrix. |
| `src/infra/startup-migration-checkpoint.test-support.ts` | 35 / 0 | Offline-only inspector replaces removed production observer. |
| `src/infra/startup-migration-checkpoint.test.ts` | 6 / 14 | Inspector moved without losing lease assertions. |
| `src/state/openclaw-state-db-cache.cleanup.test.ts` | 38 / 1 | Unlinked, recordless identity FD closes physically. |
| `src/state/openclaw-state-read-source.test.ts` | 50 / 2 | Successful one-shot CLI reads join native worker exit. |
| `src/update/cli.test.ts` | 95 / 25 | File-only terminal trial/deadline and pre-dispatch custody refusal. |
| `test/scripts/ci-workflow-guards.test.ts` | 5 / 4 | Required healthy/crash lane selection and artifacts. |
| `test/scripts/doctor-config-preflight-plugin-index.built-cli.e2e.test.ts` | 2 / 2 | Remaining offline inspector caller migration. |

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 25, 2026
## What Problem This Solves

Two update paths could claim the same installation. A converted install could fall into the retained in-place updater; reinstalling its Gateway from an unmarked npm entry could replace the resident launcher. Before first conversion, a different npm root could also claim an empty state slot. Node-only hosts were sent into a Gateway trial with nobody to activate it.

Related: #204516, #203807, #204266, and the converted-install legacy fall-through. #203628's runtime selection is a separate release-runtime issue, not changed here. #204515 npm adoption behavior is retained.

## User Impact

- Converted installs stay with their resident launcher. Installer-kind switches and immutable activation refuse with a reason and next step instead of replacing it; dry runs retain the existing read-only preview.
- Ordinary and planned Gateway service installs select the verified launcher for the captured state directory; explicit retained recovery entrypoints still win.
- Before conversion, node-only package installs with a node service but no Gateway definition or live local Gateway keep their package route; no launcher, forwarding entry or pending Gateway trial is created. Node-only Git checkouts keep the release updater and requested `--sha`. Already-converted installs keep their resident release owner, including `--no-restart` preparation after the Gateway service was removed.
- Node-only package results name the updated installation's `node install --force` and `node restart` commands. They do not claim a retained node runtime was restarted, and guidance consumes captured result facts without a new service scan or state read.
- Documented versions, dist-tags, npm specs/artifacts, deferred restart and implicit Git channel selection keep their existing behavior.
- Windows process snapshots honor the existing native inspection budget instead of two hidden five-second ceilings. Unknown inspection remains distinct from proof that a service stopped.

## Ownership Cut

The existing admission adapter owns the release-versus-package decision; the complete release routing block moved there to keep `update-command.ts` below its 700-line ratchet. The same read-only ownership guard stays before CLI cleanup/run creation and is rechecked under preparation's lock. Final service argument selection replaces the old invocation-based launcher selector. No new persistent state, schema, marker or flag.

After the single custody integration, production `tokei` code on this PR's eleven touched runtime files, excluding tests/support/harness: **4,595 → 4,814 (+219)** against integrated main `8aaf3820112a4755d9aebb431e6c247b6d5d5412`. Shared native-observer changes already landed in #204868 and are no longer counted here. No unrelated deletion was used to meet a line quota.

## Evidence

AWS [targeted proof](https://crabbox.openclaw.ai/portal/runs/run_8314f1f6e7468775618b5e1b8125915c) passed **151 tests across nine files**: routing 14, service entry/planning 62, Windows inspection 75. These lanes ran independently on Linux; the Windows lane uses native-inspection mocks, not a Windows live claim. Runtime source is `b59eee4e13b3a71725b69a914211eea9e7ae75ad`; the subsequent commit is documentation-only.

The [qualified base comparison](https://crabbox.openclaw.ai/portal/runs/run_59926da4d8eb490b0855d67398d0fcd1) has **18 intended assertion failures and 133 passing controls**: routing eight, service-entry/planning four, inspection budgets six. Earlier archived-checkout dependency failures were fixture setup, not product reds; fixed green lanes were not rerun for that repair.

## Integration and remaining proof

The scheduled-task SQL-to-file observer hunk is shared with #204868; the second PR to land rebases the identical hunk rather than maintaining an independent variant.

A rare first-conversion refusal applies when a live foreground Gateway's root is opaque and it cannot accept the requested update over RPC. With operator access, the Gateway can classify its own argv and handle `update.run`. Otherwise the message offers Control UI/operator-access update or stopping the Gateway through its existing owner and rerunning. No lock or protocol field was added.

Against integrated main, the test change measures **+740 lines**, with **340 reviewed allocation lines** above the normal 400-line allowance. `config/test-lines-allocations/204866-install-update-owner.txt` maps the thirteen changed test files to their contracts; upstream-owned native-observer credit was removed. Existing controls preserve package routing, Git SHA, converted/legacy ownership and immutable inspection-only output.

The two existing legacy-layout launcher cases in `git-release.test.ts` now pass the captured state environment and `{ planned: entry }`, retaining both launcher and legacy path assertions. An explicit string entrypoint is reserved for `--restore-service-cli` and must win over ordinary launcher selection; those cases represent ordinary installation planning, not recovery.

The retained legacy service-staging producer resolves its release launcher before passing an explicit service CLI (`d831dde27f`). CI on that head proved the three unchanged no-restart staging cases red: the selector still treated the explicit launcher as a package CLI root. `dd83c4f630` repairs that single selector by directly selecting a recognized accessible Gateway launcher, preserving Node and other recovery strings. [Focused AWS proof](https://crabbox.openclaw.ai/portal/runs/run_cfcb09aada70caf4e34f1ea6f25fb287) passed all three regressions, the existing launcher control, and all four service-entry controls: **8 passed**, unchanged assertions. The 38 unrelated service cases were intentionally excluded by the focused name filter.

Final head `2536f8aea4` passed [CI](https://github.com/openclaw/openclaw/actions/runs/45544076053) and the [security/aggregate gate](https://github.com/openclaw/openclaw/actions/runs/45548330474): **70 successful checks, none pending or failed**. It differs from reviewed/Linux-qualified `48e606149e` only by three local test-helper rename substitutions fixing no-shadow; assertions and production bytes are identical. Main's exact-head and delta reviews are clean.

- [Integrated AWS qualification](https://crabbox.openclaw.ai/portal/runs/run_e165cd4d147a24e0808417237069d4ae) passed: current owner/preview/merge controls, full build, package integrity, and real Linux stable **2026.11.9** upgrade flows. Deferred conversion staged the launcher and committed on public restart; read-only-npm PATH service reinstall kept launcher ExecStart, committed the same pending trial, and the following update committed. A converted node-only install prepared a pending release without activating it; an unconverted node-only install used npm with no trial and named exact install/restart commands rather than claiming activation. Source `48e606149e` is production-identical to final `2536f8aea4`. Healthy relabels retain that source; this is not a schema-bump or live-Windows claim. Historical shallow-Git setup failed before tests and is not a merge gate.
- Windows 11 ARM64 status/restart follows the exclusively owned custody lane; per maintainer direction it can be recorded after landing. No live-Windows pass is claimed.
- All requested landing gates are green. The single required custody merge is complete; Main owns landing. No further scope or merge is planned.

Launcher manifest, budget and one-strike changes are deliberately outside this PR.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 25, 2026
## What Problem This Solves

The launcher currently guesses restore coverage by scanning `.pre-<generation>` files. That freezes directory depth, excluded names and ctime policy into the installed launcher. This is the candidate-writer stage of replacing that knowledge with explicit restore intent (related #204394, #204752, #204775, #198389 and #204095).

## User Impact

The active candidate writes `<prefix>/releases/<target-release-id>/.restore` as `{v:1,runId,files:[{live,preimage}]}` before publishing its replayable swap plan or canonical schema/config changes. The trial's existing target release owns the receipt by construction; run IDs are recorded, not compared. Paths are absolute; null pre-images explicitly remove new files and SQLite WAL/SHM/journal/seal companions.

Under exclusive custody, SQLite originals are checkpointed and closed, then their complete main files are hard-linked as adjacent run-bound images. Publication renames a different prepared inode over the live path; it does not modify the image. Normal adjacent images add no database byte copy. The fallback copies bytes only if the filesystem rejects hard linking, recording its cause. No new size admission or disk-copy reservation is added.

Retries within that prepared release reuse immutable images; another release cannot reuse its receipt, including a retry prepared by old2026.11.15 code. A changed or missing restore plan refuses instead of re-imaging mutated state. Known no-upgrade trials record an empty plan under the same exclusive owner. Ordinary non-trial starts are unchanged. Cleanup consumes only the manifest captured by its own candidate process after confirmed committed IPC, never rereading a slot or matching IDs.

## Scope and Compatibility

Legacy `.pre-<generation>` files and `Trial.config` remain in use: today's launcher continues to work and ignores the new manifest. This PR does not enable external stores yet, change the launcher reader, add reader floors, or start in-place migrations. A hard-linked image is valid for this rename-based swap only; the later in-place cutover must use its approved clone/copy pre-image primitive.

The state owner is the only manifest/image writer. UpdateOwner supplied both revisions of the committed-IPC cleanup caller; no `src/update/` file was edited directly here. Receipts stay with their prepared releases. Old retained-image cleanup errors cannot block a different release's no-upgrade preparation; the A-delayed/B-safe regression remains and also deletes A's receipt before invoking its captured cleanup.

## Evidence

On `8b410b54`, isolated AWS checks passed **88 owner tests**; baseline5e5ecba4 failed exactly the two selected missing-manifest/order regressions. The JSON gate positively verified those causes, not an arbitrary exit. A recovered OOM-interrupted broad run was not claimed green. On `cb5abca7`, **35 changed-owner tests**, assertion safety, SQLite worker/dialect guards, core types and targeted production lint passed on32GiB. Targeted test lint found a shadowing fixture variable, now renamed through LSP. CI's Bun lane exposed an orderly `process.exit(0)` WAL fixture; it now uses a real forced crash and retains the physical WAL/data assertions. This review repair also removes stale-run comparisons by per-release scope and captured cleanup. No manual proof on the new scope has run while the required predecessor PRs are pending.

One-worker AWS wall times at8b410b54: writer63.535s, startup63.798s, swap-owner73.935s. The first writer suite included51.888s compiled-worker preparation; the native filesystem/WAL assertions themselves are small. Current-head CI owns its fresh check results.

The real filesystem WAL/config fixtures asserted hard links with zero byte copies; the forced `EXDEV` fixture exercised one actual copy fallback. No genuine cross-device failure was observed. Adjacent images normally share their source's filesystem; individually mounted files or unsupported hard linking can require the fallback. This is not a population-frequency estimate.

**Must not land before #204868 (custody), then #204866 (install owner).** Per the lead's sequence, merge main once after both land, then run the native crash/full-package qualification on that integrated head. No further manual writer proof will run before that point. The hard-link immutability assumption requires custody; checkpointing alone is not claimed to fix the previously observed malformed rollback. The in-place/floor stage separately waits for ReaderFloor.

## Size

`tokei` on all four touched production files, including the update caller, against integrated main25efa334: **1,058 → 1,388 (+330)**. Tests: **+479 net lines**, with a 79-line excess allocation for distinct WAL, durable-ordering, retry, frozen rollback, symlink, captured cleanup and startup contracts. No competing legacy reader is deleted in this explicitly sequenced writer-first stage; its removal belongs to the following reader PR.

## Conflict Integration

Merged main25efa334 once to clear the named conflict. Resolutions retained main's config/include inventory and external/workspace/missing-include fixtures together with the managed-trial manifest case. No `src/update/` conflict or direct edit was involved. No manual proof was run. The later main merge and native crash qualification still wait for the predecessor landing order above.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 26, 2026
## What Problem This Solves

Two update paths could claim the same installation. A converted install could fall into the retained in-place updater; reinstalling its Gateway from an unmarked npm entry could replace the resident launcher. Before first conversion, a different npm root could also claim an empty state slot. Node-only hosts were sent into a Gateway trial with nobody to activate it.

Related: openclaw#204516, openclaw#203807, openclaw#204266, and the converted-install legacy fall-through. openclaw#203628's runtime selection is a separate release-runtime issue, not changed here. openclaw#204515 npm adoption behavior is retained.

## User Impact

- Converted installs stay with their resident launcher. Installer-kind switches and immutable activation refuse with a reason and next step instead of replacing it; dry runs retain the existing read-only preview.
- Ordinary and planned Gateway service installs select the verified launcher for the captured state directory; explicit retained recovery entrypoints still win.
- Before conversion, node-only package installs with a node service but no Gateway definition or live local Gateway keep their package route; no launcher, forwarding entry or pending Gateway trial is created. Node-only Git checkouts keep the release updater and requested `--sha`. Already-converted installs keep their resident release owner, including `--no-restart` preparation after the Gateway service was removed.
- Node-only package results name the updated installation's `node install --force` and `node restart` commands. They do not claim a retained node runtime was restarted, and guidance consumes captured result facts without a new service scan or state read.
- Documented versions, dist-tags, npm specs/artifacts, deferred restart and implicit Git channel selection keep their existing behavior.
- Windows process snapshots honor the existing native inspection budget instead of two hidden five-second ceilings. Unknown inspection remains distinct from proof that a service stopped.

## Ownership Cut

The existing admission adapter owns the release-versus-package decision; the complete release routing block moved there to keep `update-command.ts` below its 700-line ratchet. The same read-only ownership guard stays before CLI cleanup/run creation and is rechecked under preparation's lock. Final service argument selection replaces the old invocation-based launcher selector. No new persistent state, schema, marker or flag.

After the single custody integration, production `tokei` code on this PR's eleven touched runtime files, excluding tests/support/harness: **4,595 → 4,814 (+219)** against integrated main `44d311177c0f4e86eb4ecb6828371c9eaa81b4f6`. Shared native-observer changes already landed in openclaw#204868 and are no longer counted here. No unrelated deletion was used to meet a line quota.

## Evidence

AWS [targeted proof](https://crabbox.openclaw.ai/portal/runs/run_8314f1f6e7468775618b5e1b8125915c) passed **151 tests across nine files**: routing 14, service entry/planning 62, Windows inspection 75. These lanes ran independently on Linux; the Windows lane uses native-inspection mocks, not a Windows live claim. Runtime source is `b59eee4e13b3a71725b69a914211eea9e7ae75ad`; the subsequent commit is documentation-only.

The [qualified base comparison](https://crabbox.openclaw.ai/portal/runs/run_59926da4d8eb490b0855d67398d0fcd1) has **18 intended assertion failures and 133 passing controls**: routing eight, service-entry/planning four, inspection budgets six. Earlier archived-checkout dependency failures were fixture setup, not product reds; fixed green lanes were not rerun for that repair.

## Integration and remaining proof

The scheduled-task SQL-to-file observer hunk is shared with openclaw#204868; the second PR to land rebases the identical hunk rather than maintaining an independent variant.

A rare first-conversion refusal applies when a live foreground Gateway's root is opaque and it cannot accept the requested update over RPC. With operator access, the Gateway can classify its own argv and handle `update.run`. Otherwise the message offers Control UI/operator-access update or stopping the Gateway through its existing owner and rerunning. No lock or protocol field was added.

Against integrated main, the test change measures **+740 lines**, with **340 reviewed allocation lines** above the normal 400-line allowance. `config/test-lines-allocations/204866-install-update-owner.txt` maps the thirteen changed test files to their contracts; upstream-owned native-observer credit was removed. Existing controls preserve package routing, Git SHA, converted/legacy ownership and immutable inspection-only output.

The two existing legacy-layout launcher cases in `git-release.test.ts` now pass the captured state environment and `{ planned: entry }`, retaining both launcher and legacy path assertions. An explicit string entrypoint is reserved for `--restore-service-cli` and must win over ordinary launcher selection; those cases represent ordinary installation planning, not recovery.

The retained legacy service-staging producer resolves its release launcher before passing an explicit service CLI (`d831dde27f`). CI on that head proved the three unchanged no-restart staging cases red: the selector still treated the explicit launcher as a package CLI root. `dd83c4f630` repairs that single selector by directly selecting a recognized accessible Gateway launcher, preserving Node and other recovery strings. [Focused AWS proof](https://crabbox.openclaw.ai/portal/runs/run_cfcb09aada70caf4e34f1ea6f25fb287) passed all three regressions, the existing launcher control, and all four service-entry controls: **8 passed**, unchanged assertions. The 38 unrelated service cases were intentionally excluded by the focused name filter.

Final head `2536f8aea4` passed [CI](https://github.com/openclaw/openclaw/actions/runs/45544076053) and the [security/aggregate gate](https://github.com/openclaw/openclaw/actions/runs/45548330474): **70 successful checks, none pending or failed**. It differs from reviewed/Linux-qualified `48e606149e` only by three local test-helper rename substitutions fixing no-shadow; assertions and production bytes are identical. Main's exact-head and delta reviews are clean.

- [Integrated AWS qualification](https://crabbox.openclaw.ai/portal/runs/run_e165cd4d147a24e0808417237069d4ae) passed: current owner/preview/merge controls, full build, package integrity, and real Linux stable **2026.11.9** upgrade flows. Deferred conversion staged the launcher and committed on public restart; read-only-npm PATH service reinstall kept launcher ExecStart, committed the same pending trial, and the following update committed. A converted node-only install prepared a pending release without activating it; an unconverted node-only install used npm with no trial and named exact install/restart commands rather than claiming activation. Source `48e606149e` is production-identical to final `2536f8aea4`. Healthy relabels retain that source; this is not a schema-bump or live-Windows claim. Historical shallow-Git setup failed before tests and is not a merge gate.
- Windows 11 ARM64 status/restart follows the exclusively owned custody lane; per maintainer direction it can be recorded after landing. No live-Windows pass is claimed.
- All requested landing gates are green. The single required custody merge is complete; Main owns landing. No further scope or merge is planned.

Launcher manifest, budget and one-strike changes are deliberately outside this PR.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 26, 2026
## What Problem This Solves

The launcher currently guesses restore coverage by scanning `.pre-<generation>` files. That freezes directory depth, excluded names and ctime policy into the installed launcher. This is the candidate-writer stage of replacing that knowledge with explicit restore intent (related openclaw#204394, openclaw#204752, openclaw#204775, openclaw#198389 and openclaw#204095).

## User Impact

The active candidate writes `<prefix>/releases/<target-release-id>/.restore` as `{v:1,runId,files:[{live,preimage}]}` before publishing its replayable swap plan or canonical schema/config changes. The trial's existing target release owns the receipt by construction; run IDs are recorded, not compared. Paths are absolute; null pre-images explicitly remove new files and SQLite WAL/SHM/journal/seal companions.

Under exclusive custody, SQLite originals are checkpointed and closed, then their complete main files are hard-linked as adjacent run-bound images. Publication renames a different prepared inode over the live path; it does not modify the image. Normal adjacent images add no database byte copy. The fallback copies bytes only if the filesystem rejects hard linking, recording its cause. No new size admission or disk-copy reservation is added.

Retries within that prepared release reuse immutable images; another release cannot reuse its receipt, including a retry prepared by old2026.11.15 code. A changed or missing restore plan refuses instead of re-imaging mutated state. Known no-upgrade trials record an empty plan under the same exclusive owner. Ordinary non-trial starts are unchanged. Cleanup consumes only the manifest captured by its own candidate process after confirmed committed IPC, never rereading a slot or matching IDs.

## Scope and Compatibility

Legacy `.pre-<generation>` files and `Trial.config` remain in use: today's launcher continues to work and ignores the new manifest. This PR does not enable external stores yet, change the launcher reader, add reader floors, or start in-place migrations. A hard-linked image is valid for this rename-based swap only; the later in-place cutover must use its approved clone/copy pre-image primitive.

The state owner is the only manifest/image writer. UpdateOwner supplied both revisions of the committed-IPC cleanup caller; no `src/update/` file was edited directly here. Receipts stay with their prepared releases. Old retained-image cleanup errors cannot block a different release's no-upgrade preparation; the A-delayed/B-safe regression remains and also deletes A's receipt before invoking its captured cleanup.

## Evidence

On `8b410b54`, isolated AWS checks passed **88 owner tests**; baseline5e5ecba4 failed exactly the two selected missing-manifest/order regressions. The JSON gate positively verified those causes, not an arbitrary exit. A recovered OOM-interrupted broad run was not claimed green. On `cb5abca7`, **35 changed-owner tests**, assertion safety, SQLite worker/dialect guards, core types and targeted production lint passed on32GiB. Targeted test lint found a shadowing fixture variable, now renamed through LSP. CI's Bun lane exposed an orderly `process.exit(0)` WAL fixture; it now uses a real forced crash and retains the physical WAL/data assertions. This review repair also removes stale-run comparisons by per-release scope and captured cleanup. No manual proof on the new scope has run while the required predecessor PRs are pending.

One-worker AWS wall times at8b410b54: writer63.535s, startup63.798s, swap-owner73.935s. The first writer suite included51.888s compiled-worker preparation; the native filesystem/WAL assertions themselves are small. Current-head CI owns its fresh check results.

The real filesystem WAL/config fixtures asserted hard links with zero byte copies; the forced `EXDEV` fixture exercised one actual copy fallback. No genuine cross-device failure was observed. Adjacent images normally share their source's filesystem; individually mounted files or unsupported hard linking can require the fallback. This is not a population-frequency estimate.

**Must not land before openclaw#204868 (custody), then openclaw#204866 (install owner).** Per the lead's sequence, merge main once after both land, then run the native crash/full-package qualification on that integrated head. No further manual writer proof will run before that point. The hard-link immutability assumption requires custody; checkpointing alone is not claimed to fix the previously observed malformed rollback. The in-place/floor stage separately waits for ReaderFloor.

## Size

`tokei` on all four touched production files, including the update caller, against integrated main25efa334: **1,058 → 1,388 (+330)**. Tests: **+479 net lines**, with a 79-line excess allocation for distinct WAL, durable-ordering, retry, frozen rollback, symlink, captured cleanup and startup contracts. No competing legacy reader is deleted in this explicitly sequenced writer-first stage; its removal belongs to the following reader PR.

## Conflict Integration

Merged main25efa334 once to clear the named conflict. Resolutions retained main's config/include inventory and external/workspace/missing-include fixtures together with the managed-trial manifest case. No `src/update/` conflict or direct edit was involved. No manual proof was run. The later main merge and native crash qualification still wait for the predecessor landing order above.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 26, 2026
Related: #204915, #205578, #204868

## What Problem This Solves

Existing launcher tests construct the trial, restore manifest and candidate IPC messages themselves. A candidate producer can drift while those consumer tests remain green, despite an installed launcher keeping its frozen interface.

## User Impact

No runtime behavior changes. This adds one owner test file for compatibility with today's format4 launcher, v2 trial, v1 per-release restore manifest and compiled20-minute default. The current2-attempt and exit78 behavior remain unchanged and covered by their existing lifecycle tests. No production/stored/header/schema change or new production test seam.

## Why This Change Was Made

Three small cases cover the missing boundaries without replaying the lifecycle suite:

- Real `createTrialPending` bytes, minimal/full optional input, independent stored-key/v2 ABI guard, and literal `1_200_000` default.
- Real candidate manifest publisher output independently checked against the deployed literal v1 root/pair ABI (entry order is not pinned; positive preimages must be absolute), then consumed by the frozen manifest reader on actual files. The literal check prevents coordinated writer/reader drift from moving the oracle; existing writer tests retain their SQLite inventory coverage.
- One isolated child imports the real `announceReady`/stop listener and exchanges frames with a pinned format4 peer. A collector is installed at spawn, return must precede stop, stdin provides the serving keepalive without sleeps/polling, and child home/state/config paths are all private.

The IPC case does not distinguish ACK processing from the supported on-disk fallback. Actual stage-mark producer coverage at `config-preflight-snapshot.ts:468` is separately recorded: exercising its full admission/recovery graph is outside this bounded harness; existing launcher stage-consumer tests remain unchanged. This PR does not claim that fourth producer frame is exercised.

Production delta: **0**. One228-line owner file, below the400net test-line allowance; no allocation/waiver.

## Evidence

- Base: `b1d355fcc9fcf91a4514c2612ce7b33211c710b6`.
- **Mutation RED:** [AWS run_14f78c186994742f3077d3a597297ada](https://crabbox.openclaw.ai/portal/runs/run_14f78c186994742f3077d3a597297ada),2artifact cases passed and the IPC assertion failed with expected `openclaw.ready` / actual `openclaw.contract-mutant`. This was one temporary producer discriminant edit, restored exactly before GREEN and not included in this PR.
- **Initial restored GREEN:** [AWS run_210b1aac2726928af6ebc89d25e4ef12](https://crabbox.openclaw.ai/portal/runs/run_210b1aac2726928af6ebc89d25e4ef12),3/3cases/types/lint/guard passed; one exact formatting wrap applied from AWS oxfmt.
- **Review repair GREEN:** [AWS run_a4905843c4d73632f1ef06ac4d40e00a](https://crabbox.openclaw.ai/portal/runs/run_a4905843c4d73632f1ef06ac4d40e00a), independent manifest ABI pin added;3/3cases, owner-project types, lint, format and guard all exit0 (+228/400). No production changes or mutation repeat.
- **Cost:** AWS cases42ms/17ms/4147ms = **4.206s test time**; file wall46.91s / shard49.93s includes35.777s shared compiled-generation preparation. [CI Bun owner job](https://github.com/openclaw/openclaw/actions/runs/45763730662/job/139720273166) passed3/3 at43ms/22ms/3862ms = **3.927s test time**, file10.26s / shard11.49s. Both meet the5s test-time target; no added readiness sleeps/polls or product boots.
- Both owned AWS leases (`cbx_af0ca4a223fc`, repair `cbx_7a77e1c11a2c`) released with `--wait`, exit0; all receipts are under `direction-2026-11-24/updateowner-frozen-contract-*`.
- Existing unchanged primary tests cover format4 protection (`launcher.test.ts:496`),2-start rollback (`:216`), stage handling (`:434`), stop forwarding (`:401`), and serving/trial exit78 (`:378/:385`); real CLI refusal78 is covered by `pre-bootstrap.process.test.ts`.
- Exact-head local review on `298da439f4f024c83091c9e5148fb022753294d9` is complete: patch correct, security cleared, no findings, confidence0.88 (`~/.cache/clawsweeper-local-review/298da439f4f0.md`). No package build/native matrix is claimed or required for this test-only, production-identical change. CI pending.

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

Closes #204704

A release switch can replace or restore SQLite files while the previous Gateway or initiating CLI still holds them. On Windows this can prevent every new Gateway from starting with `EPERM` on `openclaw.sqlite-wal`. A restart can also keep waiting after its trial has already committed.

Release switches wait for the old readers to close. An adopted package's committed trial ends `gateway restart` without requiring an operator-scoped health RPC. A connected CLI without `operator.read` gets a distinct diagnostic and a clear next step, not a false startup timeout.

If an unmanaged foreground launcher dies before readiness, the old runtime exits with an error and prints `openclaw gateway` as the recovery command. It does not reopen a store that the launcher may have migrated. A live launcher remains the only recovery owner.

The existing shared-state close owner now joins native consumers and retires retained file-identity descriptors before custody transfers. The Gateway completes its boot record and closes shared state before releasing its lock; process cleanup and a final custody close precede a standalone launcher spawn. The retiring Gateway's readiness observer uses only HTTP and captured configuration; its sentinel reads/writes and in-process fallback after spawning a launcher are gone.

Restart observers use file-lock identity, native process/listener information, HTTP and RPC instead of opening the store to inspect migration and owner leases. A live file owner retains bounded startup grace during a long migration. The update CLI releases custody at its existing pre-dispatch boundary, and the adopted-result waiter consumes the terminal phase at the sole trial path: update preparation already serializes active trials under the update lock.

No schema, launcher protocol or public Plugin SDK API changes. The private QA startup collector retains its closed-fixture lease check on its existing connection.

Service-definition repair publishes its planned command/environment and effective configuration after token preparation but before activation. Start and restart observers consume those facts instead of reopening SQLite to recapture repaired credentials or arguments. Windows captures its command once before `/Run`, retires preflight custody through the existing caller hook, and uses bounded file/process observations afterward.

- On source baseline `33586124338a`, regressions fail for retained identity descriptors, an early-returning one-shot reader, RPC access after a committed trial, scope denial reported as a timeout, and a retiring successor observer reopening state.
- The reported Linux external holders and Windows native ARM64 WAL/`EPERM` failures are retained base evidence; they were not repeated just to confirm them.
- Earlier affected AWS gate on `c698a589b131` passed (`run_8c5f0a8b1085ed134733db543b577cc2`): seven Vitest shards in 189.73s, targeted types/lint and ratchets. This remains prior-head evidence, not final platform proof.
- The first Windows head (`f798ffc61fd9`) was **red**: npm exited0, restart exited1 after728.479s and nothing served; signed Handle matched the initiating CLI to control/shared/quarantine SQLite. Final stable-path evidence is below; the separately reproduced repair-path gap is explicitly tracked.
- Test growth after consolidation and the requested recovery regression is 848 net lines against the PR's base; the approved 448-line allocation covers the distinct contracts itemized below. No behavioral assertion is weakened.
- Platform packages/proofs use source `21066b69471a1998505bac4ee4758e2138694d33`, rebuilt after the required main merge (including inherited WAL/state-upgrade changes). Later changes are the status-test warning correction and the narrowly guarded SQL-free stale-listener recovery fix, qualified by124 focused pinned-Bun consumer tests/typed lint. The platform recordings do not claim to exercise that legacy recovery branch or byte-equivalence with the later head.
- **Linux crash/restore PASS** — [AWS run `run_ae3ce038d7ae16a26540b0d69c956015`](https://crabbox.openclaw.ai/portal/runs/run_ae3ce038d7ae16a26540b0d69c956015),201.82s:10 publication and6 restore snapshots, zero external native/identity holders and zero scan errors, all four families present. RestoredT served with its exact identity, read the persisted cron sentinel over RPC, and all live integrity checks passed. Actual update row finished/failed (expected injected crash); CLI settled exit1. No harness recovery. Receipt archive SHA256 `68973c89550142131208d65ca7de293b18bd9dcbfaa785a92f0e28831893766f`.
- **Windows native ARM64 stable-path PASS** — npm0; restart0 on its own in107.673s; exact2106 RPC version/build with `connected_no_operator_scope`; store read passed; complete17-file scan found no EPERM. Stable archive SHA256 `260da7b92739a2444678d1bb61dbceb679f4aeae6f3400cc21a9032d52092906`.
- Borrow qualification `run_ec051c902d31b5c93086dcbbfde87d1b` passed Node37 tests, process4 tests (including real watchdog SIGKILL and successor), and pinned Bun77 tests/1 skip. Test types and numeric guards passed. Its two static failures were a mistakenly removed required import and a stale inline suppression; both are corrected without changing borrower behavior.
- Both Node and pinned Bun fail the unlinked-path regression on b8ee (`run_40c6e4e508e393b27716dc57072b0a88`). Registry-owner fix eeee passes Node cache/lock35 tests, pinned Bun cache10 tests, and original failing files/lock114 tests with21 skips (`run_2844130f72a5635dadfbce107f8cd587`). None of the six Bun failures needed a fixture expectation change.
- Final head `da4ee212087163db858e1472f9052fd270d02f97` local review completed: patch correct, zero findings. The additional legacy-recovery guard/fixtures pass124 pinned-Bun consumer tests and targeted typed lint; migrating/healthy/unknown/foreign negative guards remain intact.
- Inherited CI timing note: #204943's Bun checkpoint assertion failed in a prior CI shard. The one identical-test/identical-pinned-Bun comparison on current main094e225 and head3c43 both passed ([run `run_adc41ae48859bff924ccce98fb5a2119`](https://crabbox.openclaw.ai/portal/runs/run_adc41ae48859bff924ccce98fb5a2119)); no expectation/source change was made for it. Maintainer owns its once-only diagnostic rerun and owner routing; passing again is not claimed as a fix.
- The approved narrow run-loop cap is1238 counted lines: inherited1235 plus the stop-budget custody join and restored required import. The cohesive persistence/custody-release block moved to run-loop-cleanup.ts; the old inline suppression and its inventory entry are removed.

The original malformed-database report remains ground truth, but its physical corruption mechanism was not established. This change removes the proven unsafe custody handoff; it does not claim to identify a corrupt SQLite page.

If a second update prepares in the short window after the first commits but before its CLI reads the trial, the first command can report the second outcome or wait until its deadline; both are visible, and `openclaw update status` shows the true runs.

Windows coverage limit, explicitly accepted for this native-install cell: its actual tree is task supervisor → job anchor → cmd → Gateway, not a converted resident release launcher. No wrong process was killed and no launcher-manager recovery is claimed. The converted-install manager-cut cell belongs to the full matrix after#204866; it is not proven here.

**Open reproduced repair gap: [#205035](#205035 TEMP-prefix service repair is not a pass: on source2106, npm0/346.427s, restart self-exit1/512.647s, target never ready, repeated EPERM publishing `control/services.sqlite`. Original archive SHA256 `29be88bba446d938eebe3dd4305f5b49c3248523b2096062c9a7cc09145fac5a`. A fresh diagnostic captured the restart CLI child node.exe PID1652/handle3E8 on that file104ms after the first error, while alive; live archive SHA256 `161ea7d9034b0a96294f37286f9473cf054c8599cd2ab14c9325b5ca73082f23`. Both source/target were non-readonly with FullControl ACLs. The post-native-install runtime-pin read (`service.ts:410–420`→`runtime-pin-store.ts:83–98`) and publication rename (`state-upgrade-tree.ts:627`) already exist on main; no repair fix or success is claimed here. Maintainer explicitly accepts landing this PR with that named gap, owned by the next repair-producer change.

`release/2026.11.15` (`f1debfde108a`) needs the custody correction: Gateway/resource retirement before lock transfer, file/HTTP-only restart observation, and CLI reader release. The serving Gateway must contain its part; a candidate cannot close an older process's handles. That release has no package-adoption waiter, so the terminal-trial waiter change is not part of the smallest backport. No backport PR was opened.

Compared with PR base `1bec22471ad0`: **848 net test/support lines; 448 allocated above the 400-line allowance**. Shared full-lock/process fixtures removed39 lines, retained child diagnostics add9. The final +33 lines are the requested stale-owner regression (+28) and verified-owner caller migration (+5), explicitly approved.

The orphan-FD case stays at the cache boundary: its native owner and admission record are already gone. The full-lock matrix instead retains a live borrower and must preserve Gateway exclusion. Combining those different states would obscure which owner failed. Repair producer, native dispatch, and caller-result tests likewise exercise different boundaries.

All changed test/support files are listed; `+/-` counts include helper cost and deletions:

| File | + / - | Contract or required migration |
| --- | ---: | --- |
| `src/cli/daemon-cli/diagnostic-readiness.test.ts` | 9 / 15 | Existing diagnostic consumers use file/HTTP snapshots. |
| `src/cli/daemon-cli/lifecycle-core.test.ts` | 51 / 22 | Async drain ordering and refusal before native dispatch. |
| `src/cli/daemon-cli/lifecycle-readiness.test.ts` | 92 / 2 | Captured facts and pre-activation readiness ownership. |
| `src/cli/daemon-cli/lifecycle.test.ts` | 40 / 17 | Repaired facts reach callers without reopening stores. |
| `src/cli/daemon-cli/restart-health-deadline.test.ts` | 3 / 3 | Existing deadline fixture cutover. |
| `src/cli/daemon-cli/restart-health-probe.test.ts` | 80 / 2 | Scope denial settles distinctly without polling. |
| `src/cli/daemon-cli/restart-health-progress.test.ts` | 77 / 1 | Long migration remains protected; verified stale stopped-listener recovery remains reachable without SQL. |
| `src/cli/daemon-cli/restart-health-wait.test.ts` | 10 / 26 | Bounded waits replace DB migration polling. |
| `src/cli/daemon-cli/restart-health.test-helpers.ts` | 0 / 3 | Remove obsolete DB observer mock. |
| `src/cli/daemon-cli/restart-health.test.ts` | 25 / 19 | Existing restart fixtures consume file-only observations. |
| `src/cli/daemon-cli/start-repair.test.ts` | 57 / 4 | Producer publishes prepared auth/command facts before activation. |
| `src/cli/gateway-cli/run-loop-mocks.test-support.ts` | 6 / 30 | Remove sentinel/fallback mocks; retain launcher owner. |
| `src/cli/gateway-cli/run-loop-natural-exit.test-support.ts` | 9 / 5 | Lifecycle cleanup ordering fixtures. |
| `src/cli/gateway-cli/run-loop-restart-ownership.test-support.ts` | 1 / 1 | Existing restart owner fixture cutover. |
| `src/cli/gateway-cli/run-loop-stop.test-support.ts` | 10 / 8 | Stop/flush ordering fixture cutover. |
| `src/cli/gateway-cli/run-loop-update-respawn.test-support.ts` | 14 / 31 | Launcher failure replaces competing in-process recovery. |
| `src/cli/gateway-cli/run-loop.direct-stop-active-work.process.test.ts` | 143 / 32 | Existing signal cases plus real stuck-borrow watchdog exit and successor. |
| `src/cli/gateway-cli/run-loop.test-support.ts` | 6 / 25 | Remove retired successor sentinel behavior. |
| `src/cli/gateway-cli/run-loop.test.ts` | 12 / 21 | Launcher death exits visibly without reopening state. |
| `src/cli/gateway-cli/update-successor.test.ts` | 36 / 0 | Successor readiness never reopens shared state. |
| `src/cli/update-cli/update-command-readiness.windows.test.ts` | 0 / 1 | Remove obsolete observer mock. |
| `src/cli/update-cli/update-command-verification.test.ts` | 11 / 6 | Preserve switched-release recovery outcomes and negative guards with correct file-owner lifetimes. |
| `src/commands/doctor-config-preflight.admission.process.test.ts` | 2 / 2 | Offline lease-inspector migration. |
| `src/commands/doctor-config-preflight.pending-read.test.ts` | 2 / 1 | Offline lease-inspector migration. |
| `src/commands/doctor-config-preflight.plugin-persistence.test.ts` | 3 / 2 | Offline lease-inspector migration. |
| `src/commands/doctor-config-preflight.pristine.process.test.ts` | 2 / 5 | Offline lease-inspector migration. |
| `src/commands/doctor-config-preflight.test.ts` | 2 / 2 | Offline lease-inspector migration. |
| `src/commands/health.test.ts` | 24 / 0 | CLI reports reached/scope denial, not timeout. |
| `src/commands/startup-config-preflight.native-bootstrap.test.ts` | 2 / 2 | Offline lease-inspector migration. |
| `src/commands/startup-config-preflight.recovery.test.ts` | 4 / 3 | Offline lease-inspector migration. |
| `src/commands/status.scan.shared.test.ts` | 25 / 1 | Status preserves reached/no-scope capability and both warnings without another probe. |
| `src/daemon/schtasks-runtime-definition.test.ts` | 54 / 5 | Captured command and exact file/PID/port observations avoid SQL. |
| `src/daemon/schtasks.start.test.ts` | 24 / 0 | Existing effect hooks can refuse before Scheduled Task Run. |
| `src/infra/gateway-lock.test.ts` | 127 / 1 | Shared/control/agent physical custody; immediate/borrowed handoff matrix. |
| `src/infra/startup-migration-checkpoint.test-support.ts` | 35 / 0 | Offline-only inspector replaces removed production observer. |
| `src/infra/startup-migration-checkpoint.test.ts` | 6 / 14 | Inspector moved without losing lease assertions. |
| `src/state/openclaw-state-db-cache.cleanup.test.ts` | 38 / 1 | Unlinked, recordless identity FD closes physically. |
| `src/state/openclaw-state-read-source.test.ts` | 50 / 2 | Successful one-shot CLI reads join native worker exit. |
| `src/update/cli.test.ts` | 95 / 25 | File-only terminal trial/deadline and pre-dispatch custody refusal. |
| `test/scripts/ci-workflow-guards.test.ts` | 5 / 4 | Required healthy/crash lane selection and artifacts. |
| `test/scripts/doctor-config-preflight-plugin-index.built-cli.e2e.test.ts` | 2 / 2 | Remaining offline inspector caller migration. |

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

Release adaptation: conflicts in src/update/cli.test.ts resolved by applying the source change over release-only hunks; source hunks verified unchanged (whitespace-insensitive).

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 26, 2026
## What Problem This Solves

Two update paths could claim the same installation. A converted install could fall into the retained in-place updater; reinstalling its Gateway from an unmarked npm entry could replace the resident launcher. Before first conversion, a different npm root could also claim an empty state slot. Node-only hosts were sent into a Gateway trial with nobody to activate it.

Related: #204516, #203807, #204266, and the converted-install legacy fall-through. #203628's runtime selection is a separate release-runtime issue, not changed here. #204515 npm adoption behavior is retained.

## User Impact

- Converted installs stay with their resident launcher. Installer-kind switches and immutable activation refuse with a reason and next step instead of replacing it; dry runs retain the existing read-only preview.
- Ordinary and planned Gateway service installs select the verified launcher for the captured state directory; explicit retained recovery entrypoints still win.
- Before conversion, node-only package installs with a node service but no Gateway definition or live local Gateway keep their package route; no launcher, forwarding entry or pending Gateway trial is created. Node-only Git checkouts keep the release updater and requested `--sha`. Already-converted installs keep their resident release owner, including `--no-restart` preparation after the Gateway service was removed.
- Node-only package results name the updated installation's `node install --force` and `node restart` commands. They do not claim a retained node runtime was restarted, and guidance consumes captured result facts without a new service scan or state read.
- Documented versions, dist-tags, npm specs/artifacts, deferred restart and implicit Git channel selection keep their existing behavior.
- Windows process snapshots honor the existing native inspection budget instead of two hidden five-second ceilings. Unknown inspection remains distinct from proof that a service stopped.

## Ownership Cut

The existing admission adapter owns the release-versus-package decision; the complete release routing block moved there to keep `update-command.ts` below its 700-line ratchet. The same read-only ownership guard stays before CLI cleanup/run creation and is rechecked under preparation's lock. Final service argument selection replaces the old invocation-based launcher selector. No new persistent state, schema, marker or flag.

After the single custody integration, production `tokei` code on this PR's eleven touched runtime files, excluding tests/support/harness: **4,595 → 4,814 (+219)** against integrated main `8aaf3820112a4755d9aebb431e6c247b6d5d5412`. Shared native-observer changes already landed in #204868 and are no longer counted here. No unrelated deletion was used to meet a line quota.

## Evidence

AWS [targeted proof](https://crabbox.openclaw.ai/portal/runs/run_8314f1f6e7468775618b5e1b8125915c) passed **151 tests across nine files**: routing 14, service entry/planning 62, Windows inspection 75. These lanes ran independently on Linux; the Windows lane uses native-inspection mocks, not a Windows live claim. Runtime source is `b59eee4e13b3a71725b69a914211eea9e7ae75ad`; the subsequent commit is documentation-only.

The [qualified base comparison](https://crabbox.openclaw.ai/portal/runs/run_59926da4d8eb490b0855d67398d0fcd1) has **18 intended assertion failures and 133 passing controls**: routing eight, service-entry/planning four, inspection budgets six. Earlier archived-checkout dependency failures were fixture setup, not product reds; fixed green lanes were not rerun for that repair.

## Integration and remaining proof

The scheduled-task SQL-to-file observer hunk is shared with #204868; the second PR to land rebases the identical hunk rather than maintaining an independent variant.

A rare first-conversion refusal applies when a live foreground Gateway's root is opaque and it cannot accept the requested update over RPC. With operator access, the Gateway can classify its own argv and handle `update.run`. Otherwise the message offers Control UI/operator-access update or stopping the Gateway through its existing owner and rerunning. No lock or protocol field was added.

Against integrated main, the test change measures **+740 lines**, with **340 reviewed allocation lines** above the normal 400-line allowance. `config/test-lines-allocations/204866-install-update-owner.txt` maps the thirteen changed test files to their contracts; upstream-owned native-observer credit was removed. Existing controls preserve package routing, Git SHA, converted/legacy ownership and immutable inspection-only output.

The two existing legacy-layout launcher cases in `git-release.test.ts` now pass the captured state environment and `{ planned: entry }`, retaining both launcher and legacy path assertions. An explicit string entrypoint is reserved for `--restore-service-cli` and must win over ordinary launcher selection; those cases represent ordinary installation planning, not recovery.

The retained legacy service-staging producer resolves its release launcher before passing an explicit service CLI (`d831dde27f`). CI on that head proved the three unchanged no-restart staging cases red: the selector still treated the explicit launcher as a package CLI root. `dd83c4f630` repairs that single selector by directly selecting a recognized accessible Gateway launcher, preserving Node and other recovery strings. [Focused AWS proof](https://crabbox.openclaw.ai/portal/runs/run_cfcb09aada70caf4e34f1ea6f25fb287) passed all three regressions, the existing launcher control, and all four service-entry controls: **8 passed**, unchanged assertions. The 38 unrelated service cases were intentionally excluded by the focused name filter.

Final head `2536f8aea4` passed [CI](https://github.com/openclaw/openclaw/actions/runs/45544076053) and the [security/aggregate gate](https://github.com/openclaw/openclaw/actions/runs/45548330474): **70 successful checks, none pending or failed**. It differs from reviewed/Linux-qualified `48e606149e` only by three local test-helper rename substitutions fixing no-shadow; assertions and production bytes are identical. Main's exact-head and delta reviews are clean.

- [Integrated AWS qualification](https://crabbox.openclaw.ai/portal/runs/run_e165cd4d147a24e0808417237069d4ae) passed: current owner/preview/merge controls, full build, package integrity, and real Linux stable **2026.11.9** upgrade flows. Deferred conversion staged the launcher and committed on public restart; read-only-npm PATH service reinstall kept launcher ExecStart, committed the same pending trial, and the following update committed. A converted node-only install prepared a pending release without activating it; an unconverted node-only install used npm with no trial and named exact install/restart commands rather than claiming activation. Source `48e606149e` is production-identical to final `2536f8aea4`. Healthy relabels retain that source; this is not a schema-bump or live-Windows claim. Historical shallow-Git setup failed before tests and is not a merge gate.
- Windows 11 ARM64 status/restart follows the exclusively owned custody lane; per maintainer direction it can be recorded after landing. No live-Windows pass is claimed.
- All requested landing gates are green. The single required custody merge is complete; Main owns landing. No further scope or merge is planned.

Launcher manifest, budget and one-strike changes are deliberately outside this PR.

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

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 26, 2026
## What Problem This Solves

The launcher currently guesses restore coverage by scanning `.pre-<generation>` files. That freezes directory depth, excluded names and ctime policy into the installed launcher. This is the candidate-writer stage of replacing that knowledge with explicit restore intent (related #204394, #204752, #204775, #198389 and #204095).

## User Impact

The active candidate writes `<prefix>/releases/<target-release-id>/.restore` as `{v:1,runId,files:[{live,preimage}]}` before publishing its replayable swap plan or canonical schema/config changes. The trial's existing target release owns the receipt by construction; run IDs are recorded, not compared. Paths are absolute; null pre-images explicitly remove new files and SQLite WAL/SHM/journal/seal companions.

Under exclusive custody, SQLite originals are checkpointed and closed, then their complete main files are hard-linked as adjacent run-bound images. Publication renames a different prepared inode over the live path; it does not modify the image. Normal adjacent images add no database byte copy. The fallback copies bytes only if the filesystem rejects hard linking, recording its cause. No new size admission or disk-copy reservation is added.

Retries within that prepared release reuse immutable images; another release cannot reuse its receipt, including a retry prepared by old2026.11.15 code. A changed or missing restore plan refuses instead of re-imaging mutated state. Known no-upgrade trials record an empty plan under the same exclusive owner. Ordinary non-trial starts are unchanged. Cleanup consumes only the manifest captured by its own candidate process after confirmed committed IPC, never rereading a slot or matching IDs.

## Scope and Compatibility

Legacy `.pre-<generation>` files and `Trial.config` remain in use: today's launcher continues to work and ignores the new manifest. This PR does not enable external stores yet, change the launcher reader, add reader floors, or start in-place migrations. A hard-linked image is valid for this rename-based swap only; the later in-place cutover must use its approved clone/copy pre-image primitive.

The state owner is the only manifest/image writer. UpdateOwner supplied both revisions of the committed-IPC cleanup caller; no `src/update/` file was edited directly here. Receipts stay with their prepared releases. Old retained-image cleanup errors cannot block a different release's no-upgrade preparation; the A-delayed/B-safe regression remains and also deletes A's receipt before invoking its captured cleanup.

## Evidence

On `8b410b54`, isolated AWS checks passed **88 owner tests**; baseline5e5ecba4 failed exactly the two selected missing-manifest/order regressions. The JSON gate positively verified those causes, not an arbitrary exit. A recovered OOM-interrupted broad run was not claimed green. On `cb5abca7`, **35 changed-owner tests**, assertion safety, SQLite worker/dialect guards, core types and targeted production lint passed on32GiB. Targeted test lint found a shadowing fixture variable, now renamed through LSP. CI's Bun lane exposed an orderly `process.exit(0)` WAL fixture; it now uses a real forced crash and retains the physical WAL/data assertions. This review repair also removes stale-run comparisons by per-release scope and captured cleanup. No manual proof on the new scope has run while the required predecessor PRs are pending.

One-worker AWS wall times at8b410b54: writer63.535s, startup63.798s, swap-owner73.935s. The first writer suite included51.888s compiled-worker preparation; the native filesystem/WAL assertions themselves are small. Current-head CI owns its fresh check results.

The real filesystem WAL/config fixtures asserted hard links with zero byte copies; the forced `EXDEV` fixture exercised one actual copy fallback. No genuine cross-device failure was observed. Adjacent images normally share their source's filesystem; individually mounted files or unsupported hard linking can require the fallback. This is not a population-frequency estimate.

**Must not land before #204868 (custody), then #204866 (install owner).** Per the lead's sequence, merge main once after both land, then run the native crash/full-package qualification on that integrated head. No further manual writer proof will run before that point. The hard-link immutability assumption requires custody; checkpointing alone is not claimed to fix the previously observed malformed rollback. The in-place/floor stage separately waits for ReaderFloor.

## Size

`tokei` on all four touched production files, including the update caller, against integrated main25efa334: **1,058 → 1,388 (+330)**. Tests: **+479 net lines**, with a 79-line excess allocation for distinct WAL, durable-ordering, retry, frozen rollback, symlink, captured cleanup and startup contracts. No competing legacy reader is deleted in this explicitly sequenced writer-first stage; its removal belongs to the following reader PR.

## Conflict Integration

Merged main25efa334 once to clear the named conflict. Resolutions retained main's config/include inventory and external/workspace/missing-include fixtures together with the managed-trial manifest case. No `src/update/` conflict or direct edit was involved. No manual proof was run. The later main merge and native crash qualification still wait for the predecessor landing order above.

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

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 26, 2026
Related: #204915, #205578, #204868

## What Problem This Solves

Existing launcher tests construct the trial, restore manifest and candidate IPC messages themselves. A candidate producer can drift while those consumer tests remain green, despite an installed launcher keeping its frozen interface.

## User Impact

No runtime behavior changes. This adds one owner test file for compatibility with today's format4 launcher, v2 trial, v1 per-release restore manifest and compiled20-minute default. The current2-attempt and exit78 behavior remain unchanged and covered by their existing lifecycle tests. No production/stored/header/schema change or new production test seam.

## Why This Change Was Made

Three small cases cover the missing boundaries without replaying the lifecycle suite:

- Real `createTrialPending` bytes, minimal/full optional input, independent stored-key/v2 ABI guard, and literal `1_200_000` default.
- Real candidate manifest publisher output independently checked against the deployed literal v1 root/pair ABI (entry order is not pinned; positive preimages must be absolute), then consumed by the frozen manifest reader on actual files. The literal check prevents coordinated writer/reader drift from moving the oracle; existing writer tests retain their SQLite inventory coverage.
- One isolated child imports the real `announceReady`/stop listener and exchanges frames with a pinned format4 peer. A collector is installed at spawn, return must precede stop, stdin provides the serving keepalive without sleeps/polling, and child home/state/config paths are all private.

The IPC case does not distinguish ACK processing from the supported on-disk fallback. Actual stage-mark producer coverage at `config-preflight-snapshot.ts:468` is separately recorded: exercising its full admission/recovery graph is outside this bounded harness; existing launcher stage-consumer tests remain unchanged. This PR does not claim that fourth producer frame is exercised.

Production delta: **0**. One228-line owner file, below the400net test-line allowance; no allocation/waiver.

## Evidence

- Base: `b1d355fcc9fcf91a4514c2612ce7b33211c710b6`.
- **Mutation RED:** [AWS run_14f78c186994742f3077d3a597297ada](https://crabbox.openclaw.ai/portal/runs/run_14f78c186994742f3077d3a597297ada),2artifact cases passed and the IPC assertion failed with expected `openclaw.ready` / actual `openclaw.contract-mutant`. This was one temporary producer discriminant edit, restored exactly before GREEN and not included in this PR.
- **Initial restored GREEN:** [AWS run_210b1aac2726928af6ebc89d25e4ef12](https://crabbox.openclaw.ai/portal/runs/run_210b1aac2726928af6ebc89d25e4ef12),3/3cases/types/lint/guard passed; one exact formatting wrap applied from AWS oxfmt.
- **Review repair GREEN:** [AWS run_a4905843c4d73632f1ef06ac4d40e00a](https://crabbox.openclaw.ai/portal/runs/run_a4905843c4d73632f1ef06ac4d40e00a), independent manifest ABI pin added;3/3cases, owner-project types, lint, format and guard all exit0 (+228/400). No production changes or mutation repeat.
- **Cost:** AWS cases42ms/17ms/4147ms = **4.206s test time**; file wall46.91s / shard49.93s includes35.777s shared compiled-generation preparation. [CI Bun owner job](https://github.com/openclaw/openclaw/actions/runs/45763730662/job/139720273166) passed3/3 at43ms/22ms/3862ms = **3.927s test time**, file10.26s / shard11.49s. Both meet the5s test-time target; no added readiness sleeps/polls or product boots.
- Both owned AWS leases (`cbx_af0ca4a223fc`, repair `cbx_7a77e1c11a2c`) released with `--wait`, exit0; all receipts are under `direction-2026-11-24/updateowner-frozen-contract-*`.
- Existing unchanged primary tests cover format4 protection (`launcher.test.ts:496`),2-start rollback (`:216`), stage handling (`:434`), stop forwarding (`:401`), and serving/trial exit78 (`:378/:385`); real CLI refusal78 is covered by `pre-bootstrap.process.test.ts`.
- Exact-head local review on `298da439f4f024c83091c9e5148fb022753294d9` is complete: patch correct, security cleared, no findings, confidence0.88 (`~/.cache/clawsweeper-local-review/298da439f4f0.md`). No package build/native matrix is claimed or required for this test-only, production-identical change. CI pending.

Co-authored-by: Ayaan Zaidi <[email protected]>
(cherry picked from commit da256ce)
Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 27, 2026
Related: openclaw#204915, openclaw#205578, openclaw#204868

## What Problem This Solves

Existing launcher tests construct the trial, restore manifest and candidate IPC messages themselves. A candidate producer can drift while those consumer tests remain green, despite an installed launcher keeping its frozen interface.

## User Impact

No runtime behavior changes. This adds one owner test file for compatibility with today's format4 launcher, v2 trial, v1 per-release restore manifest and compiled20-minute default. The current2-attempt and exit78 behavior remain unchanged and covered by their existing lifecycle tests. No production/stored/header/schema change or new production test seam.

## Why This Change Was Made

Three small cases cover the missing boundaries without replaying the lifecycle suite:

- Real `createTrialPending` bytes, minimal/full optional input, independent stored-key/v2 ABI guard, and literal `1_200_000` default.
- Real candidate manifest publisher output independently checked against the deployed literal v1 root/pair ABI (entry order is not pinned; positive preimages must be absolute), then consumed by the frozen manifest reader on actual files. The literal check prevents coordinated writer/reader drift from moving the oracle; existing writer tests retain their SQLite inventory coverage.
- One isolated child imports the real `announceReady`/stop listener and exchanges frames with a pinned format4 peer. A collector is installed at spawn, return must precede stop, stdin provides the serving keepalive without sleeps/polling, and child home/state/config paths are all private.

The IPC case does not distinguish ACK processing from the supported on-disk fallback. Actual stage-mark producer coverage at `config-preflight-snapshot.ts:468` is separately recorded: exercising its full admission/recovery graph is outside this bounded harness; existing launcher stage-consumer tests remain unchanged. This PR does not claim that fourth producer frame is exercised.

Production delta: **0**. One228-line owner file, below the400net test-line allowance; no allocation/waiver.

## Evidence

- Base: `7b7ab99c118fb9760d2f2f2078248e221c56217b`.
- **Mutation RED:** [AWS run_14f78c186994742f3077d3a597297ada](https://crabbox.openclaw.ai/portal/runs/run_14f78c186994742f3077d3a597297ada),2artifact cases passed and the IPC assertion failed with expected `openclaw.ready` / actual `openclaw.contract-mutant`. This was one temporary producer discriminant edit, restored exactly before GREEN and not included in this PR.
- **Initial restored GREEN:** [AWS run_210b1aac2726928af6ebc89d25e4ef12](https://crabbox.openclaw.ai/portal/runs/run_210b1aac2726928af6ebc89d25e4ef12),3/3cases/types/lint/guard passed; one exact formatting wrap applied from AWS oxfmt.
- **Review repair GREEN:** [AWS run_a4905843c4d73632f1ef06ac4d40e00a](https://crabbox.openclaw.ai/portal/runs/run_a4905843c4d73632f1ef06ac4d40e00a), independent manifest ABI pin added;3/3cases, owner-project types, lint, format and guard all exit0 (+228/400). No production changes or mutation repeat.
- **Cost:** AWS cases42ms/17ms/4147ms = **4.206s test time**; file wall46.91s / shard49.93s includes35.777s shared compiled-generation preparation. [CI Bun owner job](https://github.com/openclaw/openclaw/actions/runs/45763730662/job/139720273166) passed3/3 at43ms/22ms/3862ms = **3.927s test time**, file10.26s / shard11.49s. Both meet the5s test-time target; no added readiness sleeps/polls or product boots.
- Both owned AWS leases (`cbx_af0ca4a223fc`, repair `cbx_7a77e1c11a2c`) released with `--wait`, exit0; all receipts are under `direction-2026-11-24/updateowner-frozen-contract-*`.
- Existing unchanged primary tests cover format4 protection (`launcher.test.ts:496`),2-start rollback (`:216`), stage handling (`:434`), stop forwarding (`:401`), and serving/trial exit78 (`:378/:385`); real CLI refusal78 is covered by `pre-bootstrap.process.test.ts`.
- Exact-head local review on `298da439f4f024c83091c9e5148fb022753294d9` is complete: patch correct, security cleared, no findings, confidence0.88 (`~/.cache/clawsweeper-local-review/298da439f4f0.md`). No package build/native matrix is claimed or required for this test-only, production-identical change. CI pending.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 27, 2026
## Problem

A one-shot CLI (`openclaw agent --local`) boots a fresh shared-state reader worker for every state read: since #204868, each successful one-shot read retires its worker so that no SQLite handle outlives the read (Windows `EPERM` on a release switch). The handle release is required; the worker exit is not. Each boot re-imports the reader's module graph (~90-880 modules, ~140 ms CPU per boot measured with per-thread `--cpu-prof`).

## Change

`src/state/openclaw-state-read-worker.ts`: in the `cli-oneshot` role, a successful read no longer retires its reader. It closes the task, then joins `closeReadResources(pool)` before the result returns:

- Node (`explicitSqliteCloseReleasesNativeResources`): native handles close in place and the isolate stays for the next read.
- Runtimes without explicit native close: `closeReadResources` rotates the pool, which joins worker exit, as before.

The kept reader exits when the command closes shared state at CLI cleanup (`withCliCommandCleanup` resets the state-database lifecycle, which closes the read pools). Other roles are unchanged.

The #206466 gate budget drops from 19 to 17 worker threads before the first request.

## Guarantee kept

No SQLite handle outlives a successful one-shot read: the result still settles only after the native release completes. `src/state/openclaw-state-read-source.test.ts`:
- `releases CLI reader handles before a successful read returns and keeps the reader`: replaces the per-read exit assertion. The read result stays pending until the handle release settles, the task closes without retiring, one pool is created for four reads, and `closeOpenClawStateDatabaseAsync()` (the CLI cleanup path) closes that pool.
- `uses the cli-oneshot process lifetime for early awaited reads`: tasks close without retirement in `cli-oneshot`.

## Evidence

- Worker threads started before the first provider request, `src/cli/agent-local-cold-start.process.test.ts` (Node, macOS arm64): 18 -> 16. Linux CI was 19 before; the budget is 17.
- Per-thread CPU profile of one fake-provider turn (3 runs, median): 4 state-read worker boots per turn at 137 ms boot CPU each; this change removes 2 of them in the measured turn (one stays, admission reads keep their worker).
- Tests: the 26 test files under `src/state/openclaw-state-read*` plus every importer of `openclaw-state-read-worker.js`, `src/cli/agent-local-cold-start.process.test.ts`, `src/cli/agent-local-rpc-cleanup.process.test.ts`, `src/cli/one-shot-exit.cleanup.process.test.ts` pass locally.
- Wall-time ABAB is owed: host load stayed above 20 during this work; it will be appended to the W4 status at load < 10.

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

## Problem

A one-shot CLI (`openclaw agent --local`) boots a fresh shared-state reader worker for every state read: since openclaw#204868, each successful one-shot read retires its worker so that no SQLite handle outlives the read (Windows `EPERM` on a release switch). The handle release is required; the worker exit is not. Each boot re-imports the reader's module graph (~90-880 modules, ~140 ms CPU per boot measured with per-thread `--cpu-prof`).

## Change

`src/state/openclaw-state-read-worker.ts`: in the `cli-oneshot` role, a successful read no longer retires its reader. It closes the task, then joins `closeReadResources(pool)` before the result returns:

- Node (`explicitSqliteCloseReleasesNativeResources`): native handles close in place and the isolate stays for the next read.
- Runtimes without explicit native close: `closeReadResources` rotates the pool, which joins worker exit, as before.

The kept reader exits when the command closes shared state at CLI cleanup (`withCliCommandCleanup` resets the state-database lifecycle, which closes the read pools). Other roles are unchanged.

The openclaw#206466 gate budget drops from 19 to 17 worker threads before the first request.

## Guarantee kept

No SQLite handle outlives a successful one-shot read: the result still settles only after the native release completes. `src/state/openclaw-state-read-source.test.ts`:
- `releases CLI reader handles before a successful read returns and keeps the reader`: replaces the per-read exit assertion. The read result stays pending until the handle release settles, the task closes without retiring, one pool is created for four reads, and `closeOpenClawStateDatabaseAsync()` (the CLI cleanup path) closes that pool.
- `uses the cli-oneshot process lifetime for early awaited reads`: tasks close without retirement in `cli-oneshot`.

## Evidence

- Worker threads started before the first provider request, `src/cli/agent-local-cold-start.process.test.ts` (Node, macOS arm64): 18 -> 16. Linux CI was 19 before; the budget is 17.
- Per-thread CPU profile of one fake-provider turn (3 runs, median): 4 state-read worker boots per turn at 137 ms boot CPU each; this change removes 2 of them in the measured turn (one stays, admission reads keep their worker).
- Tests: the 26 test files under `src/state/openclaw-state-read*` plus every importer of `openclaw-state-read-worker.js`, `src/cli/agent-local-cold-start.process.test.ts`, `src/cli/agent-local-rpc-cleanup.process.test.ts`, `src/cli/one-shot-exit.cleanup.process.test.ts` pass locally.
- Wall-time ABAB is owed: host load stayed above 20 during this work; it will be appended to the W4 status at load < 10.

Co-authored-by: Ayaan Zaidi <[email protected]>
tideclaw-bot added a commit that referenced this pull request Nov 28, 2026
Source commit: e77d359
Source PR: #204868
Source commit: 0cf5a01
Source PR: #205101

Release adaptation: Build on fc6a025's existing lock, borrower, lease and
handoff changes. Retain stable's Scheduled Task activation split and bind
its fallback and cleanup to the captured task command and existing deadline.
Preserve stable's system-scope routing and activation callbacks. Release
custody at stable's retained updater dispatch, rechecking authority before
launch. The main-only resident launcher, file-only trials and crash-survivor
jobs have no counterpart on this branch. Retain policy limits unchanged;
move the restart attempt budget helper to its existing constants owner.
Keep native supervisor discovery and short cleanup timers real in the stop
watchdog fixture so the host's systemd cgroup does not stall the fixture.
State schema 40 and agent schema 42 are unchanged.

Co-authored-by: RomneyDa <[email protected]>
tideclaw-bot added a commit that referenced this pull request Nov 28, 2026
The #204868 remainder port checked the parent executor fence from inside the delegated native child interval. The fence deliberately refuses parent mutations during that interval, so every retained install or restart returned recovery-pending before spawning its receiver.

Release adaptation: Drain shared state and recheck the parent fence before delegating. Keep the existing child lease validation and process binding, post-settlement fence, and refusal to launch when custody release fails. This preserves the upstream custody handoff without importing main’s replacement update owner or changing either state schema.

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

Labels

cli CLI command changes commands Command implementations docker Docker and sandbox tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. 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.

[Bug]: Windows Scheduled Task restart and health CLI keep waiting after a resident Gateway trial commits

2 participants