Skip to content

Commit 7067009

Browse files
shanselmanCopilot
andcommitted
fix(setup): bind cleanup to live WSL registration
Co-authored-by: Copilot App <[email protected]>
1 parent 787db18 commit 7067009

10 files changed

Lines changed: 789 additions & 44 deletions

‎docs/ARCHITECTURE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ leading and trailing pipe. Columns, in order:
160160
| setup-shellescape-closed | closed | src/OpenClaw.SetupEngine/SetupSteps.cs | private ShellEscape helpers with divergent wrap semantics | WslShellQuoting | - | OpenClaw.SetupEngine builds WSL command lines only via WslShellQuoting; no local ShellEscape helper anywhere in the project | SetupStepsShellEscapeClosureTests.SetupEngine_DoesNotReintroduce_PrivateShellEscape | source-shape | when no file under src/OpenClaw.SetupEngine builds any WSL command strings |
161161
| setup-keepalive-process-manager | authoritative | src/OpenClaw.SetupEngine/SetupSteps.cs (StartKeepaliveStep) | setup-time WSL keepalive process discovery, start, marker read/write, command-line identity, and rollback cleanup | KeepaliveProcessManager (raw OS calls delegated to internal IKeepaliveProcessRuntime seam; StartKeepaliveStep is the only caller that reads SetupContext) | StartKeepaliveStep keeps Id/DisplayName and thin ExecuteAsync/RollbackAsync orchestration only | setup-time keepalive never hard-fails the pipeline on start failure (null PID or thrown exception both soft-fail identically); its marker path/JSON are the intentional handoff consumed by the tray keepalive service; rollback kills only wsl/wsl.exe processes whose command line matches this distro via WslCommandLineMatcher, leaves wrong-distro/unmatched command lines untouched, and deletes only its own marker/empty directory | KeepaliveProcessManagerTests.RollbackAsync_KillsOnlyMatchingDistroProcesses_LeavesOthersUntouched | behavioral | when StartKeepaliveStep contains no process/marker logic of its own |
162162
| 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 | - |
163-
| setup-managed-distro-ownership | authoritative | ExistingConfigDetector, CleanupStaleDistroStep, and CreateWslInstanceStep | durable ownership evidence parsing and marker lifecycle | ManagedDistroOwnership | detector and setup steps request ownership checks or scoped marker operations only | automatic cleanup unregisters or deletes same-named WSL data only with an exact managed registry binding, matching setup state, or a matching marker whose canonical path is the expected managed install path; exact UI or CLI destructive consent may override | SetupStepsTests.CleanupStaleDistro_PreservesUnownedRegisteredDistro | behavioral | - |
163+
| setup-managed-distro-ownership | authoritative | ExistingConfigDetector, CleanupStaleDistroStep, and CreateWslInstanceStep | durable ownership evidence parsing, current-user WSL registration binding, and marker lifecycle | ManagedDistroOwnership plus WindowsWslRegistrationInspector | detector and setup steps request ownership checks or scoped marker operations only | automatic unregister requires durable OpenClaw evidence plus exactly one readable current-user WSL registration whose canonical BasePath is the expected managed install path; automatic orphan-directory deletion requires a path-bound marker; missing, duplicate, malformed, unreadable, or mismatched registration metadata fails closed; exact UI or CLI destructive consent may override | SetupStepsTests.CleanupStaleDistro_PreservesUnownedRegisteredDistro | behavioral | - |
164164
| managed-local-provenance | authoritative | scattered connection, setup, browser, and reconnect call sites | implicit loopback trust and duplicated strong-credential listener checks | ManagedLocalGatewayPortProvenanceService | callers request inspection, authorization, or conflict repair only | unknown, incomplete, conflicting, or changed Windows listener ownership never receives strong credentials or destructive remediation; relayless ownership requires a complete empty Windows snapshot, expected-distro systemd MainPID proof, and immediate complete empty revalidation | ManagedLocalGatewayPortProvenanceServiceTests.InteractiveCredentialGate_ExpectedCacheThenOwnerChanges_FailsClosed | behavioral | - |
165165
| local-ai-gateway-distro-binding | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | hardcoded Local AI WSL distro selection | LocalAiGatewayDistroResolver | App loads the gateway registry and composes the resolver, provider coordinator, and runtime | the singleton Local AI installation binds to exactly one explicit setup-managed local no-SSH gateway record; its record ID and SetupManagedDistroName are pinned and revalidated before every WSL command, while missing, ambiguous, unavailable, or drifted ownership fails closed | LocalAiGatewayProviderCoordinatorTests.Quiesce_OwnerDriftsAfterInspection_BlocksFirstMutation | behavioral | - |
166166
| gateway-wizard-restart-recovery | authoritative | WizardPage + SetupWizardRunner reconnect call sites | duplicated exact-version terminal-restart classification and bounded provenance retry orchestration | GatewayWizardRestartRecoveryPolicy | WizardPage and SetupWizardRunner apply hosted and headless lifecycle and consume provenance inspection results | only managed-local restart-like disconnects may retry NoListener or the typed snapshot-changed race; other unknown or conflicting ownership fails immediately, retryable startup close 1013 stays inside the existing reconnect bound, and exact Gateway 2026.7.1 final model-check close 1012 completes only after a fresh hello-ok, and a terminal hosted-wizard payload completes on the exact TUI SIGTERM termination only when the request just sent answered the authoritative final done acknowledgement step | GatewayWizardRestartRecoveryPolicyTests.Exact2026_7_1TerminalModelCheckServiceRestart_IsExpected | behavioral | when the 2026.7.1 terminal-restart compatibility path is removed |

‎docs/ONBOARDING_WIZARD.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ The setup flow no longer configures remote/manual gateways inline. The Welcome p
2424
Displays the OpenClaw icon, app title, and a brief description. If an app-owned local WSL gateway already exists, the primary CTA reads **Install new WSL Gateway** and confirmation warns that the current OpenClaw WSL gateway and distro will be deleted. If only an external gateway exists, the CTA remains **Set up locally** and confirmation explains that the external connection remains available in Connections.
2525

2626
### Local setup progress
27-
Installs and connects a new app-owned `OpenClawGateway` WSL instance from a clean WSL baseline. Setup does not export from or mutate an existing user Ubuntu distro; if WSL cannot create the named app-owned distro directly, setup fails with an actionable update message. Cleanup automatically removes only a distro backed by durable OpenClaw setup or gateway-registry ownership evidence. An unproven same-named distro or leftover data directory is preserved unless the user explicitly confirms its permanent replacement in the setup UI or passes `--confirm-destructive`. When replacing an app-owned local gateway, the removal step is shown as part of progress and can be retried on failure.
27+
Installs and connects a new app-owned `OpenClawGateway` WSL instance from a clean WSL baseline. Setup does not export from or mutate an existing user Ubuntu distro; if WSL cannot create the named app-owned distro directly, setup fails with an actionable update message. Cleanup automatically unregisters a distro only when durable OpenClaw evidence is paired with exactly one readable current-user WSL registration whose canonical base path matches the expected managed install path. Automatic orphan-directory cleanup requires a marker bound to that exact path. An unproven same-named distro or leftover data directory is preserved unless the user explicitly confirms its permanent replacement in the setup UI or passes `--confirm-destructive`. When replacing an app-owned local gateway, the removal step is shown as part of progress and can be retried on failure.
2828

2929
The managed distro is locked down and is not intended to be a normal interactive Ubuntu profile. For editing `openclaw.json` as the `openclaw` user and using root for protected-file administration, see [Managing the locked-down WSL gateway](WSL_GATEWAY_ADMIN.md).
3030

‎docs/SETUP_ENGINE_REDESIGN.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ Executed sequentially. Each step is a small class (30–120 lines) in its own fi
179179
| 2 | `PreflightOsStep` | Validate Windows 64-bit, version ≥ 22H2 |
180180
| 3 | `PreflightWslStep` | Verify WSL is installed and supports direct named clean installs |
181181
| 4 | `PreflightWindowsTailscaleStep` | Validate optional Windows Tailscale prerequisites |
182-
| 5 | `CleanupStaleDistroStep` | Unregister leftover WSL distro and remove its VHD directory only when `CleanBeforeRun` is enabled and app ownership or explicit destructive confirmation is present |
182+
| 5 | `CleanupStaleDistroStep` | Unregister a leftover WSL distro only when durable app ownership and the live current-user registration base path agree, and remove an orphaned VHD directory automatically only with a path-bound marker; explicit destructive confirmation may override |
183183
| 6 | `CleanupStaleGatewayStep` | Stop orphaned gateway service, remove config |
184184
| 7 | `PreflightPortStep` | Check gateway port is available |
185185
| 8 | `CreateWslInstanceStep` | Directly install a fresh app-owned WSL distro; never export a user's Ubuntu distro |

‎src/OpenClaw.SetupEngine/CleanupStaleDistroStep.cs‎

Lines changed: 64 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,19 @@ namespace OpenClaw.SetupEngine;
1212

1313
public sealed class CleanupStaleDistroStep : SetupStep
1414
{
15+
private readonly IWslRegistrationInspector _registrationInspector;
16+
17+
public CleanupStaleDistroStep()
18+
: this(new WindowsWslRegistrationInspector())
19+
{
20+
}
21+
22+
internal CleanupStaleDistroStep(IWslRegistrationInspector registrationInspector)
23+
{
24+
_registrationInspector = registrationInspector ??
25+
throw new ArgumentNullException(nameof(registrationInspector));
26+
}
27+
1528
public override string Id => "cleanup-distro";
1629
public override string DisplayName => "Clean up stale WSL distro";
1730
public override bool CanRetry => false;
@@ -37,24 +50,27 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
3750
// Distro not registered, but disk directory may still exist from prior crash
3851
if (Directory.Exists(wslDir))
3952
{
40-
if (EnsureDestructiveCleanupAllowed(ctx, distro) is { } ownershipFailure)
53+
if (EnsureOrphanDirectoryCleanupAllowed(ctx, distro) is { } ownershipFailure)
4154
return ownershipFailure;
4255

4356
ctx.Logger.Info($"Removing orphaned WSL directory: {wslDir}");
4457
var delete = await DeleteDistroDirectoryWithRetries(ctx, distro, wslDir, ct);
4558
if (!delete.IsSuccess)
4659
return delete;
4760

48-
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro);
61+
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro, wslDir);
4962
}
5063
else
51-
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro);
64+
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro, wslDir);
5265

5366
ctx.Logger.Decision("No stale distro found", "skip cleanup");
5467
return StepResult.Ok("No stale distro to clean");
5568
}
5669

57-
if (EnsureDestructiveCleanupAllowed(ctx, distro) is { } distroOwnershipFailure)
70+
if (EnsureRegisteredDistroCleanupAllowed(
71+
ctx,
72+
distro,
73+
wslDir) is { } distroOwnershipFailure)
5874
return distroOwnershipFailure;
5975

6076
ctx.Logger.Decision($"Found existing distro '{distro}'", "terminating and unregistering");
@@ -79,7 +95,7 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
7995
if (!delete.IsSuccess)
8096
return delete;
8197

82-
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro);
98+
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro, wslDir);
8399

84100
// Wait for port to be released
85101
ctx.Logger.Info("Waiting for port release after distro termination...");
@@ -90,25 +106,59 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
90106
return StepResult.Fail($"Failed to unregister distro: {unregister.Stderr}");
91107
}
92108

93-
internal static StepResult? EnsureDestructiveCleanupAllowed(
109+
internal StepResult? EnsureRegisteredDistroCleanupAllowed(
110+
SetupContext ctx,
111+
string distroName,
112+
string expectedInstallPath)
113+
{
114+
if (HasExplicitDestructiveConsent(ctx, distroName))
115+
return null;
116+
117+
return ManagedDistroOwnership.HasRegisteredDistroEvidence(
118+
ctx.DataDir,
119+
ctx.LocalDataDir,
120+
distroName,
121+
expectedInstallPath,
122+
_registrationInspector,
123+
out var failure)
124+
? null
125+
: BuildOwnershipFailure(ctx, distroName, failure);
126+
}
127+
128+
internal static StepResult? EnsureOrphanDirectoryCleanupAllowed(
94129
SetupContext ctx,
95130
string distroName)
96131
{
97-
if (ctx.Config.ConfirmDestructive ||
98-
string.Equals(
99-
ctx.Config.ConfirmedDestructiveDistroName,
100-
distroName,
101-
StringComparison.OrdinalIgnoreCase) ||
102-
ManagedDistroOwnership.HasEvidence(
103-
ctx.DataDir,
132+
if (HasExplicitDestructiveConsent(ctx, distroName) ||
133+
ManagedDistroOwnership.HasPathBoundMarkerEvidence(
104134
ctx.LocalDataDir,
105135
distroName))
106136
{
107137
return null;
108138
}
109139

140+
return BuildOwnershipFailure(
141+
ctx,
142+
distroName,
143+
"No path-bound OpenClaw ownership marker matches the managed install path.");
144+
}
145+
146+
private static bool HasExplicitDestructiveConsent(
147+
SetupContext ctx,
148+
string distroName)
149+
=> ctx.Config.ConfirmDestructive ||
150+
string.Equals(
151+
ctx.Config.ConfirmedDestructiveDistroName,
152+
distroName,
153+
StringComparison.OrdinalIgnoreCase);
154+
155+
private static StepResult BuildOwnershipFailure(
156+
SetupContext ctx,
157+
string distroName,
158+
string? failure)
159+
{
110160
ctx.Logger.Decision(
111-
$"Existing WSL distro or data '{distroName}' is not proven app-owned",
161+
$"Existing WSL distro or data '{distroName}' is not proven app-owned: {failure}",
112162
"preserve existing data");
113163
var recovery = ctx.Config.Headless
114164
? "Rerun SetupEngine with --confirm-destructive to delete it."

‎src/OpenClaw.SetupEngine/CreateWslInstanceStep.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,10 @@ private static async Task<string> CleanupPartialInstall(SetupContext ctx, string
220220

221221
if (cleanupErrors.Count == 0)
222222
{
223-
ManagedDistroOwnership.DeleteMarker(ctx.LocalDataDir, distro);
223+
ManagedDistroOwnership.DeleteMarker(
224+
ctx.LocalDataDir,
225+
distro,
226+
installPath);
224227
return "";
225228
}
226229

‎src/OpenClaw.SetupEngine/DistroInstallPathPolicy.cs‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,68 @@ public static string WithLegacyReplacementGuidance(string? distroName, string er
9393
? $"{error} {LegacyReplacementGuidance}"
9494
: error;
9595

96+
internal static bool TryCanonicalizeAbsolutePath(
97+
string path,
98+
out string canonicalPath,
99+
out string error)
100+
{
101+
canonicalPath = "";
102+
if (string.IsNullOrWhiteSpace(path))
103+
{
104+
error = "Path is required.";
105+
return false;
106+
}
107+
108+
var candidate = path;
109+
const string extendedUncPrefix = @"\\?\UNC\";
110+
const string extendedPathPrefix = @"\\?\";
111+
if (candidate.StartsWith(extendedUncPrefix, StringComparison.OrdinalIgnoreCase))
112+
{
113+
candidate = @"\\" + candidate[extendedUncPrefix.Length..];
114+
}
115+
else if (candidate.StartsWith(extendedPathPrefix, StringComparison.OrdinalIgnoreCase))
116+
{
117+
var unprefixed = candidate[extendedPathPrefix.Length..];
118+
if (unprefixed.Length < 3 ||
119+
!char.IsAsciiLetter(unprefixed[0]) ||
120+
unprefixed[1] != ':' ||
121+
unprefixed[2] is not ('\\' or '/'))
122+
{
123+
error = "Only rooted drive or UNC paths are supported.";
124+
return false;
125+
}
126+
127+
candidate = unprefixed;
128+
}
129+
130+
try
131+
{
132+
if (!Path.IsPathFullyQualified(candidate))
133+
{
134+
error = "Path must be fully qualified.";
135+
return false;
136+
}
137+
138+
canonicalPath = NormalizePath(candidate);
139+
error = "";
140+
return true;
141+
}
142+
catch (Exception ex) when (
143+
ex is IOException
144+
or ArgumentException
145+
or NotSupportedException
146+
or PathTooLongException)
147+
{
148+
error = $"Invalid path: {ex.Message}";
149+
return false;
150+
}
151+
}
152+
153+
internal static bool PathsReferToSameLocation(string left, string right)
154+
=> TryCanonicalizeAbsolutePath(left, out var canonicalLeft, out _) &&
155+
TryCanonicalizeAbsolutePath(right, out var canonicalRight, out _) &&
156+
PathEquals(canonicalLeft, canonicalRight);
157+
96158
public static bool TryValidateDeleteTarget(
97159
string localDataDir,
98160
string? distroName,

‎src/OpenClaw.SetupEngine/ExistingConfigDetector.cs‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,18 @@ public static ExistingConfig Detect(
4848
out var distroDataDirectory,
4949
out _) &&
5050
Directory.Exists(distroDataDirectory);
51-
var distroIsAppOwned =
52-
(hasDistro || hasDistroDataDirectory) &&
53-
ManagedDistroOwnership.HasEvidence(dataDir, localDataDir, targetDistroName);
51+
var distroIsAppOwned = hasDistro
52+
? ManagedDistroOwnership.HasRegisteredDistroEvidence(
53+
dataDir,
54+
localDataDir,
55+
targetDistroName,
56+
distroDataDirectory,
57+
new WindowsWslRegistrationInspector(),
58+
out _)
59+
: hasDistroDataDirectory &&
60+
ManagedDistroOwnership.HasPathBoundMarkerEvidence(
61+
localDataDir,
62+
targetDistroName);
5463

5564
var hasIdentity = false;
5665
if (localRecord != null)

0 commit comments

Comments
 (0)