Repository navigation
fix(update): report launchd service recovery correctly after a failed update - #139393
Conversation
… update On macOS launchd installs, a failed managed update (for example a registry returning HTTP 500 for the tarball) ended with the helper logging "gateway service recovery failed" and the Control UI triage card showing `service-restore: managed-service-handoff-restore-failed`, although the LaunchAgent had already restarted healthy on the previous version. The detached helper strips launchd's own labels and the service markers from its children but keeps OPENCLAW_LAUNCHD_LABEL as the service identity. The recovery command `openclaw gateway restart --preserve-definition --json` then asked isCurrentProcessLaunchdServiceLabel whether it ran inside the service, and the configured-label-only fallback said yes. The CLI scheduled a detached restart handoff, exited 0 with result "scheduled" and no health proof, and the helper's immediate launchctl probe found nothing to verify. Remove that fallback: launchd's own label variables or the managed wrapper's service marker are the only proof of running inside the job, which is what stop, install, and the update-job guard already required. The recovery CLI now restarts synchronously, proves health, and returns "restarted"; the helper then verifies readiness and runtime identity and records the restore as successful. Regression coverage: detection unit test, an unloaded-LaunchAgent restart test in launchd.test.ts, and a lifecycle boundary test whose recovery fixture runs the real detection against the real stripped helper environment. Live proof on a launchd profile install with a poisoned release: recovery command "restarted" in 23 s, helper "recovery succeeded (readiness and runtime identity verified)", service healthy on the previous version. Release note: failed managed updates on macOS launchd installs no longer report a service-restore failure after the previous version restarts.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: blocked before merge. Reviewed September 5, 2026, 5:10 PM ET / 21:10 UTC. ClawSweeper reviewWhat this changesThe PR corrects launchd service detection so detached update helpers complete recovery synchronously and report its actual outcome, with regression coverage. Merge readiness⛔ Blocked before merge - 1 item remains This remains a useful, focused repair: current main and v2026.9.2 retain the faulty detection. No blocking correctness finding was identified, and the captured macOS recovery evidence supports the fix. Maintainer-authored, protected work is not eligible for cleanup closure. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw's managed update helper survives Gateway shutdown and restores the previous installation when an update fails safely. Its restart command and subsequent health checks determine the recovery status shown in update reports. flowchart TD
A[Chat update request] --> B[Detached update helper]
B --> C[Package update fails safely]
C --> D[Restart command checks service identity]
D --> E[Synchronous launchd recovery]
E --> F[Health and runtime verification]
F --> G[Recorded recovery outcome]
Before merge
Agent review detailsSecurityNone. PR surfaceSource -19, Tests +130. Total +111 across 9 files. View PR surface stats
Review metrics
Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Use one marker-backed service-membership check and the existing synchronous restart verifier, preserving generated-service upgrades and the explicitly documented custom-plist tradeoff. Do we have a high-confidence way to reproduce the issue? Yes: source shows that a detached helper retaining only the configured label selects a scheduled restart and skips CLI health verification. The supplied macOS before/after run exercises that failure; this reviewer did not execute it. Is this the best way to solve the issue? Yes: correcting the shared identity predicate repairs the wrong restart choice at its owner. Adding probe delays downstream would conceal the misclassification and leave scheduled recovery without synchronous verification. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against cfe5477908b9. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
|
|
Skipping the P1 merge-risk item with rationale, per the review policy. The flagged case needs a LaunchAgent whose environment sets Keeping the label-only fallback keeps the shipped defect: every detached update helper on a generated install inherits precisely that environment and would keep scheduling an unverified restart, a default-path regression, whereas the flagged case is a hand-maintained configuration with a self-healing outcome. Follow-up worth doing separately: derive in-service identity from process ancestry of the running LaunchAgent PID ( |
|
Merged via squash.
|
Carry the real stripped helper environment and emulated recovery cleanup from #139393 into the extracted transaction boundary fixture.
Carry the real stripped helper environment and emulated recovery cleanup from #139393 into the extracted transaction boundary fixture.
…s its caller (#139628) PR #139393 removed the configured-label-only fallback from launchd in-service detection so the detached update helper's recovery CLI stops being misdetected as running inside the LaunchAgent. That left a hand-written plist that sets OPENCLAW_LAUNCHD_LABEL but neither the service marker nor launchd's own label variables undetected, so `openclaw gateway restart` from inside such a service ran `launchctl kickstart -k` synchronously and killed its caller. Add a process-ancestry fallback: isCurrentProcessInsideLaunchdService keeps the env check as the fast path, then asks launchd for the job's PID and treats the caller as in-service when that PID is in its ancestry. Restart, stop, maintenance park, install, and uninstall use it. The recovery CLI inherits the label but is reparented to launchd after the gateway exits, so it stays on the synchronous path. Related: #139393
Carry the real stripped helper environment and emulated recovery cleanup from #139393 into the extracted transaction boundary fixture.
… update (openclaw#139393) On macOS launchd installs, a failed managed update (for example a registry returning HTTP 500 for the tarball) ended with the helper logging "gateway service recovery failed" and the Control UI triage card showing `service-restore: managed-service-handoff-restore-failed`, although the LaunchAgent had already restarted healthy on the previous version. The detached helper strips launchd's own labels and the service markers from its children but keeps OPENCLAW_LAUNCHD_LABEL as the service identity. The recovery command `openclaw gateway restart --preserve-definition --json` then asked isCurrentProcessLaunchdServiceLabel whether it ran inside the service, and the configured-label-only fallback said yes. The CLI scheduled a detached restart handoff, exited 0 with result "scheduled" and no health proof, and the helper's immediate launchctl probe found nothing to verify. Remove that fallback: launchd's own label variables or the managed wrapper's service marker are the only proof of running inside the job, which is what stop, install, and the update-job guard already required. The recovery CLI now restarts synchronously, proves health, and returns "restarted"; the helper then verifies readiness and runtime identity and records the restore as successful. Regression coverage: detection unit test, an unloaded-LaunchAgent restart test in launchd.test.ts, and a lifecycle boundary test whose recovery fixture runs the real detection against the real stripped helper environment. Live proof on a launchd profile install with a poisoned release: recovery command "restarted" in 23 s, helper "recovery succeeded (readiness and runtime identity verified)", service healthy on the previous version. Release note: failed managed updates on macOS launchd installs no longer report a service-restore failure after the previous version restarts.
…s its caller (openclaw#139628) PR openclaw#139393 removed the configured-label-only fallback from launchd in-service detection so the detached update helper's recovery CLI stops being misdetected as running inside the LaunchAgent. That left a hand-written plist that sets OPENCLAW_LAUNCHD_LABEL but neither the service marker nor launchd's own label variables undetected, so `openclaw gateway restart` from inside such a service ran `launchctl kickstart -k` synchronously and killed its caller. Add a process-ancestry fallback: isCurrentProcessInsideLaunchdService keeps the env check as the fast path, then asks launchd for the job's PID and treats the caller as in-service when that PID is in its ancestry. Restart, stop, maintenance park, install, and uninstall use it. The recovery CLI inherits the label but is reparented to launchd after the gateway exits, so it stays on the synchronous path. Related: openclaw#139393
Carry the real stripped helper environment and emulated recovery cleanup from #139393 into the extracted transaction boundary fixture.
* refactor(update): stage and retain package and Git transactions Stage supported package-manager layouts and prebuilt Git runtimes before activation. Expose candidate validation and activation boundaries, retain the previous package and launcher until finalization, and preserve the original failure when source exposure is cancelled. Verify the requested package version before admitting a staged no-op. Replace live Git install/build and rollback rebuild work with prepared runtime promotion. (cherry picked from commit 0a1e09cb5350e1e1268d07753c11551d24549aa1) * feat(update): validate online and verify activation or rollback Keep the gateway serving during candidate staging, lint, config/plugin checks, and an isolated SQLite-snapshot canary. Same-version and same-SHA no-ops never stop the service. Limit activation downtime to swap, owned migrations, and start. Record settle, version/build, plugin, channel, readiness, advisory inference, and downtime in the existing run ledger. Restore retained package transactions only across unchanged state schemas, using prior verification to authorize the previous gateway restart. Hand migrated-state finalization to candidate code. Park managed helpers only at activation. Give the spawn fallback runner sole ownership of helper stdin so activation acknowledgements reach its child. Protect active backups from cleanup and CLI-owned runs from premature notices. Refs #137580, #136997, #124396. (cherry picked from commit 5523f4f419652d7e6666fa53dc19c650528aba0d) * docs(update): explain staged activation and schema-neutral recovery Document no-op behavior, candidate validation, bounded activation, verified package rollback, migration refusal, downtime, and managed-helper ownership. (cherry picked from commit d1dc73c804e02626e89d677970744bf1b235269b) * fix(update): preserve run ownership and explain skipped rollback Record an explicit no-retained-package fact when post-core verification fails without a rollback transaction, keeping the original failing oracle and service policy. Verify the durable report with an isolated real ledger. Keep staging and repair under CLI completion ownership too, so sentinel expiry after an unrelated gateway boot cannot prematurely finish an active update run. The existing phase regression fails for both phases before this fix. (cherry picked from commit c212030ce05a41018c0d2f335d49e65ec999c92c) * fix(update): restore a running previous generation after rollback Restore package bytes and shims, the config writer version, the owned service definition, and the previous Node runtime across unchanged config and schemas. Scope the existing older-binary recovery allowance to service invocations. Carry complete restoration proof into the managed helper, keep its ledger run open through CLI unwind, and recover instead of unconditionally parking on exit 79. Refresh observed service facts and retain restoration receipts when bounded diagnostics are evicted. Successful recovery remains a failed update but records rolled-back, the previous version, and verified downtime. Wait on actual ownership validation readiness and isolate all helper test coordinators while preserving real cross-process arbitration within fixtures. Document the recovery boundary and the helper's observed verification limits. Follow-up: review zero-wait coordinator admission under concurrent independent updates; the existing lease reader maps SQLite contention to unavailable identity. This change does not alter production store concurrency policy. Validation: full CLI/ledger/report scope 948 passed (1 skipped); handoff/package scope 176 passed (2 skipped); two concurrent lifecycle copies passed 154/154 each during a separate checkout build; closing cross-process/CLI scope 114 passed (1 skipped). pnpm build, the complete changed-files gate, and P1 autoreview pass. (cherry picked from commit fe3fa2e7dd29ca98e9e5e8c375f9e7431d4733dc) * fix(update): preserve sibling packages during late native rollback Recheck the native global project before stopping a reachable candidate and again before restoring any project or launcher bytes. Compare the finalized staging fingerprint, excluding OpenClaw payloads, using the existing helper with per-entry digests and direct sibling entries. Refuse changed-project rollback with rollback-project-changed, preserve the candidate and backups, record names-only details, and report recovery guidance. Keep the run failed without automatically repairing the shared project. npm package-root swaps retain their existing behavior. Validation: 85 focused tests passed; three final fixture cases passed after adding required service inspection fields. The new filesystem regression failed on the parent for pnpm 10, pnpm 11, and Bun. Full changed-file checks and fresh Codex P0/P1 autoreview passed. Production +112 lines, tests +179 lines, docs +2 lines; no new fingerprint implementation, configuration, or schema. (cherry picked from commit 0abb72b514226cc0b4cd4d0f99207e93aedad99b) * fix(update): preserve verification and cancellation ownership Verify metadata-refresh restarts through the same readiness and inference path, preserve rollback recovery ownership, and reject cancelled activation after asynchronous checks. Keep schema/protocol verification fields aligned and share update step and state-snapshot types. Carry the cancellation-only hardening from campaign commit d37a9418d94 without its automatic repair integration. Regression proofs cover refresh readiness, Windows autostart compensation, and systemd/launchd cancellation boundaries. * fix(update): require safe recovery before restoring autostart Narrow the recovery verdict before consuming service health. Align native Windows fixtures with their actual enabled state, verify compensation after an enable commits and fails, and preserve the precise interrupted verification diagnostic. Keep npm staging and cleanup assertions on the current namespace. * refactor(update): keep verified service recovery in its owner Move failed-update restart into the existing recovery module, retain the service facade, and await Doctor lifecycle cleanup. Align Doctor tests with HTTP readiness and advisory inference, including a healthy service with unready HTTP and preserved probe-port coverage. Complete synthetic helper teardown before removing its files. * fix(update): preserve staging and plugin maintenance boundaries Use effective pnpm configuration arguments and verify staged root/bin destinations before installing. Preserve relative external dependency links during Git promotion through the same relocation owner as native package staging. Centralize post-plugin completion in the parent updater after the fresh child finishes package work. Park the owned service only for required Doctor maintenance, retain Windows compensation through verification, and measure the full second outage. Keep downgrade writes in the target runtime and validate unchanged-plugin configuration with that runtime's schema. Remove the recovery-to-command import cycle. Cover native destination refusal, promoted imports, fresh child/parent lease boundaries, target-owned downgrade stamps, and migration/restart timing. Isolated real pnpm and Doctor coordinator flows verify the dependency and maintenance contracts. * fix(update): finalize unmanaged runs after gateway restart Use the recorded CLI trigger or managed handoff identity to preserve verification ownership. An unmanaged RPC also reaches restarting, so its phase cannot imply an updater exists to finish it. Keep notice expiry bounded while preserving managed verification. Reproduce four unmanaged completion failures before the fix; cover successful and expired unmanaged runs, managed API/chat/control-plane/campaign handoffs, and all CLI phases. Gateway owner, sentinel, and update method tests: 150 passed. Codex P1 local review clean. * fix(update): retain complete candidate dependency stores Retain configured Git virtual stores inside the exact preflight cleanup boundary, including sibling and symlinked stores. Rebase external store metadata and launchers, preserve rollback, and refuse source or destination checkout overlap through aliases. Share native and Git relocation of links, manifests, and launchers. Keep pnpm candidate project stores private through the supported invocation environment so staging cannot prune the serving generation. Preserve operator configuration and ordinary subsequent package-manager operations. Proof: five pre-fix Git regressions; 40 Git/native transaction and 27 post-update tests passed, followed by eight focused overlap/native tests. Real pnpm proof covers seven Git layouts and four native manager/store modes, imports, launchers, metadata, rollback, promotion, and subsequent global install. Codex P1 review clean. * test(update): preserve online inspection through package executor * test(update): align transaction fixtures and prune unused exports * fix(update): retain Git runtime backups after failed restoration * test(update): consolidate post-update fixtures for lint * fix(update): preserve recovery ownership and CI prerequisites Remove the history-based cleanup lock. A killed updater leaves a running ledger row, but history is not retirement authority: migration cleanup already verifies its own archives under exclusive maintenance ownership. Package, shim, and Git runtime backups belong to separate transactions. This also avoids opening the ledger before external state ownership checks. Register the real candidate canary and migrated-update process fixtures with their runtime build owner. Partition whole-config consumers before striping, keeping one runtime build and removing the sibling-sharing exception without changing CI caps or worker budgets. Align installed-CLI validation, managed handoff, and native stop fixtures with the transaction and service-owner contracts. * test(ci): derive runtime exclusions from the consumer catalog * fix(update): preserve report ownership across candidate migration Suspend every old CLI progress reader at activation and resume only after schema compatibility is established. Let migrated candidates own final reporting, and keep the permanent finished-notice key available while CLI verification remains pending. Preserve the merged update-surface contracts, truthful acknowledgement wording, and canonical restart successor ownership. Regression coverage includes real candidate migration in text and JSON modes plus sentinel expiry followed by verified completion. * fix(update): preserve live SQLite artifacts during inspection Use the canonical private snapshot owner for candidate copies and schema inspection. Discover registered databases from the same private generation instead of reopening the live registry, and preserve original locators in rollback receipts. Keep the existing bounded inspection deadline and fail-closed rollback behavior. Regression coverage reproduces source WAL sidecar creation, checks closed WAL and rollback stores, and verifies committed schema visibility while a live writer retains its transaction. * test(update): sort artifact entries without mutation * fix(update): preserve active runtime ownership during staged updates Keep candidate pnpm stores private across installs, nested lifecycle commands, workspace configuration, native staging, and Git promotion so preparation cannot prune the serving generation or leave activated dependencies behind. Record the active package root at each activation and restoration boundary. Launch post-activation schema inspection from that package and selected Node; retain unknown identity after partial moves until recovery verifies the original. Accumulate verified outage intervals independently of mutable ledger health, excluding online plugin work. Register built schema-worker test prerequisites. Refs #136997, #137580, #124396. * test(ci): type build admission argument rows explicitly * fix(update): await the async schema preflight before activation Follow #138986's asynchronous database preflight contract before checking its result. Passing the promise to hasSchemaRefusal otherwise throws on package activation. Keep Git's mutation fence after its post-stop schema check so interruption can restore the unchanged Windows task. Reject retained recovery handles as soon as settlement begins. * fix(update): restart the unchanged gateway after native swap refusal Record live mutation in the swap owner after its native project recheck, immediately before the first move. A sibling change during shutdown now preserves safe recovery of the original package without restoring over the sibling. Extend the native refusal matrix with the original recovery version and exercise its safe restart outcome through finalization. Keep late rollback-project-changed behavior unchanged. * fix(update): preserve finalization for older downgrade targets Keep the shipped explicit downgrade contract when a candidate predates the migration-continuation worker. Record runtime validation as unavailable before invoking new-only canary commands, then use the established finalization owner. Present workers must still report their schema contract, and database preflights remain mandatory when target schema metadata is available. Do not attempt the new schema-worker or rollback contract for targets that do not provide it. * fix(update): make Windows Bun refusal actionable Preserve the pre-stop refusal for Bun's Windows launchers. Carry the inspected install spec into staging so the failed step names the exact manual Bun install, Gateway restart, and update-status commands. Bun is an opt-in runtime; keep one supported staging flow instead of adding an in-place fallback. Match the updating guide to the emitted recovery instructions. * perf(update): avoid snapshot imports during schema inspection Load the verified-snapshot dependency only when snapshot rehearsal runs. Schema-version workers do not need the snapshot module's memory and plugin import graph. Keep the same private-copy inspection and 30-second worker deadline. This changes dependency loading without changing SQLite schemas, data, or recovery policy. * fix(update): keep the owned managed-update environment when given process.env The absent-service rollback regression exposed an aliased input: clearing process.env also cleared the environment supplied to the phase. Reuse the existing snapshot for that input and preserve restoration after failure. The environment-only regression fails before the repair; copied-input and rollback sibling paths pass. * fix(triage): accept the unavailable canary advisory Preserve failure diagnostics after a confirmed downgrade to a target without migration continuation. The diagnostic boundary accepts both advisory variants while retaining only actual failed steps; the new advisory row failed schema validation before this repair. * test(ci): route real-worker update CLI tests to the process lane Keep rollback, post-update recovery and service integration tests that launch built schema workers in the existing isolated serial process owner. Move their runtime prerequisites with them and preserve CI partition, concurrency and budget assertions. All three routing regressions failed before the owner correction. * test(update): align downgrade and recovery fixtures with checks Supply the required invariant diagnostic and construct recovery table rows without map-spread. Preserve all cases and assertions. * test(ci): align CLI build admission with process ownership The shared CLI config has no runtime consumers after moving the real-worker update tests. Test it in the no-build table and retain process-lane build, failure, exclusion and SIGTERM coverage. Fixes the stale build.pid expectation from CI run 33991347672 without changing deadlines or production behavior. * test(update): verify candidate snapshots through the worker Snapshot backup and VACUUM run in a dedicated production process so cancellation can join before cleanup. Direct Vitest DELETE and symlink cases hit their 120-second deadline, while the equivalent worker copies preserved source bytes in about seven seconds. Exercise the existing worker entrypoint, retain every registry and artifact assertion, and bound the child to 30 seconds. * test(update): include helper logs in terminal outcome failures A loaded-host run restored the Gateway but left the ledger running. The six-case and full 154-case reruns passed without a production change. Preserve helper diagnostics in the assertion so a recurrence exposes the terminal-writer failure; no behavioral fix or timeout relaxation is claimed. * test(update): preserve launchd recovery identity proof after restack Carry the real stripped helper environment and emulated recovery cleanup from #139393 into the extracted transaction boundary fixture. * fix(update): retain runtime evidence across partial backup cleanup A cross-device backup move can publish its backup, remove the source dist inventory, then reject after deleting a runtime file. Directory order varies by filesystem. Older packages may legitimately lack that inventory, so a fresh verification using only surviving metadata could accept a gutted tree. Retain the expected dist files before mutation and compare the surviving runtime against them before accepting recovery without a completed rollback. A partially removed package must never be reported as the active root. Preserve recovery of an unchanged package after a refused backup move. Make the existing cleanup regression exercise inventory-first deletion; it fails before this fix with the same active-root assertion as CI. Recovery and native transaction suites pass all 57 cases. Extend CLI finalization coverage to ensure failed swaps with unsafe recovery never restart the package. * fix(update): verify recovery inventory at the previous package root * fix(update): retain backups until activation or restoration is verified * test(update): isolate handoff workers and child result publication
…w#138839) * refactor(update): stage and retain package and Git transactions Stage supported package-manager layouts and prebuilt Git runtimes before activation. Expose candidate validation and activation boundaries, retain the previous package and launcher until finalization, and preserve the original failure when source exposure is cancelled. Verify the requested package version before admitting a staged no-op. Replace live Git install/build and rollback rebuild work with prepared runtime promotion. (cherry picked from commit 0a1e09cb5350e1e1268d07753c11551d24549aa1) * feat(update): validate online and verify activation or rollback Keep the gateway serving during candidate staging, lint, config/plugin checks, and an isolated SQLite-snapshot canary. Same-version and same-SHA no-ops never stop the service. Limit activation downtime to swap, owned migrations, and start. Record settle, version/build, plugin, channel, readiness, advisory inference, and downtime in the existing run ledger. Restore retained package transactions only across unchanged state schemas, using prior verification to authorize the previous gateway restart. Hand migrated-state finalization to candidate code. Park managed helpers only at activation. Give the spawn fallback runner sole ownership of helper stdin so activation acknowledgements reach its child. Protect active backups from cleanup and CLI-owned runs from premature notices. Refs openclaw#137580, openclaw#136997, openclaw#124396. (cherry picked from commit 5523f4f419652d7e6666fa53dc19c650528aba0d) * docs(update): explain staged activation and schema-neutral recovery Document no-op behavior, candidate validation, bounded activation, verified package rollback, migration refusal, downtime, and managed-helper ownership. (cherry picked from commit d1dc73c804e02626e89d677970744bf1b235269b) * fix(update): preserve run ownership and explain skipped rollback Record an explicit no-retained-package fact when post-core verification fails without a rollback transaction, keeping the original failing oracle and service policy. Verify the durable report with an isolated real ledger. Keep staging and repair under CLI completion ownership too, so sentinel expiry after an unrelated gateway boot cannot prematurely finish an active update run. The existing phase regression fails for both phases before this fix. (cherry picked from commit c212030ce05a41018c0d2f335d49e65ec999c92c) * fix(update): restore a running previous generation after rollback Restore package bytes and shims, the config writer version, the owned service definition, and the previous Node runtime across unchanged config and schemas. Scope the existing older-binary recovery allowance to service invocations. Carry complete restoration proof into the managed helper, keep its ledger run open through CLI unwind, and recover instead of unconditionally parking on exit 79. Refresh observed service facts and retain restoration receipts when bounded diagnostics are evicted. Successful recovery remains a failed update but records rolled-back, the previous version, and verified downtime. Wait on actual ownership validation readiness and isolate all helper test coordinators while preserving real cross-process arbitration within fixtures. Document the recovery boundary and the helper's observed verification limits. Follow-up: review zero-wait coordinator admission under concurrent independent updates; the existing lease reader maps SQLite contention to unavailable identity. This change does not alter production store concurrency policy. Validation: full CLI/ledger/report scope 948 passed (1 skipped); handoff/package scope 176 passed (2 skipped); two concurrent lifecycle copies passed 154/154 each during a separate checkout build; closing cross-process/CLI scope 114 passed (1 skipped). pnpm build, the complete changed-files gate, and P1 autoreview pass. (cherry picked from commit fe3fa2e7dd29ca98e9e5e8c375f9e7431d4733dc) * fix(update): preserve sibling packages during late native rollback Recheck the native global project before stopping a reachable candidate and again before restoring any project or launcher bytes. Compare the finalized staging fingerprint, excluding OpenClaw payloads, using the existing helper with per-entry digests and direct sibling entries. Refuse changed-project rollback with rollback-project-changed, preserve the candidate and backups, record names-only details, and report recovery guidance. Keep the run failed without automatically repairing the shared project. npm package-root swaps retain their existing behavior. Validation: 85 focused tests passed; three final fixture cases passed after adding required service inspection fields. The new filesystem regression failed on the parent for pnpm 10, pnpm 11, and Bun. Full changed-file checks and fresh Codex P0/P1 autoreview passed. Production +112 lines, tests +179 lines, docs +2 lines; no new fingerprint implementation, configuration, or schema. (cherry picked from commit 0abb72b514226cc0b4cd4d0f99207e93aedad99b) * fix(update): preserve verification and cancellation ownership Verify metadata-refresh restarts through the same readiness and inference path, preserve rollback recovery ownership, and reject cancelled activation after asynchronous checks. Keep schema/protocol verification fields aligned and share update step and state-snapshot types. Carry the cancellation-only hardening from campaign commit d37a9418d94 without its automatic repair integration. Regression proofs cover refresh readiness, Windows autostart compensation, and systemd/launchd cancellation boundaries. * fix(update): require safe recovery before restoring autostart Narrow the recovery verdict before consuming service health. Align native Windows fixtures with their actual enabled state, verify compensation after an enable commits and fails, and preserve the precise interrupted verification diagnostic. Keep npm staging and cleanup assertions on the current namespace. * refactor(update): keep verified service recovery in its owner Move failed-update restart into the existing recovery module, retain the service facade, and await Doctor lifecycle cleanup. Align Doctor tests with HTTP readiness and advisory inference, including a healthy service with unready HTTP and preserved probe-port coverage. Complete synthetic helper teardown before removing its files. * fix(update): preserve staging and plugin maintenance boundaries Use effective pnpm configuration arguments and verify staged root/bin destinations before installing. Preserve relative external dependency links during Git promotion through the same relocation owner as native package staging. Centralize post-plugin completion in the parent updater after the fresh child finishes package work. Park the owned service only for required Doctor maintenance, retain Windows compensation through verification, and measure the full second outage. Keep downgrade writes in the target runtime and validate unchanged-plugin configuration with that runtime's schema. Remove the recovery-to-command import cycle. Cover native destination refusal, promoted imports, fresh child/parent lease boundaries, target-owned downgrade stamps, and migration/restart timing. Isolated real pnpm and Doctor coordinator flows verify the dependency and maintenance contracts. * fix(update): finalize unmanaged runs after gateway restart Use the recorded CLI trigger or managed handoff identity to preserve verification ownership. An unmanaged RPC also reaches restarting, so its phase cannot imply an updater exists to finish it. Keep notice expiry bounded while preserving managed verification. Reproduce four unmanaged completion failures before the fix; cover successful and expired unmanaged runs, managed API/chat/control-plane/campaign handoffs, and all CLI phases. Gateway owner, sentinel, and update method tests: 150 passed. Codex P1 local review clean. * fix(update): retain complete candidate dependency stores Retain configured Git virtual stores inside the exact preflight cleanup boundary, including sibling and symlinked stores. Rebase external store metadata and launchers, preserve rollback, and refuse source or destination checkout overlap through aliases. Share native and Git relocation of links, manifests, and launchers. Keep pnpm candidate project stores private through the supported invocation environment so staging cannot prune the serving generation. Preserve operator configuration and ordinary subsequent package-manager operations. Proof: five pre-fix Git regressions; 40 Git/native transaction and 27 post-update tests passed, followed by eight focused overlap/native tests. Real pnpm proof covers seven Git layouts and four native manager/store modes, imports, launchers, metadata, rollback, promotion, and subsequent global install. Codex P1 review clean. * test(update): preserve online inspection through package executor * test(update): align transaction fixtures and prune unused exports * fix(update): retain Git runtime backups after failed restoration * test(update): consolidate post-update fixtures for lint * fix(update): preserve recovery ownership and CI prerequisites Remove the history-based cleanup lock. A killed updater leaves a running ledger row, but history is not retirement authority: migration cleanup already verifies its own archives under exclusive maintenance ownership. Package, shim, and Git runtime backups belong to separate transactions. This also avoids opening the ledger before external state ownership checks. Register the real candidate canary and migrated-update process fixtures with their runtime build owner. Partition whole-config consumers before striping, keeping one runtime build and removing the sibling-sharing exception without changing CI caps or worker budgets. Align installed-CLI validation, managed handoff, and native stop fixtures with the transaction and service-owner contracts. * test(ci): derive runtime exclusions from the consumer catalog * fix(update): preserve report ownership across candidate migration Suspend every old CLI progress reader at activation and resume only after schema compatibility is established. Let migrated candidates own final reporting, and keep the permanent finished-notice key available while CLI verification remains pending. Preserve the merged update-surface contracts, truthful acknowledgement wording, and canonical restart successor ownership. Regression coverage includes real candidate migration in text and JSON modes plus sentinel expiry followed by verified completion. * fix(update): preserve live SQLite artifacts during inspection Use the canonical private snapshot owner for candidate copies and schema inspection. Discover registered databases from the same private generation instead of reopening the live registry, and preserve original locators in rollback receipts. Keep the existing bounded inspection deadline and fail-closed rollback behavior. Regression coverage reproduces source WAL sidecar creation, checks closed WAL and rollback stores, and verifies committed schema visibility while a live writer retains its transaction. * test(update): sort artifact entries without mutation * fix(update): preserve active runtime ownership during staged updates Keep candidate pnpm stores private across installs, nested lifecycle commands, workspace configuration, native staging, and Git promotion so preparation cannot prune the serving generation or leave activated dependencies behind. Record the active package root at each activation and restoration boundary. Launch post-activation schema inspection from that package and selected Node; retain unknown identity after partial moves until recovery verifies the original. Accumulate verified outage intervals independently of mutable ledger health, excluding online plugin work. Register built schema-worker test prerequisites. Refs openclaw#136997, openclaw#137580, openclaw#124396. * test(ci): type build admission argument rows explicitly * fix(update): await the async schema preflight before activation Follow openclaw#138986's asynchronous database preflight contract before checking its result. Passing the promise to hasSchemaRefusal otherwise throws on package activation. Keep Git's mutation fence after its post-stop schema check so interruption can restore the unchanged Windows task. Reject retained recovery handles as soon as settlement begins. * fix(update): restart the unchanged gateway after native swap refusal Record live mutation in the swap owner after its native project recheck, immediately before the first move. A sibling change during shutdown now preserves safe recovery of the original package without restoring over the sibling. Extend the native refusal matrix with the original recovery version and exercise its safe restart outcome through finalization. Keep late rollback-project-changed behavior unchanged. * fix(update): preserve finalization for older downgrade targets Keep the shipped explicit downgrade contract when a candidate predates the migration-continuation worker. Record runtime validation as unavailable before invoking new-only canary commands, then use the established finalization owner. Present workers must still report their schema contract, and database preflights remain mandatory when target schema metadata is available. Do not attempt the new schema-worker or rollback contract for targets that do not provide it. * fix(update): make Windows Bun refusal actionable Preserve the pre-stop refusal for Bun's Windows launchers. Carry the inspected install spec into staging so the failed step names the exact manual Bun install, Gateway restart, and update-status commands. Bun is an opt-in runtime; keep one supported staging flow instead of adding an in-place fallback. Match the updating guide to the emitted recovery instructions. * perf(update): avoid snapshot imports during schema inspection Load the verified-snapshot dependency only when snapshot rehearsal runs. Schema-version workers do not need the snapshot module's memory and plugin import graph. Keep the same private-copy inspection and 30-second worker deadline. This changes dependency loading without changing SQLite schemas, data, or recovery policy. * fix(update): keep the owned managed-update environment when given process.env The absent-service rollback regression exposed an aliased input: clearing process.env also cleared the environment supplied to the phase. Reuse the existing snapshot for that input and preserve restoration after failure. The environment-only regression fails before the repair; copied-input and rollback sibling paths pass. * fix(triage): accept the unavailable canary advisory Preserve failure diagnostics after a confirmed downgrade to a target without migration continuation. The diagnostic boundary accepts both advisory variants while retaining only actual failed steps; the new advisory row failed schema validation before this repair. * test(ci): route real-worker update CLI tests to the process lane Keep rollback, post-update recovery and service integration tests that launch built schema workers in the existing isolated serial process owner. Move their runtime prerequisites with them and preserve CI partition, concurrency and budget assertions. All three routing regressions failed before the owner correction. * test(update): align downgrade and recovery fixtures with checks Supply the required invariant diagnostic and construct recovery table rows without map-spread. Preserve all cases and assertions. * test(ci): align CLI build admission with process ownership The shared CLI config has no runtime consumers after moving the real-worker update tests. Test it in the no-build table and retain process-lane build, failure, exclusion and SIGTERM coverage. Fixes the stale build.pid expectation from CI run 33991347672 without changing deadlines or production behavior. * test(update): verify candidate snapshots through the worker Snapshot backup and VACUUM run in a dedicated production process so cancellation can join before cleanup. Direct Vitest DELETE and symlink cases hit their 120-second deadline, while the equivalent worker copies preserved source bytes in about seven seconds. Exercise the existing worker entrypoint, retain every registry and artifact assertion, and bound the child to 30 seconds. * test(update): include helper logs in terminal outcome failures A loaded-host run restored the Gateway but left the ledger running. The six-case and full 154-case reruns passed without a production change. Preserve helper diagnostics in the assertion so a recurrence exposes the terminal-writer failure; no behavioral fix or timeout relaxation is claimed. * test(update): preserve launchd recovery identity proof after restack Carry the real stripped helper environment and emulated recovery cleanup from openclaw#139393 into the extracted transaction boundary fixture. * fix(update): retain runtime evidence across partial backup cleanup A cross-device backup move can publish its backup, remove the source dist inventory, then reject after deleting a runtime file. Directory order varies by filesystem. Older packages may legitimately lack that inventory, so a fresh verification using only surviving metadata could accept a gutted tree. Retain the expected dist files before mutation and compare the surviving runtime against them before accepting recovery without a completed rollback. A partially removed package must never be reported as the active root. Preserve recovery of an unchanged package after a refused backup move. Make the existing cleanup regression exercise inventory-first deletion; it fails before this fix with the same active-root assertion as CI. Recovery and native transaction suites pass all 57 cases. Extend CLI finalization coverage to ensure failed swaps with unsafe recovery never restart the package. * fix(update): verify recovery inventory at the previous package root * fix(update): retain backups until activation or restoration is verified * test(update): isolate handoff workers and child result publication
…start A failed managed update's restored boot serves the previous version. The restore owner already verified that identity against the restored disk state and recorded it in the update-run ledger. The boot-time restart verification regraded the running version against the update target, turning a healthy restored boot into a false version mismatch and overwriting the verified ledger fact with a failed restart-unhealthy outcome. When the recorded verification matches the booting version, reuse it as the expected version instead of regrading against the update target. Related openclaw#139393
…start (#142817) A failed managed update's restored boot serves the previous version. The restore owner already verified that identity against the restored disk state and recorded it in the update-run ledger. The boot-time restart verification regraded the running version against the update target, turning a healthy restored boot into a false version mismatch and overwriting the verified ledger fact with a failed restart-unhealthy outcome. When the recorded verification matches the booting version, reuse it as the expected version instead of regrading against the update target. Related #139393
…start (openclaw#142817) A failed managed update's restored boot serves the previous version. The restore owner already verified that identity against the restored disk state and recorded it in the update-run ledger. The boot-time restart verification regraded the running version against the update target, turning a healthy restored boot into a false version mismatch and overwriting the verified ledger fact with a failed restart-unhealthy outcome. When the recorded verification matches the booting version, reuse it as the expected version instead of regrading against the update target. Related openclaw#139393
Related: #136588 (the managed-update recovery path this fixes), #136995, #137312
What Problem This Solves
Fixes an issue where operators updating a macOS launchd install from chat (
/updateor the gatewayupdate.runtool) would see "gateway service recovery failed" in the managed update helper log andservice-restore: managed-service-handoff-restore-failedin the Control UI "Diagnose failed update" card when the update itself failed (for example the registry returning HTTP 500 for the new tarball), even though the LaunchAgent had already restarted and stayed healthy on the previous version. The wrong verdict was also persisted in the restart sentinel, so the failure notice and triage pointed operators at a service recovery that had not failed.Why This Change Was Made
The detached update helper deliberately strips launchd's own labels (
LAUNCH_JOB_LABEL,LAUNCH_JOB_NAME,XPC_SERVICE_NAME) and the service markers from the commands it runs, but keepsOPENCLAW_LAUNCHD_LABELas the identity of the service to manage. Its recovery command,openclaw gateway restart --preserve-definition --json, decided it was running inside the managed gateway process tree becauseisCurrentProcessLaunchdServiceLabelstill had a configured-label-only fallback for exactly that environment. The CLI therefore scheduled a detached restart handoff (which waits for the CLI itself to exit), returnedresult: "scheduled"with exit 0 and no health proof, and the helper's immediatelaunchctl printprobe found no service to verify. launchd brought the service back a few seconds later on its own.The fallback is removed. Running inside the job is now proven only by launchd's own label variables or by the managed wrapper's
OPENCLAW_SERVICE_MARKER/OPENCLAW_SERVICE_KIND, which every generated LaunchAgent injects and which the stop, install, and update-job guards already required (with the comment "Detached handoffs preserve the configured label"). The recovery CLI now takes the synchronous path: enable, bootstrap, kickstart, then the existing health proof, returningrestarted; the helper then runs its own readiness and runtime-identity verification and records the restore as successful. Accepted tradeoff: a hand-written plist that both renames launchd's variables and omits the service marker is no longer treated as "inside", matching how stop and install already treat it. Production delta is net −19 lines; no new option, seam, or fallback.User Impact
After a failed update on a macOS launchd install, the helper log, the chat notice, the update run's verification, and the Control UI triage card now agree with the actual service state: the previous version is running and the recovery succeeded. The triage card names the real failing step (the npm install) instead of a fictitious restore failure. Successful updates and non-launchd installs are unchanged.
Evidence
Regression tests (all fail on the pre-fix detection, pass after):
src/daemon/launchd-current-service.test.ts: the configured label alone is not current-service identity.src/daemon/launchd.test.ts: an unloaded LaunchAgent restarted with--preserve-definitionfrom the helper's child env completes synchronously (enable → kickstart → bootstrap → kickstart) with no detached handoff. Pre-fix result:{ outcome: "scheduled" }.src/infra/update-managed-service-handoff-lifecycle.test.ts(viaupdate-managed-service-handoff-command.test-support.ts): the real helper script now runs with the exact environment the Gateway hands it, and a recovery fixture that runs the real detection module reportsrecoveryInsideService: false, restores the service, probes health once, and records aservice-restorestep with exit 0 under the updater's preserved failure reason. Pre-fix:recoveryInsideService: true, helper log "gateway service recovery failed".oxlint on all touched files: clean. tsgo lanes
tsconfig.core.test.services.jsonandtsconfig.core.test.infra.json: no diagnostics. Codex autoreview (P0/P1): scoped-clean.Live proof (macOS launchd profile install, token auth, local verdaccio): installed 2026.9.1 built from this branch as profile
shotfix, published a poisoned 2026.9.2 whose tarball GET returns 500, sent/updatefrom the Control UI chat. Helper log after the npm failure:The LaunchAgent came back on a new PID within one second of the recovery command exiting and stayed healthy for the remaining 239 s of the capture; the update run's verification recorded
serviceRunning: true, runningVersion: 2026.9.1, versionMatch: true; the restart sentinel keeps the updater's reasonglobal update (omit optional). The same scenario on the pre-fix build (PR #136588 rig, 2026-09-03) had the recovery command exit in 3.5 s with"result": "scheduled"followed by "gateway service recovery failed".Before (pre-fix build, 2026-09-03): the triage card claims
service-restore: managed-service-handoff-restore-failedwhile the gateway is healthy.After (this branch): the failure notice says the gateway is running 2026.9.1 and the triage card names the npm install step.
Observed follow-ups, not addressed here:
/updatesent from the Control UI leaves a "No reply was generated for this message" placeholder because the command returns no reply once the acknowledgement is delivered; the update report prints "version mismatch" after a successful restore because it compares the running version with the update target rather than the restored version.