Skip to content

fix(doctor): quarantine divergent device identity files - #126414

Closed
VACInc wants to merge 2 commits into
openclaw:mainfrom
VACInc:fix/doctor-device-identity-quarantine
Closed

VACInc wants to merge 2 commits into
openclaw:mainfrom
VACInc:fix/doctor-device-identity-quarantine

Conversation

@VACInc

@VACInc VACInc commented Aug 19, 2026 •

Copy link
Copy Markdown
Member

Fixes #117270

What Problem This Solves

A divergent retired device identity JSON can conflict with its SQLite migration receipt. The gateway correctly fails closed, but Doctor previously preserved the file and left startup in a crash-loop.

Why This Change Was Made

Doctor now quarantines a valid retired identity file whose bytes differ from the receipt, preserving the evidence while removing the legacy runtime blocker. The runtime fail-closed check remains unchanged.

User Impact

openclaw doctor --fix can repair this post-migration legacy-file conflict without an operator manually renaming the identity file.

Evidence

Regression proof: against pre-fix 84c2111, the new device-identity migration test failed at src/infra/state-migrations.device-identity.test.ts:725, expect(retry.warnings).toEqual([]). The received warning was Retired device identity cleanup preserved ... bytes differ from the migration receipt, confirming that the divergent legacy file was only preserved and therefore still triggered the runtime fail-closed startup guard.

Changed-surface gates passed:

  • node scripts/run-vitest.mjs src/infra/state-migrations.device-identity.test.ts: 26 passed
  • node scripts/check-changed.mjs -- src/infra/state-migrations.device-identity.ts src/infra/state-migrations.device-identity.test.ts: passed (core and coreTests lanes)
  • pnpm build: passed

Isolated Doctor CLI proof, using the branch build with a throwaway OPENCLAW_STATE_DIR: Doctor first imported a valid legacy identity to SQLite, then a different valid device.json was introduced. A second node dist/index.js doctor --fix --non-interactive reported Quarantined retired device identity JSON that differs from its SQLite receipt; identity/device.json was absent afterward and the divergent bytes were renamed to device.json.doctor-quarantine-.bak. No live state directory or operator backup file was touched.

Deployed live validation (2026-08-19)

oc-update --skip-codex completed successfully on base 61416e12542043e521de471a1f804fd1cbb7650a; its overlay log records both #126413 and #126414 as applied. The managed service reached active/running with NRestarts=0.

Live validation did not pass. After the deploy doctor/restart sequence, the local state SQLite integrity check reported corruption in the delivery queue table. The Gateway process remained up but closed the read-only RPC connection during authentication, so no safe cron turn or admission-ledger probe could be completed. No repair, restart, retry, or data mutation was attempted after this observation.

For #126414, the operator-approved reproduction copied the existing retired artifact to identity/device.json while retaining the original .stray-aug1-identity.bak. openclaw doctor --fix --non-interactive did not emit Quarantined retired device identity JSON that differs from its SQLite receipt. and left the copied file in place. Per the validation contract, the copied file was then removed recoverably and no other identity file was edited. The canonical SQLite identity prefix was unchanged before and after (5a69fa71143b). This is a failed live validation, not a warning-preserve pass.

Post-restore result (same day): PASS

The earlier failed run above had two causes unrelated to this fix: a recurrence of this host's known WAL-reset SQLite corruption (state DB restored from the updater's pre-deploy snapshot), and doctor being invoked while the running Gateway owned the state directory — the migration lock correctly refused with "Stop the Gateway and run openclaw doctor --fix again". With the Gateway stopped, the validation passed using the real artifact:

  • The actual stray identity file from the 2026-08-19 crash-loop incident was copied back to identity/device.json.
  • openclaw doctor --fix --non-interactive (offline) emitted Quarantined retired device identity JSON that differs from its SQLite receipt. and renamed the file to device.json.doctor-quarantine-1787174079477.bak; the preserved original backup and the canonical SQLite identity (prefix 5a69fa71) were untouched.
  • The Gateway restarted healthy afterward (Runtime: running, Connectivity probe: ok).

@clawsweeper

clawsweeper Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@VACInc
VACInc marked this pull request as ready for review August 19, 2026 20:39
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Aug 19, 2026
@clawsweeper

clawsweeper Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 19, 2026, 7:55 PM ET / 23:55 UTC.

ClawSweeper review

What this changes

The PR changes device-identity migration cleanup to quarantine a receipt-mismatched retired JSON identity file rather than preserve it.

Merge readiness

⚠️ Needs maintainer review before merge - 5 items remain

The prior P1 finding remains unresolved: this Doctor-oriented change also runs automatically during node-host startup, where it can rename divergent cryptographic identity material without an explicit startup-recovery decision.

Priority: P1
Reviewed head: 047dc7766ec70f8d9d1667e26756a2e49253e59a
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Doctor recovery proof is strong, but a P1 startup-boundary defect remains.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The PR body provides after-fix Doctor CLI and real-artifact evidence, including quarantine output and a healthy post-restart; it does not establish the separate startup behavior introduced by the shared path.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Verification

Check Result Evidence
Real behavior Verified Sufficient (logs): The PR body provides after-fix Doctor CLI and real-artifact evidence, including quarantine output and a healthy post-restart; it does not establish the separate startup behavior introduced by the shared path.
Evidence reviewed 5 items Current-main behavior: Current main preserves a receipt-mismatched identity with a warning, establishing the pre-PR fail-closed behavior.
Shared startup entry point: Node-host startup detects and migrates device identity through the same migration API, with no separate cleanup policy.
Changed cleanup path: The branch moves every readable receipt-mismatched candidate to a quarantine filename and has no caller-specific guard.
Findings 1 actionable finding [P1] Keep divergent-file quarantine out of node-host startup
Security Needs attention Startup can quarantine divergent identity material: Because startup calls the same cleanup, a gateway launch can rename a valid but receipt-mismatched identity JSON before the runtime fail-closed guard evaluates it.

Live Verification

Command: pnpm openclaw doctor --help

Result: PASS (completed)

pnpm openclaw doctor --help
runner@runnervm76f27:/tmp/clawsweeper-live-proof-126414-1zexvl/target$ pnpm openclaw doctor --help
$ node scripts/run-node.mjs doctor --help
pnpm openclaw doctor --help
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 399.96 kB
[log] ‹DIR›/a2ui-v0.9.bundle.js  chunk │ size: 615.66 kB
[log]
[success] rolldown v1.2.0 Finished in 111.16 ms
[diffs] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts curated
[diffs-language-pack] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts full
[discord] build: node --import tsx ../../scripts/build-discord-activity-sdk.mts
[tsdown-build] invocation 1/2 finished in 0.7s
node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2343:30) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2343:31 ]
      │
 2343 │           ASM_CONSTS[start] = eval(func);
      │                               ──┬─
      │                                 ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2366:32) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2366:33 ]
      │
 2366 │           moduleExports[name] = eval(func);
      │                                 ──┬─
      │                                   ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

[tsdown-build] invocation 2/2 finished in 13.5s
[plugin-control-plane-loads] verified 36 built modules with native require and checked doctor closures
runtime-postbuild: 10 phases completed in 4219ms (slowest: built plugin control-plane loads 3502ms)


Assertions:

  • PASS expect_output: doctor

How this fits together

Device identity migration imports a retired JSON identity into SQLite and records its digest. Doctor and node-host startup share that migration path before gateway identity validation, so cleanup affects both explicit recovery and normal startup.

flowchart LR
A[Retired identity JSON] --> B[SQLite identity and receipt]
B --> C[Shared cleanup migrator]
H[Explicit Doctor] --> C
I[Node-host startup] --> C
C --> D{Digest matches receipt?}
D -->|yes| E[Remove retired file]
D -->|no| F[Quarantine backup]
E --> G[Gateway identity validation]
F --> G
Loading

Decision needed

Question Recommendation
May node-host startup automatically quarantine a receipt-mismatched retired device identity, or must this recovery remain an explicit Doctor operation? Keep recovery Doctor-only: Gate quarantine to explicit Doctor and preserve startup’s existing fail-closed behavior for divergent identities.

Why: The shared migrator reaches both entry points, and the change affects cryptographic identity material and an existing fail-closed startup boundary.

Before merge

  • Keep divergent-file quarantine out of node-host startup (P1) - runStartupMigrations invokes this same cleanup, so a normal node-host launch now renames a receipt-mismatched identity. The PR proves explicit Doctor recovery, while startup previously remained fail-closed. Gate this to explicit Doctor or obtain an owner decision and add startup coverage.
  • Resolve security concern: Startup can quarantine divergent identity material - Because startup calls the same cleanup, a gateway launch can rename a valid but receipt-mismatched identity JSON before the runtime fail-closed guard evaluates it.
  • Resolve merge risk (P1) - Merging would change existing divergent identity handling from preserved fail-closed state to automatic file movement during ordinary node-host startup.
  • Complete next step (P2) - An owner must decide whether automatic startup recovery is permitted before a repair can safely choose the final behavior.

Findings

  • [P1] Keep divergent-file quarantine out of node-host startup — src/infra/state-migrations.device-identity.ts:336-342
  • [medium] Startup can quarantine divergent identity material — src/infra/state-migrations.device-identity.ts:338
Agent review details

Security

Needs attention: The patch extends automatic handling of cryptographic identity material to node-host startup without an explicit startup-boundary decision.

PR surface

Source +12, Tests +10. Total +22 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 16 4 +12
Tests 1 13 3 +10
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 29 7 +22

Review metrics

Metric Value Why it matters
Production vs test delta production +12, tests +10 The added production cleanup behavior is exercised by both Doctor and startup, while the test addition covers only direct migration cleanup.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/infra/state-migrations.device-identity.test.ts, migration/backfill/repair: src/infra/state-migrations.device-identity.ts, serialized state: src/infra/state-migrations.device-identity.test.ts, serialized state: src/infra/state-migrations.device-identity.ts. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Merge-risk options

Maintainer options:

  1. Limit quarantine to Doctor (recommended)
    Pass explicit Doctor authority into receipt-mismatch cleanup and test that node-host startup leaves a divergent identity in place.
  2. Accept automatic startup recovery
    Document an owner decision for startup recovery and add a focused startup test for the automatic quarantine outcome.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Gate receipt-mismatch quarantine to explicit Doctor recovery and add startup coverage for preserved fail-closed behavior.

Technical review

Best possible solution:

Keep receipt-mismatch quarantine explicit to Doctor and add a startup regression proving a divergent identity remains fail-closed, unless the owner explicitly approves automatic startup recovery.

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

Yes, from source: a completed receipt plus a different valid identity/device.json reaches the changed shared cleanup when node-host startup invokes the migrator; no startup regression currently covers it.

Is this the best way to solve the issue?

No. The explicit Doctor recovery is well targeted, but the shared implementation also changes normal startup; it needs an authority gate or explicit owner approval.

Full review comments:

  • [P1] Keep divergent-file quarantine out of node-host startup — src/infra/state-migrations.device-identity.ts:336-342
    runStartupMigrations invokes this same cleanup, so a normal node-host launch now renames a receipt-mismatched identity. The PR proves explicit Doctor recovery, while startup previously remained fail-closed. Gate this to explicit Doctor or obtain an owner decision and add startup coverage.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.99

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against c5fd6252a7d9.

Labels

Label justifications:

  • P1: The affected identity conflict can make identity-dependent gateway requests unavailable.
  • merge-risk: 🚨 compatibility: Existing installations with a divergent retired identity would have it moved automatically at startup instead of retaining the prior fail-closed state.
  • merge-risk: 🚨 security-boundary: The patch broadens automatic handling of cryptographic device identity material beyond explicit Doctor recovery.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (logs): The PR body provides after-fix Doctor CLI and real-artifact evidence, including quarantine output and a healthy post-restart; it does not establish the separate startup behavior introduced by the shared path.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides after-fix Doctor CLI and real-artifact evidence, including quarantine output and a healthy post-restart; it does not establish the separate startup behavior introduced by the shared path.

Evidence

Security concerns:

  • [medium] Startup can quarantine divergent identity material — src/infra/state-migrations.device-identity.ts:338
    Because startup calls the same cleanup, a gateway launch can rename a valid but receipt-mismatched identity JSON before the runtime fail-closed guard evaluates it.
    Confidence: 0.99

What I checked:

Likely related people:

  • steipete: Introduced node-host retired-state migration and authored the subsequent device-identity migration and race-safety work. (role: feature owner and recent area contributor; confidence: high; commits: 6c812539859a, a742bdb33376, 21a9428a8a53; files: src/infra/state-migrations.device-identity.ts, src/node-host/startup-state-migrations.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Gate quarantine to explicit Doctor recovery, or obtain an explicit startup-recovery decision with focused startup coverage.
  • Re-run the focused migration and startup tests after the scope is resolved.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-19T22:03:24.648Z sha 047dc77 :: found issues before merge. :: [P1] Keep divergent-file quarantine out of node-host startup

@steipete

Copy link
Copy Markdown
Contributor

Thanks for tracking down the upgrade symptom and collecting Doctor evidence. Deep review shows that the reported outage was already fixed by #120610 (commit d9ff862), which this branch already contains: canonical SQLite identities are authoritative even when divergent legacy identity files reappear, with both TypeScript and OpenClawKit regression coverage.

The additional quarantine change is not safe to land as written. Its shared receipt-cleanup path also runs during ordinary node-host startup, which currently passes the same doctorOnlyStateMigrations flag as Doctor, and the divergent-file branch moves cryptographic identity material without first verifying that a valid canonical SQLite identity still exists and matches the migration receipt. The added regression also changes only a timestamp, not the actual keypair.

Correcting those authority and identity-verification boundaries would be a separate security-hardening change, not the already-fixed P1 upgrade repair. Closing this proposal as superseded by #120610 rather than introducing an automatic identity-quarantine path.

@VACInc

VACInc commented Aug 20, 2026 •

Copy link
Copy Markdown
Member Author

Agreed the quarantine patch shouldn't land as written — the two authority findings are correct (src/node-host/startup-state-migrations.ts passes doctorOnlyStateMigrations: true at ordinary node-host startup, so the shared cleanup path would move key material outside explicit Doctor authority, and the divergent branch doesn't call verifyCanonicalIdentity before moving the file).

But the supersede claim doesn't hold: the outage class is not fixed by #120610, and I reproduced it on a build containing d9ff862.

On 2026-08-19 at 11:03 my gateway crash-looped running the dist deployed 2026-08-18 from base 11997bf2117 (reflog-verified), which contains d9ff862823a (git merge-base --is-ancestor). Journal, one fresh PID every ~20s:

OpenClaw startup migrations did not complete cleanly; refusing to report the gateway ready.
- Retired device identity cleanup preserved ~/.openclaw/identity/device.json: bytes differ from the migration receipt.
Run "openclaw doctor --fix" against the same state/config, then restart the gateway.

The failing path is not the identity loader #120610 fixed. It is the startup readiness gate: src/commands/doctor-config-preflight.ts:670 treats any startup-migration warning as fatal via throwStartupMigrationRefusal, and the device-identity cleanup emits exactly such a warning for a divergent retired file (src/infra/state-migrations.device-identity.ts:337). Exit 1 → systemd restart → same file, same warning → permanent loop. The printed remedy can never succeed, because Doctor's cleanup preserves the divergent file by design — an instruction loop with no documented exit, the same dead-end #117270 reported from the request path.

#120610 changed only the identity loaders (src/infra/device-identity.ts — canonical SQLite row wins) and macOS/Swift startup. It never touched the readiness gate or the cleanup warning, so its authority ordering fires only after a boot the gate refuses to complete.

Given #120610 already makes the canonical row authoritative, I think the canonical fix is in the gate's classification, not file quarantine: a preserved divergent retired file with a completed receipt and a valid canonical identity is a recorded, non-fatal condition (surface it in doctor/status), not a readiness blocker. Happy to update this to that approach — or send it as a follow-up PR — but the unrecoverable-loop class is reproducible on current main either way.

@steipete

Copy link
Copy Markdown
Contributor

Closing as superseded by #120610, which already fixes the reported upgrade blocker. The proposed quarantine additionally risks moving cryptographic identity material during ordinary startup without verifying that the canonical SQLite identity exists and matches; detailed maintainer findings are recorded above. Thanks for the investigation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XS status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Conflicting retired device identity leaves running gateway unusable after new client activation

2 participants