Skip to content

feat(state): upgrade state by copy and swap at Gateway startup - #198389

Merged
obviyus merged 30 commits into
mainfrom
feat/state-copy-swap-upgrade
Nov 15, 2026
Merged

obviyus merged 30 commits into
mainfrom
feat/state-copy-swap-upgrade

Conversation

@obviyus

@obviyus obviyus commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Upgrades migrate state in place. Every step of the v13..v40 chain, the STRICT rebuild, the scoped pre-migration snapshots and the .bak custody 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:

Cause (state-db layer) Reports
legacy exec-approvals migration gate deadlock 18
candidate state snapshot failed 15
startup migration gate blocks on legacy leftovers 12
database schema preflight refused update 12
retained session migration source changed 12
SQLite backup probe timed out during update 5

A Gateway started on real prior-release state refuses today, for example on 2026.7.1:

OpenClaw state database schema migration required (audit-events-v2) at …/state/openclaw.sqlite; run openclaw doctor --fix to migrate it.
Gateway failed to start: … gateway.maintenance_required

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 getGatewayStartGuardErrors check 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:

  1. Copy. The state directory is copied into a private shadow (<state>/.upgrade-<version>-<pid>-<ts>/). A SQLite file with WAL or journal content is copied with VACUUM INTO from 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 under node_modules, which are code (plugin installs link node_modules/openclaw to 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).
  2. Chain. This build's Doctor (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.
  3. Validate. Every upgraded database must reach this build's schema version and pass integrity_check and foreign_key_check. Per-table row conservation compares source and result counts; tables the chain is known to merge or retire are listed in CHAIN_TRANSFORMED_TABLES. A mismatch logs, records and pins the old generation; it does not fail the upgrade.
  4. Fallback. If the chain fails (any step, or validation), the shadow databases are discarded and rebuilt by the generic engine: the current schema (with the first-use feature tables the source already has), name-matched columns cast to the declared type, defaults for new columns, the shipped row-moving steps on a private scratch copy (state: v12/v13 fold-ins; agents: the pre-v14 session migration into session_nodes/session_windows), the shipped derivation of session reference predicates (migrateAgentJsonPredicatesInTransaction), a small map for the one released rename (v36 claw_* → 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 into diagnostic_events (upgrade.set-aside). Foreign-key orphans are found by their declared keys (WITHOUT ROWID tables report no rowid), repeated until foreign_key_check is 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.
  5. Swap. This process's handles on the shared database are released (also before finishing an interrupted plan). Only files the run wrote, created or deleted since the copy become the plan, which is written and fsynced before any live file changes; files written live during the upgrade are not reverted. Applying it hard-links each replaced or retired live file to <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.
  6. Retention. One prior generation is kept. Older .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 as logs/state-upgrade-<version>.log. Rollback to the previous release is a rename: <name>.pre-<version> back to <name>.

This round (rebased onto main 81ca4f4; base is now main, not the canary-removal branch)

ClawSweeper findings at 901f316, each with a regression test that fails on the previous head and passes here:

Finding Fix Test
P1 resume skipped the handle release beforeSwap runs before a recovered plan is applied state-upgrade.test.ts "releases retained handles before finishing an interrupted plan"
P1 pre-v26 fallback lost reference predicates the fallback runs the shipped migrateAgentJsonPredicatesInTransaction before stamping "derives session reference predicates for a pre-v26 agent database" (2026.8.35 agent DB, previousSessionId → has_optional_references = 1)
P2 WITHOUT ROWID FK orphans published orphans located by declared keys, set aside, clean final foreign_key_check required "sets aside orphans of a WITHOUT ROWID child and publishes a clean foreign_key_check"
P1 failed collision replacement dropped a row savepoint around delete + insert "restores the displaced row when the newer row also collides on another key"
P1 (1e0d318 review) refused start could still publish the upgraded config is validated before the plan; a refusal publishes nothing e2e "a start refused for invalid config publishes nothing" (10.10 corpus, gateway.bind=lan + Tailscale serve): red on 1e0d318 (DB hashes changed), green here
P1 (372cd14 review) mixed engines: PostgreSQL shared state + outdated SQLite agent DB failed on the anchor with the shared state on PostgreSQL the startup upgrade does nothing; that agent family keeps the previous path (accepted edge case) "leaves a PostgreSQL anchor or empty catalog to the normal bootstrap" now includes a v41 SQLite agent DB: red before, green after
P1 (372cd14 review) shadow Doctor inherited OPENCLAW_AGENT_DIR / PI_CODING_AGENT_DIR selectors inside the state dir point at the copy; others are dropped for the shadow run createDoctorChain "points agent-directory selectors into the private copy": red before, green after
P1 (1d919d0 review) external config on another filesystem: plan rename fails with EXDEV the new config is staged beside the live one after admission, so the rename stays on one filesystem "publishes a config outside the state directory by a rename within its directory": red before, green after
Data-model compatibility proof the e2e test reads upgraded data through the Gateway: agents.list, cron.list and chat.history for every corpus session; the whole-tree check now ignores logs and diagnostic_events test/state-upgrade.e2e.test.ts 6/6

Defects this round's proof found and fixed:

  • First-use feature tables missing from the fallback (found by the tightened e2e check): main moved user-profile DDL into feature schemas, so the fallback set user_profiles/user_profile_emails rows aside as "table removed". Regression: the corpus rebuild test now fails on any "table removed" set-aside outside a named list (only device_identities, moved to the client credential store at v29).
  • Boot copy too slow on real-sized state: the copy ran VACUUM INTO on 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".
  • Fallback swapped the client credential directory with the umask mode (found by CI under umask 022: 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 under umask 022.
  • PostgreSQL starts hung (CI PostgreSQL conformance 1/3 and 3/3 at 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 postgres against pgvector pg17 locally on server-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.
  • Copy followed node_modules/openclaw links 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 doctor with --cpu-prof on a cp -c clone of Peanutto state (base 81ca4f4, isolated HOME):

Run How config-flow
Candidate rehearsal real prepareUpdateCandidateRehearsal snapshot + its env, doctor --fix --non-interactive --no-workspace-suggestions 493.5 s
Post-activation update Doctor env, doctor --repair --non-interactive --no-workspace-suggestions 30.0 s
This PR's boot chain (shadow Doctor, Peanutto clone one agent schema behind) Gateway start 19.6 s

Cause: 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 :165 when resolveUpdateRehearsalRoot (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 shadow config-flow is 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 base at 1e0d318 (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), isolated HOME/OPENCLAW_STATE_DIR/TMPDIR, no inherited OPENCLAW_*, free port, /readyz polled. "Values" = every value the release wrote and the manifest located, found outside .pre-*, logs and diagnostic_events. "Old bytes" = SHA-256 of every original DB and WAL equals its .pre-2026.11.3 copy.

Prior-release state Start Values Old bytes Report
2026.7.1 corpus ready, 220 s 41/41 identical chain, 0 set aside
2026.7.1-blob ready, 229 s 41/41 identical chain
2026.8.35 ready, 186 s 47/47 identical chain
2026.9.37 ready, 187 s 47/47 identical chain
2026.10.10 ready, 189 s 46/46 identical chain
2026.11.3 state (10.10 corpus migrated by released 2026.11.3's own Doctor and Gateway: state v22, agents v42) ready, 216 s 46/46 identical for the swapped shared DB (the current agent DBs are not swapped; the running Gateway writes them) chain, from: state v22

(12 runs in parallel, so wall times include contention.)

Faults (kill -9 via a NODE_OPTIONS=--import crash probe, no product seam; 2026.7.1 corpus):

Fault After the fault Next start
after copy (chain spawn) live identical, no plan upgrades, ready, 41/41
during the shadow Doctor live identical discards the attempt, upgrades, ready, 41/41
plan durable live identical, plan present finishes the plan, ready, 41/41
after the 1st / 3rd applied step old bytes identical finishes, ready, 41/41
all steps done, before cleanup old bytes identical under .pre finishes, ready, 41/41
ENOSPC (40 MiB APFS volume, ~2 MiB free) start refused (disk I/O error), live identical, no work dir after freeing space: upgrades, ready, 41/41

Peanutto-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):

Base 81ca4f4 (in-place Doctor, then Gateway) This PR (Gateway start, copy and swap)
Doctor migration 89 s 99 s (whole upgrade: copy, shadow Doctor, swap)
Gateway ready after that 7 s 7 s
Total 96 s 106 s
Doctor config-flow 41.0 s 36.5 s
Old files afterwards rewritten in place, plus a *.pre-startup-migration-*.scoped.bak byte-identical under .pre-2026.11.3; old backups pruned
State dir afterwards 4.6 GB 7.5 GB (one prior generation kept)
session_entry_snapshots (main) 1760 → 1685, silently 1760 → 1685 (same Doctor retention), reported as a conservation mismatch, generation pinned

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 update from released 2026.11.3 (npm, isolated prefix, real 11.3 state) to this PR's packed tarball (at 1d0c1d6, 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

  • The admission check reads gateway.mode from the raw config file. A mode set only through $include reads as missing, so that start is not upgraded and keeps the previous path (Doctor).
  • A database inside a symlinked directory is not upgraded by the swap (a rename cannot cross it); it keeps the previous path. A symlinked database file is upgraded; the old symlink is kept as .pre-<version>.
  • With the shared state on PostgreSQL, the startup upgrade does nothing (its report and set-aside rows have no SQLite home); SQLite agent databases beside it keep the previous path (Doctor).
  • Plugin-owned config is validated at admission, after the upgrade, because its metadata lives in the upgraded state; a start refused only for plugin config keeps the upgraded files (rollback is the .pre rename).
  • Links under node_modules stay links in the shadow. A Doctor write through one would reach its target, like any write outside the state directory (configured workspaces, $include files), none of which is part of the swap.
  • A database with WAL content is copied with 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.
  • A kill -9 while the shadow Doctor runs leaves that child to finish in the work directory, which the next start discards.
  • The shadow copy needs free space about equal to what the run writes (copy-on-write on APFS, Btrfs and XFS). On a full disk the upgrade stops, the live tree is untouched and the next start retries.
  • Values the shipped chain itself retires are retired here too (native CLI-shaped OAuth profiles, expired pending pairing requests).
  • The fallback cannot run Doctor's file imports. A 7.x install whose chain fails starts, but agents with legacy session JSON stay unavailable until openclaw doctor --fix; the old generation is pinned. device_identities rows 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_OWNERS gains sqlite-copy-swap.ts, state-upgrade-tree.ts, state-upgrade-validate.ts and state-upgrade.ts as the SQLite file upgrade owner; file-private rowid in sqlite-copy-swap.ts (collision set-aside) and typeof in state-upgrade-tree.ts (BLOB decode, path rewrite); the Kysely raw-SQLite allowlist gains the same modules plus the two *-db-swap.ts map 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 update run above shows the first one still runs in a real update.

  1. Doctor delegates version migration to this owner (slice 3's "Doctor advisory"). Route prepareDoctorDatabaseMigrations through upgradeStateDirectory when 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 on main):

    File Lines
    src/infra/sqlite-migration-scoped-snapshot.ts 665
    src/commands/doctor-migration-backup.ts (+ -artifacts 125, -names 55, -restore 27) 893
    src/state/schema-migration-backup-scope.ts + -tables.ts 162
    src/commands/doctor-heartbeat-migration-backup.ts 173
    database restore-migration-backup command unmeasured

    About 1.9k production lines plus about 0.7k test lines, against +2.4k here.

  2. 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.

  3. CLI runtime opens (ensureOpenClawStateRuntimeSchema outside 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.

  4. 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.txt records 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.

@openclaw-barnacle openclaw-barnacle Bot added cli CLI command changes size: XL labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@obviyus
obviyus force-pushed the feat/state-copy-swap-upgrade branch from 8032fd2 to d2cfb25 Compare November 13, 2026 17:40
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This 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.

  • Before: Startup can refuse with an audit-events-v2 migration-required error.
  • After: Startup upgrades the private copy, preserves previous files as .pre-2026.11.3, and serves the migrated state.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful implementation with no established code blocker; proof remains incomplete for the latest changed publication path.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: Users starting a newer Gateway against older populated state can be blocked by migration failures and require manual recovery.
Reason: The maintainer-authored direction addresses demonstrated upgrade failures, preserves recovery copies, and records the deliberate limits of this startup slice.

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
Reviewed head: b5707820640daed54bb021604e422d801474a648

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Show a real Gateway upgrade that rewrites OPENCLAW_CONFIG_PATH on a different filesystem from OPENCLAW_STATE_DIR and reaches readiness with the migrated config; redact credentials and non-public endpoints.
Agent review details

How this fits together

Gateway 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]
Loading

Technical review

Best 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

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Previous finding resolved: The latest commit stages changed external configuration beside its destination after admission, so publication no longer renames it across filesystems. (src/state/state-upgrade.ts:558, b5707820640d)
  • Existing regression coverage: The new external-config test exercises the real upgrade owner and checks destination-local publication and resulting config contents, but uses an injected chain and one temporary filesystem. (src/state/state-upgrade.test.ts:83, b5707820640d)
  • Supplied upgrade evidence: The complete PR body records real Gateway readiness, preserved database bytes, prior-release value checks, crash recovery, ENOSPC recovery, canonical Gateway readers, and an update from released 2026.11.3. (b5707820640d)
  • Current-main boundary: Current main proceeds from proxy release into the existing selected-config guard without this startup copy-and-swap owner. (src/cli/gateway-cli/pre-bootstrap.ts:622, 257759ae2be0)
  • Accepted scope and tradeoffs: The maintainer-authored body explicitly accepts fallback set-aside behavior, retained generations, temporary disk requirements, PostgreSQL and symlink exclusions, and later plugin-config validation; it also explains why Doctor and updater cutovers remain separate work. (b5707820640d)
  • Feature history: History identifies Chunyue Wang's startup-bootstrap work, Peter Steinberger's admission and database-upgrade repairs, and Patrick Erichsen's Templates migration. Older Doctor follow-history encountered an unavailable promised object; no unsupported introduction claim is made. (src/cli/gateway-cli/pre-bootstrap.ts:611, 257759ae2be0)

Likely related people:

  • Peter Steinberger: Raw commit 31d7030 adds src/cli/gateway-cli/pre-bootstrap.ts:628 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 31d703061650; files: src/cli/gateway-cli/pre-bootstrap.ts)
  • Chunyue Wang: Raw commit df521a6 adds src/cli/gateway-cli/pre-bootstrap.ts:622 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: df521a645977; files: src/cli/gateway-cli/pre-bootstrap.ts)

PR surface

PR surface statistics unavailable: the file list is incomplete.

Preflight source

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

Review metrics

Metric Value Why it matters
Production versus tests Production +2,504/-4; tests +819 Growth implements private copying, fallback rebuilding, durable publication, and distinct migration regressions; the maintainer-authored body explains the staged retention of existing Doctor and updater paths.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove proof: sufficient: Current real behavior proof status is not_applicable, not sufficient.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: The change addresses real upgrade failures that prevent Gateway startup.
  • merge-risk: 🚨 compatibility: Startup now publishes migrated state and prunes older recovery files; the maintainer-authored body explicitly accepts and documents these compatibility tradeoffs.
  • merge-risk: 🚨 availability: Gateway readiness now includes copying and migration with additional disk requirements; the documented startup and full-disk tradeoffs are accepted.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

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

Workflow

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

History

Review history (7 earlier review cycles)
  • reviewed 2026-11-13T17:56:35.359Z sha d2cfb25 :: blocked before merge. :: [P1] Preserve startup admission before committing an upgrade | [P1] Migrate legacy sessions before the agent fallback copy | [P1] Persist fallback diagnostics when only an agent needs upgrading | [P1] Materialize symlinked databases inside the private copy | [P2] Use private rollback recovery during database discovery
  • reviewed 2026-11-13T20:18:27.939Z sha 901f316 :: blocked before merge. :: [P1] Release retained database handles before resuming a swap | [P1] Backfill session reference predicates before stamping the fallback | [P2] Resolve WITHOUT ROWID foreign-key violations before publication | [P1] Roll back a displaced row when collision replacement fails
  • reviewed 2026-11-15T15:31:57.866Z sha 1e0d318 :: needs changes before merge. :: [P1] Preserve full read-only admission before publishing upgraded state
  • reviewed 2026-11-15T15:58:39.373Z sha cf3d875 :: needs changes before merge. :: [P1] Preserve full read-only admission before publishing upgraded state
  • reviewed 2026-11-15T16:49:02.005Z sha 1287642 :: needs changes before merge. :: [P1] Exclude PostgreSQL anchors from SQLite schema upgrades
  • reviewed 2026-11-15T17:48:21.191Z sha 372cd14 :: needs changes before merge. :: [P1] Preserve mixed-engine startup when recording upgrade diagnostics | [P1] Remap inherited agent directories into the private copy
  • reviewed 2026-11-15T18:31:04.911Z sha 1d919d0 :: needs changes before merge. :: [P1] Publish external config on its destination filesystem

Reviewed November 15, 2026, 2:35 PM ET / 19:35 UTC (Revision 8).

@obviyus
obviyus marked this pull request as ready for review November 13, 2026 18:54
@clawsweeper clawsweeper Bot removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 13, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Nov 13, 2026
@obviyus

obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 13, 2026
@obviyus
obviyus force-pushed the feat/state-copy-swap-upgrade branch from df17822 to ea2bef4 Compare November 14, 2026 04:31
@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Nov 14, 2026
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]>
steipete added a commit that referenced this pull request Nov 16, 2026
…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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…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.
obviyus added a commit that referenced this pull request Nov 17, 2026
…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]>
obviyus added a commit that referenced this pull request Nov 17, 2026
## 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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 18, 2026
…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]>
RomneyDa added a commit that referenced this pull request Nov 18, 2026
## 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]>
obviyus added a commit that referenced this pull request Nov 25, 2026
## What Problem This Solves

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

## User Impact

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

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

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

## Scope and Compatibility

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

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

## Evidence

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

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

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

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

## Size

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

## Conflict Integration

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

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

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

## User Impact

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

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

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

## Scope and Compatibility

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

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

## Evidence

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

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

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

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

## Size

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

## Conflict Integration

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

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

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

## User Impact

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

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

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

## Scope and Compatibility

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

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

## Evidence

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

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

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

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

## Size

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

## Conflict Integration

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

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

Co-authored-by: RomneyDa <[email protected]>
Co-authored-by: vincentkoc <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 26, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes commands Command implementations dependencies-changed PR changes dependency-related files merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant