Repository navigation
feat(state): upgrade state by copy and swap at Gateway startup - #198389
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
8032fd2 to
d2cfb25
Compare
|
Codex review: needs maintainer review before merge. What this changesThis PR upgrades older SQLite state in a private copy and publishes it through a resumable file swap during Gateway startup. Example: Start a new Gateway against populated OpenClaw 2026.7.1 state.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep this PR open: it provides useful startup recovery absent from main, and the previous cross-filesystem config finding is fixed in source; no new actionable code defect was established. Priority: P1 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherGateway bootstrap admits the selected installation, acquires file-only state ownership, runs Doctor against a private state copy, and publishes validated databases and configuration before normal readers start. flowchart TD
A[Gateway startup] --> B[Admission and state ownership]
B --> C[Private state copy]
C --> D[Doctor migration chain]
D --> E[Validation or fallback rebuild]
E --> F[Durable swap plan]
F --> G[Live state and preserved generation]
Technical reviewBest possible solution: Keep startup migration under the existing state-ownership boundary, reuse Doctor's transformations, and publish only the admitted private result with recoverable previous files. Do we have a high-confidence way to reproduce the issue? The existing startup path and supplied prior-release Gateway results establish the migration-refusal problem; this read-only review executed no target code. Is this the best way to solve the issue? The staged implementation reuses Doctor's migration owners and adds the missing private-copy publication boundary, with retained paths and compatibility exceptions explicitly explained. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 257759ae2be0. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfacePR surface statistics unavailable: the file list is incomplete. Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (7 earlier review cycles)
Reviewed November 15, 2026, 2:35 PM ET / 19:35 UTC (Revision 8). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
df17822 to
ea2bef4
Compare
Gateway startup now owns the state upgrade. When the shared or an agent database is older than this build, the state directory is copied into a private shadow, this build's Doctor runs on the shadow only, the result is validated (version, integrity_check, foreign_key_check, per-table row conservation) and a durable plan renames it into place. Every replaced or retired live file is kept as <name>.pre-<version>; the live files are never written before the plan is durable, and an interrupted plan is finished on the next start. If the chain fails, a generic name-matched rebuild produces the databases: casts to declared types, BLOB text decoding, the shipped v12/v13 fold-in steps on a scratch copy, newest row on key collisions, and rows that do not fit set aside in diagnostic_events. The old generation is pinned and the Gateway still starts. One prior generation is retained. Adds the populated prior-release corpus (2026.7.1 to 2026.10.10) with a generic-rebuild test and an e2e test that starts the Gateway on each. Co-authored-by: obviyus <[email protected]>
…199929) Follow-up hardening of the Gateway startup copy-and-swap state upgrade (#198389, owner @obviyus). - Copy only migration inputs: exclude managed worktrees, agent workspaces, nested mounts/subvolumes, Knowledge, browser profiles, backups, caches and media payloads (outgoing records stay); skip non-target SQLite families above 64 MiB. - Copy SQLite files as byte copies (never reflinked) into NOCOW-prepared directories on btrfs, best-effort; recover WAL/journal content privately in the shadow. - Refuse before copying when free space is short, with exact numbers; log large copies with size, elapsed time and rate. - Never replace or remove a live file the copy did not include (fixes Doctor templates overwriting uncopied workspace files). - Prune only older `.pre-<version>` generations beside files the upgrade publishes; keep retired migration backups and recovery images and report their count and bytes. Inherited red: check-lint-core-2 fails on src/agents/tool-search-prepared-catalog.ts:118 (unicorn/prefer-structured-clone), a file this change does not touch.
…penclaw#199929) Follow-up hardening of the Gateway startup copy-and-swap state upgrade (openclaw#198389, owner @obviyus). - Copy only migration inputs: exclude managed worktrees, agent workspaces, nested mounts/subvolumes, Knowledge, browser profiles, backups, caches and media payloads (outgoing records stay); skip non-target SQLite families above 64 MiB. - Copy SQLite files as byte copies (never reflinked) into NOCOW-prepared directories on btrfs, best-effort; recover WAL/journal content privately in the shadow. - Refuse before copying when free space is short, with exact numbers; log large copies with size, elapsed time and rate. - Never replace or remove a live file the copy did not include (fixes Doctor templates overwriting uncopied workspace files). - Prune only older `.pre-<version>` generations beside files the upgrade publishes; keep retired migration backups and recovery images and report their count and bytes. Inherited red: check-lint-core-2 fails on src/agents/tool-search-prepared-catalog.ts:118 (unicorn/prefer-structured-clone), a file this change does not touch.
…ase link (#199706) ## Problem A Git checkout install runs its Gateway from `<checkout>/dist/index.js`, and `openclaw update` rewrites that same tree. Everything around the rewrite exists to survive it: the updater copies its own runtime first (133–892 s on a 183k-file checkout), builds the candidate in a private repository and imports it through a pack (256 MB cap), stops and parks the serving Gateway, and rewrites the service definition every update. ## Change Extends #198835's linked package root (merged as `b868ed4c`) to Git checkouts, per the #197949 design. Based on `main`. It reuses #198835's release resolver, `switchPackageReleaseLink`, leases and 24 h collection unchanged. Its fallback follows `installStagedPackage`: when the layout can't be used, the update runs in place with a `recoverable-maintenance` warning, and the next update tries the layout again. The Gateway process never writes the release link. The only other writer is the boot launcher, and it only points the link back to the release recorded in a failed trial. - **Layout.** `<stateDir>/git-install/lib/node_modules/openclaw -> releases/<id>/lib/node_modules/openclaw`. Each release is `git worktree add --detach` off the developer's checkout (shared object store, no clone or copy). - **Stage.** The existing candidate preflight (candidate walk, local-commit replay, `pnpm install --frozen-lockfile`, build, candidate checks) runs in the new release's worktree, then `--version` with the service's Node. A same-source no-op requires the serving release to be at the checkout's commit and its artifacts to verify (#158931). - Deviation from the design: the worktree is built at `releases/<id>/build`, then moved into place with `git worktree move`. Node refuses to strip types under `node_modules` (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`), and the build runs `.mts` scripts. The built tree has no absolute symlinks, so the move is safe. - **Switch.** `switchPackageReleaseLink` from #198835. The serving Gateway keeps its release (Node resolves the entry's real path), so nothing is stopped, parked or verified before the flip. - **Restart.** The serving Gateway's maintenance tick sees the link move (installation replacement) and restarts itself into the new release. The updater waits for that successor (up to 90 s), then verifies. It falls back to a native restart only if no successor appears. A native restart from inside the service job (`update.run`) would end the updater itself. - **Service.** Written once, at conversion, to a frozen launcher `<stateDir>/git-install/openclaw-launcher.mjs`. A unit that names the launcher is never regenerated. The launcher is needed because a release that fails while loading never reaches Gateway code. - **Trial.** The switch writes `releases/.trial`. The launcher counts starts. - After two failed starts it switches the link back and restores the trial build's `*.pre-<buildId>` state files (falling back to #198389's `*.pre-<version>`). Each SQLite family is restored together, and trial-created WAL/journal/SHM/seal files without a preserved predecessor are removed. The launcher mirrors #198389's `companionRemovals` list because it must not load release code. - The trial ends when the Gateway's first maintenance tick runs, or when the updater verifies the restarted Gateway. The second path also covers targets that predate this PR. - Writes made during a failed trial are lost (approved). - **The layout never fails an update** (#197949 decision 8). If `releases/` cannot be created, or something other than a release link sits at the package path, the update records a warning and takes the in-place runner. The next update tries the layout again. - **Post-core work** (requested-channel persistence, plugin convergence) runs in the updater, but only after the restarted release verified and its trial ended. A failed trial therefore never leaves plugins that require the release it switched away from. It runs without Doctor maintenance, which the Gateway holds, and without a plugin cohort, because no core rollback exists to pair it with. If plugins changed, the Gateway is asked to restart again (SIGUSR2). Under `--no-restart` the release is unverified, so only the requested channel is persisted and plugins converge on a later update. - **The developer's checkout** is never written. The first update builds the commit that serves now as the first release, rewrites the unit once, then stages the target. - **Retention.** #198835's collection, followed by `git worktree prune`. `git-install` is excluded from backups and from the startup state-upgrade copy. The latter is the same change as #199770, included here so the stack stands alone. - **One owner.** `usesGitReleases` selects releases. Windows checkouts and package-to-Git switches keep the in-place runner, and the in-place CLI tests are pinned to that runner. For Git releases this skips: - runtime retention - the pack transfer/import - the managed-service stop/park - the database rollback capture - the checkout's source-artifact lock - the native restart from inside the service job - per-update service regeneration ## In-place fallback (decided) Windows Git checkouts, package-to-Git switches, and checkouts with no installed Gateway service still use the in-place runner, so this PR bypasses that runner on POSIX instead of deleting it. A checkout with no service is run by hand, so nothing would start through the release link and its next start would run the old commit. `gatewayServiceOwnsGitInstall` reads the installed service once and accepts it only when the service owns the checkout or its release link. The command decides once and hands that decision to the runner. Prod LOC is net **+980**. Decided 2026-11-16: Windows Git updates are not refused. A follow-up, slice 4b (stacked on this PR), moves Windows to releases using junctions and then deletes the in-place Git runner. ## E2E (mbp-m5, launchd, isolated profiles, shared-clone checkout; ≤15 min per run, ≤3 in parallel) **Final head `0b96d640` (rebased on `main` at `8a82b5e0`): local ClawSweeper review clean** (gpt-6.1-sol, normal speed). After the rebase: `sweepPackageReleaseTemporaryLinks` is exported again, because the first Git publish uses it. The CI ratchets are satisfied: a lazy generation name, Node-only release tests, and an allocation record for the regression tests. A conversion's first release is now the commit the checkout's `dist` serves, not a pulled HEAD that was never rebuilt. A failed trial also restores a symlinked config: a preserved symlink is judged by its own time, not its target's. Rollback across same-version upgrades (decision d): the state upgrade now keeps a replaced file as `<file>.pre-<buildId>`, named after the build that replaced it, so two builds of one version each keep their own predecessor. Builds without a build ID, and earlier releases, still write `.pre-<version>`. Retention handles both forms. A failed trial restores the `.pre-<buildId>` of its own build, falling back to `.pre-<version>`. Fixes to the trial and launcher from the review rounds: - the inventory is recorded before anything is restored, so an interrupted rollback can resume without losing a restored WAL; - the trial's applied or interrupted upgrade plan is retired and the files it added are removed; a removal that fails is retried at the next start; - the config path is the one the update resolved (`~` and external paths included); - state is restored before the link moves back. The release layout is used only when the release switch actually reaches the next start: either the service already starts the launcher, or it owns the checkout and this update rewrites its definition and restarts it. `--no-restart` on a converted install leaves the serving release selected. The next start, which the operator triggers, selects the new release, without the two-start fallback. A first conversion requested with `--no-restart` stays in place. | Run (mbp-m5, isolated launchd profiles) | Head | Result | |---|---|---| | Release that crashes on boot | `d6d30a5e` (the final head changes only how a symlinked backup is dated) | update reports `build-id-mismatch` after 179 s; two "e2e boot crash" starts, then "failed to start twice; switched back"; link back on the previous release, trial cleared, `ready` | | Conversion before the crash run | `d6d30a5e` | ok, 267 s | **Current head `6d9acd6e` (on `main`), mbp-m5, isolated launchd profiles:** | Run | Result | |---|---| | Conversion (first update from a checkout service) | ok, root on the release link; 610 s with three runs in parallel; longest outage 9.7 s | | Release → release | ok, 239 s, longest outage 9.9 s | | `update.run` through the Gateway | `finished\|succeeded`, 135 s; link moved, Gateway restarted, plist unchanged; outage 7.8 s | | Checkout with no Gateway service | updated in place: checkout HEAD moved to the target, no `git-install/releases`, result `ok`, mode `git` | | Release that crashes on boot (at `0e3fefae`) | update reports `build-id-mismatch` after 188 s; after two "e2e boot crash" starts the launcher logs "failed to start twice; switched back", and the previous release serves `ready` | | v2026.11.4 state → this head | see Data-model compatibility | Older rows below ran at earlier heads. Rows marked ‡ ran at head `8a720e49`, rows marked † at `6032dedf`; the rest ran at `1140b601`, before plugin convergence moved after verification. At the final head `99b7f080` (rebased onto `823fa6d2`), three runs ran in parallel on mbp-m5. (1) Conversion and release→release passed again, with the root on the release link and a longest outage of 7.6 s. (2) `update.run` finished `succeeded` (link moved, Gateway restarted, plist unchanged, outage 8.0 s). (3) A checkout with **no Gateway service** updated in place: checkout HEAD moved to the bumped commit, no `git-install/releases` was created, and the result was `ok`, mode `git`, root the checkout. An intermediate head `2d2387b6` keyed this choice on a preflight fact that Git installs never fill in, so conversion fell back to in-place (about 120 s outage). That head was never pushed. | Case | Result | | --- | --- | | † First update of a checkout install (conversion, head→head+1) | ok, 402 s wall (two builds, three runs in parallel), longest outage 7.6 s, total 13.1 s (unit rewrite, then a restart after plugin convergence); unit rewritten once to the launcher; checkout tree clean; no retention, pack or handoff steps | | ‡ Release→release (head+1→head+2) | ok, 180 s wall, one outage of 7.2 s; unit untouched (mtime unchanged since conversion); service runs from `releases/` | | ‡ `--no-restart` on a switched release | the updater leaves the Gateway running and converges no plugins; within the next maintenance tick the Gateway restarts itself into the release, and the trial is cleared; outage 7.5 s | | † `update.run` via the Gateway (`openclaw gateway call update.run`) | run `finished|succeeded`, 140 s; link moved; the Gateway restarted itself; unit untouched; outage 7.4 s | | Already-current rerun from the preserved checkout after conversion (head `60503ab3`) | `skipped: already-current`, link unchanged, 113 s | | † Release that crashes on boot | two crashes, the launcher switched back to the previous release, Gateway ready again; the update reports `build-id-mismatch`; longest outage 28.9 s | | kill -9 mid-stage | link and serving Gateway unchanged; the rerun succeeds; a partial release directory left by the killed run is collected after 24 h | | kill -9 right after the link moves, before restart | the old Gateway keeps serving; the rerun reports `skipped: already-current`; the Gateway restarts itself into the new release and the trial is cleared | | `env -i` + `umask 077` (conversion, then release→release) | ok, 376 s and 198 s, outages 5.5 s and 7.5 s; launcher `0700` under umask 077 | | Install whose unit and state were written by 2026.11.3, moved to head, then converted | ok, 229 s, outage 5.9 s; state DB `integrity_check` ok. 2026.11.3's own updater could not reach head on mbp-m5: it walked back to `already-current` (Node 24.21 below head's `engines`), so that hop was done with `git reset` + `ocx build` | | Production-shaped install (207,229-file checkout, +3 GB SQLite in state), release→release | ok, 145 s, outage 6.9 s, no retention step. Main was not timed on this host. Peanutto's production main run `90c601fc` took 4,150 s, with 892 s retention and a 300 s outage | Not exercised: a plugin-only restart (SIGUSR2) after npm plugins actually change; the fixtures have no npm plugins. ## Data-model compatibility - **No new state schema.** This diff adds or changes no SQLite schema, migration, or config schema file. The update ledger (`update_runs`), Gateway owner lease and config are read and written exactly as on the base. - **`origin` stays compatible.** `UpdateRunRecordSchema.origin` (including #198835's `packageStage` and `packageRelease`) is unchanged, and Git-release updates write no new `origin` key. A Git release records its switch in the result step and the release directories, not the ledger. So rows written by older builds parse as before, and rows written by this build parse in an older build. A Git checkout that can't use the layout falls back to the in-place runner with a `recoverable-maintenance` advisory (`git-release-layout` step), the same contract as `installStagedPackage`'s swap fallback. - **New on-disk state is additive and lives under `<stateDir>/git-install/`:** `releases/<id>/` (detached worktrees), the `lib/node_modules/openclaw` link, `releases/.trial`, and the launcher. An install without them is treated as unconverted and gets the conversion path. If the layout is unusable, the update falls back to in-place (decision 8). - **Existing data proof: v2026.11.4 state upgraded and converted (E2E, `6d9acd6e`).** - The v2026.11.4 Gateway, started with `--profile`, created `state/openclaw.sqlite` (schema 22) and an agent DB. - This head's `gateway install` then stopped with "Client credentials require backed-up migration custody; … run openclaw doctor --fix". Plain `main` (`964ab522`) stops with the same message on a copy of that state, so it comes from `main`, not this diff. - Following the message, `openclaw doctor --fix --non-interactive` migrated the state to schema 40. After that, install succeeded and the update converted the checkout onto the release link. The `update_runs` row in the stable-created database reads `finished|succeeded`, and the stable config (Gateway port) still reads back. - **Rollback keeps data readable:** the crash-release trial switches the link back to the previous release, and the launcher restores the SQLite family (`openclaw.sqlite`, `-wal`, `-shm`) captured before the trial. The previous build reopens its own database (crash row, 28.9 s). ## Tests - `src/infra/git-release.test.ts`: - trial fallback restores the SQLite family and drops trial-only companions - trial settlement - launcher mapping - a launcher unit is owned without regeneration - a non-link package path falls back to the in-place runner with a reason - `src/infra/update-runner-git-release.test.ts`: - a same-commit release with unverified artifacts is rebuilt - a current release is reported prepared, so finalization never regenerates it - the first release comes from the serving worktree's commit, and the checkout's different target is still built - `update-command-post-update.test.ts`: a switched release converges plugins only after its restart. - `git-release.test.ts`: a checkout with no owning Gateway service keeps the in-place runner. The test fails without the gate. - `update-command-execution-validation.test.ts`: when a developer build holds the checkout's artifact lock, a Git release update still runs. It never takes that lock, because releases build in their own worktrees. The test fails without the fix. - `update-command-convergence-authority.test.ts`: under `--no-restart`, a switched release persists the channel and leaves plugins alone; an already-current rerun from the checkout of a converted install completes. - `update-runner-git-release.test.ts`: a successful rebuild of an incomplete runtime reports the new release's verdict. - `update-command-convergence-authority.test.ts`: release convergence runs in the updater, with no fresh process and no Doctor. - `update-command-verification.test.ts`: - a verified release ends its trial - a switched release's Gateway restarts itself without a native restart - `src/state/state-upgrade.test.ts`: `git-install` stays out of the startup upgrade copy. - Gates: `pnpm tsgo:core`, `pnpm check:test-types`, oxlint/oxfmt on changed files. On mbp-m5 at `99b7f080`, the broad update suite plus the package-release and package-update tests pass 1,944 / 1,948, with 1 skipped. The 3 failures are environmental: - `update-runner-git-node-preflight` ×3: mbp-m5's Node 24.21 is below `engines`. ## LOC prod +1018 / −38 (net +980); test +951 / −3. Draft: lands after #198835. #198389 has merged; #199770 carries the same startup-copy exclusion for main. Co-authored-by: Ayaan Zaidi <[email protected]>
## Problem When a Gateway upgrades existing state at startup (copy-and-swap from #198389), a later read through the shared-state read worker can fail with `disk I/O error` (`ERR_SQLITE_ERROR`, errcode 1802 = `SQLITE_IOERR_FSTAT`). The failing component depends on which reader runs next: - secret activation: `Startup failed: required secrets are unavailable ... disk I/O error`. The Gateway does not start. - host-link repair: `Could not repair OpenClaw host links: Error: disk I/O error`. Warning only. Fresh state (no upgrade) does not fail. ## Cause 1. Before the swap, `admitConfig` validates the shadow config. That reads plugin metadata from the **shadow** `state/openclaw.sqlite` through a read worker, which retains the connection (keyed by physical identity). 2. `beforeSwap` closes only the predecessor (live) identity, so the shadow reader survives. 3. The swap renames the shadow inode into the live path. The retained reader still records the shadow pathname. 4. The upgrade left the database in rollback-journal mode; startup's first writer switches it back to WAL. The retained reader then looks for WAL/SHM at the vanished shadow pathname and fails. ## Fix In `upgradeStateDirectory`, close the shadow shared-state path through the existing `closeOpenClawStateDatabaseByPathAsync` in a `finally` right after config admission, before refusal cleanup or rename. ## Evidence - Regression test `state-upgrade.test.ts` › "reopens shared-state workers after the copy-and-swap upgrade": old-schema state, lock inspection, shadow metadata read in `admitConfig`, real predecessor close in `beforeSwap`, swap, first writer WAL transition, then a worker read of the newly written row. - Red on merge base `1f75f9ce`: `Error: disk I/O error`, `{ code: 'ERR_SQLITE_ERROR', errcode: 1802 }`. - Green with the fix (12/12 in the file). - End to end (Gateway from source): state written by released `[email protected]`, then the same pristine copy started on the merge base and on this branch. Both run the state upgrade. Merge base: 1 `disk I/O` error after the upgrade. This branch: 0. - `tsgo:core`, oxfmt, oxlint on changed files: pass. Co-authored-by: Ayaan Zaidi <[email protected]>
…ase link (openclaw#199706) ## Problem A Git checkout install runs its Gateway from `<checkout>/dist/index.js`, and `openclaw update` rewrites that same tree. Everything around the rewrite exists to survive it: the updater copies its own runtime first (133–892 s on a 183k-file checkout), builds the candidate in a private repository and imports it through a pack (256 MB cap), stops and parks the serving Gateway, and rewrites the service definition every update. ## Change Extends openclaw#198835's linked package root (merged as `540d13a5`) to Git checkouts, per the openclaw#197949 design. Based on `main`. It reuses openclaw#198835's release resolver, `switchPackageReleaseLink`, leases and 24 h collection unchanged. Its fallback follows `installStagedPackage`: when the layout can't be used, the update runs in place with a `recoverable-maintenance` warning, and the next update tries the layout again. The Gateway process never writes the release link. The only other writer is the boot launcher, and it only points the link back to the release recorded in a failed trial. - **Layout.** `<stateDir>/git-install/lib/node_modules/openclaw -> releases/<id>/lib/node_modules/openclaw`. Each release is `git worktree add --detach` off the developer's checkout (shared object store, no clone or copy). - **Stage.** The existing candidate preflight (candidate walk, local-commit replay, `pnpm install --frozen-lockfile`, build, candidate checks) runs in the new release's worktree, then `--version` with the service's Node. A same-source no-op requires the serving release to be at the checkout's commit and its artifacts to verify (openclaw#158931). - Deviation from the design: the worktree is built at `releases/<id>/build`, then moved into place with `git worktree move`. Node refuses to strip types under `node_modules` (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`), and the build runs `.mts` scripts. The built tree has no absolute symlinks, so the move is safe. - **Switch.** `switchPackageReleaseLink` from openclaw#198835. The serving Gateway keeps its release (Node resolves the entry's real path), so nothing is stopped, parked or verified before the flip. - **Restart.** The serving Gateway's maintenance tick sees the link move (installation replacement) and restarts itself into the new release. The updater waits for that successor (up to 90 s), then verifies. It falls back to a native restart only if no successor appears. A native restart from inside the service job (`update.run`) would end the updater itself. - **Service.** Written once, at conversion, to a frozen launcher `<stateDir>/git-install/openclaw-launcher.mjs`. A unit that names the launcher is never regenerated. The launcher is needed because a release that fails while loading never reaches Gateway code. - **Trial.** The switch writes `releases/.trial`. The launcher counts starts. - After two failed starts it switches the link back and restores the trial build's `*.pre-<buildId>` state files (falling back to openclaw#198389's `*.pre-<version>`). Each SQLite family is restored together, and trial-created WAL/journal/SHM/seal files without a preserved predecessor are removed. The launcher mirrors openclaw#198389's `companionRemovals` list because it must not load release code. - The trial ends when the Gateway's first maintenance tick runs, or when the updater verifies the restarted Gateway. The second path also covers targets that predate this PR. - Writes made during a failed trial are lost (approved). - **The layout never fails an update** (openclaw#197949 decision 8). If `releases/` cannot be created, or something other than a release link sits at the package path, the update records a warning and takes the in-place runner. The next update tries the layout again. - **Post-core work** (requested-channel persistence, plugin convergence) runs in the updater, but only after the restarted release verified and its trial ended. A failed trial therefore never leaves plugins that require the release it switched away from. It runs without Doctor maintenance, which the Gateway holds, and without a plugin cohort, because no core rollback exists to pair it with. If plugins changed, the Gateway is asked to restart again (SIGUSR2). Under `--no-restart` the release is unverified, so only the requested channel is persisted and plugins converge on a later update. - **The developer's checkout** is never written. The first update builds the commit that serves now as the first release, rewrites the unit once, then stages the target. - **Retention.** openclaw#198835's collection, followed by `git worktree prune`. `git-install` is excluded from backups and from the startup state-upgrade copy. The latter is the same change as openclaw#199770, included here so the stack stands alone. - **One owner.** `usesGitReleases` selects releases. Windows checkouts and package-to-Git switches keep the in-place runner, and the in-place CLI tests are pinned to that runner. For Git releases this skips: - runtime retention - the pack transfer/import - the managed-service stop/park - the database rollback capture - the checkout's source-artifact lock - the native restart from inside the service job - per-update service regeneration ## In-place fallback (decided) Windows Git checkouts, package-to-Git switches, and checkouts with no installed Gateway service still use the in-place runner, so this PR bypasses that runner on POSIX instead of deleting it. A checkout with no service is run by hand, so nothing would start through the release link and its next start would run the old commit. `gatewayServiceOwnsGitInstall` reads the installed service once and accepts it only when the service owns the checkout or its release link. The command decides once and hands that decision to the runner. Prod LOC is net **+980**. Decided 2026-11-16: Windows Git updates are not refused. A follow-up, slice 4b (stacked on this PR), moves Windows to releases using junctions and then deletes the in-place Git runner. ## E2E (mbp-m5, launchd, isolated profiles, shared-clone checkout; ≤15 min per run, ≤3 in parallel) **Final head `0b96d640` (rebased on `main` at `78d37094`): local ClawSweeper review clean** (gpt-6.1-sol, normal speed). After the rebase: `sweepPackageReleaseTemporaryLinks` is exported again, because the first Git publish uses it. The CI ratchets are satisfied: a lazy generation name, Node-only release tests, and an allocation record for the regression tests. A conversion's first release is now the commit the checkout's `dist` serves, not a pulled HEAD that was never rebuilt. A failed trial also restores a symlinked config: a preserved symlink is judged by its own time, not its target's. Rollback across same-version upgrades (decision d): the state upgrade now keeps a replaced file as `<file>.pre-<buildId>`, named after the build that replaced it, so two builds of one version each keep their own predecessor. Builds without a build ID, and earlier releases, still write `.pre-<version>`. Retention handles both forms. A failed trial restores the `.pre-<buildId>` of its own build, falling back to `.pre-<version>`. Fixes to the trial and launcher from the review rounds: - the inventory is recorded before anything is restored, so an interrupted rollback can resume without losing a restored WAL; - the trial's applied or interrupted upgrade plan is retired and the files it added are removed; a removal that fails is retried at the next start; - the config path is the one the update resolved (`~` and external paths included); - state is restored before the link moves back. The release layout is used only when the release switch actually reaches the next start: either the service already starts the launcher, or it owns the checkout and this update rewrites its definition and restarts it. `--no-restart` on a converted install leaves the serving release selected. The next start, which the operator triggers, selects the new release, without the two-start fallback. A first conversion requested with `--no-restart` stays in place. | Run (mbp-m5, isolated launchd profiles) | Head | Result | |---|---|---| | Release that crashes on boot | `d6d30a5e` (the final head changes only how a symlinked backup is dated) | update reports `build-id-mismatch` after 179 s; two "e2e boot crash" starts, then "failed to start twice; switched back"; link back on the previous release, trial cleared, `ready` | | Conversion before the crash run | `d6d30a5e` | ok, 267 s | **Current head `6d9acd6e` (on `main`), mbp-m5, isolated launchd profiles:** | Run | Result | |---|---| | Conversion (first update from a checkout service) | ok, root on the release link; 610 s with three runs in parallel; longest outage 9.7 s | | Release → release | ok, 239 s, longest outage 9.9 s | | `update.run` through the Gateway | `finished\|succeeded`, 135 s; link moved, Gateway restarted, plist unchanged; outage 7.8 s | | Checkout with no Gateway service | updated in place: checkout HEAD moved to the target, no `git-install/releases`, result `ok`, mode `git` | | Release that crashes on boot (at `0e3fefae`) | update reports `build-id-mismatch` after 188 s; after two "e2e boot crash" starts the launcher logs "failed to start twice; switched back", and the previous release serves `ready` | | v2026.11.4 state → this head | see Data-model compatibility | Older rows below ran at earlier heads. Rows marked ‡ ran at head `8a720e49`, rows marked † at `6032dedf`; the rest ran at `1140b601`, before plugin convergence moved after verification. At the final head `99b7f080` (rebased onto `823fa6d2`), three runs ran in parallel on mbp-m5. (1) Conversion and release→release passed again, with the root on the release link and a longest outage of 7.6 s. (2) `update.run` finished `succeeded` (link moved, Gateway restarted, plist unchanged, outage 8.0 s). (3) A checkout with **no Gateway service** updated in place: checkout HEAD moved to the bumped commit, no `git-install/releases` was created, and the result was `ok`, mode `git`, root the checkout. An intermediate head `2d2387b6` keyed this choice on a preflight fact that Git installs never fill in, so conversion fell back to in-place (about 120 s outage). That head was never pushed. | Case | Result | | --- | --- | | † First update of a checkout install (conversion, head→head+1) | ok, 402 s wall (two builds, three runs in parallel), longest outage 7.6 s, total 13.1 s (unit rewrite, then a restart after plugin convergence); unit rewritten once to the launcher; checkout tree clean; no retention, pack or handoff steps | | ‡ Release→release (head+1→head+2) | ok, 180 s wall, one outage of 7.2 s; unit untouched (mtime unchanged since conversion); service runs from `releases/` | | ‡ `--no-restart` on a switched release | the updater leaves the Gateway running and converges no plugins; within the next maintenance tick the Gateway restarts itself into the release, and the trial is cleared; outage 7.5 s | | † `update.run` via the Gateway (`openclaw gateway call update.run`) | run `finished|succeeded`, 140 s; link moved; the Gateway restarted itself; unit untouched; outage 7.4 s | | Already-current rerun from the preserved checkout after conversion (head `60503ab3`) | `skipped: already-current`, link unchanged, 113 s | | † Release that crashes on boot | two crashes, the launcher switched back to the previous release, Gateway ready again; the update reports `build-id-mismatch`; longest outage 28.9 s | | kill -9 mid-stage | link and serving Gateway unchanged; the rerun succeeds; a partial release directory left by the killed run is collected after 24 h | | kill -9 right after the link moves, before restart | the old Gateway keeps serving; the rerun reports `skipped: already-current`; the Gateway restarts itself into the new release and the trial is cleared | | `env -i` + `umask 077` (conversion, then release→release) | ok, 376 s and 198 s, outages 5.5 s and 7.5 s; launcher `0700` under umask 077 | | Install whose unit and state were written by 2026.11.3, moved to head, then converted | ok, 229 s, outage 5.9 s; state DB `integrity_check` ok. 2026.11.3's own updater could not reach head on mbp-m5: it walked back to `already-current` (Node 24.21 below head's `engines`), so that hop was done with `git reset` + `ocx build` | | Production-shaped install (207,229-file checkout, +3 GB SQLite in state), release→release | ok, 145 s, outage 6.9 s, no retention step. Main was not timed on this host. Peanutto's production main run `90c601fc` took 4,150 s, with 892 s retention and a 300 s outage | Not exercised: a plugin-only restart (SIGUSR2) after npm plugins actually change; the fixtures have no npm plugins. ## Data-model compatibility - **No new state schema.** This diff adds or changes no SQLite schema, migration, or config schema file. The update ledger (`update_runs`), Gateway owner lease and config are read and written exactly as on the base. - **`origin` stays compatible.** `UpdateRunRecordSchema.origin` (including openclaw#198835's `packageStage` and `packageRelease`) is unchanged, and Git-release updates write no new `origin` key. A Git release records its switch in the result step and the release directories, not the ledger. So rows written by older builds parse as before, and rows written by this build parse in an older build. A Git checkout that can't use the layout falls back to the in-place runner with a `recoverable-maintenance` advisory (`git-release-layout` step), the same contract as `installStagedPackage`'s swap fallback. - **New on-disk state is additive and lives under `<stateDir>/git-install/`:** `releases/<id>/` (detached worktrees), the `lib/node_modules/openclaw` link, `releases/.trial`, and the launcher. An install without them is treated as unconverted and gets the conversion path. If the layout is unusable, the update falls back to in-place (decision 8). - **Existing data proof: v2026.11.4 state upgraded and converted (E2E, `6d9acd6e`).** - The v2026.11.4 Gateway, started with `--profile`, created `state/openclaw.sqlite` (schema 22) and an agent DB. - This head's `gateway install` then stopped with "Client credentials require backed-up migration custody; … run openclaw doctor --fix". Plain `main` (`14466930`) stops with the same message on a copy of that state, so it comes from `main`, not this diff. - Following the message, `openclaw doctor --fix --non-interactive` migrated the state to schema 40. After that, install succeeded and the update converted the checkout onto the release link. The `update_runs` row in the stable-created database reads `finished|succeeded`, and the stable config (Gateway port) still reads back. - **Rollback keeps data readable:** the crash-release trial switches the link back to the previous release, and the launcher restores the SQLite family (`openclaw.sqlite`, `-wal`, `-shm`) captured before the trial. The previous build reopens its own database (crash row, 28.9 s). ## Tests - `src/infra/git-release.test.ts`: - trial fallback restores the SQLite family and drops trial-only companions - trial settlement - launcher mapping - a launcher unit is owned without regeneration - a non-link package path falls back to the in-place runner with a reason - `src/infra/update-runner-git-release.test.ts`: - a same-commit release with unverified artifacts is rebuilt - a current release is reported prepared, so finalization never regenerates it - the first release comes from the serving worktree's commit, and the checkout's different target is still built - `update-command-post-update.test.ts`: a switched release converges plugins only after its restart. - `git-release.test.ts`: a checkout with no owning Gateway service keeps the in-place runner. The test fails without the gate. - `update-command-execution-validation.test.ts`: when a developer build holds the checkout's artifact lock, a Git release update still runs. It never takes that lock, because releases build in their own worktrees. The test fails without the fix. - `update-command-convergence-authority.test.ts`: under `--no-restart`, a switched release persists the channel and leaves plugins alone; an already-current rerun from the checkout of a converted install completes. - `update-runner-git-release.test.ts`: a successful rebuild of an incomplete runtime reports the new release's verdict. - `update-command-convergence-authority.test.ts`: release convergence runs in the updater, with no fresh process and no Doctor. - `update-command-verification.test.ts`: - a verified release ends its trial - a switched release's Gateway restarts itself without a native restart - `src/state/state-upgrade.test.ts`: `git-install` stays out of the startup upgrade copy. - Gates: `pnpm tsgo:core`, `pnpm check:test-types`, oxlint/oxfmt on changed files. On mbp-m5 at `99b7f080`, the broad update suite plus the package-release and package-update tests pass 1,944 / 1,948, with 1 skipped. The 3 failures are environmental: - `update-runner-git-node-preflight` ×3: mbp-m5's Node 24.21 is below `engines`. ## LOC prod +1018 / −38 (net +980); test +951 / −3. Draft: lands after openclaw#198835. openclaw#198389 has merged; openclaw#199770 carries the same startup-copy exclusion for main. Co-authored-by: Ayaan Zaidi <[email protected]>
…0656) ## Problem When a Gateway upgrades existing state at startup (copy-and-swap from openclaw#198389), a later read through the shared-state read worker can fail with `disk I/O error` (`ERR_SQLITE_ERROR`, errcode 1802 = `SQLITE_IOERR_FSTAT`). The failing component depends on which reader runs next: - secret activation: `Startup failed: required secrets are unavailable ... disk I/O error`. The Gateway does not start. - host-link repair: `Could not repair OpenClaw host links: Error: disk I/O error`. Warning only. Fresh state (no upgrade) does not fail. ## Cause 1. Before the swap, `admitConfig` validates the shadow config. That reads plugin metadata from the **shadow** `state/openclaw.sqlite` through a read worker, which retains the connection (keyed by physical identity). 2. `beforeSwap` closes only the predecessor (live) identity, so the shadow reader survives. 3. The swap renames the shadow inode into the live path. The retained reader still records the shadow pathname. 4. The upgrade left the database in rollback-journal mode; startup's first writer switches it back to WAL. The retained reader then looks for WAL/SHM at the vanished shadow pathname and fails. ## Fix In `upgradeStateDirectory`, close the shadow shared-state path through the existing `closeOpenClawStateDatabaseByPathAsync` in a `finally` right after config admission, before refusal cleanup or rename. ## Evidence - Regression test `state-upgrade.test.ts` › "reopens shared-state workers after the copy-and-swap upgrade": old-schema state, lock inspection, shadow metadata read in `admitConfig`, real predecessor close in `beforeSwap`, swap, first writer WAL transition, then a worker read of the newly written row. - Red on merge base `44ee25b8`: `Error: disk I/O error`, `{ code: 'ERR_SQLITE_ERROR', errcode: 1802 }`. - Green with the fix (12/12 in the file). - End to end (Gateway from source): state written by released `[email protected]`, then the same pristine copy started on the merge base and on this branch. Both run the state upgrade. Merge base: 1 `disk I/O` error after the upgrade. This branch: 0. - `tsgo:core`, oxfmt, oxlint on changed files: pass. Co-authored-by: Ayaan Zaidi <[email protected]>
## Problem When a Gateway upgrades existing state at startup (copy-and-swap from #198389), a later read through the shared-state read worker can fail with `disk I/O error` (`ERR_SQLITE_ERROR`, errcode 1802 = `SQLITE_IOERR_FSTAT`). The failing component depends on which reader runs next: - secret activation: `Startup failed: required secrets are unavailable ... disk I/O error`. The Gateway does not start. - host-link repair: `Could not repair OpenClaw host links: Error: disk I/O error`. Warning only. Fresh state (no upgrade) does not fail. ## Cause 1. Before the swap, `admitConfig` validates the shadow config. That reads plugin metadata from the **shadow** `state/openclaw.sqlite` through a read worker, which retains the connection (keyed by physical identity). 2. `beforeSwap` closes only the predecessor (live) identity, so the shadow reader survives. 3. The swap renames the shadow inode into the live path. The retained reader still records the shadow pathname. 4. The upgrade left the database in rollback-journal mode; startup's first writer switches it back to WAL. The retained reader then looks for WAL/SHM at the vanished shadow pathname and fails. ## Fix In `upgradeStateDirectory`, close the shadow shared-state path through the existing `closeOpenClawStateDatabaseByPathAsync` in a `finally` right after config admission, before refusal cleanup or rename. ## Evidence - Regression test `state-upgrade.test.ts` › "reopens shared-state workers after the copy-and-swap upgrade": old-schema state, lock inspection, shadow metadata read in `admitConfig`, real predecessor close in `beforeSwap`, swap, first writer WAL transition, then a worker read of the newly written row. - Red on merge base `1f75f9ce`: `Error: disk I/O error`, `{ code: 'ERR_SQLITE_ERROR', errcode: 1802 }`. - Green with the fix (12/12 in the file). - End to end (Gateway from source): state written by released `[email protected]`, then the same pristine copy started on the merge base and on this branch. Both run the state upgrade. Merge base: 1 `disk I/O` error after the upgrade. This branch: 0. - `tsgo:core`, oxfmt, oxlint on changed files: pass. Co-authored-by: Ayaan Zaidi <[email protected]> Release adaptation retains existing broader deletion tests; adds only the new reader-replacement regression. (cherry picked from commit f8038cd) Co-authored-by: RomneyDa <[email protected]>
## 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]>
## Problem Gateway boot copies a private state tree, runs Doctor there, and publishes database replacements. The generic rebuild fallback adds another migration owner. Update cost grows with unrelated state and retains competing copy/swap machinery. Based on main ba96ee5, including #204956. Main only; no release-branch changes. ## Fix - Migrate canonical databases in place through existing state, agent and engine owners under exclusive custody. - Keep `discoverDatabases` as the inventory. Reuse #204915's per-release `.restore` v1 receipt; only a raised reader floor needs a database image. SQLite images are independent CoW clones or byte copies, never hard links. PostgreSQL copies a namespace only as its rollback image. - Keep the installed launcher's `.pre-<build-generation>` naming and existing `kind: add` receipt contract. No launcher reader or resident transition is added. - Reuse legacy-file imports, native credential custody, heartbeat/config repair and session imports on live paths. Include repair preserves authored directives and images every changed physical file. - Admit projected config and its source/hot-journal guard first; close that snapshot, migrate under the exclusive owner, then enforce database readiness. Config still invalid after projection refuses before writes. - Retain the session import/post-session handoff from Doctor (`doctor-health-contribution-runners.state.ts:62–84`; `doctor-session-transcripts.ts:227–355`). - Retain historical BLOB-backed TEXT repair from `de5a86ead888^:src/state/state-upgrade-tree.ts:719–753`, now in existing schema repair before typed readers and only for outdated databases. The original order normalized before `runChain` (`state-upgrade.ts:454–481`), not inside Doctor. Normalization now uses one existing transaction per database; conflicts roll back, name the table/key and take the existing exit-78 refusal path. - Preserve an already-lower reader floor during same-version Doctor repair. - Delete the shadow-tree writer, generic rebuild/value helpers, forward database swap wrappers, copied-target validation/readability, Doctor-on-copy process, copy-only CLI handoff and copied-state fixtures. Existing retention and historical receipt readers remain. - Settle only already-written `.upgrade-*/plan.json` before state reads. Stable 2026.11.10 shipped these plans; finishing one preserves committed WAL rows after an interrupted companion removal. No new plan is written. - Implement the engine gate's existing migrations permission at its one execution owner. Ordinary Gateway, closed/expired custody and config-only custody still refuse. No new table, column, stored-row shape, migration option or fallback. Clone reuse follows @fuller-stack-dev's #201716 via existing `copySqliteFile`. Related: #198389, #168750, #161888; retains #204752/#204227 inventory and clean-WAL work. ## User impact Starts and updates stop copying/replacing the state tree. Compatible schema steps, including compatible external stores, take no database image. Floor-raising rollback uses only the recorded image; unsupported paths refuse before the old Gateway stops with move/retry instructions. Accepted cost: without CoW, a floor-raising boot takes one byte copy of that database. No size refusal or 30-second probe. Required-image failure refuses before that step. Non-trial starts do not acquire copy-only prerequisites. Historical imports must retain sessions. The six published-release corpora remain required. One-time empty-source ownership maintenance is followed by a no-op boot; its regression preserves bytes on the second boot. Inherited frozen-reader edge: **A commits → downgrade T → return to the same A build → A fails before replacing its receipt** can consume stale build-keyed `kind: add` entries (`rollback-source.ts:39–55`). Existing debt; the paused per-release manifest reader removes it. Legacy-import plans may conservatively declare prospective stores. A future manifest reader could remove a store created later at such a path during rollback. This is accepted only on the one-time legacy-import path, not schema-only/additive updates; absent targets are now excluded unless existing source owners report legacy import sources. Accepted recovery edge: an invalid legacy `device.json` with no canonical identity is refused after the in-place schema upgrade; the existing full original backup preserves the pre-upgrade bytes. Canonical identity retains its shipped precedence over an invalid legacy file. No new credential reader or custody bypass is added. ## Evidence and current gate Remote head: **d449180993a4ee51aa180d9cb0a6b25ecdd27d52**. Current CI is the maintainer's final gate; earlier results remain scoped to their tested heads. The latest focused PostgreSQL proof is recorded below. - On the preceding 033d3de production tree, `ocx build --dist` passed, then selected **2026.7.1-blob E2E passed (20.94s)** with combined projection, additive-only and corrected historical non-STRICT normalization changes. The first version-only gate failed this corpus; the corrected gate passed. - Corrected Doctor/native-bootstrap/admission files **49/49 passed**; restored original fresh-profile pending-pin/offline-handoff contract **9/9 passed**; recovery tests passed, including localhost/0.0.0.0. - Final catalog-only migration observer **7/7 passed**. Inventory **27/27 passed**. Leasehold **4/4** and admission gate **7 passed/3 PostgreSQL skipped** passed on the initial catalog repair; the final historical gate was additionally qualified by the observer and BLOB corpus. - PostgreSQL tests had **6 skips** without a qualified local connection. Neither skips nor the inventory-only run qualify the live PostgreSQL behavior. - Local import-cycles, Madge (0 cycles) and Kysely guards passed on the repair batch. This is not behavioral proof. - On committed **bda681956e**, `ocx build --dts` completed the actual full build in 13m05s (not a cache hit), including native declarations and all 165 public SDK subpaths. Earlier infrastructure-only lock/admission failures were resolved without changing source or bypassing ownership. - Baseline regressions proved: [run_f5d15c230817a891fa97f1a7218498af](https://crabbox.openclaw.ai/portal/runs/run_f5d15c230817a891fa97f1a7218498af). Pinned `434459170f` loses the WAL witness at the selected assertion and refuses with `config original must precede manifest`; pinned `d31b2ca386` refuses the repairable include with `config-invalid: diagnostics.otel`. Only test fixtures were overlaid. Lease released with `--wait`. - **Older a5ef head:** [run_d4822472e48e3a5f847c9bde74317959](https://crabbox.openclaw.ai/portal/runs/run_d4822472e48e3a5f847c9bde74317959): full build, package and all six historical corpora **passed** (2026.7.1, 7.1-blob, 7.35, 8.35, 9.37, 10.10; seven tests including invalid-config preservation, zero skips). Admission/owner/live-PG/test-types/lint failed; subsequent fixes are not called green without verification. - **Older 78af head only:** published 2026.11.10 routed Gateway API upgrade passed: [run_605e7f763523ff2d8dd7d20b7428893f](https://crabbox.openclaw.ai/portal/runs/run_605e7f763523ff2d8dd7d20b7428893f), product row `e4d2cb81-841a-46a1-a6b7-50164052d3cd`, state40→42/agent42→44, clean WAL without SHM accepted, exact commit serving, no sampled/final `.upgrade-*` tree. Product downtime82.424s; sampled95.671s. This does not qualify the current head's modern selective-image contract. - **539 diagnostic only:** [run_cbb2a0713d7096f4e6a9588d3b0a4f9c](https://crabbox.openclaw.ai/portal/runs/run_cbb2a0713d7096f4e6a9588d3b0a4f9c), one cron case: Gateway ready, zero provider requests, pre-run persistence refused missing `public.unaccent`. The private AWS driver omitted extension provisioning present in canonical CI; the driver is corrected, with no speculative product change. This is setup-failure evidence, not a passing cron result. Lease released with `--wait`. - Obsolete 716 proof lanes were stopped by maintainer direction; every lease was released with `--wait`. Current-head native rollback, interrupted-plan startup and additive-boot qualification remain unproven. No AWS lease remains allocated. Remaining proof gaps: current-head CI, live PostgreSQL, and the native scenarios above. Inherited failures left unchanged: checkpoint timing at `agent-database-startup-verification.test.ts:340` (#205290); scheduled-turn budget failure matches [scheduled main run45634242694/job139276192521](https://github.com/openclaw/openclaw/actions/runs/45634242694/job/139276192521) exactly. For be51's merge-only stale-validator failure, owner regeneration left all52 outputs unchanged with identical SHA-256 manifests; no generated output was hand-edited. On 033d3de, `tokei` on all46 touched `src` production files, excluding `*.test.ts`, `*.test-support.ts` and `*.test-harness.ts`, against ba96ee5: **15,307→13,481 (-1,826)** code lines. Whole PR including tests/docs: **+3,586/-6,364, net -2,778**. ### PostgreSQL startup admission follow-up Under PostgreSQL, retired heartbeat configuration is now repaired at startup instead of merely reported: startup is valid, the legacy heartbeat is durably removed, and PostgreSQL configuration is retained. The ordinary main-thread PostgreSQL refusal remains enforced. Only synchronous Doctor manifest selection uses the existing engine admission; no admission spans asynchronous preparation. The focused regression passed locally against the CI-pinned PostgreSQL 16 Docker image with `unaccent`, `pg_trgm` and `vector`: **1 passed, 5 unselected cases skipped**. Extended-stack reproduction identified the bundled-discovery policy read during Doctor manifest selection; the fixed test verifies the persisted repair. The owned container was removed after proof. This qualifies the selected regression, not the entire PostgreSQL suite. Co-authored-by: Ayaan Zaidi <[email protected]>
## 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]>
…205165) ## Problem Gateway boot copies a private state tree, runs Doctor there, and publishes database replacements. The generic rebuild fallback adds another migration owner. Update cost grows with unrelated state and retains competing copy/swap machinery. Based on main c6eb8cd, including openclaw#204956. Main only; no release-branch changes. ## Fix - Migrate canonical databases in place through existing state, agent and engine owners under exclusive custody. - Keep `discoverDatabases` as the inventory. Reuse openclaw#204915's per-release `.restore` v1 receipt; only a raised reader floor needs a database image. SQLite images are independent CoW clones or byte copies, never hard links. PostgreSQL copies a namespace only as its rollback image. - Keep the installed launcher's `.pre-<build-generation>` naming and existing `kind: add` receipt contract. No launcher reader or resident transition is added. - Reuse legacy-file imports, native credential custody, heartbeat/config repair and session imports on live paths. Include repair preserves authored directives and images every changed physical file. - Admit projected config and its source/hot-journal guard first; close that snapshot, migrate under the exclusive owner, then enforce database readiness. Config still invalid after projection refuses before writes. - Retain the session import/post-session handoff from Doctor (`doctor-health-contribution-runners.state.ts:62–84`; `doctor-session-transcripts.ts:227–355`). - Retain historical BLOB-backed TEXT repair from `de5a86ead888^:src/state/state-upgrade-tree.ts:719–753`, now in existing schema repair before typed readers and only for outdated databases. The original order normalized before `runChain` (`state-upgrade.ts:454–481`), not inside Doctor. Normalization now uses one existing transaction per database; conflicts roll back, name the table/key and take the existing exit-78 refusal path. - Preserve an already-lower reader floor during same-version Doctor repair. - Delete the shadow-tree writer, generic rebuild/value helpers, forward database swap wrappers, copied-target validation/readability, Doctor-on-copy process, copy-only CLI handoff and copied-state fixtures. Existing retention and historical receipt readers remain. - Settle only already-written `.upgrade-*/plan.json` before state reads. Stable 2026.11.10 shipped these plans; finishing one preserves committed WAL rows after an interrupted companion removal. No new plan is written. - Implement the engine gate's existing migrations permission at its one execution owner. Ordinary Gateway, closed/expired custody and config-only custody still refuse. No new table, column, stored-row shape, migration option or fallback. Clone reuse follows @fuller-stack-dev's openclaw#201716 via existing `copySqliteFile`. Related: openclaw#198389, openclaw#168750, openclaw#161888; retains openclaw#204752/openclaw#204227 inventory and clean-WAL work. ## User impact Starts and updates stop copying/replacing the state tree. Compatible schema steps, including compatible external stores, take no database image. Floor-raising rollback uses only the recorded image; unsupported paths refuse before the old Gateway stops with move/retry instructions. Accepted cost: without CoW, a floor-raising boot takes one byte copy of that database. No size refusal or 30-second probe. Required-image failure refuses before that step. Non-trial starts do not acquire copy-only prerequisites. Historical imports must retain sessions. The six published-release corpora remain required. One-time empty-source ownership maintenance is followed by a no-op boot; its regression preserves bytes on the second boot. Inherited frozen-reader edge: **A commits → downgrade T → return to the same A build → A fails before replacing its receipt** can consume stale build-keyed `kind: add` entries (`rollback-source.ts:39–55`). Existing debt; the paused per-release manifest reader removes it. Legacy-import plans may conservatively declare prospective stores. A future manifest reader could remove a store created later at such a path during rollback. This is accepted only on the one-time legacy-import path, not schema-only/additive updates; absent targets are now excluded unless existing source owners report legacy import sources. Accepted recovery edge: an invalid legacy `device.json` with no canonical identity is refused after the in-place schema upgrade; the existing full original backup preserves the pre-upgrade bytes. Canonical identity retains its shipped precedence over an invalid legacy file. No new credential reader or custody bypass is added. ## Evidence and current gate Remote head: **d449180993a4ee51aa180d9cb0a6b25ecdd27d52**. Current CI is the maintainer's final gate; earlier results remain scoped to their tested heads. The latest focused PostgreSQL proof is recorded below. - On the preceding 033d3de production tree, `ocx build --dist` passed, then selected **2026.7.1-blob E2E passed (20.94s)** with combined projection, additive-only and corrected historical non-STRICT normalization changes. The first version-only gate failed this corpus; the corrected gate passed. - Corrected Doctor/native-bootstrap/admission files **49/49 passed**; restored original fresh-profile pending-pin/offline-handoff contract **9/9 passed**; recovery tests passed, including localhost/0.0.0.0. - Final catalog-only migration observer **7/7 passed**. Inventory **27/27 passed**. Leasehold **4/4** and admission gate **7 passed/3 PostgreSQL skipped** passed on the initial catalog repair; the final historical gate was additionally qualified by the observer and BLOB corpus. - PostgreSQL tests had **6 skips** without a qualified local connection. Neither skips nor the inventory-only run qualify the live PostgreSQL behavior. - Local import-cycles, Madge (0 cycles) and Kysely guards passed on the repair batch. This is not behavioral proof. - On committed **bda681956e**, `ocx build --dts` completed the actual full build in 13m05s (not a cache hit), including native declarations and all 165 public SDK subpaths. Earlier infrastructure-only lock/admission failures were resolved without changing source or bypassing ownership. - Baseline regressions proved: [run_f5d15c230817a891fa97f1a7218498af](https://crabbox.openclaw.ai/portal/runs/run_f5d15c230817a891fa97f1a7218498af). Pinned `434459170f` loses the WAL witness at the selected assertion and refuses with `config original must precede manifest`; pinned `d31b2ca386` refuses the repairable include with `config-invalid: diagnostics.otel`. Only test fixtures were overlaid. Lease released with `--wait`. - **Older a5ef head:** [run_d4822472e48e3a5f847c9bde74317959](https://crabbox.openclaw.ai/portal/runs/run_d4822472e48e3a5f847c9bde74317959): full build, package and all six historical corpora **passed** (2026.7.1, 7.1-blob, 7.35, 8.35, 9.37, 10.10; seven tests including invalid-config preservation, zero skips). Admission/owner/live-PG/test-types/lint failed; subsequent fixes are not called green without verification. - **Older 78af head only:** published 2026.11.10 routed Gateway API upgrade passed: [run_605e7f763523ff2d8dd7d20b7428893f](https://crabbox.openclaw.ai/portal/runs/run_605e7f763523ff2d8dd7d20b7428893f), product row `e4d2cb81-841a-46a1-a6b7-50164052d3cd`, state40→42/agent42→44, clean WAL without SHM accepted, exact commit serving, no sampled/final `.upgrade-*` tree. Product downtime82.424s; sampled95.671s. This does not qualify the current head's modern selective-image contract. - **539 diagnostic only:** [run_cbb2a0713d7096f4e6a9588d3b0a4f9c](https://crabbox.openclaw.ai/portal/runs/run_cbb2a0713d7096f4e6a9588d3b0a4f9c), one cron case: Gateway ready, zero provider requests, pre-run persistence refused missing `public.unaccent`. The private AWS driver omitted extension provisioning present in canonical CI; the driver is corrected, with no speculative product change. This is setup-failure evidence, not a passing cron result. Lease released with `--wait`. - Obsolete 716 proof lanes were stopped by maintainer direction; every lease was released with `--wait`. Current-head native rollback, interrupted-plan startup and additive-boot qualification remain unproven. No AWS lease remains allocated. Remaining proof gaps: current-head CI, live PostgreSQL, and the native scenarios above. Inherited failures left unchanged: checkpoint timing at `agent-database-startup-verification.test.ts:340` (openclaw#205290); scheduled-turn budget failure matches [scheduled main run45634242694/job139276192521](https://github.com/openclaw/openclaw/actions/runs/45634242694/job/139276192521) exactly. For be51's merge-only stale-validator failure, owner regeneration left all52 outputs unchanged with identical SHA-256 manifests; no generated output was hand-edited. On 033d3de, `tokei` on all46 touched `src` production files, excluding `*.test.ts`, `*.test-support.ts` and `*.test-harness.ts`, against c6eb8cd: **15,307→13,481 (-1,826)** code lines. Whole PR including tests/docs: **+3,586/-6,364, net -2,778**. ### PostgreSQL startup admission follow-up Under PostgreSQL, retired heartbeat configuration is now repaired at startup instead of merely reported: startup is valid, the legacy heartbeat is durably removed, and PostgreSQL configuration is retained. The ordinary main-thread PostgreSQL refusal remains enforced. Only synchronous Doctor manifest selection uses the existing engine admission; no admission spans asynchronous preparation. The focused regression passed locally against the CI-pinned PostgreSQL 16 Docker image with `unaccent`, `pg_trgm` and `vector`: **1 passed, 5 unselected cases skipped**. Extended-stack reproduction identified the bundled-discovery policy read during Doctor manifest selection; the fixed test verifies the persisted repair. The owned container was removed after proof. This qualifies the selected regression, not the entire PostgreSQL suite. Co-authored-by: Ayaan Zaidi <[email protected]>
## 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]>
Gateway boot copies a private state tree, runs Doctor there, and publishes database replacements. The generic rebuild fallback adds another migration owner. Update cost grows with unrelated state and retains competing copy/swap machinery. Based on main ba96ee5, including #204956. Main only; no release-branch changes. - Migrate canonical databases in place through existing state, agent and engine owners under exclusive custody. - Keep `discoverDatabases` as the inventory. Reuse #204915's per-release `.restore` v1 receipt; only a raised reader floor needs a database image. SQLite images are independent CoW clones or byte copies, never hard links. PostgreSQL copies a namespace only as its rollback image. - Keep the installed launcher's `.pre-<build-generation>` naming and existing `kind: add` receipt contract. No launcher reader or resident transition is added. - Reuse legacy-file imports, native credential custody, heartbeat/config repair and session imports on live paths. Include repair preserves authored directives and images every changed physical file. - Admit projected config and its source/hot-journal guard first; close that snapshot, migrate under the exclusive owner, then enforce database readiness. Config still invalid after projection refuses before writes. - Retain the session import/post-session handoff from Doctor (`doctor-health-contribution-runners.state.ts:62–84`; `doctor-session-transcripts.ts:227–355`). - Retain historical BLOB-backed TEXT repair from `de5a86ead888^:src/state/state-upgrade-tree.ts:719–753`, now in existing schema repair before typed readers and only for outdated databases. The original order normalized before `runChain` (`state-upgrade.ts:454–481`), not inside Doctor. Normalization now uses one existing transaction per database; conflicts roll back, name the table/key and take the existing exit-78 refusal path. - Preserve an already-lower reader floor during same-version Doctor repair. - Delete the shadow-tree writer, generic rebuild/value helpers, forward database swap wrappers, copied-target validation/readability, Doctor-on-copy process, copy-only CLI handoff and copied-state fixtures. Existing retention and historical receipt readers remain. - Settle only already-written `.upgrade-*/plan.json` before state reads. Stable 2026.11.10 shipped these plans; finishing one preserves committed WAL rows after an interrupted companion removal. No new plan is written. - Implement the engine gate's existing migrations permission at its one execution owner. Ordinary Gateway, closed/expired custody and config-only custody still refuse. No new table, column, stored-row shape, migration option or fallback. Clone reuse follows @fuller-stack-dev's #201716 via existing `copySqliteFile`. Related: #198389, #168750, #161888; retains #204752/#204227 inventory and clean-WAL work. Starts and updates stop copying/replacing the state tree. Compatible schema steps, including compatible external stores, take no database image. Floor-raising rollback uses only the recorded image; unsupported paths refuse before the old Gateway stops with move/retry instructions. Accepted cost: without CoW, a floor-raising boot takes one byte copy of that database. No size refusal or 30-second probe. Required-image failure refuses before that step. Non-trial starts do not acquire copy-only prerequisites. Historical imports must retain sessions. The six published-release corpora remain required. One-time empty-source ownership maintenance is followed by a no-op boot; its regression preserves bytes on the second boot. Inherited frozen-reader edge: **A commits → downgrade T → return to the same A build → A fails before replacing its receipt** can consume stale build-keyed `kind: add` entries (`rollback-source.ts:39–55`). Existing debt; the paused per-release manifest reader removes it. Legacy-import plans may conservatively declare prospective stores. A future manifest reader could remove a store created later at such a path during rollback. This is accepted only on the one-time legacy-import path, not schema-only/additive updates; absent targets are now excluded unless existing source owners report legacy import sources. Accepted recovery edge: an invalid legacy `device.json` with no canonical identity is refused after the in-place schema upgrade; the existing full original backup preserves the pre-upgrade bytes. Canonical identity retains its shipped precedence over an invalid legacy file. No new credential reader or custody bypass is added. Remote head: **d449180993a4ee51aa180d9cb0a6b25ecdd27d52**. Current CI is the maintainer's final gate; earlier results remain scoped to their tested heads. The latest focused PostgreSQL proof is recorded below. - On the preceding 033d3de production tree, `ocx build --dist` passed, then selected **2026.7.1-blob E2E passed (20.94s)** with combined projection, additive-only and corrected historical non-STRICT normalization changes. The first version-only gate failed this corpus; the corrected gate passed. - Corrected Doctor/native-bootstrap/admission files **49/49 passed**; restored original fresh-profile pending-pin/offline-handoff contract **9/9 passed**; recovery tests passed, including localhost/0.0.0.0. - Final catalog-only migration observer **7/7 passed**. Inventory **27/27 passed**. Leasehold **4/4** and admission gate **7 passed/3 PostgreSQL skipped** passed on the initial catalog repair; the final historical gate was additionally qualified by the observer and BLOB corpus. - PostgreSQL tests had **6 skips** without a qualified local connection. Neither skips nor the inventory-only run qualify the live PostgreSQL behavior. - Local import-cycles, Madge (0 cycles) and Kysely guards passed on the repair batch. This is not behavioral proof. - On committed **bda681956e**, `ocx build --dts` completed the actual full build in 13m05s (not a cache hit), including native declarations and all 165 public SDK subpaths. Earlier infrastructure-only lock/admission failures were resolved without changing source or bypassing ownership. - Baseline regressions proved: [run_f5d15c230817a891fa97f1a7218498af](https://crabbox.openclaw.ai/portal/runs/run_f5d15c230817a891fa97f1a7218498af). Pinned `434459170f` loses the WAL witness at the selected assertion and refuses with `config original must precede manifest`; pinned `d31b2ca386` refuses the repairable include with `config-invalid: diagnostics.otel`. Only test fixtures were overlaid. Lease released with `--wait`. - **Older a5ef head:** [run_d4822472e48e3a5f847c9bde74317959](https://crabbox.openclaw.ai/portal/runs/run_d4822472e48e3a5f847c9bde74317959): full build, package and all six historical corpora **passed** (2026.7.1, 7.1-blob, 7.35, 8.35, 9.37, 10.10; seven tests including invalid-config preservation, zero skips). Admission/owner/live-PG/test-types/lint failed; subsequent fixes are not called green without verification. - **Older 78af head only:** published 2026.11.10 routed Gateway API upgrade passed: [run_605e7f763523ff2d8dd7d20b7428893f](https://crabbox.openclaw.ai/portal/runs/run_605e7f763523ff2d8dd7d20b7428893f), product row `e4d2cb81-841a-46a1-a6b7-50164052d3cd`, state40→42/agent42→44, clean WAL without SHM accepted, exact commit serving, no sampled/final `.upgrade-*` tree. Product downtime82.424s; sampled95.671s. This does not qualify the current head's modern selective-image contract. - **539 diagnostic only:** [run_cbb2a0713d7096f4e6a9588d3b0a4f9c](https://crabbox.openclaw.ai/portal/runs/run_cbb2a0713d7096f4e6a9588d3b0a4f9c), one cron case: Gateway ready, zero provider requests, pre-run persistence refused missing `public.unaccent`. The private AWS driver omitted extension provisioning present in canonical CI; the driver is corrected, with no speculative product change. This is setup-failure evidence, not a passing cron result. Lease released with `--wait`. - Obsolete 716 proof lanes were stopped by maintainer direction; every lease was released with `--wait`. Current-head native rollback, interrupted-plan startup and additive-boot qualification remain unproven. No AWS lease remains allocated. Remaining proof gaps: current-head CI, live PostgreSQL, and the native scenarios above. Inherited failures left unchanged: checkpoint timing at `agent-database-startup-verification.test.ts:340` (#205290); scheduled-turn budget failure matches [scheduled main run45634242694/job139276192521](https://github.com/openclaw/openclaw/actions/runs/45634242694/job/139276192521) exactly. For be51's merge-only stale-validator failure, owner regeneration left all52 outputs unchanged with identical SHA-256 manifests; no generated output was hand-edited. On 033d3de, `tokei` on all46 touched `src` production files, excluding `*.test.ts`, `*.test-support.ts` and `*.test-harness.ts`, against ba96ee5: **15,307→13,481 (-1,826)** code lines. Whole PR including tests/docs: **+3,586/-6,364, net -2,778**. Under PostgreSQL, retired heartbeat configuration is now repaired at startup instead of merely reported: startup is valid, the legacy heartbeat is durably removed, and PostgreSQL configuration is retained. The ordinary main-thread PostgreSQL refusal remains enforced. Only synchronous Doctor manifest selection uses the existing engine admission; no admission spans asynchronous preparation. The focused regression passed locally against the CI-pinned PostgreSQL 16 Docker image with `unaccent`, `pg_trgm` and `vector`: **1 passed, 5 unselected cases skipped**. Extended-stack reproduction identified the bundled-discovery policy read during Doctor manifest selection; the fixed test verifies the persisted repair. The owned container was removed after proof. This qualifies the selected regression, not the entire PostgreSQL suite. Co-authored-by: Ayaan Zaidi <[email protected]> (cherry picked from commit e43debf) Release adaptation: floorRaisingDatabases drops the agent v44 member-access additive exception because release has no v44 schema; release keeps the restore-path owner in state-upgrade-databases.ts as on main (release-only state-upgrade-paths.ts from the #204916 adaptation removed along with state-upgrade-tree.ts); modify/delete conflicts on files absent from release (upgrade-survivor-migration-chain test, historical declared-input fixtures) keep the release state; remaining conflicts resolved by applying the source change over release-only hunks. Co-authored-by: RomneyDa <[email protected]> Co-authored-by: vincentkoc <[email protected]>
Problem
Upgrades migrate state in place. Every step of the v13..v40 chain, the STRICT rebuild, the scoped pre-migration snapshots and the
.bakcustody exists to make writing the live file safe, and that machinery is itself the top source of state failures in the field. Of 2,720 classified real upgrade failures, 351 are in the state-database layer (7 with data loss), led by migration gates and snapshot/backup custody:A Gateway started on real prior-release state refuses today, for example on 2026.7.1:
What changed
Gateway startup now owns the state upgrade, by copy and swap. It runs in
prepareGatewayRunBootstrap, before the config guard or any database reader, under file-only state ownership (acquireGatewayLock({ databaseAccess: "none" })).It runs only when the start would be admitted: the same
getGatewayStartGuardErrorscheck is asked with the raw config file (gateway.mode,--allow-unconfigured). A start that the guard refuses leaves every state file unchanged, so the previous package can still read it (the read-only admission contract from #141451). Before the plan is written, the upgraded config is also validated (core schema, includes and env refs resolved, read-only); if this build would refuse it, the private copy is discarded and the start refuses as before, with every live file unchanged.When the shared state DB or any agent DB is older than this build:
<state>/.upgrade-<version>-<pid>-<ts>/). A SQLite file with WAL or journal content is copied withVACUUM INTOfrom a read-only connection (committed WAL frames included, the live file never opened for writing; a hot rollback journal is rolled back on a private copy). Every other file, including closed databases, is a copy-on-write clone. Each copy's stamp (inode, size, mtime, ctime) is recorded. A symlink is copied as the file or directory it points to, so nothing written to the shadow can reach a live target, except links undernode_modules, which are code (plugin installs linknode_modules/openclawto the whole OpenClaw package) and stay links. Configured workspaces,tmp/,locks/, earlier generations and old backups are skipped. BLOB values in TEXT columns are decoded on the copy (v2026.7.2 STRICT migration fails on databases with BLOB-stored TEXT values and PRIMARY KEY constraints #110186).doctor --fix --non-interactive,OPENCLAW_SERVICE_REPAIR_POLICY=external) runs against the shadow only. Absolute paths into the live tree are pointed at the shadow for the run and back afterwards, in the files the run wrote.integrity_checkandforeign_key_check. Per-table row conservation compares source and result counts; tables the chain is known to merge or retire are listed inCHAIN_TRANSFORMED_TABLES. A mismatch logs, records and pins the old generation; it does not fail the upgrade.session_nodes/session_windows), the shipped derivation of session reference predicates (migrateAgentJsonPredicatesInTransaction), a small map for the one released rename (v36claw_*→template_*), newest row kept on key collisions (inside a savepoint, so a replacement that still collides restores the displaced row), and rows that do not fit (constraints, missing parents, removed tables) set aside intodiagnostic_events(upgrade.set-aside). Foreign-key orphans are found by their declared keys (WITHOUT ROWID tables report no rowid), repeated untilforeign_key_checkis clean; a database that still fails it is not published. Leases are dropped. Doctor's migrated config and the stores it created are kept. The old generation is pinned and a warning names the failed step. The Gateway still starts.<name>.pre-<version>, removes stale WAL/SHM/journal/seal companions, renames each new file into place and fsyncs the directories. Every step is idempotent, so the next start finishes an interrupted plan..pre-*copies and the backups the in-place migration left (*.pre-startup-migration-*,*.scoped.bak,*.sqlite*.bak,openclaw-media-persistence-recovery-*) are pruned, except pinned generations.A report row (
upgrade.report) records the mode, failed step, source versions, conservation result and set-aside count. The chain's output is kept aslogs/state-upgrade-<version>.log. Rollback to the previous release is a rename:<name>.pre-<version>back to<name>.This round (rebased onto
main81ca4f4; base is nowmain, not the canary-removal branch)ClawSweeper findings at
901f316, each with a regression test that fails on the previous head and passes here:beforeSwapruns before a recovered plan is appliedstate-upgrade.test.ts"releases retained handles before finishing an interrupted plan"migrateAgentJsonPredicatesInTransactionbefore stampingpreviousSessionId→has_optional_references = 1)foreign_key_checkrequired1e0d318review) refused start could still publishgateway.bind=lan+ Tailscale serve): red on1e0d318(DB hashes changed), green here372cd14review) mixed engines: PostgreSQL shared state + outdated SQLite agent DB failed on the anchor372cd14review) shadow Doctor inheritedOPENCLAW_AGENT_DIR/PI_CODING_AGENT_DIRcreateDoctorChain"points agent-directory selectors into the private copy": red before, green after1d919d0review) external config on another filesystem: plan rename fails with EXDEVagents.list,cron.listandchat.historyfor every corpus session; the whole-tree check now ignores logs anddiagnostic_eventstest/state-upgrade.e2e.test.ts6/6Defects this round's proof found and fixed:
mainmoved user-profile DDL into feature schemas, so the fallback setuser_profiles/user_profile_emailsrows aside as "table removed". Regression: the corpus rebuild test now fails on any "table removed" set-aside outside a named list (onlydevice_identities, moved to the client credential store at v29).VACUUM INTOon every SQLite file (old backups, other tools' databases), the diff compared every file byte for byte, and the path rewrite scanned every database. On a Peanutto clone (19 GB) the copy was still running after 13 minutes. Regression: "clones closed databases and moves only what the upgrade wrote".Client credential directory is unsafe): the chain-created stores were moved out of the shadow and back, recreating their directory as 0755. They now stay in the shadow directory the chain created. Covered by the e2e forced-fallback cases, run locally underumask 022.1287642): a PostgreSQL install keeps version-zero SQLite anchors, and native clients can create a version-zero catalog before the first Gateway; the upgrade treated v0 as outdated and ran the chain on it. Version 0 is no released schema (2026.7.1 is v1), so only released versions below this build are upgraded. Regression:state-upgrade.test.ts"leaves a PostgreSQL anchor or empty catalog to the normal bootstrap" (red before, green after). Proof:scripts/test-database-conformance.mjs --engine postgresagainst pgvector pg17 locally onserver-database-engine.postgres.test.ts,config-preflight.postgres.test.ts,interactive-setup.integration.test.ts: 23/23 on the final head (all previously failing cases pass); e2e lane 7/7 on the final head.node_modules/openclawlinks into the OpenClaw package (for a git install, the whole checkout). Same test.Config-flow experiment (candidate Doctor 15-45x slower than post-activation)
Profiled
doctorwith--cpu-profon acp -cclone of Peanutto state (base81ca4f4, isolatedHOME):config-flowprepareUpdateCandidateRehearsalsnapshot + its env,doctor --fix --non-interactive --no-workspace-suggestionsdoctor --repair --non-interactive --no-workspace-suggestionsCause: only a rehearsal runs
completeUpdateCandidatePluginRehearsal(src/infra/update-candidate-plugin-repair.ts:31), from the config-snapshot read (src/commands/doctor-config-preflight.ts:145, selected at:165whenresolveUpdateRehearsalRoot(src/infra/update-rehearsal-paths.ts:58) recognizes the rehearsal env, read at:211). It walks every installed plugin's module graph twice, once in the copy (:100) and once in the original source (:153), each through throwaway generation artifacts (src/plugins/plugin-generation-source-inspection.ts:30,:152→createPluginGenerationArtifact,src/plugins/plugin-generation-preparation.worker.ts:371) that byte-copy files (copyRootFileWithAdmissionSync) and Babel-transform them through jiti. The two worker profiles hold 231 s and 154 s of that walk while the main thread idles 490 s. The post-activation profile has no generation work.The boot chain does not hit it: its Doctor env does not match
resolveUpdateRehearsalRoot, and the measured shadowconfig-flowis 19.6 s. The cost belongs to the candidate rehearsal that #198268 removes, so nothing changes here.Proof
E2E on mbp-m5 (18 cores, load 4-14; another worker's runs shared it) with this PR's code built by
ocx baseat1e0d318(the later commits change the fallback store handling, the refused-config check and tests; the chain path these runs exercise is unchanged, and the e2e lane below ran on the final head). Real Gateway (node openclaw.mjs gateway run), isolatedHOME/OPENCLAW_STATE_DIR/TMPDIR, no inheritedOPENCLAW_*, free port,/readyzpolled. "Values" = every value the release wrote and the manifest located, found outside.pre-*, logs anddiagnostic_events. "Old bytes" = SHA-256 of every original DB and WAL equals its.pre-2026.11.3copy.from: state v22(12 runs in parallel, so wall times include contention.)
Faults (
kill -9via aNODE_OPTIONS=--importcrash probe, no product seam; 2026.7.1 corpus):.predisk I/O error), live identical, no work dirPeanutto-shaped timing on mbp-m5 (clone of Peanutto's state dir minus retired backups and non-state code dirs: 4.6 GB, 3.1 GB main agent DB with WAL, 5 agents; every agent DB set one schema back, v41 → v42; channels/providers/cron/Tailscale off; base and head run one after the other):
81ca4f4(in-place Doctor, then Gateway)config-flow*.pre-startup-migration-*.scoped.bak.pre-2026.11.3; old backups prunedsession_entry_snapshots(main)The same pair on Studio (load 70-88) measured 345 s vs 299 s; those numbers are contended and not used.
E2E lane on the final head (
test/state-upgrade.e2e.test.ts, prebuilt dist): 7/7, including the refused-config case, forced fallback on 8.35 and 10.10, and canonical readers (agents.list,cron.list,chat.history).openclaw updatefrom released 2026.11.3 (npm, isolated prefix, real 11.3 state) to this PR's packed tarball (at1d0c1d6, on Studio):status: ok(1268 s under load ~80), the updated Gateway ready in 33 s, state v40 / agents v42. In this flow head's post-install Doctor still migrates the live files in place before the Gateway starts, so the copy-and-swap finds nothing to do (next PR 1 below).Gates on the final head:
pnpm tsgo:core,pnpm check:test-types, oxlint + oxfmt on changed files,sqlite-copy-swap.test.ts+state-upgrade.test.ts+pre-bootstrap.process.test.ts+doctor-systemd-activation.test.ts, assertion-safety, mock-exports, database-dialect, env-var-count, Kysely guardrails, test-lines ratchet.Accepted edge cases
gateway.modefrom the raw config file. A mode set only through$includereads as missing, so that start is not upgraded and keeps the previous path (Doctor)..pre-<version>..prerename).node_modulesstay links in the shadow. A Doctor write through one would reach its target, like any write outside the state directory (configured workspaces,$includefiles), none of which is part of the swap.VACUUM INTO(3.1 GB on Peanutto); closed ones are cloned. A clone of a closed database assumes no writer while the Gateway holds state ownership.kill -9while the shadow Doctor runs leaves that child to finish in the work directory, which the next start discards.openclaw doctor --fix; the old generation is pinned.device_identitiesrows reach the client credential store only through the chain; if the chain fails before writing it, they stay set aside.Guard classifications for maintainer review
Unchanged from the previous revision:
SQLITE_PRIMITIVE_OWNERSgainssqlite-copy-swap.ts,state-upgrade-tree.ts,state-upgrade-validate.tsandstate-upgrade.tsas the SQLite file upgrade owner; file-privaterowidinsqlite-copy-swap.ts(collision set-aside) andtypeofinstate-upgrade-tree.ts(BLOB decode, path rewrite); the Kysely raw-SQLite allowlist gains the same modules plus the two*-db-swap.tsmap files. The dialect ratchet reports no construct-group growth.Not in this PR (next PRs)
This PR adds the single owner but deletes nothing yet: two callers still migrate live files in place, and the 11.3 → head
openclaw updaterun above shows the first one still runs in a real update.Doctor delegates version migration to this owner (slice 3's "Doctor advisory"). Route
prepareDoctorDatabaseMigrationsthroughupgradeStateDirectorywhen Doctor is not itself the shadow chain, then delete the in-place safety machinery it no longer needs. Risky here: Doctor holds open handles across sections, the shipped 11.3 updater runs head's Doctor post-install and checks its result, and the files overlap perf(update): replace the candidate canary with a runtime contract check #198268. Deletes (production lines onmain):src/infra/sqlite-migration-scoped-snapshot.tssrc/commands/doctor-migration-backup.ts(+-artifacts125,-names55,-restore27)src/state/schema-migration-backup-scope.ts+-tables.tssrc/commands/doctor-heartbeat-migration-backup.tsdatabase restore-migration-backupcommandAbout 1.9k production lines plus about 0.7k test lines, against +2.4k here.
The updater stops rolling databases back after a failed activation (
src/infra/update-migrated-finalize.worker.ts, 668 lines): once Doctor no longer migrates live state, that rollback is a rename of.pre-<version>. Update-thread files.CLI runtime opens (
ensureOpenClawStateRuntimeSchemaoutside the Gateway) refuse an outdated schema and name the Gateway as the upgrader; the STRICT pass and bounded runner then run only in the shadow.Collapse the unreleased v23..v40 steps (separate PR, as agreed).
Size
Production +2,504 / -4 under
src/and guard scripts, tests +825 (config/test-lines-allocations/198389-state-copy-swap-upgrade.txtrecords 419 over the allowance: one regression per review finding plus the corpus and e2e proofs), fixtures about 12,600 lines of text plus SQLite files (6 real state directories). Nothing is deleted yet; the deletions this enables (about 1.9k production lines in PR 1, 0.7k in PR 2) are listed above.