Skip to content

feat(gateway): auto-apply safe doctor config migrations at startup - #132135

Merged
steipete merged 5 commits into
mainfrom
steipete/gateway-auto-doctor-fix-c670a2
Aug 29, 2026
Merged

steipete merged 5 commits into
mainfrom
steipete/gateway-auto-doctor-fix-c670a2

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Resolves a problem where upgrading OpenClaw could leave the Gateway unable to start: a config containing retired legacy keys (for example session.idleMinutes) failed strict validation, and startup refused readiness with Run "openclaw doctor --fix" to repair, then retry. For headless service installs (launchd/systemd) nobody sees that hint — the gateway simply stays down until an operator SSHes in and runs doctor by hand. This is the worst bug class for the out-of-box path: an upgrade that silently turns into an outage.

Why This Change Was Made

Gateway startup already runs a full doctor preflight under the startup migration lease (state migrations, cron store repair, plugin host-link repair, plugin convergence). The one thing it refused to do was rewrite openclaw.json — except for a deliberately narrow repair that unset exactly two keys authored by stable 2026.7.1-2 (automatic-upgrade-config-repair.ts, whose comment warned that widening it "would turn Gateway startup into a general doctor repair"). This PR makes that product decision deliberately (maintainer-requested): the narrow repair is generalized into automatic-startup-config-repair.ts, which applies the full deterministic, prompt-free legacy config migration set — the same pure transform openclaw doctor --fix uses (applyLegacyDoctorMigrations), which subsumes the old two-key case.

Fail-closed conditions preserved:

  • Only single-file configs — $include configs, Nix mode, configs written by a newer OpenClaw, and update-in-progress runs (plugin validation deferred) still refuse.
  • The write happens only when the complete migrated result validates, including plugin config, with no remaining legacy issues; anything else keeps today's refusal + doctor hint.
  • The write runs under the startup migration lease, after state migrations (which must consume retired locators like cron.store before the config write removes them), guarded by a fresh-disk-read drift check immediately before commit, and the previous config lands in the 5-slot .bak ring.
  • The gateway pre-bootstrap drift guard accepts only the canonical stamped writer result (isStartupConfigRepairResult); anything else refuses startup.

Legacy session-store import, SQLite schema migrations requiring doctor, and service repairs intentionally stay doctor-owned.

User Impact

After an upgrade, gateways with migratable legacy config keys now start normally — including non-interactive service startups — logging the applied migrations as a "Doctor changes" panel. Operators no longer need to run openclaw doctor --fix for deterministic config-key migrations. Docs updated on 8 pages that stated the old "startup never rewrites config" contract.

Evidence

Pre-fix baseline (shipped 2026.8.1, isolated state dir, config with session.idleMinutes):

Gateway failed to start: Invalid config at .../openclaw.json:
openclaw.json:3 — session: Unrecognized key: "idleMinutes"
Run "openclaw doctor --fix" to repair, then retry.

Patched build, same config (live run, isolated OPENCLAW_STATE_DIR, own port):

◇  Doctor changes
│  Migrated legacy config keys at startup:
│  - Moved session.idleMinutes → session.reset.idleMinutes.
[gateway] http server listening (17 plugins: ...)
[gateway] ready
  • Config canonically rewritten (session.reset.idleMinutes, stamped meta.lastTouchedVersion); original preserved byte-identical in openclaw.json.bak.
  • Second start: no re-migration, clean [gateway] ready (checkpoint hit).
  • Non-migratable config (definitelyNotAKey): still exits 78 with the doctor hint, file byte-identical, no .bak created.
  • Refusing startups stay side-effect-free: process test proves a startup refused for unrelated reasons leaves a migratable config untouched with no .bak.
  • Tests: new planner suite (deterministic plan, include/Nix/partial-validation refusals, canonical-writer matcher) + preflight integration tests (migration under lease with checkpoint reread, retired-locator preservation, update-in-progress and remaining-error refusals). 270 tests across touched files pass; pnpm check:changed green; regression tests fail on pre-fix code.
  • Codex autoreview: scoped-clean, no accepted findings.
  • Production LOC: +114/−127 (net −13) | Tests: +183/−37 | Docs: +33/−15.

@clawsweeper

clawsweeper Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@steipete
steipete marked this pull request as ready for review August 28, 2026 21:28
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes commands Command implementations size: M maintainer Maintainer-authored PR labels Aug 28, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. 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 28, 2026
@clawsweeper

clawsweeper Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed August 28, 2026, 8:39 PM ET / August 29, 2026, 00:39 UTC.

ClawSweeper review

What this changes

The PR lets Gateway startup apply Doctor’s deterministic legacy-key migrations to eligible single-file configurations after full validation, preserving a backup before booting.

Merge readiness

⚠️ Ready for maintainer review - 2 items remain

Keep open for maintainer review: this deliberately changes the upgrade contract from refusing an invalid legacy config to automatically rewriting eligible configurations at Gateway startup. The implementation has no supported blocking defect in the reviewed head, but that compatibility policy requires an explicit maintainer choice.

Priority: P1
Reviewed head: 2fe948b82247e18bedbcce8f57d95522f3060cc3
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent owner-boundary implementation with focused migration and refusal coverage, pending the human compatibility decision and completion of exact-head checks.
Proof confidence 🌊 off-meta tidepool Not applicable: This MEMBER-authored Gateway PR is exempt from the external-contributor proof gate; its supplied before/after startup transcript is supportive context, while the review independently checked the migration, validation, backup, and refusal boundaries in source.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This MEMBER-authored Gateway PR is exempt from the external-contributor proof gate; its supplied before/after startup transcript is supportive context, while the review independently checked the migration, validation, backup, and refusal boundaries in source.
Evidence reviewed 6 items Introduced migration boundary: The introduced planner accepts only invalid, existing, single-file configs, applies the shared Doctor migrations, and requires plugin-aware validation with no remaining legacy issues before returning a repair plan.
Preflight owns the mutation after state migration: Gateway preflight constructs the plan only for startup checkpoints and commits it after migration work and repeated disk guards; it then rereads the resulting snapshot.
Regression coverage: Tests cover a valid migrated session key, backup preservation, checkpoint reread, retained state locators, and refusals for update-in-progress and remaining validation errors; the pre-bootstrap test rejects unrelated post-migration drift.
Findings None None.
Security None None.

How this fits together

Gateway startup first prepares a trusted configuration snapshot, then Doctor preflight performs state/config migration before the service starts. This PR makes a fully validated legacy-key migration an allowed preflight write while retaining fail-closed exclusions for includes, Nix, newer configs, deferred plugin validation, and remaining errors.

flowchart LR
A[Existing configuration] --> B[Gateway pre-bootstrap]
B --> C[Doctor preflight]
C --> D[Legacy migration plan]
D --> E[Full config and plugin validation]
E --> F[Backup-preserving config write]
F --> G[Gateway ready]
Loading

Decision needed

Question Recommendation
Should Gateway startup automatically rewrite an eligible legacy configuration after full validation, rather than require an operator to run Doctor? Adopt the safe startup migration boundary: Allow deterministic, fully validated single-file legacy-key migrations with backup preservation and the existing fail-closed exclusions.

Why: This is an intentional compatibility and operator-experience policy change, not a mechanical defect fix; the supplied context does not include an independently verifiable maintainer decision beyond the PR’s assertion.

Before merge

  • Resolve merge risk (P1) - Merging changes eligible existing configurations from a startup refusal into an automatic canonical rewrite; maintainers should explicitly accept that upgrade behavior and retain the documented exclusions and full-validation boundary.
Agent review details

Security

None.

PR surface

Source +65, Tests +206, Docs +18. Total +289 across 21 files.

View PR surface stats
Area Files Added Removed Net
Source 8 277 212 +65
Tests 5 346 140 +206
Docs 8 33 15 +18
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 21 656 367 +289

Review metrics

Metric Value Why it matters
Production versus test delta production +277/-212 (net +65); tests +346/-140 (net +206); docs +33/-15 (net +18) The production increase generalizes and replaces a prior narrow repair; the added tests cover the new migration and refusal boundaries.
Startup configuration policy 1 behavior changed Eligible legacy configurations now move from a startup failure to an automatic backup-preserving rewrite.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/cli/gateway-cli/pre-bootstrap.ts, migration/backfill/repair: src/commands/backup-restore.ts, migration/backfill/repair: src/commands/backup-shared.ts, migration/backfill/repair: src/commands/doctor-config-preflight.ts, migration/backfill/repair: src/commands/doctor/shared/automatic-startup-config-repair.ts, migration/backfill/repair: src/commands/doctor/shared/automatic-upgrade-config-repair.ts, and 5 more. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Confirm the startup-write policy (recommended)
    Approve the documented automatic-migration subset only after confirming that changing eligible upgrades from refusal to rewrite is the intended operator contract.
  2. Pause the policy expansion
    Keep the existing manual Doctor path if automatic config mutation during service startup is not an intended upgrade behavior.

Technical review

Best possible solution:

Retain one Doctor-owned migration planner and land it only if maintainers endorse automatic rewriting for the documented eligible-config subset, with exact-head CI completing successfully.

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

Yes—source-reproducible: pinned main limits startup repair to two paths, while the new planner transforms additional legacy keys such as session.idleMinutes. The checkout was not executed because this is a read-only review.

Is this the best way to solve the issue?

Yes technically: reusing the Doctor migration owner, validating the full result, and deleting the narrower predecessor is the cleanest implementation shape; maintainer approval is still required for the new startup-write policy.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • remove rating: 🦞 diamond lobster: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P1: The branch changes Gateway startup recovery for upgraded installations, including non-interactive services that otherwise remain unavailable.
  • merge-risk: 🚨 compatibility: It intentionally changes how existing invalid legacy configuration files are handled during startup.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This MEMBER-authored Gateway PR is exempt from the external-contributor proof gate; its supplied before/after startup transcript is supportive context, while the review independently checked the migration, validation, backup, and refusal boundaries in source.

Evidence

What I checked:

Likely related people:

  • Timur Turatbekov: Current-main blame attributes the former bounded startup migration module to this commit; the new behavior replaces that boundary. (role: introduced prior narrow startup-repair policy; confidence: high; commits: 22d4279245a2; files: src/commands/doctor/shared/automatic-upgrade-config-repair.ts)
  • ToToKr: Recent current-main history includes work on non-interactive preflight warnings in the same preflight owner. (role: recent preflight contributor; confidence: medium; commits: 26442aadaa3d; files: src/commands/doctor-config-preflight.ts)

Rank-up moves

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

  • Record maintainer approval of the automatic startup-write policy and let the remaining exact-head checks complete.

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 (4 earlier review cycles)
  • reviewed 2026-08-28T21:37:50.200Z sha c55ed1d :: needs changes before merge. :: [P1] Preserve the future-config guard for invalid legacy configs
  • reviewed 2026-08-28T23:13:02.263Z sha e36232f :: needs maintainer review before merge. :: none
  • reviewed 2026-08-28T23:58:00.227Z sha d88ebe1a65ae91b2f0f5d38ba3a1e184ca67de2f :: found issues before merge. :: [P1] Allow plugin-owned migrations to reach startup preflight
  • reviewed 2026-08-29T00:13:57.595Z sha dd0f6e10ffa85503867cb6e1f531c59a5cfdbedc :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the steipete/gateway-auto-doctor-fix-c670a2 branch from c55ed1d to 557dbfc Compare August 28, 2026 22:42
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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 28, 2026
@steipete
steipete force-pushed the steipete/gateway-auto-doctor-fix-c670a2 branch from e36232f to d88ebe1 Compare August 28, 2026 23:48
@clawsweeper clawsweeper Bot added 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. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 28, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed the ClawSweeper P1 (plugin-only migrations unreachable from the pre-bootstrap trust check) in dd0f6e10ffa85503867cb6e1f531c59a5cfdbedc: resolveStartupConfigSnapshot now runs the full planner (plugin doctor contracts included) first, and falls back to the state-free preview only when the installed-plugin registry store is unreachable — backup discovery and broken-store startups stay fail-closed.

Rank-up move ("isolated bootstrap-to-preflight proof for a plugin-only migration"): partially applied. The new unit regression proves the trust check admits a config whose only repair is the bundled Active Memory retired-QMD contract and returns the plugin-migrated snapshot; the guarded config write for plugin migrations goes through the same preflight commit path proven by the existing core-key integration tests (lease, retired-locator ordering, checkpoint reread, canonical-writer drift matcher). A full bootstrap→preflight e2e with a plugin-only fixture is noted as follow-up rather than blocking this landing.

@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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 29, 2026
Gateway startup now runs the same deterministic, prompt-free legacy
config-key migrations as "openclaw doctor --fix" when an otherwise
invalid single-file config can be fully migrated, instead of refusing
readiness with a doctor hint. The write happens under the existing
startup migration lease, after state migrations consume retired
locators, only when the complete result validates including plugins,
and keeps the previous config in the .bak ring. Configs using
$include, Nix mode, newer-version configs, update-in-progress runs,
and configs that stay invalid keep the current fail-closed refusal.

This replaces the narrow two-key stable-upgrade repair with the full
migration set (which subsumes it), so headless service gateways just
work across upgrades instead of stopping on retired config keys.
resolveStartupConfigSnapshot serves gateway pre-bootstrap selection and
backup discovery, which run before state-database admission. The full
planner resolves plugin doctor contracts through the installed-plugin
registry, which opens the shared SQLite store — a broken store (or
backup's pre-validation guarantee) must not break those callers. The
preview tier now applies only state-free migrations with raw validation;
the preflight committer and canonical-write matcher stay authoritative.
…nments

CI unit shards and unbuilt checkouts have no dist/build-info.json, so the
checkpoint layer fails open by design and the startup-repair checkpoint
assertions could never hold there. Wrap the real module with a pinned
build identity so recording and needs-checks stay meaningful.
The pre-bootstrap trust check admitted only state-free core migrations,
so a config whose sole repair belongs to a plugin doctor contract was
refused before the plugin-aware preflight could migrate it. The resolver
now runs the full planner first and falls back to the state-free preview
only when the installed-plugin registry store is unreachable, keeping
backup discovery and broken-store startups fail-closed.
@steipete
steipete force-pushed the steipete/gateway-auto-doctor-fix-c670a2 branch from dd0f6e1 to 2fe948b Compare August 29, 2026 00:32
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. labels Aug 29, 2026
@steipete
steipete merged commit 52e43a4 into main Aug 29, 2026
238 checks passed
@steipete
steipete deleted the steipete/gateway-auto-doctor-fix-c670a2 branch August 29, 2026 00:56
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Aug 29, 2026
…penclaw#132135)

* feat(gateway): auto-apply safe doctor config migrations at startup

Gateway startup now runs the same deterministic, prompt-free legacy
config-key migrations as "openclaw doctor --fix" when an otherwise
invalid single-file config can be fully migrated, instead of refusing
readiness with a doctor hint. The write happens under the existing
startup migration lease, after state migrations consume retired
locators, only when the complete result validates including plugins,
and keeps the previous config in the .bak ring. Configs using
$include, Nix mode, newer-version configs, update-in-progress runs,
and configs that stay invalid keep the current fail-closed refusal.

This replaces the narrow two-key stable-upgrade repair with the full
migration set (which subsumes it), so headless service gateways just
work across upgrades instead of stopping on retired config keys.

* fix(doctor): keep startup repair preview off the shared state database

resolveStartupConfigSnapshot serves gateway pre-bootstrap selection and
backup discovery, which run before state-database admission. The full
planner resolves plugin doctor contracts through the installed-plugin
registry, which opens the shared SQLite store — a broken store (or
backup's pre-validation guarantee) must not break those callers. The
preview tier now applies only state-free migrations with raw validation;
the preflight committer and canonical-write matcher stay authoritative.

* test(doctor): avoid shadowing the path module in repair fixtures

* test(doctor): pin checkpoint build provenance for unbuilt test environments

CI unit shards and unbuilt checkouts have no dist/build-info.json, so the
checkpoint layer fails open by design and the startup-repair checkpoint
assertions could never hold there. Wrap the real module with a pinned
build identity so recording and needs-checks stay meaningful.

* fix(doctor): reach plugin-owned migrations from the startup trust check

The pre-bootstrap trust check admitted only state-free core migrations,
so a config whose sole repair belongs to a plugin doctor contract was
refused before the plugin-aware preflight could migrate it. The resolver
now runs the full planner first and falls back to the state-free preview
only when the installed-plugin registry store is unreachable, keeping
backup discovery and broken-store startups fail-closed.
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 docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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