Skip to content

Commit 29bb8ad

Browse files
committed
feat: update Companion-owned Gateway safely in place
1 parent 19145d0 commit 29bb8ad

57 files changed

Lines changed: 12483 additions & 135 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/ci.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ jobs:
3232
timeout-minutes: 45
3333
outputs:
3434
sha256: ${{ steps.package.outputs.sha256 }}
35+
version: ${{ steps.package.outputs.version }}
3536
steps:
3637
- name: Fail if repo hygiene failed
3738
if: ${{ needs.repo-hygiene.result != 'success' }}
@@ -141,6 +142,7 @@ jobs:
141142
"$wizard_base" \
142143
"$sha256"
143144
echo "sha256=$sha256" >>"$GITHUB_OUTPUT"
145+
echo "version=$packaged_version" >>"$GITHUB_OUTPUT"
144146
145147
- name: Upload composed gateway package
146148
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
@@ -578,7 +580,7 @@ jobs:
578580
env:
579581
OPENCLAW_RUN_E2E: 1
580582
OPENCLAW_E2E_GATEWAY_SOURCE: ${{ matrix.gateway_source }}
581-
OPENCLAW_E2E_GATEWAY_VERSION: ${{ matrix.gateway_version }}
583+
OPENCLAW_E2E_GATEWAY_VERSION: ${{ matrix.gateway_source == 'composed' && needs.gateway-composed.outputs.version || matrix.gateway_version }}
582584
OPENCLAW_E2E_GATEWAY_PACKAGE_SPEC: ${{ matrix.gateway_source == 'composed' && steps.gateway_package_host.outputs.package_spec || '' }}
583585
OPENCLAW_E2E_GATEWAY_PACKAGE_SHA256: ${{ matrix.gateway_source == 'composed' && steps.gateway_package_host.outputs.package_sha256 || '' }}
584586
OPENCLAW_E2E_GATEWAY_PACKAGE_HOST_DISTRO: ${{ matrix.gateway_source == 'composed' && steps.gateway_package_host.outputs.distro_name || '' }}

‎.github/workflows/gateway-lkg-update.yml‎

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,43 @@ jobs:
3030
run: |
3131
pinned="$(python3 - <<'PY'
3232
import pathlib, re
33-
source = pathlib.Path("src/OpenClaw.SetupEngine/GatewayLkgVersion.cs").read_text(encoding="utf-8")
34-
match = re.search(r'LkgVersion\s*=\s*"([^"]+)"', source)
35-
if not match:
33+
lkg_path = pathlib.Path("src/OpenClaw.SetupEngine/GatewayLkgVersion.cs")
34+
metadata_path = pathlib.Path("src/OpenClaw.Shared/OpenClaw.Shared.csproj")
35+
lkg_test_path = pathlib.Path("tests/OpenClaw.SetupEngine.Tests/GatewayLkgVersionTests.cs")
36+
target_test_path = pathlib.Path("tests/OpenClaw.Connection.Tests/GatewayPackageTargetTests.cs")
37+
lkg_match = re.search(r'LkgVersion\s*=\s*"([^"]+)"', lkg_path.read_text(encoding="utf-8"))
38+
metadata_match = re.search(
39+
r'<OpenClawGatewayPackageExpectedVersion[^>]*>([^<]+)</OpenClawGatewayPackageExpectedVersion>',
40+
metadata_path.read_text(encoding="utf-8"),
41+
)
42+
lkg_test_match = re.search(
43+
r'ExpectedLkgVersion\s*=\s*"([^"]+)"',
44+
lkg_test_path.read_text(encoding="utf-8"),
45+
)
46+
target_test_match = re.search(
47+
r'BuildTargetResolver_UsesOrdinaryUpstreamAssemblyDefault\(\).*?'
48+
r'Assert\.Equal\("([^"]+)", target\.ExpectedVersion\);',
49+
target_test_path.read_text(encoding="utf-8"),
50+
re.DOTALL,
51+
)
52+
if not lkg_match:
3653
raise SystemExit("Could not parse LkgVersion constant from GatewayLkgVersion.cs")
37-
pinned = match.group(1)
54+
if not metadata_match:
55+
raise SystemExit("Could not parse OpenClawGatewayPackageExpectedVersion from OpenClaw.Shared.csproj")
56+
if not lkg_test_match:
57+
raise SystemExit("Could not parse ExpectedLkgVersion from GatewayLkgVersionTests.cs")
58+
if not target_test_match:
59+
raise SystemExit("Could not parse ordinary upstream target version assertion")
60+
pinned = lkg_match.group(1)
61+
metadata_version = metadata_match.group(1)
62+
lkg_test_version = lkg_test_match.group(1)
63+
target_test_version = target_test_match.group(1)
64+
if metadata_version != pinned or lkg_test_version != pinned or target_test_version != pinned:
65+
raise SystemExit(
66+
"Gateway package defaults disagree: "
67+
f"LkgVersion={pinned}, metadata={metadata_version}, "
68+
f"lkg-test={lkg_test_version}, target-test={target_test_version}"
69+
)
3870
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', pinned):
3971
raise SystemExit(f"Pinned LkgVersion must be an exact stable version: {pinned}")
4072
print(pinned)
@@ -101,6 +133,17 @@ jobs:
101133
r'(ExpectedLkgVersion\s*=\s*")([^"]+)(")',
102134
"ExpectedLkgVersion constant",
103135
),
136+
(
137+
pathlib.Path("src/OpenClaw.Shared/OpenClaw.Shared.csproj"),
138+
r'(<OpenClawGatewayPackageExpectedVersion[^>]*>)([^<]+)(</OpenClawGatewayPackageExpectedVersion>)',
139+
"OpenClawGatewayPackageExpectedVersion",
140+
),
141+
(
142+
pathlib.Path("tests/OpenClaw.Connection.Tests/GatewayPackageTargetTests.cs"),
143+
r'(?s)(BuildTargetResolver_UsesOrdinaryUpstreamAssemblyDefault\(\).*?'
144+
r'Assert\.Equal\(")([^"]+)(", target\.ExpectedVersion\);)',
145+
"ordinary upstream target assertion",
146+
),
104147
)
105148
for path, pattern, label in replacements:
106149
source = path.read_text(encoding="utf-8")
@@ -121,6 +164,8 @@ jobs:
121164
run: |
122165
update_paths=(
123166
src/OpenClaw.SetupEngine/GatewayLkgVersion.cs
167+
src/OpenClaw.Shared/OpenClaw.Shared.csproj
168+
tests/OpenClaw.Connection.Tests/GatewayPackageTargetTests.cs
124169
tests/OpenClaw.SetupEngine.Tests/GatewayLkgVersionTests.cs
125170
)
126171
if git diff --quiet -- "${update_paths[@]}"; then
@@ -147,7 +192,7 @@ jobs:
147192
148193
- Previous pinned LKG: \`${{ steps.versions.outputs.pinned }}\`
149194
- Candidate latest: \`${{ steps.versions.outputs.latest }}\`
150-
- Updated files: LKG source and its contract test
195+
- Updated files: LKG source, package metadata, and both LKG contract tests
151196
152197
The automation only proposes exact stable versions newer than the current pin.
153198

‎docs/ARCHITECTURE.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ leading and trailing pipe. Columns, in order:
117117
| wsl-posix-quoting | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | ad hoc ShellEscape with divergent wrap semantics | WslShellQuoting | - | WSL command lines use POSIX single-quote quoting via WslShellQuoting not cmd/PowerShell quoting | WslShellQuotingTests.QuotePosixSingleQuote_WrapsAndEscapesEmbeddedQuote | behavioral | when no code builds WSL command lines outside WslShellQuoting |
118118
| setup-shellescape-closed | closed | src/OpenClaw.SetupEngine/SetupSteps.cs | private ShellEscape helpers with divergent wrap semantics | WslShellQuoting | - | SetupSteps builds WSL command lines only via WslShellQuoting; no local ShellEscape helper | SetupStepsShellEscapeClosureTests.SetupSteps_DoesNotReintroduce_PrivateShellEscape | source-shape | when SetupSteps.cs no longer builds any WSL command strings |
119119
| wsl-distro-install-path | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | inline Path.Combine wsl distro install-path derivation | DistroInstallPathPolicy | - | new installs use the strict supported name grammar; teardown accepts only unambiguous single-segment names whose canonical path is an immediate child of LocalDataDir\wsl with no aliases, case or Unicode collisions, or reparse points at the root or child | SetupStepsTests.DistroInstallPathPolicy_ResolvesImmediateChild | behavioral | - |
120+
| gateway-version-alignment | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | local WSL version probe, pinned update transaction, and recovery result policy | OpenClaw.Connection/GatewayVersionAlignmentCoordinator | App composes the service and presents confirmation/results only | normal update never unregisters/imports; exact package version, verified protection point, and Gateway/Node/pairing health gate completion | GatewayVersionAlignmentCoordinatorTests.UpdateAsync_DefaultNativeProtectionCompletesHealthyTransaction | behavioral | - |
121+
| gateway-rollback-points | authoritative | none | native backup protection by default; opt-in offline VHD export; manifest receipts, retention, verification, and explicit VHD emergency restore | OpenClaw.Connection/GatewayRollbackPointManager | SettingsPage owns selection and confirmation UI only | native backups preserve portable recovery material without stopping the distro; only immutable verified FullVhd points permit unregister/import-in-place restore; direct ext4.vhdx replacement is forbidden | GatewayVersionAlignmentCoordinatorTests.RestoreAsync_RecreatesOnlyRegistrationThenProvesVersionIdentityAndSynchronization | behavioral | - |
120122
| app-window-manager | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | window creation/show/hide/shutdown | IWindowManager | composition/delegation only | startup/shutdown ordering deterministic; disposed once | none | review-only | extracted in Phase 3 |
121123
| app-tray-controller | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | tray icon/menu/action routing | ITrayController | composition/delegation only | tray actions route unchanged | none | review-only | extracted in Phase 3 |
122124
| app-activation-router | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | deep-link/toast/single-instance activation | IActivationRouter | composition/delegation only | activation routes land on the same UI/actions; current-user pipe security preserved | none | review-only | extracted in Phase 3 |

‎docs/CONNECTION_ARCHITECTURE.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,39 @@ Settings changes are classified by `SettingsChangeClassifier.Classify()` which c
105105
| `OperatorReconnectRequired` | Reconnect operator (SSH tunnel changed) |
106106
| `FullReconnectRequired` | Full tear down and reconnect (gateway URL changed) |
107107

108+
## Companion-owned Gateway update and rollback
109+
110+
`GatewayVersionAlignmentCoordinator` resolves one immutable `GatewayPackageTarget` for the process: package source (`Official` or `Composed`), exact expected version, optional credential-free HTTP(S) `.tgz` URI, and SHA-256. The target is embedded as shared-assembly build metadata. Ordinary upstream builds resolve to the repository's Official `2026.7.1` LKG; a composed build must supply all composed-package fields without placing a private URI or digest in source.
111+
112+
Update routing is a pure, immutable two-lane decision made before package dispatch:
113+
114+
- **Companion installer lane:** every installed version at or below `2026.7.2` (including prereleases and older versions), every unproven source version, and every composed target. Official targets use the upstream TLS-fetched installer pinned to the exact required version; this path does not claim an artifact-digest guarantee. Composed targets carry an immutable package URI and SHA-256, and verify that package before invoking the installer. Both forms send zero `update.run` or `update.complete` RPCs and remain protected by a verified protection point plus exact post-update version verification. Sources older than `2026.7.2` predate the native backup contract and therefore use Full VHD protection even when the default preference is native backup.
115+
- **Core transaction lane:** only an official target from an explicitly audited future installed version. This lane sends one `update.run`, retains the accepted Core transaction provenance, and later sends `update.complete`.
116+
117+
Both lanes share the same rollback and exact-version gates. A normal update:
118+
119+
1. proves the active gateway is the setup-managed WSL gateway;
120+
2. proves current Gateway, Companion, Windows Node, and pairing health;
121+
3. asks `GatewayRollbackPointManager` to create a verified native OpenClaw backup by default, without stopping the distro; an explicitly selected `FullVhd` mode first proves host capacity, then terminates only that distro and exports a complete offline VHD;
122+
4. verifies the selected artifact's byte size, SHA-256, private manifest receipt, distro machine identity, and exact OpenClaw version (including build metadata); `FullVhd` additionally verifies the VHDX signature and repeats identity/version attestation after export;
123+
5. durably records the immutable target, selected route, and `Prepared` dispatch state before crossing either dispatch boundary;
124+
6. dispatches exactly once through the selected lane; Core records `Ambiguous` if the RPC result is not trusted or `Accepted` with the original request ID, transaction ID, and confirmation deadline, while the Companion lane records `Accepted` after installer dispatch returns;
125+
7. verifies the exact installed version, resynchronizes Gateway, Companion, Windows Node, and pairing, and re-verifies the rollback point plus live distro identity;
126+
8. for an accepted Core transaction only, calls `update.complete` with the persisted transaction ID and original request ID, outcome `healthy` plus the observed exact version, or outcome `failed` plus the actually observed exact version when a valid probe result is available; and
127+
9. marks the local update healthy, re-attests the live distro immediately before cleanup, and only then applies retention.
128+
129+
Normal update never unregisters, imports, recreates, or directly replaces the distro's `ext4.vhdx`. The verified protection point remains the fail-closed recovery boundary until the update is healthy. A native backup is created in the distro and streamed by `wsl.exe` to a host-owned partial file before hash verification and atomic promotion; it does not depend on disabled WSL drive automounts. A native backup is portable recovery material but is not Companion-restoreable; only an explicitly selected verified `FullVhd` point supports the emergency restore operation below. Any durable `Prepared`, `Ambiguous`, or `Accepted` dispatch receipt blocks a second package dispatch and blocks cross-lane fallback. `Prepared` is deliberately treated as possibly dispatched; it is not permission to retry. `Ambiguous` requires explicit recovery. An accepted Core receipt may resume finalization after process restart only from its persisted request ID, transaction ID, and deadline; it never sends a second `update.run`. An accepted Companion-installer receipt likewise never falls through to Core or repeats the installer. Pending-update discovery is scoped to the fixed Companion-owned distro rather than the mutable Gateway record ID; a receipt belonging to an earlier record or a different immutable target blocks for explicit recovery.
130+
131+
Settings resolves a pending native-backup receipt without pretending to restore it. The operator confirms the exact point, Companion re-verifies the retained backup and probes the live distro, then accepts only the exact recorded source or target version. Recovery ownership follows the fixed Companion-owned distro and exact receipt, so replacement of the mutable Gateway registry record does not strand historical recovery. The source path must also pass distro identity plus Gateway, Windows Node, and pairing synchronization before the receipt becomes `RecoveryResolved`; accepted Core transactions are completed with the observed failed/source outcome first, while the target path re-enters normal post-update finalization with its persisted dispatch provenance. Any third version, identity drift, missing provenance, Core completion failure, or health failure preserves the blocking receipt.
132+
133+
Immediately after the durable receipt write and before dispatch, and again before Core healthy completion or retention cleanup, canonical registration BasePath, machine identity, WSL registration configuration, effective default user, and the expected exact normalized package version must still match the receipt and observed transaction state. Exact equality is ordinal and includes prerelease and build metadata. Ordered numeric build identifiers such as `companion.3` are compared without discarding metadata; differing metadata that cannot be safely ordered blocks instead of guessing. Concurrent drift, including a newer observed package, preserves the receipt and never triggers a downgrade.
134+
135+
Privileged `update.run` and `update.complete` dispatch is bound to the expected Gateway record and fails closed if the live active-connection identity changes before send. Caller cancellation flows through the long-running correlated RPC wait, removes pending correlation state, releases the coordinator operation gate, and leaves the durable `UpdateInProgress` rollback receipt intact.
136+
137+
Emergency restore is a separate confirmed operation available only for a verified `FullVhd` point. It copies the immutable retained VHD through a private `.partial` staging file, flushes and verifies it before promotion, and safely recreates stale or invalid regular staging files from the immutable point before any destructive WSL lifecycle call. Before unregister, it verifies the same-name WSL registry entry maps to the canonical app-owned `BasePath`, the directory contains only its regular `ext4.vhdx`, and no owned path boundary is a reparse point; it repeats host-side validation after termination and revalidates registration absence/path safety before import. It may then unregister the current Companion-owned distro, move the verified staged copy into the canonical app-owned install directory, and use documented `wsl --import-in-place` under the same distro name. The retained rollback VHD never becomes the mutable live disk. Manifest receipts independently capture the supported WSL registration version/default UID/flags and the effective default username/UID selected inside the distro on both sides of export; `/etc/wsl.conf` may make those UID values differ. Receipt writes use write-through and disk flush before `UnregisterPending` and `ImportPending` lifecycle transitions. Across the entire Companion-owned distro, regardless of a later Gateway record-id change, a receipt in `RestoreStaged`, `UnregisterPending`, `DistroUnregistered`, `ImportPending`, or `Imported` blocks both the app-level package probe and every fresh update. Multiple unresolved restore receipts fail as ambiguous. Only `RestoreStaged` may be durably cancelled as `RestoreCancelled`; Settings exposes that exact-point-confirmed non-destructive exit. After the unregister boundary, recovery must resume the same point, and `Imported` remains blocking until full synchronization plus a final exact live attestation records `RestoreHealthy`. Once a receipt reaches the unregister boundary, later probe/preflight failures preserve that monotonic phase rather than degrading it to a generic failure that could repeat lifecycle operations. After import, the supported WSL configuration API restores the recorded registration UID/flags and readback must match before the internal machine identity and independently recorded effective default user are accepted. Durable phases support retry after unregister or failed import; a same-name distro with a different internal machine identity, mismatched registration/default user, or any registration/install-path collision fails closed.
138+
139+
Retention keeps at least the newest verified known-good point. The default keeps one previous verified point plus every point younger than seven days. Settings also allow two previous versions or indefinite retention, and the age window remains additive to the count floor. Points are cleanup-eligible only after successful post-update or post-restore health. Unresolved update or restore receipts retain their artifacts even if a later verification fails, so cleanup cannot destroy the evidence required to diagnose or resolve the blocking receipt.
140+
108141
## Connection state machine
109142

110143
`ConnectionStateMachine` (internal) drives state transitions for both operator and node roles:

0 commit comments

Comments
 (0)