Skip to content

fix(state): leave Git release installations out of the startup upgrade copy - #199770

Closed
obviyus wants to merge 1 commit into
mainfrom
fix/state-upgrade-skip-managed-roots
Closed

obviyus wants to merge 1 commit into
mainfrom
fix/state-upgrade-skip-managed-roots

Conversation

@obviyus

@obviyus obviyus commented Nov 15, 2026

Copy link
Copy Markdown
Collaborator

Problem

The startup state upgrade from #198389 copies the whole state directory into a private shadow, skipping only work directories, locks/, tmp/ and configured workspaces. #199706 puts Git release installations under <stateDir>/git-install/releases/<id>/: full worktrees with node_modules and dist. Every schema-changing start would copy each retained release before serving. On filesystems without clone support it would also duplicate their bytes, which can exhaust disk during startup.

Change

upgradeStateDirectory skips the top-level git-install directory, as it already skips tmp and locks. Release installations are code, never state.

Evidence

src/state/state-upgrade.test.ts adds "leaves Git release installations out of the private copy". It upgrades the populated 2026.10.10 corpus with a release tree present and asserts the shadow has no git-install and the release file is untouched. The test is red without the skip (the shadow contains it).

Needed by #199706 (ClawSweeper finding on 665e0d64). It is safe to land on its own: today no such directory exists, so behavior is unchanged.

@clawsweeper

clawsweeper Bot commented Nov 15, 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Exclude the top-level git-install directory from startup state copying and generation cleanup.

Example: A schema-changing startup finds state/git-install/releases/r1/package.json beside older state databases.

  • Before: The private upgrade copy includes the retained release tree.
  • After: The upgrade skips git-install and leaves the original release files in place.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The patch is focused and source-correct, but required shipped-entry-point evidence for the changed startup behavior is absent.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Schema-changing startup would traverse and potentially duplicate retained Git installations before the Gateway can serve.
Reason: The maintainer-authored direction preserves the existing separation between code and state with one focused exclusion.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR provides a focused prerequisite for the linked Git-release work, and current main still copies that directory; no introduced code defect was found.

Priority: P2
Reviewed head: f20620c5ad1ba43d94f1e9547303a5c11b5e386e

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Provide redacted Gateway-startup output for an upgrade from v2026.11.3 state with a retained git-install release, showing readiness, preserved settings/data and release files, and exclusion from the private copy.
Agent review details

How this fits together

Gateway bootstrap acquires exclusive state ownership, copies outdated state into a shadow, runs migration or fallback rebuilding, and publishes changed files through a durable swap plan.

flowchart TD
  A[Gateway startup] --> B[Exclusive state ownership]
  B --> C[Copy state with exclusions]
  C --> D[Shadow migration or rebuild]
  D --> E[Validate and swap changed files]
  E --> F[Prune old generations]
  C --> G[Leave Git installations untouched]
Loading

Technical review

Best possible solution:

Keep the exclusion in the existing shared skip predicate so state upgrades leave managed Git installations untouched.

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

Source inspection establishes that a git-install tree beside outdated databases reaches recursive copying on current main; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The existing upgrade owner’s exclusion predicate is the smallest complete fix, and the single added regression covers a distinct filesystem failure without new production machinery.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Startup state-copy and retention exclusions keeps the original intent (ef930eb: Upgrade outdated state privately while preserving live files, and avoid pulling package code into the shadow through installation links.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit ef930eb adds src/state/state-upgrade.ts:373 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ef930ebbad77; files: src/state/state-upgrade.ts)

PR surface

Source +2, Tests +26. Total +28 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 2 0 +2
Tests 1 26 0 +26
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 28 0 +28

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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This prevents unnecessary release-tree copying and potential disk exhaustion when the linked Git-release feature encounters a schema-changing startup.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 15, 2026, 4:55 PM ET / 21:55 UTC.

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
…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]>
@obviyus

obviyus commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #205165 (merged as e43debf). Startup no longer copies the state directory into a shadow tree: state upgrades now run in place, and state-upgrade-tree.ts is deleted. Retained Git release directories are therefore no longer copied at startup, which was this PR's goal.

@obviyus obviyus closed this Nov 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XS status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant