Skip to content

fix(doctor): converge plugin data upgrades without stopping a sealed system service - #186648

Merged
steipete merged 6 commits into
mainfrom
upd/upd-l1928
Oct 28, 2026
Merged

steipete merged 6 commits into
mainfrom
upd/upd-l1928

Conversation

@steipete

@steipete steipete commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #186612. Thanks @cryptoninja1stat for the report.

What Problem This Solves

Fixes plugin data/settings upgrades remaining unfinished after a successful same-version cold start, and Doctor draining a system-owned Gateway that the current user cannot stop.

User Impact

The Gateway can confirm an already-complete plugin upgrade during startup. Doctor reports the blocked Gateway-stop phase and exact privileged command before draining an inaccessible system service. Actual pending migrations retain their safety boundary and require offline repair.

Why This Change Was Made

The durable plugin-convergence ledger was settled by Doctor, while Gateway startup only consumed its pending obligations. Startup now uses the existing plugin-readiness owner and Doctor's existing two-phase completion inspection under the plugin lifecycle lease, validates settings, then settles already-complete obligations. An explicitly required state migration is retained if the installed plugin has no detector. Startup never executes offline mutation callbacks.

The follow-up removes the parallel state-migrations.plugin-readiness.ts module and its separate completion calculation. Existing Doctor behavior without the explicit startup inspection selection remains unchanged. That ownership simplification reduced migration-related net production growth from 161 to 153 lines without weakening lease, config, or retained-state checks. The diagnostic-worker repair below adds six net production lines.

The systemd timeout probe addresses the selected manager/unit. Maintenance checks the existing root permission before drain and carries the inspected native identity into stop, retaining the existing bounded activation path. Unprivileged callers get a structured gateway-stop / service-mutation-refused finding. Model-retirement deferrals name their actual blocker, the updating parent's plugin-package convergence, and retire the stale warning after repair completes.

No dependency, SQLite-schema, config-option, or CLI-option changes. Production: +179/-23, net +156. Tests: +438/-438, net 0; docs: +10. The test-lines baseline is unchanged.

Evidence

Rebase integration with #186792

Rebased onto main 39b3d94413ba1400822dc644743fe3045acb8a64; current head is 6bc9059a1345bf46879459db4ffadd1d2325e0d3. The conflicting timeout implementation is absorbed into main's existing systemd-stop-policy.ts. Its reader retains the selected system/user installation and explicit target precedence. Maintenance and native lifecycle use that one reader; the existing permission guard remains shared and runs before policy preparation or drain.

The native systemctl stop path from #186792 remains bounded by the effective unit timeout plus 5 seconds, with its finite fallback, warning and recorded timeout reason unchanged. The native-identity fixture keeps both the pinned StopUnit effect and main's show response (LoadState=loaded, TimeoutStopUSec=330s). Existing tables retain selected sealed-manager reads, unprivileged Doctor refusal before drain with the exact privileged stop command, native-identity recovery/refusals, finite/infinite/unavailable stop budgets and timeout reasons. No duplicate permission or timeout implementation, assertion weakening, timeout increase, dependency, option or schema change.

The consumer run exposed an existing synthetic procfs defect: /proc/<changed-pid>/stat returned the original PID in its first field. The fixture now returns the PID from the requested path, letting the existing changed-process refusal assertion execute. That case was red before this one-line fixture repair and green afterward; production identity validation and assertions are unchanged. Net test lines remain zero.

Validation used isolated HOME/state, the repository Vitest wrapper, and --maxWorkers=1. The 35-file selection includes the touched daemon/Doctor suites plus direct and one-barrel consumers discovered with rg -l for the policy/maintenance/lifecycle modules and systemd.js. OPENCLAW_NODE_TEST_PLAN_CONTINUE_ON_FAILURE=1 collected the entire selection on both runtimes:

  • Node: 35 files / 868 tests passed, exit 0, 481.575 s wall including runtime preparation and compiler/ownership waits.
  • Pinned Bun: 34 files passed / 1 failed; 867 tests passed / 1 failed, 302.904 s wall. Every touched daemon, Doctor native-identity and service-maintenance-identity case passed. The sole extended-consumer failure was doctor-maintenance.finish-revalidation.test.ts / restores the unchanged Gateway after gateway-lifecycle-contended inspection (catalog: exact): a SQLite child reported a native Bun SIGTRAP, elapsed 1 ms, RSS 2.56 MB. No JavaScript assertion or timeout failure was reported for that case. The same signed ARM64 Bun binary verified successfully and reported version 1.4.4. One focused replay passed all original assertions, but this is not a fix verdict; the native crash's exact cause remains unresolved. No retry, skip, timeout change or runtime workaround was introduced.
  • Test config typechecks: node scripts/run-tsgo.mjs -p test/tsconfig/tsconfig.core.test.{services,commands-doctor,config-cli}.json --incremental, each run separately, all exit 0. Services was checked again after the final correction.
  • Production/test oxlint on all changed TypeScript files and oxfmt on all changed TypeScript/docs: exit 0.
  • Test-lines ratchet against the pinned base: 6,307,529; ceiling 6,310,000; slack 2,471, exit 0. The baseline is unchanged by this PR. Mock-export ratchet: 6,554 grandfathered factories, exit 0. Madge: 0 cycles.
  • Local Codex autoreview, P0/P1: rebased branch and final two-file correction both scoped-clean. The first review lacked unchanged surrounding source context; direct owner inspection and the integration tests supply that coverage. A shared local ClawSweeper checkout was dirty and was left untouched.

The longest Node case was 15.943 s. Existing service integration and Doctor finish-revalidation files used about 69.592 s and 45.884 s of test time respectively; overall wall time also includes shared compilation/preparation. Full check:changed/SQLite inventory was not run under the lane's local gate budget. Exact-head PR CI remains the broad proof. The earlier hosted Doctor CLI deadline below remains unresolved; this rebase is not claimed to fix it. No merge.

Prior-head controlled comparison — hosted timeout unresolved

The repeated hosted Doctor deadline remains an unresolved PR signal; these passing local measurements are not a repair verdict. Those measurements retained no production/test change and were taken at prior head a115619c52620b77a32cd5fdfdf257ef815d90fa; current rebase results are above.

Built PR head and unmodified main c336a1ec75862fea6f42282656b1dd89ab347ae7 with pnpm build (247.3 s / 270.986 s, both exit 0). Measured the exact inner managed doctor --fix --non-interactive --no-workspace-suggestions in serves canonical state after Doctor repairs cron and preserves retired plugin sidecars, retaining its 30-second child deadline and every subsequent cron, sidecar and Gateway assertion. Both Node and pinned Bun test hosts use the fixture's Node CLI child; this does not claim a Bun CLI measurement. Identical temporary test-output observation exposed successful stderr traces and elapsed child time; both worktrees were restored byte-for-byte afterward.

Five serial, interleaved cold CLI samples per revision/test host on macOS, Node 26.12.1, with isolated HOME/state, NODE_DISABLE_COMPILE_CACHE=1 and separate compiler caches. All 20 complete target cases passed. Phase columns are medians, in seconds except where labeled:

Test host / revision Inner Doctor s Maintenance begin s Config flow s Database inspection s Memory search ms Maintenance finish ms
Node / main 11.687 2.263 4.372 1.285 53.0 0.8
Node / PR 11.993 2.322 4.560 1.172 52.5 0.8
Bun / main 12.556 2.424 4.488 1.328 54.6 0.8
Bun / PR 11.644 2.264 4.447 1.137 53.4 0.8

Inner samples in seconds, in execution order: Node main [17.837, 11.500, 11.742, 11.687, 11.417]; Node PR [13.514, 12.821, 11.938, 11.993, 10.880]; Bun main [14.580, 14.186, 12.556, 11.784, 11.581]; Bun PR [13.169, 12.441, 11.644, 11.617, 10.949]. Command: OPENCLAW_VITEST_RUNTIME=node or bun, then node scripts/run-vitest.mjs src/commands/doctor-config-preflight.process.test.ts --maxWorkers=1 -t 'serves canonical state after Doctor repairs cron and preserves retired plugin sidecars'.

The CI logs show a workload difference that prevents the probe from isolating the added cost: PR job 122860135628 ran this file concurrently with doctor-config-flow.legacy-composition.test.ts in two forks on two CPUs; probe job 122874228472 ran the process file alone. This is not grounds to label the repeated failure flaky or inherited.

Replayed that complete two-file cohort locally in Linux ARM64 Docker, Node 24.22.1, two pinned CPUs, a two-CPU cgroup quota, 8 GiB memory, no installed systemctl, isolated HOME/state, and the same unchanged child deadline. Runtime prerequisites were rebuilt inside Linux before tests; their preparation time is excluded from inner Doctor measurements. Exact selection: node scripts/run-vitest.mjs src/commands/doctor-config-flow.legacy-composition.test.ts src/commands/doctor-config-preflight.process.test.ts --maxWorkers=2, with OPENCLAW_VITEST_RUNTIME=node or bun and OPENCLAW_E2E_SKIP_BUILD=1.

Linux cohort / revision Inner Doctor s Maintenance begin s Config flow s Database inspection s Memory search ms Maintenance finish ms
Node / main 14.990 2.644 5.836 1.821 66.1 1.8
Node / PR 14.214 2.643 5.509 1.603 64.8 1.9
Bun first / main 14.427 2.581 5.526 1.755 72.9 1.7
Bun first / PR 16.710 2.799 7.767 1.538 64.1 1.7
Bun reversed repeat / main 14.164 2.493 5.397 1.829 67.9 1.8
Bun reversed repeat / PR 15.664 3.025 6.104 1.734 71.6 0.9

All six target cases and their inner Doctors passed. Each full cohort returned exit 1 with 31 passed / 1 failed: the separate reloads tool ownership after updater-managed manifest repair case left legacy tools unchanged and found no repaired tool owner. The assertion and blocked-plugin warning match on unmodified main and PR, on both test hosts; no plugin/snapshot permission policy was changed. Existing slow real-flow cases also reproduce on main (the v17 double-repair case is about 39 s and the July upgrade case about 41 s). These complete-cohort failures are disclosed rather than called clean proof.

Finally, profiled the exact focused target on Linux Node, main then PR, by adding identical temporary --cpu-prof arguments to the fixture child entrypoint. Both complete cases passed; the copied test observers/profile flags were removed after capture. Main inner Doctor was 12.2365 s, PR 12.2421 s. Main/PR phases: maintenance begin 2.1011 / 2.3078 s, config flow 4.6727 / 4.8394 s, database inspection 1.4131 / 1.2126 s, Memory search 70.5 / 67.5 ms, maintenance finish 1.1 / 1.9 ms. This focused pair identifies no stable added Doctor cost; it does not substitute for the failed hosted workload.

Doctor main-thread profile weights (overlapping inclusive categories), main/PR: idle 7.843 / 7.963 s, spawnSync 0.970 / 0.991 s, compilation 0.482 / 0.494 s, GC 0.184 / 0.182 s, fixture dependency resolver 0.405 / 0.365 s, and SQLite 1.853 / 1.868 s. These are sampled time weights, not OS CPU accounting. Doctor worker profiles were not captured, so the roughly eight idle seconds remain unattributed to individual child/worker operations. No resolver optimization is justified by this profile.

In the actual failed CI trace, maintenance begin cost 4.7852 s, config flow 12.6471 s and database inspection 3.6118 s. The last recorded pre-Memory phase ended at 29.7963 s, leaving roughly 0.2 s of the child budget. There is no evidence here of a slow maintenance-finish wait. Source audit found no extra plugin detector pass in this Doctor path: startup alone invokes the new convergence entrypoint, Doctor does not pass its optional inspection selection, and the new permission check is synchronous and occurs only for an owned service. The earlier snapshot-worker count reduction is not accepted as proof of this timeout's cause.

Prior investigation verdict (before this rebase): no validated owner fix for the hosted deadline was established, so no speculative optimization, new commit, repush, timeout change, retry, skip, or readiness claim was made. The remaining gap is a matched Linux x64 CI cohort comparison and attribution of its extra cold-runtime cost; local ARM64 passing replays do not resolve it. At that prior head, whole-PR production was +186/-27, net +159; tests +438/-438, net 0. Both requested ratchets pass at this unchanged head. The disposable baseline worktree and Linux container are removed after all owned commands settle. No merge.

The original regressions were reproduced red before the fix: version-parity startup settlement, selected system-manager timeout inspection, permission-before-drain, stale retirement warning, and privileged-command preservation through finding redaction. Required-state obligations with absent/empty contracts remain pending.

The final test consolidation reuses Doctor’s real-plugin fixture for nine startup scenarios and retains required-obligation checks through both startup and Doctor. The startup callback writes a sentinel before throwing, so the unchanged-file assertion detects any attempted offline migration. Absent/empty contracts, pending default/post-session migrations, detector failures, and invalid config stay blocked; version-parity and explicitly stateless upgrades converge. The retirement blocker and warning clearing are now checked through the existing durable config-write flow. Native-manager cases share tables; startup metadata uses its existing fixture owner and embedding-warning cases share a table without losing scenarios.

The current test-lines and mock-export ratchets pass against the pinned rebase base (outputs above); whole-PR net test delta is 0. This PR does not change config/test-lines-baseline.txt.

Before the latest CI follow-up, the 8 then-touched test files passed on Node and the pinned Bun runtime: 206 tests per runtime, using OPENCLAW_VITEST_RUNTIME=node / bun with node scripts/run-vitest.mjs <selected files> --maxWorkers=1, isolated HOME/state, normal macOS TMPDIR, and separate runtime compiler caches. Successful per-file results are combined across the focused runs; passing reruns are not used to classify the historical F3 failure.

Touched file Tests Node test time Bun test time
update-command-service-maintenance-identity.test.ts 31 0.28s 0.19s
doctor-config-flow.billing-route.test.ts 7 133.42s 138.73s
doctor-config-preflight.plugin-deferral.test.ts 22 183.56s 180.44s
doctor-maintenance.native-identity.test.ts 6 2.80s 2.85s
systemd-maintenance.test.ts 19 2.02s 0.68s
systemd.test.ts 83 1.36s 1.43s
server-startup-plugins.test.ts 23 5.65s 5.08s
state-migrations.plugin-doctor.test.ts 15 6.52s 4.96s

Test times are sums of the reported case durations, excluding shared transform/preparation. Final Node deferral/systemd wrapper: 199.40s; Bun five-file wrapper: 69.63s; Bun three-Doctor-file wrapper: 355.08s. The existing Doctor integration flows remain expensive: billing’s result-channel case took 32.127s on Node, and the files exceed 120s of tests. They repeatedly run actual Doctor config/state/plugin inspection at swap, durable convergence, and idempotent replay boundaries. Those pre-existing flows were retained under the campaign’s slow-suite ruling; the new retirement checks add assertions, not Doctor boots. No timeout, retry, or skip was introduced.

Affected test-type leaves (Gateway server, infra, Doctor commands, update CLI, services), touched-file oxlint and oxfmt, and diff checks pass. Initial validation caught consolidation fixture/type/lint mistakes, which were corrected before the final results above. Independent Codex autoreview of the final candidate was scoped-clean for P0–P2. Final rebase onto 0f1de690fa59c8e9e684b1466f52977a574ff9a5 completed without conflicts; git range-diff verified all three PR patches unchanged from the tested/reviewed candidate.

Prior owner-reuse proof remains historical: all 34 selected direct/barrel consumer files completed with 261 passed, 5 skipped, wrapper wall time 846.91 seconds; runtime build/bootstrap guards passed. Core typecheck, prior affected Gateway/infra/plugin test-type leaves, and production cycle checks (0 cycles) passed. Full check:changed SQLite inventory was omitted under the campaign’s local gate budget. Exact-head PR CI is the broad proof; hosted CI success is not claimed here.

Repeated Doctor timeout investigation and owner repair

The repeated failures at e03d32a820edfcb0136078be7a115eb0826c0f29 are treated as a PR signal, not attributed to a flake or to main: sandbox Bun job, process-test Bun job. The separately owned status recovery ordering failures are tracked by #186663 / #186728 and were left untouched.

Measured defect repaired: inspectDatabaseStore is asynchronous, but used the synchronous private-snapshot API. Every physical store therefore blocked its inspection worker while a fresh snapshot child loaded its runtime. Doctor already has a reusable read-only worker owner; its database-inspection worker did not establish that scope. Diagnostics now awaits the existing snapshot API with preserveSourceArtifacts:true, awaits cleanup, and shares one existing read-only worker scope across the inspection task. It still prepares fresh bytes for each store. No new cache, state, schema, permission rule, dependency, timeout, retry, or CLI option was introduced.

The unchanged real two-store inspection fixture was traced on local Linux with strace -f -e trace=process. Before: 5 SQLite child launches, including 2 one-shot children for physical-store diagnostics. After: 4 launches, with 1 shared session child for those two diagnostics; the other three launches remain. Artifact-preservation and physical-engine assertions passed in both traced runs. This is a measured removal of cold runtime work, not a claim that a passing replay proves the exact hosted deadline crossing repaired.

The existing version, engine-mismatch, and unversioned-journal cases now share a table. They use the actual awaited snapshot producer and require an event-loop turn to run before inspection completes, while retaining schema, mismatch, custody, next-step, and unchanged-byte checks. With the original synchronous implementation restored as a negative control, all 3 table cases fail because that turn has not run. Returning to the awaited implementation makes the complete 9-case file pass on Node and Bun. This adds one net test line locally; the whole PR remains net 0 test lines after prior consolidation. No test-lines baseline was changed.

Both requested files were run against pnpm build output on Node and pinned Bun, with isolated HOME/state and NODE_DISABLE_COMPILE_CACHE=1. The complete process file and sandbox E2E passed on macOS before and after the owner repair. Final owner/consumer proof covers 77 tests per runtime across 8 files, combining the focused runs and the strengthened diagnostics-file replay. It includes diagnostics, database-engine inspection/report/network-storage, worker-env boundary, the complete Doctor process file, the sandbox E2E, and compiled-worker artifact consumers.

OPENCLAW_VITEST_RUNTIME=node OPENCLAW_E2E_SKIP_BUILD=1 NODE_DISABLE_COMPILE_CACHE=1 node scripts/run-vitest.mjs src/infra/database-engine/diagnostics.test.ts src/commands/doctor-database-engine-inspection.test.ts src/commands/doctor-database-engine.test.ts src/commands/doctor-database-network-storage.test.ts src/infra/worker-env-boundary.test.ts src/commands/doctor-config-preflight.process.test.ts src/commands/doctor.warns-per-agent-sandbox-docker-browser-prune.e2e.test.ts --maxWorkers=1
OPENCLAW_VITEST_RUNTIME=bun OPENCLAW_E2E_SKIP_BUILD=1 NODE_DISABLE_COMPILE_CACHE=1 node scripts/run-vitest.mjs src/infra/database-engine/diagnostics.test.ts src/commands/doctor-database-engine-inspection.test.ts src/commands/doctor-database-engine.test.ts src/commands/doctor-database-network-storage.test.ts src/infra/worker-env-boundary.test.ts src/commands/doctor-config-preflight.process.test.ts src/commands/doctor.warns-per-agent-sandbox-docker-browser-prune.e2e.test.ts --maxWorkers=1

The artifact consumer file was also run separately with each runtime: 30/30 passed (Node wrapper 109.90s, Bun 159.52s). The final strengthened diagnostics file passed 9/9 separately (Node wrapper 38.91s including 77% shared transform; Bun 18.57s). The unchanged v17 two-Doctor migration case still takes 36.288s / 32.128s on Node / Bun (before this repair: 39.277s / 34.654s). These existing slow proofs were recorded, without timeout or assertion changes.

Local Docker additionally exercised Node 24.22.1 on Linux, without a systemd user session or installed user service. A task-owned systemctl stub logs arguments and executes sleep 60. Only the existing bounded --system is-system-running classification fallback was observed; no stop-timeout show, stop, start, or restart command was reached. Both runtimes passed the exact reported process case and both sandbox cases, using the same two-file command with -t 'serves canonical state|warns when per-agent|does not warn'.

Candidate, runtime / host Cron/sidecar readiness case Sandbox warning case
Node / macOS 21.188s 7.506s
Bun / macOS 22.565s 8.108s
Node / Linux with sleeping systemctl 23.550s 23.833s
Bun / Linux with sleeping systemctl 24.593s 8.005s

These are individual outcome/timing observations, not a controlled latency-improvement claim. Both pnpm build runs passed (191.4s before / 137.0s after, with preparation reuse). The container used a frozen-lockfile Linux dependency install and the built JS output. An initial full-file Linux run passed the reported cron/sidecar case but failed the separate reloads tool ownership after updater-managed manifest repair expectation (legacy manifest remained unrepaired). This occurred before the new diagnostic repair; it is not claimed to match a main failure or to be resolved by the focused Linux runs. The complete file passes on macOS. The task-owned container and its processes were stopped and removed after proof; no remote lease or host service was used.

Attribution limit: the CI sandbox timer expired during Database engines after roughly 15s already spent in config flow. Doctor: Memory search in the process failure is a phase-start label, so it does not establish that service finish ran or stalled. The diagnostic sandbox returns before maintenance admission and mocks memory/daemon checks; the new stop-permission assertion is synchronous. No new service probe or permission wait explains both signatures. The synchronous per-store runtime launches above are a concrete cost owner now repaired, but the exact hosted timeout cause remains unproven. The repeated failures are not dismissed as pre-existing or flaky, and exact-head CI remains necessary broad proof.

Final checks: infra and Doctor test types, touched-file oxlint/oxfmt, diff checks, Madge (0 cycles), and fresh independent Codex P0-P2 review pass. Mock-export ratchet: 6563 grandfathered factories. Test-line ratchet: 6,300,406; ceiling 6,299,646; net delta 0. Full check:changed SQLite inventory remains omitted under the campaign time budget. Production growth for this follow-up is +10/-4, net +6; whole-PR LOC is reported above.

Earlier mock-export CI follow-up

The baseline-ratchets job and Bun changed-test job were inspected once at head 2aa36d78f0a2c8982522bdb944049f16f40a38f0.

Mock-export failure: fixed. The six startup mock factories now use typed importOriginal spreads and override only their intended functions. Their six obsolete grandfathered exceptions were removed from config/test-mock-exports-baseline.txt (6569 → 6563); no allowance was added. Resetting the existing lookup mock replaces duplicated fixture construction. Its fixture now supplies the real required worker-provider field, and the auto-enable mock accepts the real optional config contract.

node --import ./scripts/tsx.mjs scripts/check-test-mock-exports.mts --base origin/main
Mock factory ratchet OK: 6563 grandfathered factories.
node --import ./scripts/tsx.mjs scripts/check-test-lines-ratchet.mts --base origin/main
Test lines: 6300405; ceiling: 6299646; net delta: -1.

The repaired server-startup-plugins.test.ts passed all 23 cases on Node and 23 on pinned Bun (wrapper wall 20.53s / 19.23s; Vitest 16.18s / 15.71s). Gateway-server test types, oxlint, oxfmt, and diff checks pass. Fresh independent Codex autoreview of this CI repair was scoped-clean for P0–P2. This follow-up changes no production code, timeout, assertion, skip, snapshot policy, or test-lines ceiling.

Doctor timeout: not reproduced; hosted cause remains unknown. The exact full file src/commands/doctor.warns-per-agent-sandbox-docker-browser-prune.e2e.test.ts ran three times per runtime at the original head and at unmodified main 4b4c689140e726478c02fea5303a1d3ab1ce9261. All 12 invocations passed both cases. Passing replays do not establish that the hosted timeout was fixed or prove an identical failure on main.

Revision / runtime Target case seconds, runs 1 / 2 / 3 Wrapper wall seconds, runs 1 / 2 / 3
PR head / Node 17.850 / 8.605 / 7.126 38.930 / 29.256 / 24.708
Main / Node 20.695 / 10.389 / 10.755 57.645 / 21.237 / 22.075
PR head / pinned Bun 17.740 / 14.946 / 10.338 242.488 / 37.289 / 32.257
Main / pinned Bun 18.874 / 9.314 / 8.967 36.678 / 26.011 / 26.185

Commands were OPENCLAW_VITEST_RUNTIME=node / bun with node scripts/run-vitest.mjs src/commands/doctor.warns-per-agent-sandbox-docker-browser-prune.e2e.test.ts --maxWorkers=1. Each checkout used isolated HOME/state under task artifacts, separate runtime compiler caches, inherited macOS TMPDIR, and unchanged tracked sources throughout the comparison. Main used supported OPENCLAW_E2E_SKIP_BUILD=1 for this source-fixture-only suite after automatic package preparation hit the nested-checkout declaration boundary and collected zero tests. That setup failure is excluded. Head’s first Bun wrapper includes full E2E package preparation; Vitest itself took 51.09s and the target took 17.740s, so the 242.488s wrapper is not mislabeled as test time. Main’s cold Node compiler preparation was 26.978s, also outside the target timer.

One additional unchanged-source Bun run on each revision enabled the existing OPENCLAW_GATEWAY_STARTUP_TRACE=1 / OPENCLAW_E2E_VERBOSE=1 instrumentation with supported build skipping. Both passed. Maintenance admission was 0.3/0.2ms at head and 0.2/0.2ms on main, with sub-millisecond release. The existing config-flow and database-engine health phases consume seconds on both:

Timed phase Head first / second case Main first / second case
Config flow 1.791s / 1.064s 1.957s / 0.925s
Database-engine contribution 1.663s / 1.089s 3.494s / 1.612s
All contributions 3.539s / 3.096s 5.147s / 3.709s

The fixture invokes diagnostic Doctor with nonInteractive:true, without repair/yes or a heartbeat repair plan. beginDoctorMaintenance returns before the stop/permission/drain path, and the added systemd permission helper remains behind its existing lazy maintenance boundary. The cold/warm cost pattern occurs on both revisions; these samples do not show a consistent head-only regression. The source loader resets modules per case and restores the real health-contribution flow, including database-engine checks unrelated to the sandbox warning. That identifies existing workload, not the precise cause of the Linux hosted deadline crossing. The CI log shows the timed-out Doctor continuing alongside the second case; this overlap is a consequence observed after timeout, not an established original cause. No speculative production repair, broader fixture mock, timeout increase, or retry was added to conceal that uncertainty.

The temporary main comparison worktree was removed normally after all owned proof processes exited; its path and Git registration are absent. Exact-head PR CI remains the broad proof for the new repair head; CI success is not claimed here.

Controlled recovery comparison

The exact src/cli/update-cli/update-command-original-service.test.ts file ran five times at PR head c5fe9d1efc0a6a5c08577d1b0bc6929a9ac8b6ab, with tracked sources frozen, and five times on an unmodified detached main checkout at a9e8614de1ecce3e6e5234dfb46251019ac2fd5f. Each invocation used fresh isolated HOME/state and a checkout-specific compiler cache, inherited normal macOS TMPDIR, the same Node/toolchain/runtime, and node scripts/run-vitest.mjs <file> --maxWorkers=1. Lockfile/workspace dependency inputs matched. Logs merged stdout/stderr into one descriptor. Setup-only dependency-link failures collected no tests and were excluded from the five runs.

Run PR-head full file, wall time Main full file, wall time F3 healthy case, head / main
1 48 passed; 302.44s 47 passed, 1 failed; 377.33s passed 9.209s / passed 18.909s
2 48 passed; 333.76s 48 passed; 359.65s passed 16.524s / passed 16.464s
3 48 passed; 366.85s 48 passed; 374.04s passed 17.614s / passed 13.632s
4 48 passed; 358.41s 48 passed; 348.53s passed 10.250s / passed 10.679s
5 48 passed; 387.45s 46 passed, 2 failed; 323.15s passed 15.758s / passed 10.015s

Main's failures were distinct from the historical F3 case:

  • Run 1, “keeps B facts and current data through split-root failure: readiness-failed”: expected one native restart, observed zero (9.483s).
  • Run 5, “keeps B facts and current data through split-root failure: windows-autostart”: expected one suspension, observed two (17.565s).
  • Run 5, “capable original recovery binds definition after native lock: unchanged”: expected {value: "healthy"}, observed {value: "failed"} (8.491s).

One additional unchanged-main replay enforced the observed preceding-file order: database rollback → dreaming Cron Doctor integration → original-service. All 75 tests across three files passed, including F3 healthy (14.552s); wrapper wall time 822.37s. A sequencer-launch setup error collected no tests and was excluded. Existing long test costs were recorded rather than changing timeouts or assertions: database rollback git-edited 63.538s, git 55.271s, and standalone F3 not-ready 30.698s.

Lead verdict: treat the single historical F3 “healthy” failure as a flaky test, not something this PR causes. The file passed all five runs at the PR head; unchanged main demonstrated other failures in the same suite. The exact F3 case also passed all five main runs and the ordered replay. This is the lead’s attribution decision, not a claim that a race was repaired by rerunning. No retries, timeout increases, weakened assertions, baseline exceptions, or speculative production changes were added. Exact-head PR CI is the broad proof.

Doctor temporary-directory attribution

The continuation fixture creates its snapshot root through createTempDirTracker → canonical os.tmpdir(), independent of HOME/state isolation. Relevant fixture, capture, and permission-policy sources are identical on main and the PR.

Temporary root PR head Unmodified main
Normal inherited macOS temporary directory 2/2 passed 2/2 passed
Private mode-700 TMPDIR beneath the external volume 1 passed, 1 failed 1 passed, 1 failed

Both relocated runs fail the same “keeps Doctor continuation with its repair scope (cached writer: false)” case with SQLite staging ancestor must not allow another user to replace its child, naming the external volume's mode-775 ancestor. The false branch captures a snapshot; the cached-writer branch does not. Verdict: reproduced environment/temporary-root constraint, not this PR. The earlier blanket description of a host-volume failure is refined to this specific placement condition. Snapshot permissions and admission policy were not changed.

Live CLI and remaining proof limits

The real CLI used an isolated HOME/state and an owned Gateway on loopback port 29829. The version-parity fixture uses the production migration contract; its mutation callback throws if invoked. The sealed-service adapter simulates external native inspection as existing tests do, with mutations forbidden. OpenClaw state was isolated and no host service was mutated.

pnpm openclaw doctor --fix --non-interactive
exit 1, 11 seconds
Gateway stop phase blocked: run `sudo systemctl stop openclaw.service`
structured finding: check=gateway-stop, code=service-mutation-refused
configHash=unchanged; native mutation not reached

pnpm openclaw gateway run --port 29829 --allow-unconfigured
Deferred state migration completed for plugin "upgrade-fixture".
Gateway ready; offline migration callback not invoked

pnpm openclaw update status --json
exit 0; no migration warnings or inspection errors

Cold Gateway settlement and status were repeated after the owner-reuse refactor, then the owned Gateway was stopped. The original 83-file run remains historical evidence: 1,203 passed, 2 failed, 5 skipped, 2,287.27s wall time; the two failures are investigated above. All proof was local; no remote leases were used.

The prior ClawSweeper review reported no discrete code finding and requested additional native systemd reassignment/revocation and package-upgrade traces. Those rank-up proof requests were not added in this follow-up; native systemd remains simulated and no real Linux service or full package upgrade was exercised. The existing native-identity tests and stored-ledger/version-parity fixtures remain the available proof. Those additional advisory proof requests are not claimed complete; the lead has settled F3 as a flaky-test verdict above.

The temporary main worktree was removed normally after all proof processes exited; its path and Git registration were verified absent. Head: 04bc9a3d6165c769a976f02c44abb594ccc0d108. The task worktree is clean at the pushed head. This PR is ready for review and has not been merged.

@clawsweeper

clawsweeper Bot commented Oct 28, 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 gateway Gateway runtime cli CLI command changes commands Command implementations size: M labels Oct 28, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 28, 2026
@clawsweeper

clawsweeper Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

The PR confirms already-complete plugin upgrades during startup and refuses unauthorized system-service maintenance before draining the Gateway.

Example: An unprivileged account runs openclaw doctor --fix against the system-owned openclaw.service.

  • Before: Doctor can enter lifecycle drain before discovering that it cannot stop the service.
  • After: Doctor returns a gateway-stop refusal with sudo systemctl stop openclaw.service before draining.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, focused repair with meaningful CLI evidence and no discrete code finding; authority and existing-state upgrade validation remain incomplete.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Users repeatedly see unfinished plugin-upgrade warnings, while Doctor can drain a system-owned Gateway that their account cannot stop.
Reason: The maintainer-authored direction addresses concrete recovery failures while preserving genuine pending migrations and existing system-service ownership.

Merge readiness

⛔ Blocked before merge - 5 items remain

Keep this PR open: it addresses concrete upgrade and maintenance failures, and no discrete introduced bug was found; the author's explicit draft STOP remains unresolved.

Priority: P2
Reviewed head: c5fe9d1efc0a6a5c08577d1b0bc6929a9ac8b6ab

Before merge

  • Add real behavior proof - Authority-chain proof required: supplied isolated CLI/Gateway output exercises startup receipt settlement and unprivileged pre-drain refusal, but systemd is simulated and the changed stop route lacks evidence that reassignment or revoked caller authority prevents StopUnit after drain; provide a production-path authority harness or native trace, with sensitive values redacted. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Resolve security review attention item - No reachable authorization bypass was found, but the changed retained-identity stop path needs final-effect refusal evidence.
  • Resolve merge risk - Before merge, the PR owner should prove that identity reassignment or caller-authority loss during drain prevents the newly identity-bound StopUnit effect.
  • Complete next step - Establish the cause of the healthy-recovery failure in the original consumer discovery order, repair it if patch-caused, and resolve the recorded draft STOP.
  • 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

None.

Tests

  • Missing end-to-end proof: Add changed-stop final-effect refusal coverage and a v2026.10.8-to-candidate upgrade preserving settings, plugin data, and genuine pending obligations.
Agent review details

How this fits together

Gateway startup consumes durable plugin-migration obligations, while Doctor and update share managed-service inspection, drain, stop, and restoration owners.

flowchart TD
  A[Gateway startup] --> B[Plugin lifecycle lease]
  B --> C[Read-only detectors and settings validation]
  C --> D[Migration receipt settlement]
  E[Doctor or update] --> F[Service permission check]
  F --> G[Drain and identity-bound native stop]
Loading

Technical review

Best possible solution:

Keep the existing detector, ledger, and native lifecycle owners, complete the outstanding validation, and retain the draft until its recorded STOP is resolved.

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

Source establishes the missing startup settlement and permission-after-drain paths, supported by reported red regressions; the reporter's exact prolonged Doctor stall was not independently reproduced.

Is this the best way to solve the issue?

The patch uses the appropriate existing owners and preserves offline-only mutation; the added readiness module provides a focused startup inspection boundary without a competing ledger or migration executor.

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Prove refusal at native stop (recommended)
    Exercise the real maintenance and native identity owners with an allowed stop, account or manager reassignment during drain, and revoked caller authority; record that forbidden cases never submit StopUnit.

Provenance checked

Testing

Proof path: shipped entry point.

Security

Needs attention: No reachable authorization bypass was found, but the changed retained-identity stop path needs final-effect refusal evidence.

Evidence

What I checked:

  • Introduced patch and clean checkout: Reviewed the pinned merge-base-to-head hunks, original behavior, callers, tests, and fetched-main context; the checkout remained clean and no target code was executed. (c5fe9d1efc0a)
  • Conservative startup settlement: Startup requires successful inspection of both migration phases, no remaining plan, and valid settings; a required state obligation survives removal of its detector, and settlement uses the existing generation-checked ledger writer. (src/infra/state-migrations.plugin-readiness.ts:42, c5fe9d1efc0a)
  • Permission precedes drain: The system-scope permission check precedes maintenance preparation and lifecycle drain; stop now receives the captured identity, whose existing native owner revalidates manager, unit, account, and caller authority before I/O. (src/cli/update-cli/update-command-service-maintenance.ts:531, c5fe9d1efc0a)
  • Reported release failure: The report by cryptoninja1stat identifies OpenClaw 2026.10.8, persistent plugin warnings after cold boot, and externally terminated Doctor attempts against a system unit; its discussion distinguishes migration receipts from unchanged config files.
  • Supplied behavior evidence and explicit pause: The PR supplies isolated CLI/Gateway output for startup settlement and pre-drain refusal, discloses simulated systemd transport, and explicitly pauses over an unexplained recovery-test failure; passing reruns are not presented as a repair. (c5fe9d1efc0a)
  • Existing ownership intent: fix(doctor): restore Gateways after systemd inspection failures #153017 established identity-bound native activation and refusal on account or manager replacement; this PR extends that existing owner to stop rather than creating another authority path. (src/daemon/systemd-service-identity.ts:232, e375277a9b50)

Likely related people:

  • Peter Steinberger: Raw commit 47a84c8 adds src/infra/state-migrations.plugin-doctor.ts:102 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 47a84c8f1f39; files: src/infra/state-migrations.plugin-doctor.ts)
  • Jason (Json): Raw commit 6277d6d adds src/infra/state-migrations.plugin-doctor.ts:65 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 6277d6da1331; files: src/infra/state-migrations.plugin-doctor.ts)

PR surface

Source +161, Tests +178, Docs +10. Total +349 across 16 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 8 176 15 +161
Tests 7 193 15 +178
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 379 30 +349

Labels

Label changes:

  • add P2: The PR repairs bounded upgrade convergence and Doctor maintenance failures without evidence of an ongoing core runtime outage.
  • add merge-risk: 🚨 security-boundary: Stop now consumes a retained manager/account identity across lifecycle drain; final-effect refusal coverage for that changed path remains incomplete.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: The PR repairs bounded upgrade convergence and Doctor maintenance failures without evidence of an ongoing core runtime outage.
  • merge-risk: 🚨 security-boundary: Stop now consumes a retained manager/account identity across lifecycle drain; final-effect refusal coverage for that changed path remains incomplete.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

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

  • Add final-effect proof that account or manager reassignment and caller-authority revocation during drain prevent StopUnit.
  • Demonstrate a v2026.10.8 upgrade with settings and plugin data intact, completed obligations settled, and pending migrations retained.

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 October 28, 2026, 4:56 AM ET / 08:56 UTC.

@steipete
steipete marked this pull request as ready for review October 28, 2026 10:23
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-28T17:24:56.950947Z 6bc9059 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: e03d32a820

ℹ️ 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".

Comment on lines +632 to +634
...(inspected.serviceSystemdIdentity
? { systemdIdentity: inspected.serviceSystemdIdentity }
: {}),

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 Wait for the identity-bound stop job to finish

When Doctor stops a stale or legacy Linux Gateway, passing systemdIdentity changes service.stop() from blocking systemctl stop to activateSystemdServiceIdentity(), which returns after the D-Bus StopUnit call yields a job path, without waiting for that job to complete. (The inspected systemctl --help describes --no-block as “Do not wait until operation finished”; the previous invocation did not use that option.) Doctor then immediately calls assertStaleDoctorGatewayStopped() or assertLegacyGatewayStoppedForMaintenance(), both of which reject a still-shutting-down process without polling. Consequently, a legitimate asynchronous shutdown can abort repair and trigger restoration instead of completing maintenance. Retain the identity-bound dispatch, but await stop-job completion before reporting the service as stopped.

Useful? React with 👍 / 👎.

Let Gateway startup certify already-complete deferred plugin migrations
through both read-only inspection phases and settings validation. Preserve
explicit state obligations when the installed contract has no detector.

Check systemd stop authority before maintenance drains the Gateway, query
the selected manager/unit, and retain the inspected native stop identity.
Report the blocked phase and privileged command through structured findings.
Retire completed model-retirement deferrals and identify package ownership.

Fixes #186612. Thanks @cryptoninja1stat for the report.

Validation: focused regressions, isolated CLI/Gateway fixture, type/lint/
format/cycle/build checks and independent review. Broad consumer proof has
one unexplained recovery flake and one host snapshot-admission failure;
publish as draft under the campaign STOP rule, with full PR evidence.
Move Gateway confirmation into the existing plugin readiness owner and
reuse Doctor's two-phase completion calculation. Remove the parallel
readiness module while preserving read-only inspection, explicit state
obligations, config validation, and lease-bound ledger settlement.

Validate with all 34 direct/barrel consumers, targeted types and static
checks, an isolated cold Gateway/status fixture, and independent review.
The original-service file passed five runs at the preceding PR head;
unchanged main has independent recovery failures documented in PR evidence.
Keep selected-manager policy in the shared timeout reader while retaining the permission check before drain and #186792's bounded native stop with its recorded reason.

Correct the immutable-service fixture's procfs PID so its changed-process guard is exercised without weakening the assertion.
@steipete
steipete merged commit ca1b1e6 into main Oct 28, 2026
133 of 134 checks passed
@steipete
steipete deleted the upd/upd-l1928 branch October 28, 2026 17:47
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 29, 2026
…system service (openclaw#186648)

On npm installs whose Gateway runs as a systemd system unit, a plugin's 'data/settings upgrade is unfinished' warning survived restarts even at version parity, openclaw doctor --fix waited on a service stop it could not perform until it was killed, and model retirement repair stayed deferred. Gateway startup now confirms already-complete plugin data upgrades; Doctor checks stop permission before draining and ends with a gateway-stop finding naming the privileged command, while the native stop keeps its bounded timeout; database inspection reuses the async snapshot workers instead of per-store synchronous subprocesses; and the retirement deferral names its blocker and clears after convergence. Fixes openclaw#186612. Thanks @cryptoninja1stat.
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 merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

1 participant