Skip to content

fix(state): bound startup upgrade copies and pruning to owned state - #199929

Merged
steipete merged 5 commits into
mainfrom
steipete/fix-state-upgrade-copy-20261116
Nov 16, 2026
Merged

steipete merged 5 commits into
mainfrom
steipete/fix-state-upgrade-copy-20261116

Conversation

@steipete

@steipete steipete commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes startup upgrades copying and pruning unrelated bulk state, sharing SQLite extents with preserved originals, and overwriting uncopied workspace files with Doctor templates.

User Impact

Large installations copy only migration inputs and get an explicit space check and copy progress. SQLite copies use read/write file handles, with NOCOW directory preparation on btrfs; quiescent WAL/journal content is recovered privately. Uncopied live files remain unchanged with a warning.

Retired startup-migration backups, SQLite .bak files, and media-persistence recovery images are deliberately retained, with observed counts and bytes in the upgrade report and log. Their deletion belongs to the operator or Doctor: deleting large shared clones synchronously during startup can stall a CoW filesystem. Older unpinned .pre-<version> generations are pruned only beside files this upgrade publishes.

Why This Change Was Made

This is follow-up hardening of feature owner @obviyus's copy-and-swap design in #198389 (ef930eb), alongside #199847. It retains the durable plan, crash recovery, migration chain/generic fallback, pinning, config-admission refusal, and publication boundary.

A large btrfs installation has 81 GB and 26 GB NOCOW databases alongside approximately 3.4 TB of managed worktrees (about 1,300 subvolumes). Reflink sharing forces CoW on subsequent database writes despite NOCOW; observed filesystem commits stalled for 8–18 seconds and queued database writes for up to 14 seconds. The original upgrade would copy unrelated trees and synchronously delete large operator recovery images during startup.

The copy now excludes default/configured worktrees and agent workspaces, nested mount/subvolume boundaries, Knowledge, browser profiles, backups, caches, and media payloads. Legacy outgoing-media record JSON remains because Doctor still imports it; legacy session, push, identity, device, credential, exec-approval, audit, config, and extension inputs remain. Ancillary SQLite families above 64 MiB are omitted; outdated targets and shared state are always included. The cutoff keeps small legacy stores available without copying large current databases or archives. Space accounting includes ordinary files because FICLONE may fall back to byte copying, plus an equal-sized scratch margin of at least 256 MiB.

Production delta: +284 lines (403 added, 119 removed). The necessary growth is the bounded inventory, byte-copy and space/progress handling; recursive whole-tree pruning was removed.

A required database inside a nested mount or subvolume is refused before any copy, with nothing live changed: the swap publishes by rename, which cannot cross filesystem or subvolume boundaries. NOCOW directory preparation is a performance policy and stays best-effort, so a btrfs host without chattr still upgrades (with a warning).

Pruning no longer recursively walks the live tree. It uses the swap's file ownership, preserves pins, and never deletes retired recovery artifacts. Replacements require copy-baseline membership in both chain and fallback paths; adds require an absent live path.

Evidence

  • Regression reproduced on the base: diffTree incorrectly emitted replace:workspace/AGENTS.md for an uncopied live workspace file. The focused test passes with the fix.
  • Focused tests: 37 passed across src/state/state-upgrade.test.ts and src/state/sqlite-copy-swap.test.ts. Covers scope, retained recovery count/bytes, old-generation pruning, exact space refusal before copy, SQLite file-handle/NOCOW ordering, and committed WAL recovery without source changes.
  • Changed-file oxfmt and type-aware lint passed. Exact-head CI run 43801195156 completed on 57bf41e57a51f7d20d0034404504df5808ebf995. All executed test/type jobs and the repaired baseline/import-closure checks passed; CI is not green because check-lint-core-2 fails on the inherited unicorn/prefer-structured-clone error at src/agents/tool-search-prepared-catalog.ts:118 (exact-head job), which also fails the aggregate gate.
  • CI found two lane defects, now fixed: the extracted worktree resolver was missing from the PR wrapper inventory, and config parsing used a new raw assertion instead of the existing coercion owner. Both failed import-closure tests and all seven affected state-upgrade tests pass locally after repair. Prior-head CI also found an inherited unicorn/prefer-structured-clone error at src/agents/tool-search-prepared-catalog.ts:118 (job log); the same code was verified on fetched main. The final exact-head log confirms the identical inherited error. No failed CI jobs were rerun.
  • Synthetic 2 GiB SQLite file with unused trailing pages: buffered byte copy took 0.7 seconds, 3,283 MB/s locally. This is a local copy timing, not btrfs or fsync performance evidence.
  • Populated prior-release Gateway E2E: all six fixtures passed (2026.7.1, 2026.7.1-blob, 2026.7.35, 2026.8.35, 2026.9.37, 2026.10.10), plus two forced-fallback cases and config refusal. The full existing seven-case run passed cleanly, then the two newly added July cases passed separately with unchanged production code. An earlier attempt passed its assertions but was rejected by the source-change guard; it was discarded and rerun.
  • No production access, deployment, schema bump, new configuration, or new environment controls. Native btrfs extent behavior is not measured locally; the file-handle and directory-policy boundary is tested without requiring btrfs.

Source evidence for exclusions: state-migrations.doctor.ts and state-migrations.doctor-discovery.ts migrate managed-worktree registry rows, not checkout trees; state-migrations.managed-outgoing-images.ts imports media/outgoing/records, with payload retention outside the copy; Knowledge's doctor-contract-api.ts only normalizes configuration, with its store root owned by extensions/knowledge/src/stores.ts; browser profiles are owned by extensions/browser/src/browser/chrome.ts, outside the core migration chain. Workspace paths use the canonical agent resolvers and remain outside the existing startup copy contract. State-relative backups, cache, locks, and tmp are absent from the core step/source inventory in state-migrations.doctor.ts; nested filesystem boundaries are excluded during inventory before descending. Logs and installed extensions are retained because their migration/import ownership is broader than a simple root exclusion.

  • Follow-up commit 8b7ccff: NOCOW preparation failures warn instead of aborting the copy; new focused test, 38 focused tests passed locally.

Harden the copy-and-swap design from #198389: exclude bulk state, byte-copy SQLite with NOCOW directory policy, preflight space, and preserve uncopied live files and retired operator recovery images. Keep durable publication, fallback and generation pins.
@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

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

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: L labels Nov 16, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-16T04:19:05.751327Z 8b7ccff New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 00ca262b2d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

? [resolveUserPath(config.agents.defaults.workspace, env)]
: []),
resolveManagedWorktreeRoot(env),
resolveManagedWorktreeRoot(env, config.worktreeRoot),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Expand the configured worktree root before excluding it

For a supported configuration such as worktreeRoot: "~/.openclaw/custom-checkouts", readUpgradeConfig() returns the unmaterialized string and resolveManagedWorktreeRoot() returns it unchanged. The subsequent path.resolve() treats ~ as a literal directory, whereas runtime config materialization expands it to the user's home (src/config/materialize.ts). Consequently, the actual custom worktree directory inside the state tree is still inventoried and copied, potentially exhausting disk space or substantially delaying startup—the bulk-copy behavior this change is intended to prevent. Resolve the configured root with resolveUserPath(..., env) before constructing the exclusions.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 16, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Nov 16, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 16, 2026
@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR limits startup upgrade copies and pruning to migration-owned state while preserving unrelated files and recovery backups.

Example: Doctor creates workspace/AGENTS.md in the private upgrade copy while the live workspace contains custom instructions.

  • Before: The generated template can replace the uncopied live instructions.
  • After: The live instructions remain unchanged and the upgrade records a warning.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful, well-scoped hardening with meaningful production-entry-point tests, one confirmed exclusion defect, and incomplete runtime and latest-stable upgrade evidence.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Startup upgrades can copy unrelated bulk directories, stall while deleting recovery images, and overwrite workspace instructions that were excluded from the private copy.
Reason: The maintainer-authored direction addresses a concrete large-installation incident while retaining the established durable publication and recovery design.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep this PR open: it addresses concrete startup-upgrade failures, but the configured worktree exclusion still misses supported home-relative paths.

Priority: P2
Reviewed head: 8b7ccff51b7575107d77f6f31ee7ce206a4ac2a6

Before merge

  • Expand the configured worktree root before excluding it (P2) - With HOME=/home/alex and worktreeRoot="/.openclaw/custom-checkouts", readUpgradeConfig preserves the raw string and resolveManagedWorktreeRoot returns it unchanged. The following path.resolve treats '' literally, so /home/alex/.openclaw/custom-checkouts is still inventoried and copied during an upgrade. Runtime configuration expands this supported value in src/config/materialize.ts. Apply resolveUserPath with the supplied environment before constructing this exclusion, and cover the home-relative configuration in the existing scope regression.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P2] Expand the configured worktree root before excluding it — src/state/state-upgrade.ts:322

Tests

  • Missing end-to-end proof: Provide redacted Gateway runtime output showing bounded copying and uncopied workspace preservation, plus a v2026.11.4 upgrade with existing settings and data intact; redact IPs, keys, phone numbers, and non-public endpoints.
Agent review details

How this fits together

Gateway startup passes existing state and configuration to the copy-and-swap upgrade owner, which prepares a private Doctor migration and publishes validated files through a durable rename plan.

flowchart TD
  A[Live state and configuration] --> B[Scoped inventory and space check]
  B --> C[Private state copy]
  C --> D[Doctor migration or generic rebuild]
  D --> E[Validated durable swap plan]
  E --> F[Updated state and preserved originals]
Loading

Technical review

Best possible solution:

Keep the existing upgrade owner and scoped-copy design, and expand configured worktree paths before constructing exclusions.

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

Current-main source confirms broad copying and recursive backup pruning, while its diff logic can replace a live file absent from the copy baseline; no target code was executed during this review.

Is this the best way to solve the issue?

The existing copy-and-swap owner is the right repair boundary, and the added inventory and baseline guards are justified by the reported workload rather than speculative machinery.

Full review comments:

  • [P2] Expand the configured worktree root before excluding it — src/state/state-upgrade.ts:322
    With HOME=/home/alex and worktreeRoot="/.openclaw/custom-checkouts", readUpgradeConfig preserves the raw string and resolveManagedWorktreeRoot returns it unchanged. The following path.resolve treats '' literally, so /home/alex/.openclaw/custom-checkouts is still inventoried and copied during an upgrade. Runtime configuration expands this supported value in src/config/materialize.ts. Apply resolveUserPath with the supplied environment before constructing this exclusion, and cover the home-relative configuration in the existing scope regression.
    Confidence: 0.99
    Late finding: first raised on code an earlier review cycle already covered.

Overall correctness: patch is incorrect
Overall confidence: 0.95

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Startup copy scope and baseline publication keeps the original intent (ef930eb: Run Doctor privately and publish validated changes while preserving original bytes and crash recovery.)
  • Generation and retired-backup pruning changes intended behavior with a stated reason (ef930eb: Keep one prior generation and remove retired migration backups; this PR explains that large shared recovery clones cause filesystem stalls and leaves their deletion to the operator or Doctor.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/state/state-upgrade.test.ts src/state/sqlite-copy-swap.test.ts --maxWorkers=1
  • pnpm tsgo:core
  • git diff --check

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit ef930eb adds src/state/state-upgrade-tree.ts:1 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ef930ebbad77; files: src/state/state-upgrade-tree.ts)

PR surface

Source +289, Tests +235, Docs +32, Other +1. Total +557 across 10 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 408 119 +289
Tests 3 240 5 +235
Docs 1 32 0 +32
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 10 681 124 +557

Preflight source

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

Review metrics

Metric Value Why it matters
Production versus test LOC Runtime src: +408 / -119; tests: +240 / -5 Runtime growth implements inventory, byte copying, space admission, and copy reporting within the existing owner; regression coverage exercises distinct preservation, retention, and SQLite boundaries.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a focused startup-upgrade repair with substantial value for large installations and one remaining configured-path defect.
  • merge-risk: 🚨 compatibility: Required databases beneath nested mounts or subvolumes now refuse startup upgrade and direct operators to offline Doctor; the maintainer-authored body explicitly accepts this boundary because publication uses rename.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

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

Workflow

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

Reviewed November 15, 2026, 11:34 PM ET / November 16, 2026, 04:34 UTC.

@steipete
steipete merged commit 618bf31 into main Nov 16, 2026
163 of 166 checks passed
@steipete
steipete deleted the steipete/fix-state-upgrade-copy-20261116 branch November 16, 2026 04:43
@steipete

Copy link
Copy Markdown
Contributor Author

Merged at exact head 8b7ccff (squash 618bf31).

The only red was check-lint-core-2 → openclaw/ci-gate: a unicorn/prefer-structured-clone error at src/agents/tool-search-prepared-catalog.ts:118. This PR does not touch that file, and it is identical to current main. Every other check on the head passed.

Local proof on the final head:

  • focused state-upgrade tests (38);
  • sibling worktree and Doctor tests (55);
  • eager-import and PR-wrapper closure tests;
  • export-name collision guard.

The lane ran the populated prior-release corpora (2026.7.1–2026.10.10) on the previous head; the final commit only makes NOCOW preparation best-effort.

@obviyus: follow-up hardening of #198389. The main deliberate behavior change is that retired startup-migration backups and recovery images are retained and reported instead of deleted at startup. Happy to adjust if you see a migration input the bounded copy now misses.

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 21, 2026
…ades (#203130)

## Problem

The Gateway's startup state upgrade copies state into a shadow, runs the Doctor chain there, and swaps the result in. To bound the copy, it leaves out current SQLite files larger than 64 MiB (`src/state/state-upgrade-tree.ts`, from #199929).

Doctor, running in that shadow, then sees the registered main agent database as missing and removes its `agent_databases` row (`discoverAgentDatabaseMigrationTargets` in `src/infra/state-migrations.media-persistence-targets.ts`). The conservation check reports `openclaw.sqlite:agent_databases 5 -> 4`, but the swap keeps the result.

Seen on a copy of a real state directory (Linux, no network). The main agent database (3.7 GB, already at the current schema) lost its registry row in every boot. The file and its sessions were intact: 1,187 sessions and 712,991 transcript events, and `sessions list` and `agents list` still worked. The registry is the only owner record for an agent database outside config, so an unconfigured agent drops out of discovery until something opens it again.

## Change

- Doctor no longer unregisters an agent database only because its file is missing. It still reports `Skipped missing registered agent database <path>.`
- The relative session store repair (runs in Doctor preflight, so also inside the shadow) no longer unregisters a missing source either. Its cleanup after a verified move is unchanged.
- Real deletion keeps its own unregister path (`unregisterOpenClawAgentDatabases`).

Runtime readers handle a registered row whose file is missing: the read-only opener returns `database-missing` (`openclaw-agent-db-readonly-open.ts`), session listing returns no entries, and auth lookup returns nothing. Only an explicit writable open creates a database, and that path does not come from registry discovery.

Accepted edge case: a file that is really gone keeps its row and the warning, instead of being forgotten automatically.

## Evidence

- New `src/state/state-upgrade.large-agent-db.test.ts` (database-worker lane): a registered, current agent database larger than 64 MiB keeps its row through `upgradeStateDirectory`, with no conservation mismatch and no pinned generation.
  - On `origin/main` 3eb60f7: `expected [] to deeply equal [ { agent_id: 'main', … } ]`.
  - With this change: passes.
- Updated tests that asserted the removal: `state-migrations.media-persistence-targets.test.ts`, `agent-deletion-journal-initialization.test.ts`.
- Focused run, 5 files and 49 tests passing: `state-upgrade.test.ts`, `agent-deletion-journal-initialization.test.ts`, `state-migrations.media-persistence-targets.test.ts`, `doctor-relative-session-store.test.ts`, and the new test.
- Real-state boot, control on `origin/main` 3eb60f7: `agent_databases 5 -> 4`, main absent, pinned. Doctor took 99.8 s and the whole boot 168.5 s.
- Real-state boot, with this change (built from `git archive` of this commit; the compiled `state-migrations.media-persistence-targets` chunk has the `Skipped` warning and no `Removed missing agent database registry entry`): `agent_databases 5 -> 5`, main present, conservation clean, not pinned. Doctor took 72.6 s and the whole boot 119.2 s, all exit 0. The log still shows `Skipped missing registered agent database` for the omitted shadow file.
- Both runs used fresh copies of the same state; all 17 SQLite files passed `integrity_check` before boot.

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

## Problem

The Gateway's startup state upgrade copies state into a shadow, runs the Doctor chain there, and swaps the result in. To bound the copy, it leaves out current SQLite files larger than 64 MiB (`src/state/state-upgrade-tree.ts`, from openclaw#199929).

Doctor, running in that shadow, then sees the registered main agent database as missing and removes its `agent_databases` row (`discoverAgentDatabaseMigrationTargets` in `src/infra/state-migrations.media-persistence-targets.ts`). The conservation check reports `openclaw.sqlite:agent_databases 5 -> 4`, but the swap keeps the result.

Seen on a copy of a real state directory (Linux, no network). The main agent database (3.7 GB, already at the current schema) lost its registry row in every boot. The file and its sessions were intact: 1,187 sessions and 712,991 transcript events, and `sessions list` and `agents list` still worked. The registry is the only owner record for an agent database outside config, so an unconfigured agent drops out of discovery until something opens it again.

## Change

- Doctor no longer unregisters an agent database only because its file is missing. It still reports `Skipped missing registered agent database <path>.`
- The relative session store repair (runs in Doctor preflight, so also inside the shadow) no longer unregisters a missing source either. Its cleanup after a verified move is unchanged.
- Real deletion keeps its own unregister path (`unregisterOpenClawAgentDatabases`).

Runtime readers handle a registered row whose file is missing: the read-only opener returns `database-missing` (`openclaw-agent-db-readonly-open.ts`), session listing returns no entries, and auth lookup returns nothing. Only an explicit writable open creates a database, and that path does not come from registry discovery.

Accepted edge case: a file that is really gone keeps its row and the warning, instead of being forgotten automatically.

## Evidence

- New `src/state/state-upgrade.large-agent-db.test.ts` (database-worker lane): a registered, current agent database larger than 64 MiB keeps its row through `upgradeStateDirectory`, with no conservation mismatch and no pinned generation.
  - On `origin/main` c9377e0: `expected [] to deeply equal [ { agent_id: 'main', … } ]`.
  - With this change: passes.
- Updated tests that asserted the removal: `state-migrations.media-persistence-targets.test.ts`, `agent-deletion-journal-initialization.test.ts`.
- Focused run, 5 files and 49 tests passing: `state-upgrade.test.ts`, `agent-deletion-journal-initialization.test.ts`, `state-migrations.media-persistence-targets.test.ts`, `doctor-relative-session-store.test.ts`, and the new test.
- Real-state boot, control on `origin/main` c9377e0: `agent_databases 5 -> 4`, main absent, pinned. Doctor took 99.8 s and the whole boot 168.5 s.
- Real-state boot, with this change (built from `git archive` of this commit; the compiled `state-migrations.media-persistence-targets` chunk has the `Skipped` warning and no `Removed missing agent database registry entry`): `agent_databases 5 -> 5`, main present, conservation clean, not pinned. Doctor took 72.6 s and the whole boot 119.2 s, all exit 0. The log still shows `Skipped missing registered agent database` for the omitted shadow file.
- Both runs used fresh copies of the same state; all 17 SQLite files passed `integrity_check` before boot.

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

## Problem

The Gateway's startup state upgrade copies state into a shadow, runs the Doctor chain there, and swaps the result in. To bound the copy, it leaves out current SQLite files larger than 64 MiB (`src/state/state-upgrade-tree.ts`, from #199929).

Doctor, running in that shadow, then sees the registered main agent database as missing and removes its `agent_databases` row (`discoverAgentDatabaseMigrationTargets` in `src/infra/state-migrations.media-persistence-targets.ts`). The conservation check reports `openclaw.sqlite:agent_databases 5 -> 4`, but the swap keeps the result.

Seen on a copy of a real state directory (Linux, no network). The main agent database (3.7 GB, already at the current schema) lost its registry row in every boot. The file and its sessions were intact: 1,187 sessions and 712,991 transcript events, and `sessions list` and `agents list` still worked. The registry is the only owner record for an agent database outside config, so an unconfigured agent drops out of discovery until something opens it again.

## Change

- Doctor no longer unregisters an agent database only because its file is missing. It still reports `Skipped missing registered agent database <path>.`
- The relative session store repair (runs in Doctor preflight, so also inside the shadow) no longer unregisters a missing source either. Its cleanup after a verified move is unchanged.
- Real deletion keeps its own unregister path (`unregisterOpenClawAgentDatabases`).

Runtime readers handle a registered row whose file is missing: the read-only opener returns `database-missing` (`openclaw-agent-db-readonly-open.ts`), session listing returns no entries, and auth lookup returns nothing. Only an explicit writable open creates a database, and that path does not come from registry discovery.

Accepted edge case: a file that is really gone keeps its row and the warning, instead of being forgotten automatically.

## Evidence

- New `src/state/state-upgrade.large-agent-db.test.ts` (database-worker lane): a registered, current agent database larger than 64 MiB keeps its row through `upgradeStateDirectory`, with no conservation mismatch and no pinned generation.
  - On `origin/main` 3eb60f7: `expected [] to deeply equal [ { agent_id: 'main', … } ]`.
  - With this change: passes.
- Updated tests that asserted the removal: `state-migrations.media-persistence-targets.test.ts`, `agent-deletion-journal-initialization.test.ts`.
- Focused run, 5 files and 49 tests passing: `state-upgrade.test.ts`, `agent-deletion-journal-initialization.test.ts`, `state-migrations.media-persistence-targets.test.ts`, `doctor-relative-session-store.test.ts`, and the new test.
- Real-state boot, control on `origin/main` 3eb60f7: `agent_databases 5 -> 4`, main absent, pinned. Doctor took 99.8 s and the whole boot 168.5 s.
- Real-state boot, with this change (built from `git archive` of this commit; the compiled `state-migrations.media-persistence-targets` chunk has the `Skipped` warning and no `Removed missing agent database registry entry`): `agent_databases 5 -> 5`, main present, conservation clean, not pinned. Doctor took 72.6 s and the whole boot 119.2 s, all exit 0. The log still shows `Skipped missing registered agent database` for the omitted shadow file.
- Both runs used fresh copies of the same state; all 17 SQLite files passed `integrity_check` before boot.

(cherry picked from commit c2af38c)

Release adaptation: Preserve every stable worker-test routing entry and add only the new large agent database regression, not the unrelated main session-controller context line.

Companion audit: No later production overlaps or PR/SHA mentions. Later edits sharing the worker list route unrelated tests and are not-applicable. The existing worker lane is present-equivalent; the relative-store and media-persistence owners keep explicit unregister behavior for a verified move or real deletion.

Co-authored-by: Ayaan Zaidi <[email protected]>
Co-authored-by: RomneyDa <[email protected]>
maplel pushed a commit to maplel/openclaw that referenced this pull request Nov 24, 2026
…aw#194058)

Failed-update triage now captures the operator's environment before managed candidate admission, so a coding agent installed only on the operator's PATH is still offered when the Gateway service's PATH differs. Restores the operator-environment contract from openclaw#134490 and keeps the launch confirmation from openclaw#143139.

Proof: shipped CLI on isolated Linux (Crabbox) with a running systemd Gateway: accept launches the operator-only agent, decline starts nothing, base 18bee8e reports no agent found; published 2026.11.1 upgrades to the fix with settings intact.

Co-authored-by: TorstenW <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
Co-authored-by: steipete <[email protected]>

(cherry picked from commit 7c702c3)

Release adaptation: Capture invoking operator env before candidate admission, forward to interactive triage only; preserve latest target selectors, confirmation and lease cleanup ordering. Exact three authorized production paths plus real lifecycle regression.

Follow-up dispositions: ad4863d fix: preserve the running installation when an agent updates its Gateway (openclaw#201570); dc73ec0 fix: let updates finish when another tool briefly reads OpenClaw's databases (openclaw#202541); d07b530 fix: clarify PostgreSQL schema upgrades for Git installs (openclaw#202098); e60ea9f test(update): add a Git release upgrade-survivor scenario (openclaw#201956); 2ef6f7b fix(update): build and serve Git releases outside node_modules (openclaw#201917); dbc1aa0 fix: keep the openclaw command and Gateway working after updating a pnpm install (openclaw#201735); f5e7641 fix: Git checkout updates across a schema change no longer end as post-update-failed after the new release starts (openclaw#201600); 2183caf fix: Git checkout updates no longer fail before the new release starts on a schema change or a busy database (openclaw#201463); 47e8649 fix: explain why Doctor cannot restore a scheduled job’s account (openclaw#201550); 8f2cfd4 fix: remove updater-only restrictions from agent maintenance guidance; cb5cfb2 fix: keep a doubtful killed-update recovery on the repair path (openclaw#201361); 24cb734 fix: keep carried-over scheduled jobs running after updates (openclaw#200653); d1276e1 feat(doctor): check OpenClaw ID member roles and honor an optional roles default (openclaw#197785); 0a39956 fix: finish updates when another tool reads OpenClaw's databases during the update (openclaw#201330); ea1c9d5 fix(update): settle remounted package publications before admission (openclaw#201336); 66b5212 fix(update): isolate malformed retained-install markers (openclaw#201199); 7e79c83 fix: let the next update finish a killed source checkout update (openclaw#201009); d905d8a fix: let the next update finish a killed update after the machine restarted (openclaw#200994); fdf0c95 fix: let the next update finish a killed update that had already installed the new version (openclaw#200866); 0c19bcd chore(release): close out 2026.11.5 on main (openclaw#200577); a1940e0 fix(matrix): keep explicit recovery available during deferred migration (openclaw#200805); 18b4776 improve: explain package baseline drift during updates (openclaw#200802); 1ad4cad fix(doctor): reclaim macOS updater runtimes blocked by non-updater processes (openclaw#200732); 427c857 fix: keep one missing archived transcript from blocking every update (openclaw#200733); 802e3f7 fix(update): keep valid cold archives from blocking updates (openclaw#200659); 23fca1a fix: let the next update continue after a killed update when nothing is left to repair (openclaw#200680); 3afe212 fix: let Doctor publish unchanged plugin migrations in any order (openclaw#200658); f65e4db fix(doctor): reclaim runtimes blocked by unrelated Linux processes (openclaw#200657); dab086c fix(update): let candidate Doctor read plugin dependencies from the staged package (openclaw#200595); 3447bee fix(update): keep updates going when the predecessor writes during its stop (openclaw#200569); 0ce9c77 fix: let the next update settle a package publication that a killed update left behind (openclaw#200550); ae31ea3 fix(update): repair handoffs in the journal-pinned lease store (openclaw#200532); 74020ea fix: continue updates when initial SQLite capture is stale (openclaw#200328); 6747b1e feat(update): run Git checkout installs from releases behind the release link (openclaw#199706); e3f8a67 fix(state): keep completed retained agent stores out of startup upgrade (openclaw#200284); 3c512c5 fix(gateway): move managed update lease operations off the main thread (openclaw#200169); ea69fcb chore(release): close out 2026.11.4 on main (openclaw#199956); 618bf31 fix(state): bound startup upgrade copies and pruning to owned state (openclaw#199929); e4a3093 perf(update): replace the candidate canary with a runtime contract check (openclaw#198268); 5dbf569 fix(update): plugin failures never fail an update or Gateway health; 764761e fix(update): refuse missing host prerequisites in one line and record a cause per attempt; 4c4fef4 fix(ui): update dialog claims installation before progress is confirmed (openclaw#199254); 136e1f6 fix(update): retrying an update from a dev checkout is refused after a killed update (openclaw#198673); 3bd03da fix(update): avoid duplicate database copies while the Gateway is stopped (openclaw#198148); 68a839b fix: isolate held agent databases until explicit restoration (openclaw#198180); e333f7e chore(ci): drop retired test-lines allocation records (3/3) (openclaw#197657); fd6fa47 fix: converge Gateway updates with environment-only service overrides (openclaw#196371); 7cf5e75 fix: clarify split-install updates and blocked Doctor repairs (openclaw#196342); 6ff8c86 fix(update): retain lazy sqlite catalog generation (openclaw#197095); 930e1f7 fix: keep stable updates and recovery free of premature migrations (openclaw#196474); a15f737 fix: preserve external plugin data during update rehearsal (openclaw#196301); 92798ae fix: updates survive interrupted heartbeat runs (openclaw#195656); c1e55e2 fix(update): restore LaunchAgent registration after repair contention (openclaw#195406); 715c610 fix(doctor): repair retained ISO session end timestamps (openclaw#194685); 689cfc8 fix(update): reclaim dead closing triage repair leases (openclaw#194503); 86bc89e fix(doctor): keep standing Codex parameter advice out of retirement blockers (openclaw#193650); 691bc8d fix(backup): read the backup engine without copying the live database (openclaw#194234); 000542f fix(backup): backups and updates fail on slow storage when a header probe batch misses its deadline (openclaw#194239); 31a65d5 fix(update): skip --no-lazy-fetch on Git versions without it (openclaw#194198); e45e99d fix(update): preserve dev update sources in tag-only Git clones (openclaw#193109)

Validation: Baseline2 intended operator-agent failures/32 controls passed; candidate34/34passed (194058-green.log). Accept launches synthetic operator-only CLI with expected env, decline starts nothing. Isolated updater flow, not live systemd/upgrade qualification.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 6689fd575ada8fe40a9593784deac18ec73041cd)
(cherry picked from commit 92e7a9fa223b0dc35801f25f70be90b472d9a6b7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant