Skip to content

feat(update): keep each release in its own directory on OpenClaw-owned installs - #198835

Merged
fuller-stack-dev merged 24 commits into
openclaw:mainfrom
fuller-stack-dev:feat/update-linked-package-root
Nov 16, 2026
Merged

fuller-stack-dev merged 24 commits into
openclaw:mainfrom
fuller-stack-dev:feat/update-linked-package-root

Conversation

@fuller-stack-dev

@fuller-stack-dev fuller-stack-dev commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

Related: #197949 (design, slice 4). Builds on #198489 (linked-root Docker mode, now on main); this PR adds only the owned-prefix and follow-up modes to those harness files.

What Problem This Solves

A package update on an OpenClaw-owned install displaces the old release from its path: two directory renames, whole-tree fingerprints, a launcher backup, deletion of the old tree inside the activation window, and a journal to survive a crash in between.

User Impact

On macOS and Linux, installs made by install-cli.sh and the durable service copy at <state dir>/npm now keep each release in <prefix>/releases/<id>/, and lib/node_modules/openclaw becomes a link to the selected one. An update installs the new release beside the old one and switches the link with one rename; rollback renames a link to the previous release back. The previous release is never written and is kept for at least a day. openclaw update status lists the active and retained releases.

This changes what existing installations do. The first update by an updater with this change converts a plain package directory on those prefixes. npm prefixes you manage, npm link checkouts, pnpm, Bun, Git checkouts and Windows keep today's swap. A manual npm install -g into an owned prefix turns the link back into a directory; the next update converts it again.

Why This Change Was Made

It implements route 3 of the update generations design as one cutover, because the parts only work together:

  • Install identity is the link. resolveUpdateInstallRoot returns the link's own path for a release link, and maps a path inside the release the link currently selects to the link (a process finds its own root by real path). The executor key, child admission, the restart sentinel, post-core and native-receiver root checks, and the managed handoff lease key stay the same across a switch. A published updater on a linked root keys its leases by the release path, so a candidate child checking its executor grant takes the parent's spelling when updateInstallRootsMatch says both name one installation. Root discovery (resolveOpenClawInstallationRootSync, used by resolveUpdateRoot and Gateway update admission) maps the selected release to the link, which covers a start through the bin launcher. Only a link into <prefix>/releases/<id>/lib/node_modules/openclaw of the same prefix and owner counts.
  • Releases are installed where they stay. runGlobalPackageUpdateSteps (flag set only by openclaw update) stages into releases/<label> and hands the stage to the switch instead of the swap.
  • The switch: capture the link; stop the service; record origin.packageRelease (validated before the stop); create a temporary link, sync, recheck the lease and the captured link, rename, confirm, sync. Rollback decides from the link on disk (it handles a failure after the rename), and refuses a previous release whose content changed since it was recorded.
  • The layout never fails an update. Everything that rules it out for this run is found before the Gateway stops, and the existing swap installs the same stage instead, with a warning on the package-swap step that names the reason; the next update tries the layout again. installStagedPackage in package-update-release-switch.ts is the one owner of that decision. The conditions: the candidate's bin links differ from the prefix's; releases/ cannot be created or is on another filesystem than the package path (checked when the stage is allocated, so the candidate is staged beside the package path); the package path cannot be captured, the candidate cannot be read, the adoption prefix cannot be allocated, or the record fails its schema. A fallback over a release link turns the link back into a directory (the documented result of a manual npm install -g), and the next update adopts it again.
  • Adoption (plain directory): the directory moves into releases/ and a prepared link naming it takes its place, then the normal switch. Between those two renames the package path is missing. That moment is not journaled: the journal's candidate is a sealed tree, and nothing can run openclaw while the package path is missing anyway. A process killed there leaves lib/node_modules/.openclaw.release-link-* naming the unchanged old tree; renaming it onto lib/node_modules/openclaw restores the install. The docs say so. A failed second rename moves the directory back and keeps the leftover link if that fails too.
  • Run record: optional origin.packageRelease (slot, from and to: path, dev:ino, version, build), kept exact by the codec beside origin.packageStage and removed from the public projection. Interrupted managed handoff reads the install identity through the link and takes the candidate from this record. assertManagedServiceUpdateHandoffRoot is unchanged.
  • Service bound to a release path: a published updater run through the link writes the release's real path into the service definition (2026.10.9 and 2026.11.3 both do), which would keep the service on the old release after a switch. The npm destination gate retargets the update at that release, so the swap replaces it in place, as published updaters do, and the Gateway starts the new version. The update reports the package path as its root (resolvePackageReleaseSlotForRootSync), so the restart's service refresh reinstalls the service from the package path, and the next update switches releases. The warning names openclaw gateway install --force for the case where the restart cannot rewrite the definition or does not run (--no-restart). For the in-place swap, executor slot reservation accepts the release the link selects (updateInstallRootsMatch), and the publication journal is skipped because it publishes at the installation key, which is the link.
  • Retention: after a verified update, a release is removed only when the link does not name it, no Gateway lease (releases/.leases/) holds it, no open update run names it, and it was not selected or changed for 24 hours. A switch stamps the release it deselects.

Not done here, by decision or for follow-up: Windows, npm-owned prefixes, the macOS app; the node host is not made a caller (it would move its activation without removing code), and its collection and activation.lock rule from slice 4 are left for a follow-up. A future release that adds or renames a bin command takes the swap for that update; the next update adopts the layout again. Only Gateways take leases; other processes rely on the 24-hour age. A plain CLI update killed between the switch and its post-switch Doctor is left to openclaw update repair (not exercised). package-update-steps.ts was already over the 700-line lint limit on main; the pnpm environment binding moved, unchanged, into package-update-manager-preflight.ts.

The design doc in #197949 is updated with an "as built" section for these changes.

Evidence

Branched from origin/main a9a3d62; rebased onto 09d322a before opening (the 45 commits between touch no update, package, root-discovery or Docker-cell path; typecheck and the release tests were rerun on the rebased head). Local runs on macOS (Node 26.12.1); Docker cells on linux/arm64.

Red on base, green with the change (each run with the production file reverted to origin/main, then restored):

Test Fails on base because
package-release-slot.test.ts › link path stays the installation identity across a switch base keys the install by the release's real path
package-update-release-switch.test.ts (8 cases: record before change and before the database capture, previous release bytes unchanged, rollback, rollback after a post-rename failure, refused rollback of a rewritten release, adoption, launcher refusal, automatic rollback) base swaps a directory over the link
package-update-release-switch.process.test.ts (real child, SIGKILL before the temporary link, after it and before the rename, after the rename and before confirmation, and between the adoption renames) base never reaches those cuts and leaves no release layout
update-command-executor-release-link.test.ts › post-switch child runs under the installation's lease base acquires a second lease for the new release path
update-managed-service-handoff-interrupted-release.test.ts (continue, not activated, neither) base refuses the link as an unsafe publication object
update-command-package-destination.release-link.test.ts › service bound to a release path base switches it (superseded: it is now updated in place, see below)

Regression guards for defects found in review and Docker (red against the earlier version of this branch): collection age stamped at deselection, rollback reading the link after a failed fsync, adoption keeping its leftover link when both renames fail, restart sentinel accepting the selected release, record written before the database capture. Negative controls that pass on base too: npm link checkout, plain directory, another prefix's release, unselected release takes no lease, non-owned prefixes keep the swap.

Docker published-driver cells (scripts/e2e/published-driver-update-docker.sh, with #198489's linked-root mode; run before #198489 landed, with its commit cherry-picked):

Cell Result
Published 2026.11.3 → candidate on an install-cli.sh-shaped prefix, then candidate → second candidate (OWNED_PREFIX=1 FOLLOW_UP=switch) Pass. The published updater's swap left a plain directory; the candidate's update adopted it, switched the link, kept the previous release byte for byte, restarted the Gateway on the new release (readyz 200, version checked, durable session kept), the service unit still names the package path, and update status listed both releases with the new one leased.
Same, second candidate's post-activation Doctor fails (FOLLOW_UP=rollback) Pass. Switch, Doctor failure, database rollback, link pointed back, previous Gateway verified. A first run that wrote origin.packageRelease after the database capture failed here (database rollback refused, link left on the candidate); fixed. A control on a plain npm prefix (today's swap) rolled back.
Published 2026.11.3 on a linked root → candidate (LINKED_ROOT=1) Pass, on earlier packages of this branch (first hop of superseded rollback runs). Those runs also found the post-core, native-receiver and executor-grant root checks fixed here.

Update behavior per hop: published drivers on a plain prefix keep today's swap (plain directory stays); this candidate adopts on its first update of an owned prefix; published drivers on a linked root swap inside the release behind the link and keep it; this candidate refuses to switch a service a published driver bound to a release path.

Suites (pnpm test on all package-update-*, package-release*, update-run-*, update-managed-service-handoff*, restart-sentinel*, update-plugin-cohort*, update-migrated*, gateway update methods, stale-install, openclaw-root, src/cli/update-cli/* and update-executor*): 2,927 of 2,929 pass. Two update-command-database-rollback.test.ts variants hit the 120 s test timeout while the whole set ran in parallel; that file alone passes 16/16 on this branch (those variants 22–38 s) and on base (28–41 s). pnpm tsgo:all passes; oxlint and formatting clean on changed files; pnpm lint:docker-e2e passes; docs format and markdownlint clean.

CI on 0225b11, fixed in 7180dfe. The local suites above covered src/cli/update-cli/* but not the src/cli/update-cli.*.test.ts files next to it, which is where most of the failures were:

Failure Cause Fix
18 update-cli.*.test.ts files (compact shards) resolveUpdateRoot called resolveOpenClawInstallationRootSync, which the shared update-cli mock of openclaw-root.js does not export. The destination gate also read the service layout before returning an owned destination, so tests whose layout read throws now reported unreadable-layout. resolveUpdateRoot applies the reverse rule (resolvePackageReleaseSlotForRootSync) directly; the answer is the same because only a release slot was ever kept. The service layout is read early only when the package path is a release link.
eager-import-closure, pr-wrapper-source-closure, pr-worktree-provision The PR wrapper imports openclaw-root.ts, which now imports package-release-slot-path.ts; the file was missing from scripts/pr-lib/wrapper-components.txt, so extracted provisioners failed before receiving their private store. Added it to the inventory.
madge-import-cycles Type-only cycle between package-release-slot.ts and package-update-swap-contract.ts. PackageReleaseTarget now lives in package-release-slot.ts.
check-lint-core-3 prefer-array-find in package-release-slot.test.ts (plain oxlint missed it; scripts/run-oxlint.mjs reports it). Fixed.
test-lines budget (+1,280 vs 400) New subsystem tests. Audited the touched files: three slot-level cases (adoption contents, launcher refusal, rewritten-release refusal) duplicated switch-level cases that also check that nothing stopped and that the inode is unchanged; removed them (-60 lines). The remaining +820 is recorded in config/test-lines-allocations/update-linked-package-root.txt.

Existing failures, the same on base 09d322a with this branch's sources swapped out: check-extension-package-tsc-boundary.test.ts (the canary copy lacks src/infra/directory-walk.ts, imported by native-declaration-emitter.mts since #198661), extensions/telegram/src/send.history.test.ts › edited captions, update-cli.fresh-doctor.test.ts › Git version before a dry-run downgrade, and update-cli.target-schema.test.ts › previews explicit artifacts. On this Mac, pr-worktree-provision.test.ts › cold/warm PR siblings takes 184 s against its 120 s timeout when run alone; its other 17 cases pass. Rerun on 7180dfe: the failing files above pass apart from those cases, the release tests pass, and pnpm tsgo:all, madge, the test-lines ratchet, oxfmt and run-oxlint on changed files all pass.

Merged origin/main (99157f8), CI on 7180dfe fixed in af223b7. #198489 landed as eb1a21d; the merge takes main's version of its five harness files and keeps only this PR's additions (owned-prefix and follow-up modes, two package.json scripts, the follow-up budget and env passthrough, docs). No history was rewritten. Remaining diff-caused failure on 7180dfe: checks-node-changed-compact-small-11 › update-command-executor-settlement.test.ts (7 cases), whose hand-written mock of update-install-root.js lacked updateInstallRootsMatch, now used by the executor grant. The mock now spreads the real module and overrides only resolveUpdateInstallRoot; red 7 failed, green 22/22. That retires one config/test-mock-exports-baseline.txt entry (pruned) and costs one test line (allocation 820 → 821). checks-fast-baseline-ratchets failed in mock-exports on src/infra/worker-request-diagnostics.test.ts, a main file this PR does not touch, because the old ratchet base predated it; against current main the ratchet passes. The OpenClawKit, Telegram send.history and package-acceptance failures were fixed on main. On the merged head: pnpm tsgo:all, madge (0 cycles), test-lines and mock-exports ratchets, lint:docker-e2e, oxfmt and run-oxlint on changed files pass; 321 affected test files (src/cli/update-cli*, package release/update, managed handoff, restart sentinel, root discovery, PR wrapper closure, tsc boundary) pass apart from 9 cases that timed out or lost their temp state database under that parallel load; those three files pass 47/47 run alone.

Fallback instead of refusal (head f094976). The release layout no longer fails an update. Red runs used the production files of 30e5edc (e69fb64 merged with main; of the changed production files only update-command-target.ts differs from e69fb64, from main, and no case below exercises it); green runs are on the head.

Removed refusal Test Red (refusal or failed update) Green
Candidate launcher differs package-update-release-switch.test.ts › takes the package swap when the candidate's launchers differ, and the next update adopts again failed package-swap step committed through the swap with the warning, launcher replaced, previous release untouched; the next update adopts and switches
Package directory cannot be adopted (adoption prefix) › takes the package swap when the previous directory cannot be adopted failed step committed, warning, no record written, the allocated adoption prefix removed
releases/ cannot be created › stages beside the package path when releases/ cannot be created, then swaps failed package-stage stage beside the package path, swap committed with the warning
releases/ on another filesystem › stages beside the package path when releases/ is on another filesystem release stage on the other filesystem (adoption then refused after the Gateway stop) plain stage, releaseUnavailable recorded, empty release prefix removed
Service bound to a release path update-command-package-destination.release-link.test.ts › replaces the release in place when the service starts it by its real path foreign refusal owned, install target at the selected release, warning names gateway install --force
(in-place support) update-command-executor-release-link.test.ts › reserves the selected release by its real path as the installation, and refuses a deselected one reservation throws selected release accepted, deselected refused

Negative controls on the head: a candidate that adds a command the update does not manage still switches (red on 3813375, which fell back on every such update); a plain package reached through a symlinked prefix keeps its journaled activation (package-update-publication-durability.test.ts, red on 1a25681, see review below); in-place composition (resolvePackageReleaseStage picks no release for a release root, the swap replaces it behind the unchanged link). Commands: pnpm test on each file above (red with the production files of 30e5edc checked out, then restored: switch 4 failed / 12, destination 1 / 2, executor 1 / 2; green on the head: switch 13 / 13, slot, retention, process, destination, interrupted-link, executor, settlement and interrupted-release files all pass, publication durability 19 / 19, reclamation 11 / 11, test/scripts/update-restart-module-outcome.test.ts passes).

Docker cells on this branch (scripts/e2e/published-driver-update-docker.sh):

Cell Package Result
Published 2026.10.9 on a linked root, its service bound to releases/2026.10.9 (asserted), candidate update, then a second candidate update (LINKED_ROOT=1 FOLLOW_UP=rebind) 56bb795; 115668d Pass on both. Release replaced in place, link unchanged; the restart reinstalled the service from the package path (unit names no release path); Gateway on the new version; the second update switched to a new release with the service still on the package path.
Same start, Gateway stopped, update with --no-restart (FOLLOW_UP=in-place) 56bb795 (cell from f2ebcb5); 115668d Pass, 3 of 3 on 56bb795 and 1 of 1 on 115668d. Release replaced in place, link unchanged, warning with gateway install --force; after a service restart the Gateway runs the new version.
Published 2026.11.3 on an install-cli.sh prefix, prefix bin/openclaw replaced by an absolute link, candidate update, then a second candidate update (OWNED_PREFIX=1 FOLLOW_UP=launcher) 56bb795; 115668d Pass on both. On 115668d the cell starts from published 2026.11.4, the latest release, instead of 2026.11.3. The first update took the swap and recorded the launcher reason, bin/openclaw replaced, no empty release directory left; the second update adopted the directory and switched, service on the package path.

All three cells were rerun on 56bb795 (this branch merged with main at 3900bb2, which includes #198268). #198268 replaced the candidate canary with a runtime contract check: the release stage, the fallback swap and the in-place path still call the candidate check on the staged root before the swap, through the same validateCandidate callback (none of package-update-* or package-release-* changed). It also removed updateRehearsalProtocol from package.json, which the published drivers read on the first hop, so every cell's path changed. The later merges touch no file of this change and no harness file these cells load: bc8ef0c (10 commits), and 823fa6d (51 commits, through adf70ab, including #199882). Of the latter, only package.json scripts overlap; its src/state upgrade changes (#199847) are not imported from src/infra, src/cli/update-cli or src/daemon.

Merged origin/main again (115668d, then f094976). 115668d merges 171 commits through 99eb4aa. The update commits among them, read against this change:

The 2026.11.4 close-out (#199956, ea69fcb) bumps the candidate to 2026.11.4 and records 2026.11.4 in update-compat-inventory.json, which the first-hop fixture reads. All three cells were rerun on the 115668d tarball for that reason, and all pass. The follow-up fixture is now 2026.11.5-first-hop.1. f094976 then merges 6 more commits through 4a74c61 (Control UI, subagents, compaction, plugin tests, local path commands). They touch no update, package, daemon, Docker-harness, package.json or lockfile path, so no cell or unit file was rerun for them.

Checks:

  • On 115668d: pnpm tsgo:all exit 0. The 15 update test files pass (212 tests), and main's handoff lifecycle and command tests pass (2 files, 94 tests).
  • On the 99eb4aa diff: run-oxlint on 50 changed code files, oxfmt on 59 changed files, git diff --check and lint:docker-e2e all pass.
  • On f094976 against 4a74c61: the mock-export ratchet, the test-lines ratchet (+1476 net, within 400 + 1076 allocation), madge (0 cycles), the PR wrapper closure test and git diff --check all pass.

Known main defect: --no-restart while the Gateway runs. The first in-place run on 56bb795, with the Gateway running, failed. The update exited 1: openclaw doctor failed with Gateway process changed during maintenance drain. The package was rolled back, the link was unchanged, and the Gateway was left running the new version from the rolled-back files (Expected Gateway version 2026.11.3; observed 2026.11.4-first-hop.1). Cause: under --no-restart the updater leaves the Gateway running. Every 30 seconds the Gateway checks build-info.json at its installation (src/gateway/stale-install.ts) and restarts itself when the package changed. If that check lands between the swap and update Doctor's stop of the old Gateway (src/infra/update-candidate-predecessor-stop.ts), Doctor reaches the restarting process and fails. A probe watcher polling build-info.json every 100 ms measured that window: 1.80–1.88 s for the in-place path, and 1.75–1.83 s for a plain install with a candidate from main b58c23c. In one main run the self-restart fired 0.24 s before Doctor's stop. Runs: in-place 1 failure in 13; plain main 0 failures in 11, with that one near miss; 567a560 (before #198268) 3 of 3 passed. The window is the same on both paths and runs after the swap, so this change does not cause or widen it, and #198268 (which removed a step before the swap) does not move it. The in-place cell now stops the Gateway before its --no-restart update, with every assertion unchanged, so it checks the in-place replacement without that race. The race is left for a separate fix at the drain or installation-check owner; its evidence is with the fix owner.

A first rebind cell on 038d6fb, which switched the link and left the rebind to the restart, failed: post-update revalidation re-inspects the service against the recorded root, which now resolved to the new release, and stopped with service-revalidation-failed. Published 2026.11.3 on a linked root binds its service to the release as well, so the in-place update is the only path for that state.

Refusals kept, because they protect an installation another writer is changing, not a layout precondition: the link and candidate rechecks immediately before the rename (switchPackageReleaseLink), the rollback guard when another writer changed the link, refusing a rewritten release as a rollback target, and a failed write of the run record (onPackageRelease, after the Gateway stop): that is the run ledger, which the swap's own transaction writes use too, and interrupted-handoff recovery reads the record. A link changed between capture and the first rename is not captured again: the record and the database capture already name the previous release.

Cleanup after a fallback: the stage under releases/<label> loses its release marker and is removed by the steps' stage cleanup (the Docker launcher cell asserts no empty release directory); its packages were moved out by the swap. Old releases stay while the package path is a plain directory, because collection runs only behind a link; the next update adopts and its collection removes unselected releases older than 24 hours that no lease or open run names.

Review: the repository autoreview helper cannot run on this machine; an independent reviewer agent reviewed 038d6fb. High: the in-place swap would be refused by executor slot reservation and would publish over the link through the activation journal; fixed (selected-release reservation, journal skipped for a release behind its link), with the reservation test and the in-place Docker cell. Low: the gate's restart condition differed from the restart decision; superseded by always updating in place. Low: adoption-prefix cleanup untested; the adoption test now fails after the prefix exists and asserts its removal. A later review of 1a25681 found the journal skip matched any non-canonical spelling; confirmed with the symlinked-prefix test and fixed, the skip now reported through onUnavailable. CI on b3f067f then found two regressions from this work, fixed in 567a560: the broad reservation check let an occupied symlink slot skip its own lease (update-managed-service-handoff-reclamation.test.ts), and plain swaps called the release owner, which the swap fixture stubs (update-restart-module-outcome.test.ts).

The update-cli.candidate-admission.test.ts failure noted for 567a560 was main's stale test, which #198268 fixed. It passes on 56bb795, along with the other update files this change touches (15 files, 212 tests), and again on 115668d (15 files, 212 tests; with main's handoff lifecycle and command files, 2 files, 94 tests).

Not proven: a published reader of origin.packageRelease (published 2026.11.3 cannot open state this candidate migrates, schema 40 vs 22; by source, its origin schema is a plain z.object, which drops unknown keys); the durable service copy prefix; launchd/macOS; a Gateway-initiated update on a linked root; an unmanaged CLI crash after the switch (left to openclaw update repair). Earlier review: an independent reviewer agent reviewed the first version; both high findings and the low ones were fixed. Also not proven: a release-bound service whose definition the update cannot rewrite (in place by the same path as --no-restart, not run in Docker); the local suite sweep on the final head (CI is the broad proof). The in-place cell no longer runs with the Gateway up: --no-restart with a running Gateway is covered by no cell until the separate fix for the race above.

OPENCLAW_PUBLISHED_DRIVER_LINKED_ROOT=1 moves the installed driver into
releases/<version>/ under the prefix and leaves a relative link at the
package path before the update. No shipped release produces that layout;
it is what a downgrade would leave under the proposed release-directory
design, and this mode shows what a published updater does with it.

The update, readiness, version, and session assertions are unchanged. The
incognito scan also covers the directory behind the link, where such an
updater keeps its backups, and the installed-tree budget is measured at
the link's target because the budget refuses a link. The cell records
where the package path points before and after the update, including
after a failed update.

Adds the test:docker:published-driver-linked-root script and its Docker
lane. No CI workflow selects the lane.
…fixes

On the install-cli.sh prefix and the durable service copy, `openclaw update`
now installs each release into <prefix>/releases/<id>/ and makes
lib/node_modules/openclaw a link to the selected one. Activation and rollback
rename one temporary link over it; the previous release is never written.
The first update converts a plain package directory into a release behind
the link. npm prefixes the user manages, npm link checkouts, pnpm, Bun, Git
and Windows keep the existing swap.

The link is the installation's identity: resolveUpdateInstallRoot keeps the
link path and maps the selected release to it, so executor leases, child
admission, the restart sentinel and the handoff lease key survive a switch.
Root discovery maps a start through the bin launcher to the link. The update
run record gains optional origin.packageRelease, written before the database
capture, and interrupted managed handoff reads through the link. Unselected
releases are collected after 24 hours when no Gateway lease or open run names
them. update status lists the releases. The switch refuses before any change
when the candidate's launchers differ or the service starts a release path.
@clawsweeper

clawsweeper Bot commented Nov 14, 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 scripts Repository scripts docker Docker and sandbox tooling size: XL labels Nov 14, 2026
fuller-stack-dev added a commit to fuller-stack-dev/openclaw that referenced this pull request Nov 14, 2026
Releases live under the npm prefix; the link is the installation identity,
with the selected release mapped to it; adoption is two renames with a
documented manual recovery; origin.packageRelease is written before the
database capture; rollback reads the link; Gateway leases and deselection
stamps drive collection; a service bound to a release path is refused.
Records what the Docker cells in openclaw#198835 proved and what they did not.
@fuller-stack-dev
fuller-stack-dev marked this pull request as ready for review November 14, 2026 11:25
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 14, 2026
@clawsweeper

clawsweeper Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR installs releases side by side on OpenClaw-owned prefixes and activates them by switching the package symlink.

Example: An install-cli.sh installation updates from 2026.11.3 to 2026.12.1.

  • Before: The updater moves the installed package aside and publishes its replacement.
  • After: Both releases remain under releases/, while lib/node_modules/openclaw selects the new release through a symlink.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation has useful boundary coverage and no identified blocking code defect, but required upgrade compatibility evidence remains uninspectable and exact-head CI is red.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Complete
User problem: Package updates displace the installed release and require backup, publication, and recovery work during activation.
Reason: Maintainer authorship supplies direction approval, and the feature coherently implements the owned-prefix slice with documented exclusions and fallback behavior.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this maintainer-authored feature remains useful and absent from main; the previous blockers are resolved, and no new definite correctness defect was identified.

Priority: P2
Reviewed head: 823fa6d2b07be8d1cd88076ef394e7b9c03bd50c

Before merge

  • 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: Attach inspectable output from the reported latest-stable upgrade, adoption, switch, and failed-Doctor rollback showing settings and durable sessions preserved; redact credentials, IPs, phone numbers, and non-public endpoints.
Agent review details

How this fits together

The package updater receives an installation and candidate package, stages and validates the candidate, activates it under the existing update transaction, and verifies Doctor and Gateway recovery.

flowchart TD
  A[CLI or Gateway update] --> B[Resolve installation identity]
  B --> C[Stage candidate release]
  C --> D[Existing update transaction]
  D --> E[Switch package link or use swap]
  E --> F[Doctor and Gateway verification]
  F --> G[Retain and collect releases]
  F --> H[Rollback package link]
Loading

Technical review

Best possible solution:

Keep one stable package-link identity and reuse existing staging, transaction, recovery, and verification owners, retaining the ordinary swap for unsupported layouts.

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

This is a new installation-layout capability; current-main source confirms the existing displacement-based swap, while the PR supplies focused filesystem, process-interruption, executor, and recovery tests.

Is this the best way to solve the issue?

The stable-link design fits the approved scope, and the new switch path shares the existing transaction interface while preserving swap behavior for other installation types.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Staged package activation and rollback keeps the original intent (d1a69c0: Prepare and validate candidates while the old Gateway serves, then retain the transaction through activation and verified recovery.)
  • Installation identity changes intended behavior with a stated reason (ef16771: Bind handoffs and restart receipts to their originating installation while accepting equivalent symlink spellings.)
  • Local package overrides keeps the original intent (265f857: Preserve operator edits as recovery material and replay them only into a private candidate when explicitly requested.)
  • Lifecycle custody keeps the original intent (616a395: Keep unresolved lifecycle writers exclusive and preserve stages under their custody.)
  • Interrupted managed updates changes intended behavior with a stated reason (29503e1: Recover a verified installation after updater death through the existing managed handoff owner.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Vincent Koc: Raw commit ca7ef93 adds src/infra/package-update-swap.ts:6 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: ca7ef93a9985; files: src/infra/package-update-swap.ts)

PR surface

Source +1323, Tests +1476, Docs +87, Config +5, Other +377. Total +3268 across 59 files. Added test files: 10.

View PR surface stats
Area Files Added Removed Net
Source 34 1391 68 +1323
Tests 13 1477 1 +1476
Docs 4 87 0 +87
Config 1 5 0 +5
Generated 0 0 0 0
Other 7 382 5 +377
Total 59 3342 74 +3268

Preflight source

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

Review metrics

Metric Value Why it matters
New harness controls 2 environment variables; 0 production config options OWNED_PREFIX and FOLLOW_UP select the additional Docker scenarios without adding operator-facing configuration.

Labels

Label changes:

  • remove merge-risk: 🚨 automation: Current PR review merge-risk labels are merge-risk: 🚨 compatibility.
  • remove status: ⏳ waiting on author: Current PR status no longer selects a status label.

Label justifications:

  • P2: This is an approved update reliability improvement rather than an established urgent regression.
  • merge-risk: 🚨 compatibility: Existing owned installations automatically adopt a persisted release-directory layout; the maintainer-authored proposal explicitly records the adoption and service-binding tradeoffs.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-14T11:44:57.283Z sha 0225b11 :: blocked before merge. :: [P1] Include the new root resolver dependency in the wrapper inventory | [P2] Preserve the new resolver export in the shared update CLI mock | [P2] Keep the generated handoff source within its existing ratchet

Reviewed November 15, 2026, 10:22 PM ET / November 16, 2026, 03:22 UTC (Revision 2).

fuller-stack-dev and others added 5 commits November 14, 2026 11:41
- Read the Gateway service layout early only when the package path is a
  release link; other owned destinations inspect exactly as before.
- Map a release root to its link in resolveUpdateRoot with the reverse
  rule directly, so update-cli mocks of openclaw-root stay complete.
- Add package-release-slot-path.ts to the PR wrapper inventory; the
  wrapper imports openclaw-root.ts.
- Move PackageReleaseTarget to package-release-slot.ts to break a type
  import cycle with the swap contract.
- Drop three slot-level tests that the switch-level tests cover, fix a
  prefer-array-find lint error, and record the remaining test-line growth.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
openclaw#198489 landed on main as eb1a21d; the branch's copy of it
(b676afe) now resolves to main's version, leaving only slice 4's
owned-prefix and follow-up additions in those five files.
…ment mock

The executor grant now compares roots with updateInstallRootsMatch, which
the settlement test's hand-written mock of update-install-root.js did not
export. Spread the real module and keep only the identity override, and
drop the now-unneeded mock-exports baseline entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…lease layout

The release layout is an optimisation. A candidate launcher that differs, a
releases/ directory that cannot be created or sits on another filesystem, or
a package that cannot be read as a release now makes the update take the
existing swap with a recorded warning; the next update tries the layout again.
A service bound to a release path no longer refuses: the switch's restart
rebinds it through the install-root refresh, and when that cannot happen the
update replaces the selected release in place.
A Gateway service that starts a release's real path keeps that release after the
link moves, and the post-update ownership check then refuses it. Replace that
release in place instead, report the package path as the update root so the
restart's service refresh binds the service there, and let the executor reserve
and publish a release that the link selects by its real path.
@fuller-stack-dev
fuller-stack-dev merged commit b868ed4 into openclaw:main Nov 16, 2026
233 of 243 checks passed
@fuller-stack-dev

Copy link
Copy Markdown
Member Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

@fuller-stack-dev
fuller-stack-dev deleted the feat/update-linked-package-root branch November 16, 2026 18:24
fuller-stack-dev added a commit to fuller-stack-dev/openclaw that referenced this pull request Nov 16, 2026
…ound service

The plan to switch the link and then rebind the service failed in Docker: the
post-update ownership check ran first and left the Gateway stopped. As landed
in openclaw#198835, the update replaces the release the service starts in place and
the restart's service refresh binds the service to the package path. The
launcher comparison covers only the launchers the swap publishes. Decision 8
is closed, and the separate --no-restart race on main points at openclaw#200181.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 17, 2026
…d installs (openclaw#198835)

* test(update): run the published-driver cell on a linked package path

OPENCLAW_PUBLISHED_DRIVER_LINKED_ROOT=1 moves the installed driver into
releases/<version>/ under the prefix and leaves a relative link at the
package path before the update. No shipped release produces that layout;
it is what a downgrade would leave under the proposed release-directory
design, and this mode shows what a published updater does with it.

The update, readiness, version, and session assertions are unchanged. The
incognito scan also covers the directory behind the link, where such an
updater keeps its backups, and the installed-tree budget is measured at
the link's target because the budget refuses a link. The cell records
where the package path points before and after the update, including
after a failed update.

Adds the test:docker:published-driver-linked-root script and its Docker
lane. No CI workflow selects the lane.

* feat(update): keep releases behind a linked package root on owned prefixes

On the install-cli.sh prefix and the durable service copy, `openclaw update`
now installs each release into <prefix>/releases/<id>/ and makes
lib/node_modules/openclaw a link to the selected one. Activation and rollback
rename one temporary link over it; the previous release is never written.
The first update converts a plain package directory into a release behind
the link. npm prefixes the user manages, npm link checkouts, pnpm, Bun, Git
and Windows keep the existing swap.

The link is the installation's identity: resolveUpdateInstallRoot keeps the
link path and maps the selected release to it, so executor leases, child
admission, the restart sentinel and the handoff lease key survive a switch.
Root discovery maps a start through the bin launcher to the link. The update
run record gains optional origin.packageRelease, written before the database
capture, and interrupted managed handoff reads through the link. Unselected
releases are collected after 24 hours when no Gateway lease or open run names
them. update status lists the releases. The switch refuses before any change
when the candidate's launchers differ or the service starts a release path.

* fix(update): keep release-link checks off unrelated update paths

- Read the Gateway service layout early only when the package path is a
  release link; other owned destinations inspect exactly as before.
- Map a release root to its link in resolveUpdateRoot with the reverse
  rule directly, so update-cli mocks of openclaw-root stay complete.
- Add package-release-slot-path.ts to the PR wrapper inventory; the
  wrapper imports openclaw-root.ts.
- Move PackageReleaseTarget to package-release-slot.ts to break a type
  import cycle with the swap contract.
- Drop three slot-level tests that the switch-level tests cover, fix a
  prefer-array-find lint error, and record the remaining test-line growth.

* test(update): keep the real install-root match in the executor settlement mock

The executor grant now compares roots with updateInstallRootsMatch, which
the settlement test's hand-written mock of update-install-root.js did not
export. Spread the real module and keep only the identity override, and
drop the now-unneeded mock-exports baseline entry.

* fix(update): fall back to the package swap instead of refusing the release layout

The release layout is an optimisation. A candidate launcher that differs, a
releases/ directory that cannot be created or sits on another filesystem, or
a package that cannot be read as a release now makes the update take the
existing swap with a recorded warning; the next update tries the layout again.
A service bound to a release path no longer refuses: the switch's restart
rebinds it through the install-root refresh, and when that cannot happen the
update replaces the selected release in place.

* fix(update): replace a release-bound service's release in place

A Gateway service that starts a release's real path keeps that release after the
link moves, and the post-update ownership check then refuses it. Replace that
release in place instead, report the package path as the update root so the
restart's service refresh binds the service there, and let the executor reserve
and publish a release that the link selects by its real path.

* test(update): record the test-line allocation for the release fallback

* fix(update): skip the publication journal only for a release behind its link

The journal skip compared the live root with its resolved installation root, so
any non-canonical spelling (a symlinked prefix or volume, macOS /tmp) also lost
journaled activation, silently. Skip only when the live root is the release a
package link selects, and report it through onUnavailable.

* fix(update): compare only the launchers the update manages before a release switch

The swap publishes only the openclaw launcher, so a candidate that adds another
command fell back on every update and never adopted the layout again. Compare
the managed launchers only, and drive the Docker launcher cell with an absolute
prefix launcher instead of an added command.

* fix(update): reserve only the selected release, and keep plain swaps off the release owner

Slot reservation accepted any spelling that resolves to the installation, so an
occupied symlink slot no longer took its own lease. Accept only the release the
installation's package link selects. Plain swaps call the directory swap
directly again; only release stages go through the release owner.

* test(update): stop the Gateway before the in-place release cell's --no-restart update

With the Gateway running, its 30-second installation check can restart it
into the replaced package while update Doctor stops it, and Doctor then
fails the update. Measured on a plain install from main as well, so the race
belongs to every --no-restart package update, not to the release layout.
The cell now checks the in-place replacement without it; its assertions are
unchanged.
obviyus added a commit that referenced this pull request Nov 17, 2026
…lds it (#200389)

## Problem

During `openclaw update --no-restart` with the Gateway running, the Gateway's installation check (`src/gateway/server-maintenance.ts`, every 30 s) sees the new `build-info.json` and restarts the Gateway into the new package while the update still owns the installation. The update's own Gateway start then waits on state ownership held by the self-restarted process, stalls for 120 s, and the update fails with `activated-gateway-startup-failed` and rolls back (exit 1). This happens on plain package installs and on the release-directory layout from #198835. The natural rate is about the race window divided by 30 s. #198835 measured that window at 1.75–1.88 s, which gives about 6% per run; I did not re-measure the window.

## Change

The update run is the one owner of the installation while it holds the install lease (the same `managed-update-handoffs` row the updater's executor takes). `checkGatewayInstallationReplacement` (`src/gateway/stale-install.ts`) now skips the self-restart while a live process holds that lease. A Gateway the run leaves stale restarts on a later check, after the lease is released.

- The lease key is captured with the installation root when the observer registers.
- Lease reads and process-identity probes are synchronous, so they run in the existing handoff worker (`prepareManagedHandoffParentStore`), never on the serving thread. They run only when a changed build is observed.
- An unreadable lease keeps today's behavior (self-restart).
- No new gate in the updater, no schema or config change.

## Impact

`--no-restart` updates with a running Gateway no longer race the update's Doctor and Gateway start. Behavior outside an update run is unchanged.

## Evidence

**Unit:** `src/gateway/stale-install.test.ts` › "leaves a replaced installation to the update run that holds it". It holds a real lease, checks that a changed build does not restart the Gateway, releases the lease, then checks that the next tick does restart it. Red on `2435c1faa791` (handoff called once while the lease is held), green on this head; the other 14 tests in the file pass.

**E2E (mbp-m5, real `openclaw update --no-restart` against a launchd Gateway, isolated `--profile`):** the reproduction makes the installation check fire every 250 ms in the *running* build. Only `server-maintenance` changes in a packed copy; the build ID differs, the code is otherwise identical. Each arm: install, start the Gateway service, then `update --no-restart --tag <next build>` with the Gateway running.

| Arm | Layout | Result | Update wall time |
|---|---|---|---|
| main `2435c1fa` | release dirs (`install-cli.sh` prefix, adopted) | **fail**: self-restart at T+0.25 s, `activated-gateway-startup-failed`, rolled back | 351 s |
| main `2435c1fa` | plain user npm prefix | **fail**: same | 455 s |
| this PR `d6f23896` | release dirs | **ok**, no self-restart signal, Gateway healthy on the new build | 133 s |
| this PR `d6f23896` | plain user npm prefix | **ok**, no self-restart signal, Gateway healthy on the new build | 188 s |

Gates: `pnpm tsgo:core`, `pnpm check:test-types`, oxlint and oxfmt on changed files all pass.

Local ClawSweeper review (gpt-6.1-sol, normal speed) at `d6f23896`: patch is correct, 0 findings. The previous head's single finding (synchronous lease reads on the Gateway thread) is fixed by the worker move.

Not covered: the missing-runtime-chunk path in `classifyGatewayStaleInstall` still restarts on a request failure during an in-place swap. That path triggers on a real load failure and was left as is.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Nov 17, 2026
…ase link (#199706)

## Problem

A Git checkout install runs its Gateway from `<checkout>/dist/index.js`, and `openclaw update` rewrites that same tree. Everything around the rewrite exists to survive it: the updater copies its own runtime first (133–892 s on a 183k-file checkout), builds the candidate in a private repository and imports it through a pack (256 MB cap), stops and parks the serving Gateway, and rewrites the service definition every update.

## Change

Extends #198835's linked package root (merged as `b868ed4c`) to Git checkouts, per the #197949 design. Based on `main`. It reuses #198835's release resolver, `switchPackageReleaseLink`, leases and 24 h collection unchanged. Its fallback follows `installStagedPackage`: when the layout can't be used, the update runs in place with a `recoverable-maintenance` warning, and the next update tries the layout again. The Gateway process never writes the release link. The only other writer is the boot launcher, and it only points the link back to the release recorded in a failed trial.

- **Layout.** `<stateDir>/git-install/lib/node_modules/openclaw -> releases/<id>/lib/node_modules/openclaw`. Each release is `git worktree add --detach` off the developer's checkout (shared object store, no clone or copy).
- **Stage.** The existing candidate preflight (candidate walk, local-commit replay, `pnpm install --frozen-lockfile`, build, candidate checks) runs in the new release's worktree, then `--version` with the service's Node. A same-source no-op requires the serving release to be at the checkout's commit and its artifacts to verify (#158931).
  - Deviation from the design: the worktree is built at `releases/<id>/build`, then moved into place with `git worktree move`. Node refuses to strip types under `node_modules` (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`), and the build runs `.mts` scripts. The built tree has no absolute symlinks, so the move is safe.
- **Switch.** `switchPackageReleaseLink` from #198835. The serving Gateway keeps its release (Node resolves the entry's real path), so nothing is stopped, parked or verified before the flip.
- **Restart.** The serving Gateway's maintenance tick sees the link move (installation replacement) and restarts itself into the new release. The updater waits for that successor (up to 90 s), then verifies. It falls back to a native restart only if no successor appears. A native restart from inside the service job (`update.run`) would end the updater itself.
- **Service.** Written once, at conversion, to a frozen launcher `<stateDir>/git-install/openclaw-launcher.mjs`. A unit that names the launcher is never regenerated. The launcher is needed because a release that fails while loading never reaches Gateway code.
- **Trial.** The switch writes `releases/.trial`. The launcher counts starts.
  - After two failed starts it switches the link back and restores the trial build's `*.pre-<buildId>` state files (falling back to #198389's `*.pre-<version>`). Each SQLite family is restored together, and trial-created WAL/journal/SHM/seal files without a preserved predecessor are removed. The launcher mirrors #198389's `companionRemovals` list because it must not load release code.
  - The trial ends when the Gateway's first maintenance tick runs, or when the updater verifies the restarted Gateway. The second path also covers targets that predate this PR.
  - Writes made during a failed trial are lost (approved).
- **The layout never fails an update** (#197949 decision 8). If `releases/` cannot be created, or something other than a release link sits at the package path, the update records a warning and takes the in-place runner. The next update tries the layout again.
- **Post-core work** (requested-channel persistence, plugin convergence) runs in the updater, but only after the restarted release verified and its trial ended. A failed trial therefore never leaves plugins that require the release it switched away from. It runs without Doctor maintenance, which the Gateway holds, and without a plugin cohort, because no core rollback exists to pair it with. If plugins changed, the Gateway is asked to restart again (SIGUSR2). Under `--no-restart` the release is unverified, so only the requested channel is persisted and plugins converge on a later update.
- **The developer's checkout** is never written. The first update builds the commit that serves now as the first release, rewrites the unit once, then stages the target.
- **Retention.** #198835's collection, followed by `git worktree prune`. `git-install` is excluded from backups and from the startup state-upgrade copy. The latter is the same change as #199770, included here so the stack stands alone.
- **One owner.** `usesGitReleases` selects releases. Windows checkouts and package-to-Git switches keep the in-place runner, and the in-place CLI tests are pinned to that runner.

For Git releases this skips:
- runtime retention
- the pack transfer/import
- the managed-service stop/park
- the database rollback capture
- the checkout's source-artifact lock
- the native restart from inside the service job
- per-update service regeneration

## In-place fallback (decided)

Windows Git checkouts, package-to-Git switches, and checkouts with no installed Gateway service still use the in-place runner, so this PR bypasses that runner on POSIX instead of deleting it. A checkout with no service is run by hand, so nothing would start through the release link and its next start would run the old commit. `gatewayServiceOwnsGitInstall` reads the installed service once and accepts it only when the service owns the checkout or its release link. The command decides once and hands that decision to the runner. Prod LOC is net **+980**. Decided 2026-11-16: Windows Git updates are not refused. A follow-up, slice 4b (stacked on this PR), moves Windows to releases using junctions and then deletes the in-place Git runner.

## E2E (mbp-m5, launchd, isolated profiles, shared-clone checkout; ≤15 min per run, ≤3 in parallel)

**Final head `0b96d640` (rebased on `main` at `8a82b5e0`): local ClawSweeper review clean** (gpt-6.1-sol, normal speed). After the rebase: `sweepPackageReleaseTemporaryLinks` is exported again, because the first Git publish uses it. The CI ratchets are satisfied: a lazy generation name, Node-only release tests, and an allocation record for the regression tests. A conversion's first release is now the commit the checkout's `dist` serves, not a pulled HEAD that was never rebuilt. A failed trial also restores a symlinked config: a preserved symlink is judged by its own time, not its target's.

Rollback across same-version upgrades (decision d): the state upgrade now keeps a replaced file as `<file>.pre-<buildId>`, named after the build that replaced it, so two builds of one version each keep their own predecessor. Builds without a build ID, and earlier releases, still write `.pre-<version>`. Retention handles both forms. A failed trial restores the `.pre-<buildId>` of its own build, falling back to `.pre-<version>`. Fixes to the trial and launcher from the review rounds:
- the inventory is recorded before anything is restored, so an interrupted rollback can resume without losing a restored WAL;
- the trial's applied or interrupted upgrade plan is retired and the files it added are removed; a removal that fails is retried at the next start;
- the config path is the one the update resolved (`~` and external paths included);
- state is restored before the link moves back.

The release layout is used only when the release switch actually reaches the next start: either the service already starts the launcher, or it owns the checkout and this update rewrites its definition and restarts it. `--no-restart` on a converted install leaves the serving release selected. The next start, which the operator triggers, selects the new release, without the two-start fallback. A first conversion requested with `--no-restart` stays in place.

| Run (mbp-m5, isolated launchd profiles) | Head | Result |
|---|---|---|
| Release that crashes on boot | `d6d30a5e` (the final head changes only how a symlinked backup is dated) | update reports `build-id-mismatch` after 179 s; two "e2e boot crash" starts, then "failed to start twice; switched back"; link back on the previous release, trial cleared, `ready` |
| Conversion before the crash run | `d6d30a5e` | ok, 267 s |

**Current head `6d9acd6e` (on `main`), mbp-m5, isolated launchd profiles:**

| Run | Result |
|---|---|
| Conversion (first update from a checkout service) | ok, root on the release link; 610 s with three runs in parallel; longest outage 9.7 s |
| Release → release | ok, 239 s, longest outage 9.9 s |
| `update.run` through the Gateway | `finished\|succeeded`, 135 s; link moved, Gateway restarted, plist unchanged; outage 7.8 s |
| Checkout with no Gateway service | updated in place: checkout HEAD moved to the target, no `git-install/releases`, result `ok`, mode `git` |
| Release that crashes on boot (at `0e3fefae`) | update reports `build-id-mismatch` after 188 s; after two "e2e boot crash" starts the launcher logs "failed to start twice; switched back", and the previous release serves `ready` |
| v2026.11.4 state → this head | see Data-model compatibility |

Older rows below ran at earlier heads.
Rows marked ‡ ran at head `8a720e49`, rows marked † at `6032dedf`; the rest ran at `1140b601`, before plugin convergence moved after verification. At the final head `99b7f080` (rebased onto `823fa6d2`), three runs ran in parallel on mbp-m5. (1) Conversion and release→release passed again, with the root on the release link and a longest outage of 7.6 s. (2) `update.run` finished `succeeded` (link moved, Gateway restarted, plist unchanged, outage 8.0 s). (3) A checkout with **no Gateway service** updated in place: checkout HEAD moved to the bumped commit, no `git-install/releases` was created, and the result was `ok`, mode `git`, root the checkout. An intermediate head `2d2387b6` keyed this choice on a preflight fact that Git installs never fill in, so conversion fell back to in-place (about 120 s outage). That head was never pushed.

| Case | Result |
| --- | --- |
| † First update of a checkout install (conversion, head→head+1) | ok, 402 s wall (two builds, three runs in parallel), longest outage 7.6 s, total 13.1 s (unit rewrite, then a restart after plugin convergence); unit rewritten once to the launcher; checkout tree clean; no retention, pack or handoff steps |
| ‡ Release→release (head+1→head+2) | ok, 180 s wall, one outage of 7.2 s; unit untouched (mtime unchanged since conversion); service runs from `releases/` |
| ‡ `--no-restart` on a switched release | the updater leaves the Gateway running and converges no plugins; within the next maintenance tick the Gateway restarts itself into the release, and the trial is cleared; outage 7.5 s |
| † `update.run` via the Gateway (`openclaw gateway call update.run`) | run `finished|succeeded`, 140 s; link moved; the Gateway restarted itself; unit untouched; outage 7.4 s |
| Already-current rerun from the preserved checkout after conversion (head `60503ab3`) | `skipped: already-current`, link unchanged, 113 s |
| † Release that crashes on boot | two crashes, the launcher switched back to the previous release, Gateway ready again; the update reports `build-id-mismatch`; longest outage 28.9 s |
| kill -9 mid-stage | link and serving Gateway unchanged; the rerun succeeds; a partial release directory left by the killed run is collected after 24 h |
| kill -9 right after the link moves, before restart | the old Gateway keeps serving; the rerun reports `skipped: already-current`; the Gateway restarts itself into the new release and the trial is cleared |
| `env -i` + `umask 077` (conversion, then release→release) | ok, 376 s and 198 s, outages 5.5 s and 7.5 s; launcher `0700` under umask 077 |
| Install whose unit and state were written by 2026.11.3, moved to head, then converted | ok, 229 s, outage 5.9 s; state DB `integrity_check` ok. 2026.11.3's own updater could not reach head on mbp-m5: it walked back to `already-current` (Node 24.21 below head's `engines`), so that hop was done with `git reset` + `ocx build` |
| Production-shaped install (207,229-file checkout, +3 GB SQLite in state), release→release | ok, 145 s, outage 6.9 s, no retention step. Main was not timed on this host. Peanutto's production main run `90c601fc` took 4,150 s, with 892 s retention and a 300 s outage |

Not exercised: a plugin-only restart (SIGUSR2) after npm plugins actually change; the fixtures have no npm plugins.

## Data-model compatibility

- **No new state schema.** This diff adds or changes no SQLite schema, migration, or config schema file. The update ledger (`update_runs`), Gateway owner lease and config are read and written exactly as on the base.
- **`origin` stays compatible.** `UpdateRunRecordSchema.origin` (including #198835's `packageStage` and `packageRelease`) is unchanged, and Git-release updates write no new `origin` key. A Git release records its switch in the result step and the release directories, not the ledger. So rows written by older builds parse as before, and rows written by this build parse in an older build. A Git checkout that can't use the layout falls back to the in-place runner with a `recoverable-maintenance` advisory (`git-release-layout` step), the same contract as `installStagedPackage`'s swap fallback.
- **New on-disk state is additive and lives under `<stateDir>/git-install/`:** `releases/<id>/` (detached worktrees), the `lib/node_modules/openclaw` link, `releases/.trial`, and the launcher. An install without them is treated as unconverted and gets the conversion path. If the layout is unusable, the update falls back to in-place (decision 8).
- **Existing data proof: v2026.11.4 state upgraded and converted (E2E, `6d9acd6e`).**
  - The v2026.11.4 Gateway, started with `--profile`, created `state/openclaw.sqlite` (schema 22) and an agent DB.
  - This head's `gateway install` then stopped with "Client credentials require backed-up migration custody; … run openclaw doctor --fix". Plain `main` (`964ab522`) stops with the same message on a copy of that state, so it comes from `main`, not this diff.
  - Following the message, `openclaw doctor --fix --non-interactive` migrated the state to schema 40. After that, install succeeded and the update converted the checkout onto the release link. The `update_runs` row in the stable-created database reads `finished|succeeded`, and the stable config (Gateway port) still reads back.
- **Rollback keeps data readable:** the crash-release trial switches the link back to the previous release, and the launcher restores the SQLite family (`openclaw.sqlite`, `-wal`, `-shm`) captured before the trial. The previous build reopens its own database (crash row, 28.9 s).

## Tests

- `src/infra/git-release.test.ts`:
  - trial fallback restores the SQLite family and drops trial-only companions
  - trial settlement
  - launcher mapping
  - a launcher unit is owned without regeneration
  - a non-link package path falls back to the in-place runner with a reason
- `src/infra/update-runner-git-release.test.ts`:
  - a same-commit release with unverified artifacts is rebuilt
  - a current release is reported prepared, so finalization never regenerates it
  - the first release comes from the serving worktree's commit, and the checkout's different target is still built
- `update-command-post-update.test.ts`: a switched release converges plugins only after its restart.
- `git-release.test.ts`: a checkout with no owning Gateway service keeps the in-place runner. The test fails without the gate.
- `update-command-execution-validation.test.ts`: when a developer build holds the checkout's artifact lock, a Git release update still runs. It never takes that lock, because releases build in their own worktrees. The test fails without the fix.
- `update-command-convergence-authority.test.ts`: under `--no-restart`, a switched release persists the channel and leaves plugins alone; an already-current rerun from the checkout of a converted install completes.
- `update-runner-git-release.test.ts`: a successful rebuild of an incomplete runtime reports the new release's verdict.
- `update-command-convergence-authority.test.ts`: release convergence runs in the updater, with no fresh process and no Doctor.
- `update-command-verification.test.ts`:
  - a verified release ends its trial
  - a switched release's Gateway restarts itself without a native restart
- `src/state/state-upgrade.test.ts`: `git-install` stays out of the startup upgrade copy.
- Gates: `pnpm tsgo:core`, `pnpm check:test-types`, oxlint/oxfmt on changed files. On mbp-m5 at `99b7f080`, the broad update suite plus the package-release and package-update tests pass 1,944 / 1,948, with 1 skipped. The 3 failures are environmental:
  - `update-runner-git-node-preflight` ×3: mbp-m5's Node 24.21 is below `engines`.

## LOC

prod +1018 / −38 (net +980); test +951 / −3.

Draft: lands after #198835. #198389 has merged; #199770 carries the same startup-copy exclusion for main.

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

## Problem

During `openclaw update --no-restart` with the Gateway running, the Gateway's installation check (`src/gateway/server-maintenance.ts`, every 30 s) sees the new `build-info.json` and restarts the Gateway into the new package while the update still owns the installation. The update's own Gateway start then waits on state ownership held by the self-restarted process, stalls for 120 s, and the update fails with `activated-gateway-startup-failed` and rolls back (exit 1). This happens on plain package installs and on the release-directory layout from openclaw#198835. The natural rate is about the race window divided by 30 s. openclaw#198835 measured that window at 1.75–1.88 s, which gives about 6% per run; I did not re-measure the window.

## Change

The update run is the one owner of the installation while it holds the install lease (the same `managed-update-handoffs` row the updater's executor takes). `checkGatewayInstallationReplacement` (`src/gateway/stale-install.ts`) now skips the self-restart while a live process holds that lease. A Gateway the run leaves stale restarts on a later check, after the lease is released.

- The lease key is captured with the installation root when the observer registers.
- Lease reads and process-identity probes are synchronous, so they run in the existing handoff worker (`prepareManagedHandoffParentStore`), never on the serving thread. They run only when a changed build is observed.
- An unreadable lease keeps today's behavior (self-restart).
- No new gate in the updater, no schema or config change.

## Impact

`--no-restart` updates with a running Gateway no longer race the update's Doctor and Gateway start. Behavior outside an update run is unchanged.

## Evidence

**Unit:** `src/gateway/stale-install.test.ts` › "leaves a replaced installation to the update run that holds it". It holds a real lease, checks that a changed build does not restart the Gateway, releases the lease, then checks that the next tick does restart it. Red on `dd40e0123cdc` (handoff called once while the lease is held), green on this head; the other 14 tests in the file pass.

**E2E (mbp-m5, real `openclaw update --no-restart` against a launchd Gateway, isolated `--profile`):** the reproduction makes the installation check fire every 250 ms in the *running* build. Only `server-maintenance` changes in a packed copy; the build ID differs, the code is otherwise identical. Each arm: install, start the Gateway service, then `update --no-restart --tag <next build>` with the Gateway running.

| Arm | Layout | Result | Update wall time |
|---|---|---|---|
| main `dd40e012` | release dirs (`install-cli.sh` prefix, adopted) | **fail**: self-restart at T+0.25 s, `activated-gateway-startup-failed`, rolled back | 351 s |
| main `dd40e012` | plain user npm prefix | **fail**: same | 455 s |
| this PR `d6f23896` | release dirs | **ok**, no self-restart signal, Gateway healthy on the new build | 133 s |
| this PR `d6f23896` | plain user npm prefix | **ok**, no self-restart signal, Gateway healthy on the new build | 188 s |

Gates: `pnpm tsgo:core`, `pnpm check:test-types`, oxlint and oxfmt on changed files all pass.

Local ClawSweeper review (gpt-6.1-sol, normal speed) at `d6f23896`: patch is correct, 0 findings. The previous head's single finding (synchronous lease reads on the Gateway thread) is fixed by the worker move.

Not covered: the missing-runtime-chunk path in `classifyGatewayStaleInstall` still restarts on a request failure during an in-place swap. That path triggers on a real load failure and was left as is.

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

## Problem

A Git checkout install runs its Gateway from `<checkout>/dist/index.js`, and `openclaw update` rewrites that same tree. Everything around the rewrite exists to survive it: the updater copies its own runtime first (133–892 s on a 183k-file checkout), builds the candidate in a private repository and imports it through a pack (256 MB cap), stops and parks the serving Gateway, and rewrites the service definition every update.

## Change

Extends openclaw#198835's linked package root (merged as `540d13a5`) to Git checkouts, per the openclaw#197949 design. Based on `main`. It reuses openclaw#198835's release resolver, `switchPackageReleaseLink`, leases and 24 h collection unchanged. Its fallback follows `installStagedPackage`: when the layout can't be used, the update runs in place with a `recoverable-maintenance` warning, and the next update tries the layout again. The Gateway process never writes the release link. The only other writer is the boot launcher, and it only points the link back to the release recorded in a failed trial.

- **Layout.** `<stateDir>/git-install/lib/node_modules/openclaw -> releases/<id>/lib/node_modules/openclaw`. Each release is `git worktree add --detach` off the developer's checkout (shared object store, no clone or copy).
- **Stage.** The existing candidate preflight (candidate walk, local-commit replay, `pnpm install --frozen-lockfile`, build, candidate checks) runs in the new release's worktree, then `--version` with the service's Node. A same-source no-op requires the serving release to be at the checkout's commit and its artifacts to verify (openclaw#158931).
  - Deviation from the design: the worktree is built at `releases/<id>/build`, then moved into place with `git worktree move`. Node refuses to strip types under `node_modules` (`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`), and the build runs `.mts` scripts. The built tree has no absolute symlinks, so the move is safe.
- **Switch.** `switchPackageReleaseLink` from openclaw#198835. The serving Gateway keeps its release (Node resolves the entry's real path), so nothing is stopped, parked or verified before the flip.
- **Restart.** The serving Gateway's maintenance tick sees the link move (installation replacement) and restarts itself into the new release. The updater waits for that successor (up to 90 s), then verifies. It falls back to a native restart only if no successor appears. A native restart from inside the service job (`update.run`) would end the updater itself.
- **Service.** Written once, at conversion, to a frozen launcher `<stateDir>/git-install/openclaw-launcher.mjs`. A unit that names the launcher is never regenerated. The launcher is needed because a release that fails while loading never reaches Gateway code.
- **Trial.** The switch writes `releases/.trial`. The launcher counts starts.
  - After two failed starts it switches the link back and restores the trial build's `*.pre-<buildId>` state files (falling back to openclaw#198389's `*.pre-<version>`). Each SQLite family is restored together, and trial-created WAL/journal/SHM/seal files without a preserved predecessor are removed. The launcher mirrors openclaw#198389's `companionRemovals` list because it must not load release code.
  - The trial ends when the Gateway's first maintenance tick runs, or when the updater verifies the restarted Gateway. The second path also covers targets that predate this PR.
  - Writes made during a failed trial are lost (approved).
- **The layout never fails an update** (openclaw#197949 decision 8). If `releases/` cannot be created, or something other than a release link sits at the package path, the update records a warning and takes the in-place runner. The next update tries the layout again.
- **Post-core work** (requested-channel persistence, plugin convergence) runs in the updater, but only after the restarted release verified and its trial ended. A failed trial therefore never leaves plugins that require the release it switched away from. It runs without Doctor maintenance, which the Gateway holds, and without a plugin cohort, because no core rollback exists to pair it with. If plugins changed, the Gateway is asked to restart again (SIGUSR2). Under `--no-restart` the release is unverified, so only the requested channel is persisted and plugins converge on a later update.
- **The developer's checkout** is never written. The first update builds the commit that serves now as the first release, rewrites the unit once, then stages the target.
- **Retention.** openclaw#198835's collection, followed by `git worktree prune`. `git-install` is excluded from backups and from the startup state-upgrade copy. The latter is the same change as openclaw#199770, included here so the stack stands alone.
- **One owner.** `usesGitReleases` selects releases. Windows checkouts and package-to-Git switches keep the in-place runner, and the in-place CLI tests are pinned to that runner.

For Git releases this skips:
- runtime retention
- the pack transfer/import
- the managed-service stop/park
- the database rollback capture
- the checkout's source-artifact lock
- the native restart from inside the service job
- per-update service regeneration

## In-place fallback (decided)

Windows Git checkouts, package-to-Git switches, and checkouts with no installed Gateway service still use the in-place runner, so this PR bypasses that runner on POSIX instead of deleting it. A checkout with no service is run by hand, so nothing would start through the release link and its next start would run the old commit. `gatewayServiceOwnsGitInstall` reads the installed service once and accepts it only when the service owns the checkout or its release link. The command decides once and hands that decision to the runner. Prod LOC is net **+980**. Decided 2026-11-16: Windows Git updates are not refused. A follow-up, slice 4b (stacked on this PR), moves Windows to releases using junctions and then deletes the in-place Git runner.

## E2E (mbp-m5, launchd, isolated profiles, shared-clone checkout; ≤15 min per run, ≤3 in parallel)

**Final head `0b96d640` (rebased on `main` at `78d37094`): local ClawSweeper review clean** (gpt-6.1-sol, normal speed). After the rebase: `sweepPackageReleaseTemporaryLinks` is exported again, because the first Git publish uses it. The CI ratchets are satisfied: a lazy generation name, Node-only release tests, and an allocation record for the regression tests. A conversion's first release is now the commit the checkout's `dist` serves, not a pulled HEAD that was never rebuilt. A failed trial also restores a symlinked config: a preserved symlink is judged by its own time, not its target's.

Rollback across same-version upgrades (decision d): the state upgrade now keeps a replaced file as `<file>.pre-<buildId>`, named after the build that replaced it, so two builds of one version each keep their own predecessor. Builds without a build ID, and earlier releases, still write `.pre-<version>`. Retention handles both forms. A failed trial restores the `.pre-<buildId>` of its own build, falling back to `.pre-<version>`. Fixes to the trial and launcher from the review rounds:
- the inventory is recorded before anything is restored, so an interrupted rollback can resume without losing a restored WAL;
- the trial's applied or interrupted upgrade plan is retired and the files it added are removed; a removal that fails is retried at the next start;
- the config path is the one the update resolved (`~` and external paths included);
- state is restored before the link moves back.

The release layout is used only when the release switch actually reaches the next start: either the service already starts the launcher, or it owns the checkout and this update rewrites its definition and restarts it. `--no-restart` on a converted install leaves the serving release selected. The next start, which the operator triggers, selects the new release, without the two-start fallback. A first conversion requested with `--no-restart` stays in place.

| Run (mbp-m5, isolated launchd profiles) | Head | Result |
|---|---|---|
| Release that crashes on boot | `d6d30a5e` (the final head changes only how a symlinked backup is dated) | update reports `build-id-mismatch` after 179 s; two "e2e boot crash" starts, then "failed to start twice; switched back"; link back on the previous release, trial cleared, `ready` |
| Conversion before the crash run | `d6d30a5e` | ok, 267 s |

**Current head `6d9acd6e` (on `main`), mbp-m5, isolated launchd profiles:**

| Run | Result |
|---|---|
| Conversion (first update from a checkout service) | ok, root on the release link; 610 s with three runs in parallel; longest outage 9.7 s |
| Release → release | ok, 239 s, longest outage 9.9 s |
| `update.run` through the Gateway | `finished\|succeeded`, 135 s; link moved, Gateway restarted, plist unchanged; outage 7.8 s |
| Checkout with no Gateway service | updated in place: checkout HEAD moved to the target, no `git-install/releases`, result `ok`, mode `git` |
| Release that crashes on boot (at `0e3fefae`) | update reports `build-id-mismatch` after 188 s; after two "e2e boot crash" starts the launcher logs "failed to start twice; switched back", and the previous release serves `ready` |
| v2026.11.4 state → this head | see Data-model compatibility |

Older rows below ran at earlier heads.
Rows marked ‡ ran at head `8a720e49`, rows marked † at `6032dedf`; the rest ran at `1140b601`, before plugin convergence moved after verification. At the final head `99b7f080` (rebased onto `823fa6d2`), three runs ran in parallel on mbp-m5. (1) Conversion and release→release passed again, with the root on the release link and a longest outage of 7.6 s. (2) `update.run` finished `succeeded` (link moved, Gateway restarted, plist unchanged, outage 8.0 s). (3) A checkout with **no Gateway service** updated in place: checkout HEAD moved to the bumped commit, no `git-install/releases` was created, and the result was `ok`, mode `git`, root the checkout. An intermediate head `2d2387b6` keyed this choice on a preflight fact that Git installs never fill in, so conversion fell back to in-place (about 120 s outage). That head was never pushed.

| Case | Result |
| --- | --- |
| † First update of a checkout install (conversion, head→head+1) | ok, 402 s wall (two builds, three runs in parallel), longest outage 7.6 s, total 13.1 s (unit rewrite, then a restart after plugin convergence); unit rewritten once to the launcher; checkout tree clean; no retention, pack or handoff steps |
| ‡ Release→release (head+1→head+2) | ok, 180 s wall, one outage of 7.2 s; unit untouched (mtime unchanged since conversion); service runs from `releases/` |
| ‡ `--no-restart` on a switched release | the updater leaves the Gateway running and converges no plugins; within the next maintenance tick the Gateway restarts itself into the release, and the trial is cleared; outage 7.5 s |
| † `update.run` via the Gateway (`openclaw gateway call update.run`) | run `finished|succeeded`, 140 s; link moved; the Gateway restarted itself; unit untouched; outage 7.4 s |
| Already-current rerun from the preserved checkout after conversion (head `60503ab3`) | `skipped: already-current`, link unchanged, 113 s |
| † Release that crashes on boot | two crashes, the launcher switched back to the previous release, Gateway ready again; the update reports `build-id-mismatch`; longest outage 28.9 s |
| kill -9 mid-stage | link and serving Gateway unchanged; the rerun succeeds; a partial release directory left by the killed run is collected after 24 h |
| kill -9 right after the link moves, before restart | the old Gateway keeps serving; the rerun reports `skipped: already-current`; the Gateway restarts itself into the new release and the trial is cleared |
| `env -i` + `umask 077` (conversion, then release→release) | ok, 376 s and 198 s, outages 5.5 s and 7.5 s; launcher `0700` under umask 077 |
| Install whose unit and state were written by 2026.11.3, moved to head, then converted | ok, 229 s, outage 5.9 s; state DB `integrity_check` ok. 2026.11.3's own updater could not reach head on mbp-m5: it walked back to `already-current` (Node 24.21 below head's `engines`), so that hop was done with `git reset` + `ocx build` |
| Production-shaped install (207,229-file checkout, +3 GB SQLite in state), release→release | ok, 145 s, outage 6.9 s, no retention step. Main was not timed on this host. Peanutto's production main run `90c601fc` took 4,150 s, with 892 s retention and a 300 s outage |

Not exercised: a plugin-only restart (SIGUSR2) after npm plugins actually change; the fixtures have no npm plugins.

## Data-model compatibility

- **No new state schema.** This diff adds or changes no SQLite schema, migration, or config schema file. The update ledger (`update_runs`), Gateway owner lease and config are read and written exactly as on the base.
- **`origin` stays compatible.** `UpdateRunRecordSchema.origin` (including openclaw#198835's `packageStage` and `packageRelease`) is unchanged, and Git-release updates write no new `origin` key. A Git release records its switch in the result step and the release directories, not the ledger. So rows written by older builds parse as before, and rows written by this build parse in an older build. A Git checkout that can't use the layout falls back to the in-place runner with a `recoverable-maintenance` advisory (`git-release-layout` step), the same contract as `installStagedPackage`'s swap fallback.
- **New on-disk state is additive and lives under `<stateDir>/git-install/`:** `releases/<id>/` (detached worktrees), the `lib/node_modules/openclaw` link, `releases/.trial`, and the launcher. An install without them is treated as unconverted and gets the conversion path. If the layout is unusable, the update falls back to in-place (decision 8).
- **Existing data proof: v2026.11.4 state upgraded and converted (E2E, `6d9acd6e`).**
  - The v2026.11.4 Gateway, started with `--profile`, created `state/openclaw.sqlite` (schema 22) and an agent DB.
  - This head's `gateway install` then stopped with "Client credentials require backed-up migration custody; … run openclaw doctor --fix". Plain `main` (`14466930`) stops with the same message on a copy of that state, so it comes from `main`, not this diff.
  - Following the message, `openclaw doctor --fix --non-interactive` migrated the state to schema 40. After that, install succeeded and the update converted the checkout onto the release link. The `update_runs` row in the stable-created database reads `finished|succeeded`, and the stable config (Gateway port) still reads back.
- **Rollback keeps data readable:** the crash-release trial switches the link back to the previous release, and the launcher restores the SQLite family (`openclaw.sqlite`, `-wal`, `-shm`) captured before the trial. The previous build reopens its own database (crash row, 28.9 s).

## Tests

- `src/infra/git-release.test.ts`:
  - trial fallback restores the SQLite family and drops trial-only companions
  - trial settlement
  - launcher mapping
  - a launcher unit is owned without regeneration
  - a non-link package path falls back to the in-place runner with a reason
- `src/infra/update-runner-git-release.test.ts`:
  - a same-commit release with unverified artifacts is rebuilt
  - a current release is reported prepared, so finalization never regenerates it
  - the first release comes from the serving worktree's commit, and the checkout's different target is still built
- `update-command-post-update.test.ts`: a switched release converges plugins only after its restart.
- `git-release.test.ts`: a checkout with no owning Gateway service keeps the in-place runner. The test fails without the gate.
- `update-command-execution-validation.test.ts`: when a developer build holds the checkout's artifact lock, a Git release update still runs. It never takes that lock, because releases build in their own worktrees. The test fails without the fix.
- `update-command-convergence-authority.test.ts`: under `--no-restart`, a switched release persists the channel and leaves plugins alone; an already-current rerun from the checkout of a converted install completes.
- `update-runner-git-release.test.ts`: a successful rebuild of an incomplete runtime reports the new release's verdict.
- `update-command-convergence-authority.test.ts`: release convergence runs in the updater, with no fresh process and no Doctor.
- `update-command-verification.test.ts`:
  - a verified release ends its trial
  - a switched release's Gateway restarts itself without a native restart
- `src/state/state-upgrade.test.ts`: `git-install` stays out of the startup upgrade copy.
- Gates: `pnpm tsgo:core`, `pnpm check:test-types`, oxlint/oxfmt on changed files. On mbp-m5 at `99b7f080`, the broad update suite plus the package-release and package-update tests pass 1,944 / 1,948, with 1 skipped. The 3 failures are environmental:
  - `update-runner-git-node-preflight` ×3: mbp-m5's Node 24.21 is below `engines`.

## LOC

prod +1018 / −38 (net +980); test +951 / −3.

Draft: lands after openclaw#198835. openclaw#198389 has merged; openclaw#199770 carries the same startup-copy exclusion for main.

Co-authored-by: Ayaan Zaidi <[email protected]>
RomneyDa added a commit that referenced this pull request Nov 19, 2026
…lds it (#200389)

## Problem

During `openclaw update --no-restart` with the Gateway running, the Gateway's installation check (`src/gateway/server-maintenance.ts`, every 30 s) sees the new `build-info.json` and restarts the Gateway into the new package while the update still owns the installation. The update's own Gateway start then waits on state ownership held by the self-restarted process, stalls for 120 s, and the update fails with `activated-gateway-startup-failed` and rolls back (exit 1). This happens on plain package installs and on the release-directory layout from #198835. The natural rate is about the race window divided by 30 s. #198835 measured that window at 1.75–1.88 s, which gives about 6% per run; I did not re-measure the window.

## Change

The update run is the one owner of the installation while it holds the install lease (the same `managed-update-handoffs` row the updater's executor takes). `checkGatewayInstallationReplacement` (`src/gateway/stale-install.ts`) now skips the self-restart while a live process holds that lease. A Gateway the run leaves stale restarts on a later check, after the lease is released.

- The lease key is captured with the installation root when the observer registers.
- Lease reads and process-identity probes are synchronous, so they run in the existing handoff worker (`prepareManagedHandoffParentStore`), never on the serving thread. They run only when a changed build is observed.
- An unreadable lease keeps today's behavior (self-restart).
- No new gate in the updater, no schema or config change.

## Impact

`--no-restart` updates with a running Gateway no longer race the update's Doctor and Gateway start. Behavior outside an update run is unchanged.

## Evidence

**Unit:** `src/gateway/stale-install.test.ts` › "leaves a replaced installation to the update run that holds it". It holds a real lease, checks that a changed build does not restart the Gateway, releases the lease, then checks that the next tick does restart it. Red on `2435c1faa791` (handoff called once while the lease is held), green on this head; the other 14 tests in the file pass.

**E2E (mbp-m5, real `openclaw update --no-restart` against a launchd Gateway, isolated `--profile`):** the reproduction makes the installation check fire every 250 ms in the *running* build. Only `server-maintenance` changes in a packed copy; the build ID differs, the code is otherwise identical. Each arm: install, start the Gateway service, then `update --no-restart --tag <next build>` with the Gateway running.

| Arm | Layout | Result | Update wall time |
|---|---|---|---|
| main `2435c1fa` | release dirs (`install-cli.sh` prefix, adopted) | **fail**: self-restart at T+0.25 s, `activated-gateway-startup-failed`, rolled back | 351 s |
| main `2435c1fa` | plain user npm prefix | **fail**: same | 455 s |
| this PR `d6f23896` | release dirs | **ok**, no self-restart signal, Gateway healthy on the new build | 133 s |
| this PR `d6f23896` | plain user npm prefix | **ok**, no self-restart signal, Gateway healthy on the new build | 188 s |

Gates: `pnpm tsgo:core`, `pnpm check:test-types`, oxlint and oxfmt on changed files all pass.

Local ClawSweeper review (gpt-6.1-sol, normal speed) at `d6f23896`: patch is correct, 0 findings. The previous head's single finding (synchronous lease reads on the Gateway thread) is fixed by the worker move.

Not covered: the missing-runtime-chunk path in `classifyGatewayStaleInstall` still restarts on a request failure during an in-place swap. That path triggers on a real load failure and was left as is.

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

Labels

cli CLI command changes docker Docker and sandbox tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants