From c1df178274545c81b59020f23f3f23394083d00a Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 6 Nov 2026 17:32:02 -0800 Subject: [PATCH 1/6] fix(setup): clean uninstall leaves a Gateway cleanup task running clean-uninstall.ps1 only matched the startup tasks, so Companion's per-user Gateway cleanup task and its folder survived a full cleanup. The armed task could also unregister a WSL distro the plan said it would preserve, and deleting the leftover folder by hand orphaned the task for good. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/uninstall/HARD-CLEAN.md | 7 ++ scripts/clean-uninstall.ps1 | 101 ++++++++++++++++++++--- scripts/test-clean-uninstall.ps1 | 107 +++++++++++++++++++++++++ 3 files changed, 203 insertions(+), 12 deletions(-) diff --git a/.agents/skills/uninstall/HARD-CLEAN.md b/.agents/skills/uninstall/HARD-CLEAN.md index 4c85f6d1e5..a8d15e6a15 100644 --- a/.agents/skills/uninstall/HARD-CLEAN.md +++ b/.agents/skills/uninstall/HARD-CLEAN.md @@ -226,6 +226,12 @@ and reparse-point paths remain unsupported. Remove an out-of-scope portable/worktree instance's startup registration through that instance before cleanup; matching a startup name alone does not authorize the script to change another instance's registration. +Gateway cleanup tasks are removed after native teardown and before package +removal, because an armed task reacts to package removal and could unregister a +WSL distro the plan preserves. Their folders are deleted afterwards. Do not +delete a cleanup folder while its task is registered: the task can no longer run +or unregister itself, and tasks that start PowerShell directly keep opening a +console every minute. Already-uninstalled native packages with orphan `session.json` records need the matching package repaired/reinstalled for supported teardown. The script does not @@ -304,6 +310,7 @@ size if relevant, and preserve/remove decision. Include: | Local AI | Each selected local profile's `LocalAI\state.json`, runtime, downloads, logs, legacy models, active cached model, and additional assets. | | Isolated profiles | Paths printed by launchers or explicitly supplied by the user, including selected children of `%TEMP%\OpenClawTray` or a session's `files` directory. Never discover targets by recursively sweeping all sessions. | | Startup | Exact Run values `OpenClawTray` / `OpenClawTray-Dev`; tasks `OpenClaw Companion` / `OpenClaw Companion (Dev)`. Verify task action and principal. Inventory services without deleting by name prefix. | +| Gateway cleanup | Per-user tasks `OpenClaw Gateway cleanup - - ` and `%USERPROFILE%\.openclaw-companion\cleanup\`. Verify the task's action and principal. Dev families need `-IncludeDev`. | | WSL | Exact distro names and whether any target is in use. Native teardown does not imply WSL removal. | | Test leftovers | `OpenClawTrayTest`, `OpenClawTests`, and HKCU `Software\OpenClawTests` / `Software\OpenClawDetectorTests` only if specifically identified and included. | diff --git a/scripts/clean-uninstall.ps1 b/scripts/clean-uninstall.ps1 index 392df06404..4be89513e1 100644 --- a/scripts/clean-uninstall.ps1 +++ b/scripts/clean-uninstall.ps1 @@ -5,7 +5,8 @@ Standalone, current-user OpenClaw cleanup for demo/test devices. Dry-run by default. .DESCRIPTION Preview first, then repeat with -ConfirmDestructive. Removes release Companion - and native Gateway packages, supported Inno installs, and ordinary app profiles. + and native Gateway packages, supported Inno installs, ordinary app profiles, and + Companion's per-user Gateway cleanup tasks and their files. Runs native MXC teardown BEFORE removing the Gateway package. No build, Copilot, Python, or repository dependencies. Use Windows PowerShell as the affected user. @@ -570,6 +571,15 @@ function Assert-CleanStartupExecutable([string]$Executable, [string[]]$OwnedRoot throw "Startup executable is outside selected ownership roots: $path" } +function Get-CleanTaskPrincipalSid($Task) { + $principal = $Task.Principal.UserId + if ([string]::IsNullOrWhiteSpace($principal)) { throw 'Startup task has no identifiable principal.' } + if ($principal -notmatch '^S-1-') { + $principal = ([Security.Principal.NTAccount]$principal).Translate([Security.Principal.SecurityIdentifier]).Value + } + return $principal +} + function Get-CleanStartup([bool]$Dev, [string[]]$OwnedRoots) { $runKey = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Run' $names = @('OpenClawTray') @@ -591,11 +601,7 @@ function Get-CleanStartup([bool]$Dev, [string[]]$OwnedRoots) { } $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value foreach ($task in Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -in $taskNames }) { - $principal = $task.Principal.UserId - if ([string]::IsNullOrWhiteSpace($principal)) { throw 'Startup task has no identifiable principal.' } - if ($principal -notmatch '^S-1-') { - $principal = ([Security.Principal.NTAccount]$principal).Translate([Security.Principal.SecurityIdentifier]).Value - } + $principal = Get-CleanTaskPrincipalSid $task $actions = @($task.Actions) if ($principal -ne $sid -or $actions.Count -ne 1 -or $task.TaskPath -ne '\') { throw "Startup task has unexpected ownership. Inspect it manually: $($task.TaskPath)$($task.TaskName)" @@ -605,6 +611,70 @@ function Get-CleanStartup([bool]$Dev, [string[]]$OwnedRoots) { } } +function Get-CleanGatewayCleanupRoot { + return Join-Path $env:USERPROFILE '.openclaw-companion\cleanup' +} + +function Test-CleanCompanionFamily([string]$Family, [bool]$Dev) { + if ($Family -cmatch '^OpenClawFoundation\.OpenClaw\.Dev_[a-z0-9]{13}$') { return $Dev } + return $Family -cmatch '^OpenClawFoundation\.OpenClaw_[a-z0-9]{13}$' +} + +function Get-CleanGatewayCleanupProfiles([bool]$Dev) { + $root = Get-CleanGatewayCleanupRoot + if (-not (Test-Path -LiteralPath $root)) { return } + Get-ChildItem -LiteralPath $root -Directory -Force | + Where-Object { Test-CleanCompanionFamily $_.Name $Dev } | + ForEach-Object { $_.FullName } +} + +# Selection never depends on the task's files. A task whose folder is gone can only be removed here. +function Get-CleanGatewayCleanupTasks([bool]$Dev) { + $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $prefix = "OpenClaw Gateway cleanup - $sid - " + $root = Get-CleanGatewayCleanupRoot + $powershell = Get-CleanFullPath (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe') + foreach ($task in Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName.StartsWith($prefix, [StringComparison]::Ordinal) }) { + $family = $task.TaskName.Substring($prefix.Length) + if (-not (Test-CleanCompanionFamily $family $Dev)) { continue } + $directory = Get-CleanFullPath (Join-Path $root $family) + $actions = @($task.Actions) + $hosted = $false + $legacy = $false + if ($actions.Count -eq 1 -and -not [string]::IsNullOrWhiteSpace($actions[0].Execute)) { + $execute = Get-CleanFullPath ([string]$actions[0].Execute).Trim('"') + $arguments = [string]$actions[0].Arguments + $hosted = (Split-Path -Parent $execute) -ieq $directory -and + (Split-Path -Leaf $execute) -match '^cleanup-host-[0-9A-Fa-f]{64}\.exe$' -and $arguments -ceq $family + # Companion releases before the windowless host registered PowerShell directly. + $legacy = $execute -ieq $powershell -and + $arguments.EndsWith("-File `"$directory\cleanup.ps1`" -Family $family", [StringComparison]::OrdinalIgnoreCase) + } + if ((Get-CleanTaskPrincipalSid $task) -ne $sid -or $task.TaskPath -ne '\' -or -not ($hosted -or $legacy)) { + throw "Gateway cleanup task has unexpected ownership. Inspect it manually: $($task.TaskPath)$($task.TaskName)" + } + [pscustomobject]@{ Kind = 'Task'; Name = $task.TaskName; Key = $task.TaskPath; Value = (Export-ScheduledTask -InputObject $task) } + } +} + +function Remove-CleanTask($Entry) { + $task = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -eq $Entry.Name -and $_.TaskPath -eq $Entry.Key }) + if ($task.Count -gt 0) { + if ((Export-ScheduledTask -InputObject $task[0]) -ne $Entry.Value) { throw "Startup task changed: $($Entry.Name)" } + Unregister-ScheduledTask -InputObject $task[0] -Confirm:$false -ErrorAction Stop + } +} + +function Remove-CleanEmptyGatewayCleanupRoots { + $root = Get-CleanGatewayCleanupRoot + foreach ($path in @($root, (Split-Path -Parent $root))) { + $full = Assert-CleanPath $path + if ((Test-Path -LiteralPath $full) -and -not @(Get-ChildItem -LiteralPath $full -Force).Count) { + Remove-Item -LiteralPath $full -Force -ErrorAction Stop + } + } +} + function Get-CleanSha256([string]$Text) { $sha = [Security.Cryptography.SHA256]::Create() try { @@ -890,6 +960,7 @@ function Invoke-OpenClawClean { $profiles += Join-Path $root 'OpenClawTray' if ($Dev) { $profiles += Join-Path $root 'OpenClawTray-Dev' } } + $profiles += @(Get-CleanGatewayCleanupProfiles $Dev) $profiles += $Extra foreach ($extraPath in $Extra) { $extraFull = Assert-CleanPath $extraPath @@ -934,6 +1005,7 @@ function Invoke-OpenClawClean { if ($Models) { $modelsToRemove = @(Get-CleanModels $files | Sort-Object Path -Unique) } $processes = @(Get-CleanProcesses $ownedRoots) $startup = @(Get-CleanStartup $Dev $ownedRoots) + $cleanupTasks = @(Get-CleanGatewayCleanupTasks $Dev) $gateways = @($packages | Where-Object { $_.Name -in @('OpenClawFoundation.OpenClawGateway','OpenClaw.Gateway') }) foreach ($gateway in $gateways) { $alias = Join-Path $env:LOCALAPPDATA "Microsoft\WindowsApps\$($gateway.PackageFamilyName)\clawctl.exe" @@ -953,7 +1025,11 @@ function Invoke-OpenClawClean { } foreach ($model in $modelsToRemove) { Write-Host "REMOVE shared model: $($model.Path) ($($model.Size) bytes; digest checked before removal)" } foreach ($process in $processes) { Write-Host "STOP PID $($process.ProcessId): $($process.ExecutablePath) [$($process.CreationDate)]" } - foreach ($entry in $startup) { Write-Host "REMOVE $($entry.Kind): $($entry.Key)\$($entry.Name)" } + foreach ($entry in @($startup) + @($cleanupTasks)) { Write-Host "REMOVE $($entry.Kind): $($entry.Key)\$($entry.Name)" } + $cleanupRoot = Get-CleanGatewayCleanupRoot + foreach ($path in @($cleanupRoot, (Split-Path -Parent $cleanupRoot)) | Where-Object { Test-Path -LiteralPath $_ }) { + Write-Host "REMOVE if empty after cleanup: $path" + } foreach ($distro in $distros) { $action = if ($distro -in $selectedDistros) { 'DESTROY WSL filesystem' } else { 'PRESERVE WSL' } Write-Host "${action}: $distro" @@ -988,6 +1064,7 @@ function Invoke-OpenClawClean { models = $modelsToRemove processes = @($processes | Select-Object ProcessId, CreationDate, ExecutablePath) startup = @($startup | Select-Object Kind, Key, Name) + gatewayCleanupTasks = @($cleanupTasks | Select-Object Key, Name) removeDistros = $selectedDistros preserveDistros = @($distros | Where-Object { $_ -notin $selectedDistros }) } | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $Reports 'plan.json') -Encoding UTF8 @@ -1015,6 +1092,8 @@ function Invoke-OpenClawClean { Write-Host "TEARDOWN: $($gateway.PackageFullName)" Invoke-CleanTeardown $gateway $Reports } + # An armed task reacts to package removal: it could race this run or unregister a preserved distro. + foreach ($entry in $cleanupTasks) { Remove-CleanTask $entry } foreach ($package in @($gateways) + @($packages | Where-Object { $_ -notin $gateways })) { Write-Host "UNINSTALL: $($package.PackageFullName)" Remove-AppxPackage -Package $package.PackageFullName -ErrorAction Stop @@ -1030,11 +1109,7 @@ function Invoke-OpenClawClean { } } } else { - $task = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -eq $entry.Name -and $_.TaskPath -eq $entry.Key }) - if ($task.Count -gt 0) { - if ((Export-ScheduledTask -InputObject $task[0]) -ne $entry.Value) { throw "Startup task changed: $($entry.Name)" } - Unregister-ScheduledTask -InputObject $task[0] -Confirm:$false -ErrorAction Stop - } + Remove-CleanTask $entry } } foreach ($distro in $selectedDistros) { @@ -1063,6 +1138,7 @@ function Invoke-OpenClawClean { Write-Host "REMOVED profile: $profile" } } + Remove-CleanEmptyGatewayCleanupRoots foreach ($model in $modelsToRemove) { $null = Assert-CleanPath $model.Path if (Test-Path -LiteralPath $model.Path) { @@ -1078,6 +1154,7 @@ function Invoke-OpenClawClean { if (Test-Path -LiteralPath $path) { throw "Target remains: $path" } } if (@(Get-CleanStartup $Dev $ownedRoots).Count -gt 0) { throw 'A startup entry remains.' } + if (@(Get-CleanGatewayCleanupTasks $Dev).Count -gt 0) { throw 'A Gateway cleanup task remains.' } $afterRecords = @(Get-CleanDistroRecords) $afterDistros = @($afterRecords | ForEach-Object { $_.Name }) foreach ($distro in $selectedDistros) { diff --git a/scripts/test-clean-uninstall.ps1 b/scripts/test-clean-uninstall.ps1 index f1aab950bd..3b5695bf67 100644 --- a/scripts/test-clean-uninstall.ps1 +++ b/scripts/test-clean-uninstall.ps1 @@ -40,6 +40,8 @@ $environmentNames = @('APPDATA','LOCALAPPDATA','OPENCLAW_TRAY_DATA_DIR','OPENCLA foreach ($name in $environmentNames) { $oldEnvironment[$name] = [Environment]::GetEnvironmentVariable($name) } try { New-Item -ItemType Directory -Path $fixture | Out-Null + # The real root is the developer's own profile. Keep every test inside the fixture. + function Get-CleanGatewayCleanupRoot { "$fixture\companion-home\.openclaw-companion\cleanup" } Test-Case 'All expands only known opt-ins and never implies destructive confirmation' { $attributes = ($ast.ParamBlock.Attributes | ForEach-Object { $_.Extent.Text }) -join "`n" $entryPoint = [scriptblock]::Create( @@ -280,6 +282,67 @@ try { $task.Principal.UserId = '' Assert-Throws { Get-CleanStartup $false @("$fixture\selected") } 'no identifiable principal' } + Test-Case 'Gateway cleanup tasks require exact ownership and respect Dev scope, even when their files are gone' { + $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value + $root = Get-CleanGatewayCleanupRoot + $store = 'OpenClawFoundation.OpenClaw_rfcbke2p71se2' + $dev = 'OpenClawFoundation.OpenClaw.Dev_h1swxthnmjtwj' + $powershell = Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe' + function New-CleanupTask([string]$Name, [string]$Execute, [string]$Arguments) { + [pscustomobject]@{ + TaskName = $Name; TaskPath = '\' + Principal = [pscustomobject]@{ UserId = $sid } + Actions = @([pscustomobject]@{ Execute = $Execute; Arguments = $Arguments }) + } + } + $legacy = New-CleanupTask "OpenClaw Gateway cleanup - $sid - $store" $powershell ` + "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$root\$store\cleanup.ps1`" -Family $store" + $hosted = New-CleanupTask "OpenClaw Gateway cleanup - $sid - $dev" "$root\$dev\cleanup-host-$('A' * 64).exe" $dev + $otherUser = New-CleanupTask "OpenClaw Gateway cleanup - S-1-5-21-1-2-3-1001 - $store" 'C:\evil.exe' '' + $otherFamily = New-CleanupTask "OpenClaw Gateway cleanup - $sid - Contoso.App_abcdefghijklm" 'C:\evil.exe' '' + $tasks = @($legacy, $hosted, $otherUser, $otherFamily) + function Get-ScheduledTask { $tasks } + function Export-ScheduledTask { 'fixture task XML' } + Assert-True (-not (Test-Path -LiteralPath $root)) 'Fixture unexpectedly has cleanup files.' + $default = @(Get-CleanGatewayCleanupTasks $false) + Assert-True ($default.Count -eq 1 -and $default[0].Name -eq $legacy.TaskName) 'Default scope selected the wrong tasks.' + $withDev = @(Get-CleanGatewayCleanupTasks $true) + Assert-True ($withDev.Count -eq 2 -and $withDev.Name -contains $hosted.TaskName) 'Dev scope did not select the Dev task.' + $good = $legacy.Actions[0].Arguments + $legacy.Actions[0].Arguments = "-File `"C:\elsewhere\cleanup.ps1`" -Family $store" + Assert-Throws { Get-CleanGatewayCleanupTasks $false } 'unexpected ownership' + $legacy.Actions = @([pscustomobject]@{ Execute = 'C:\evil\powershell.exe'; Arguments = $good }) + Assert-Throws { Get-CleanGatewayCleanupTasks $false } 'unexpected ownership' + $legacy.Actions = @([pscustomobject]@{ Execute = $powershell; Arguments = $good }, [pscustomobject]@{ Execute = $powershell; Arguments = $good }) + Assert-Throws { Get-CleanGatewayCleanupTasks $false } 'unexpected ownership' + $legacy.Actions = @([pscustomobject]@{ Execute = $powershell; Arguments = $good }) + $legacy.TaskPath = '\Microsoft\' + Assert-Throws { Get-CleanGatewayCleanupTasks $false } 'unexpected ownership' + $legacy.TaskPath = '\' + $legacy.Principal.UserId = 'S-1-5-21-1-2-3-1001' + Assert-Throws { Get-CleanGatewayCleanupTasks $false } 'unexpected ownership' + $legacy.Principal.UserId = $sid + $hostPath = "$root\$dev\cleanup-host-$('A' * 64).exe" + $hosted.Actions = @([pscustomobject]@{ Execute = $hostPath; Arguments = "$dev -Extra" }) + Assert-Throws { Get-CleanGatewayCleanupTasks $true } 'unexpected ownership' + $hosted.Actions = @([pscustomobject]@{ Execute = "$root\$dev\other.exe"; Arguments = $dev }) + Assert-Throws { Get-CleanGatewayCleanupTasks $true } 'unexpected ownership' + $hosted.Actions = @([pscustomobject]@{ Execute = "$root\$store\cleanup-host-$('A' * 64).exe"; Arguments = $dev }) + Assert-Throws { Get-CleanGatewayCleanupTasks $true } 'unexpected ownership' + } + Test-Case 'task removal refuses a task that changed after the reviewed plan' { + $task = [pscustomobject]@{ TaskName = 'fixture task'; TaskPath = '\' } + $entry = [pscustomobject]@{ Name = 'fixture task'; Key = '\'; Value = 'reviewed XML' } + $script:unregistered = 0 + function Get-ScheduledTask { $task } + function Unregister-ScheduledTask { $script:unregistered++ } + function Export-ScheduledTask { 'changed XML' } + Assert-Throws { Remove-CleanTask $entry } 'Startup task changed' + Assert-True ($script:unregistered -eq 0) 'A changed task was unregistered.' + function Export-ScheduledTask { 'reviewed XML' } + Remove-CleanTask $entry + Assert-True ($script:unregistered -eq 1) 'The reviewed task was not unregistered.' + } Test-Case 'tree inventory includes hidden files but refuses source checkout' { $tree = Join-Path $fixture 'tree' New-Item -ItemType Directory -Path $tree | Out-Null @@ -750,6 +813,15 @@ try { } function Get-CleanProcesses { } function Get-CleanStartup { } + $script:cleanupTasks = @() + $script:cleanupTaskRemovedAfter = $null + $script:cleanupTaskRemovalFails = $false + function Get-CleanGatewayCleanupTasks { $script:cleanupTasks } + function Remove-CleanTask { + param($Entry) + $script:cleanupTaskRemovedAfter = $script:events.Count + if (-not $script:cleanupTaskRemovalFails) { $script:cleanupTasks = @() } + } function Invoke-CleanTeardown { $script:events.Add('teardown') if ($script:teardownFails) { throw 'TEST native teardown failed' } @@ -834,6 +906,41 @@ try { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\repeat-reports" Assert-True ($events.Count -eq 0) 'Absent package was acted on.' } + Test-Case 'Gateway cleanup tasks are disarmed after teardown but before package removal, and their selected files are removed' { + $root = Get-CleanGatewayCleanupRoot + $store = "$root\OpenClawFoundation.OpenClaw_rfcbke2p71se2" + $dev = "$root\OpenClawFoundation.OpenClaw.Dev_h1swxthnmjtwj" + foreach ($directory in @($store, $dev)) { + New-Item -ItemType Directory -Path $directory -Force | Out-Null + Set-Content -LiteralPath "$directory\owned.json" -Value '{}' + } + $entry = [pscustomobject]@{ Kind = 'Task'; Name = 'fixture cleanup task'; Key = '\'; Value = 'fixture task XML' } + $script:cleanupTasks = @($entry) + Invoke-OpenClawClean -Apply $false -Dev $false -Models $false -Wsl $false -Extra @() + Assert-True ($script:cleanupTasks.Count -eq 1 -and (Test-Path -LiteralPath $store)) 'Preview changed cleanup state.' + $script:registered = $true + $events.Clear() + Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-task-reports" + Assert-True ($script:cleanupTaskRemovedAfter -eq 1) 'Cleanup task must be removed after teardown and before package removal.' + Assert-True (($events -join ',') -eq 'teardown,package') 'Unexpected lifecycle order.' + Assert-True (-not (Test-Path -LiteralPath $store)) 'Selected cleanup files remain.' + Assert-True (Test-Path -LiteralPath "$dev\owned.json") 'Unselected Dev cleanup files were removed.' + $plan = Get-Content -LiteralPath "$fixture\cleanup-task-reports\plan.json" -Raw | ConvertFrom-Json + Assert-True (@($plan.gatewayCleanupTasks).Count -eq 1) 'Cleanup task was not recorded in the plan.' + Invoke-OpenClawClean -Apply $true -Dev $true -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-dev-reports" + Assert-True (-not (Test-Path -LiteralPath (Split-Path -Parent $root))) 'Empty Companion home remains.' + New-Item -ItemType Directory -Path $root -Force | Out-Null + Set-Content -LiteralPath "$(Split-Path -Parent $root)\unrelated.txt" -Value 'keep' + Invoke-OpenClawClean -Apply $true -Dev $true -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-keep-reports" + Assert-True (Test-Path -LiteralPath "$(Split-Path -Parent $root)\unrelated.txt") 'Unrelated Companion home data was removed.' + Remove-Item -LiteralPath (Split-Path -Parent $root) -Recurse -Force + $script:cleanupTasks = @($entry) + $script:cleanupTaskRemovalFails = $true + Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-remains-reports" } 'Gateway cleanup task remains' + $script:cleanupTaskRemovalFails = $false + $script:cleanupTasks = @() + $events.Clear() + } Test-Case 'WSL deletion is opt-in and exact, with dev distro preserved by default' { $script:distroInventory = @('OpenClawGateway', 'OpenClawGateway-Dev', 'UnrelatedDistro', 'OpenClawGateway-extra') Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $true -Extra @() -Reports "$fixture\wsl-reports" From b72262942d8d870db61e6ae909fa1bbb97164f10 Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Tue, 1 Dec 2026 20:57:30 -0800 Subject: [PATCH 2/6] fix(uninstall): wait for the Gateway cleanup lock before disarming its task Acquire each cleanup family's cleanup.lock before any mutation and hold it while stopping and unregistering the task and ending waiting workers, so a running worker cannot unregister a preserved distro. Match legacy task arguments exactly and recheck task XML case-sensitively. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- scripts/clean-uninstall.ps1 | 70 +++++++++++++++++++++++++++++--- scripts/test-clean-uninstall.ps1 | 59 ++++++++++++++++++++++++++- 2 files changed, 122 insertions(+), 7 deletions(-) diff --git a/scripts/clean-uninstall.ps1 b/scripts/clean-uninstall.ps1 index 4be89513e1..4217836770 100644 --- a/scripts/clean-uninstall.ps1 +++ b/scripts/clean-uninstall.ps1 @@ -646,23 +646,74 @@ function Get-CleanGatewayCleanupTasks([bool]$Dev) { $arguments = [string]$actions[0].Arguments $hosted = (Split-Path -Parent $execute) -ieq $directory -and (Split-Path -Leaf $execute) -match '^cleanup-host-[0-9A-Fa-f]{64}\.exe$' -and $arguments -ceq $family - # Companion releases before the windowless host registered PowerShell directly. + # Companion releases before the windowless host registered PowerShell directly, with exactly these arguments. $legacy = $execute -ieq $powershell -and - $arguments.EndsWith("-File `"$directory\cleanup.ps1`" -Family $family", [StringComparison]::OrdinalIgnoreCase) + $arguments -cmatch '^-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File "([^"]+)" -Family (\S+)$' -and + $Matches[1] -ieq "$directory\cleanup.ps1" -and $Matches[2] -ceq $family } if ((Get-CleanTaskPrincipalSid $task) -ne $sid -or $task.TaskPath -ne '\' -or -not ($hosted -or $legacy)) { throw "Gateway cleanup task has unexpected ownership. Inspect it manually: $($task.TaskPath)$($task.TaskName)" } - [pscustomobject]@{ Kind = 'Task'; Name = $task.TaskName; Key = $task.TaskPath; Value = (Export-ScheduledTask -InputObject $task) } + [pscustomobject]@{ + Kind = 'Task'; Name = $task.TaskName; Key = $task.TaskPath; Value = (Export-ScheduledTask -InputObject $task) + Directory = $directory + } } } function Remove-CleanTask($Entry) { $task = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -eq $Entry.Name -and $_.TaskPath -eq $Entry.Key }) if ($task.Count -gt 0) { - if ((Export-ScheduledTask -InputObject $task[0]) -ne $Entry.Value) { throw "Startup task changed: $($Entry.Name)" } + if ((Export-ScheduledTask -InputObject $task[0]) -cne $Entry.Value) { throw "Startup task changed: $($Entry.Name)" } + Unregister-ScheduledTask -InputObject $task[0] -Confirm:$false -ErrorAction Stop + } +} + +function Get-CleanGatewayCleanupLockTimeoutSeconds { + $value = 0 + if ([int]::TryParse([string]$env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS, [ref]$value) -and $value -gt 0) { return $value } + # Longer than the worker's own 150-second lock wait plus its 120-second WSL removal. + return 300 +} + +# The Gateway cleanup worker holds cleanup.lock for its whole run, including any WSL unregister. +# Holding it here means no worker is mid-run, so the plan's preserved distros cannot be removed under us. +function Enter-CleanGatewayCleanupLock($Entry) { + if (-not (Test-Path -LiteralPath $Entry.Directory -PathType Container)) { return $null } + $lockPath = Join-Path $Entry.Directory 'cleanup.lock' + $deadline = [DateTimeOffset]::UtcNow.AddSeconds((Get-CleanGatewayCleanupLockTimeoutSeconds)) + while ($true) { + try { return [IO.File]::Open($lockPath, 'OpenOrCreate', 'ReadWrite', 'None') } + catch [IO.IOException] { + if ([DateTimeOffset]::UtcNow -ge $deadline) { + throw "A Gateway cleanup worker is still running. Nothing was removed; retry later: $($Entry.Name)" + } + Start-Sleep -Milliseconds 200 + } + } +} + +# Call only while holding the entry's cleanup.lock: any remaining worker is still waiting for it and has not acted. +function Remove-CleanGatewayCleanupTask($Entry) { + $task = @(Get-ScheduledTask -ErrorAction Stop | Where-Object { $_.TaskName -eq $Entry.Name -and $_.TaskPath -eq $Entry.Key }) + if ($task.Count -gt 0) { + if ((Export-ScheduledTask -InputObject $task[0]) -cne $Entry.Value) { throw "Gateway cleanup task changed: $($Entry.Name)" } + Stop-ScheduledTask -InputObject $task[0] -ErrorAction Stop Unregister-ScheduledTask -InputObject $task[0] -Confirm:$false -ErrorAction Stop } + $worker = "$($Entry.Directory)\cleanup.ps1" + foreach ($process in Get-CimInstance Win32_Process -ErrorAction Stop) { + $path = [string]$process.ExecutablePath + $hosted = $path -and (Split-Path -Parent $path) -ieq $Entry.Directory + $script = $process.Name -ieq 'powershell.exe' -and + ([string]$process.CommandLine).IndexOf($worker, [StringComparison]::OrdinalIgnoreCase) -ge 0 + if ($hosted -or $script) { Stop-Process -Id $process.ProcessId -Force -ErrorAction Stop } + } +} + +function Close-CleanLocks($Locks) { + foreach ($lock in @($Locks)) { $lock.Dispose() } + $Locks.Clear() } function Remove-CleanEmptyGatewayCleanupRoots { @@ -1052,6 +1103,7 @@ function Invoke-OpenClawClean { if (Test-Path -LiteralPath $Reports) { throw "Use a new report directory: $Reports" } New-Item -ItemType Directory -Path $Reports -Force | Out-Null $transcribing = $false + $cleanupLocks = [Collections.Generic.List[IO.FileStream]]::new() try { Start-Transcript -LiteralPath (Join-Path $Reports 'cleanup.log') | Out-Null $transcribing = $true @@ -1087,13 +1139,18 @@ function Invoke-OpenClawClean { } Assert-CleanDistroStorage @(Get-CleanDistroRecords) $deletionTargets $selectedDistros foreach ($profile in $isolatedToRemove) { $null = Get-CleanIsolatedProfileForRemoval $profile } + # Wait out any running cleanup worker before mutating; a failed run releases the locks and keeps tasks armed. + foreach ($entry in $cleanupTasks) { + $lock = Enter-CleanGatewayCleanupLock $entry + if ($lock) { $cleanupLocks.Add($lock) } + } foreach ($process in $processes) { Stop-CleanProcess $process } foreach ($gateway in $gateways) { Write-Host "TEARDOWN: $($gateway.PackageFullName)" Invoke-CleanTeardown $gateway $Reports } # An armed task reacts to package removal: it could race this run or unregister a preserved distro. - foreach ($entry in $cleanupTasks) { Remove-CleanTask $entry } + foreach ($entry in $cleanupTasks) { Remove-CleanGatewayCleanupTask $entry } foreach ($package in @($gateways) + @($packages | Where-Object { $_ -notin $gateways })) { Write-Host "UNINSTALL: $($package.PackageFullName)" Remove-AppxPackage -Package $package.PackageFullName -ErrorAction Stop @@ -1131,6 +1188,8 @@ function Invoke-OpenClawClean { } } foreach ($profile in $isolatedToRemove) { Remove-CleanIsolatedProfile $profile } + # Tasks and their waiting workers are gone, so the lock files can be released and deleted with their folders. + Close-CleanLocks $cleanupLocks foreach ($profile in $profiles) { $null = @(Get-CleanTree $profile) if (Test-Path -LiteralPath $profile) { @@ -1174,6 +1233,7 @@ function Invoke-OpenClawClean { Write-Warning "PARTIAL OR BLOCKED CLEANUP. Do not assume a clean device. Reports: $Reports" throw } finally { + Close-CleanLocks $cleanupLocks if ($transcribing) { Stop-Transcript | Out-Null } } } diff --git a/scripts/test-clean-uninstall.ps1 b/scripts/test-clean-uninstall.ps1 index 3b5695bf67..5b3b7a4d5a 100644 --- a/scripts/test-clean-uninstall.ps1 +++ b/scripts/test-clean-uninstall.ps1 @@ -309,6 +309,8 @@ try { $withDev = @(Get-CleanGatewayCleanupTasks $true) Assert-True ($withDev.Count -eq 2 -and $withDev.Name -contains $hosted.TaskName) 'Dev scope did not select the Dev task.' $good = $legacy.Actions[0].Arguments + $legacy.Actions[0].Arguments = "-NoProfile -Command `"& C:\evil.ps1`" -File `"$root\$store\cleanup.ps1`" -Family $store" + Assert-Throws { Get-CleanGatewayCleanupTasks $false } 'unexpected ownership' $legacy.Actions[0].Arguments = "-File `"C:\elsewhere\cleanup.ps1`" -Family $store" Assert-Throws { Get-CleanGatewayCleanupTasks $false } 'unexpected ownership' $legacy.Actions = @([pscustomobject]@{ Execute = 'C:\evil\powershell.exe'; Arguments = $good }) @@ -339,10 +341,51 @@ try { function Export-ScheduledTask { 'changed XML' } Assert-Throws { Remove-CleanTask $entry } 'Startup task changed' Assert-True ($script:unregistered -eq 0) 'A changed task was unregistered.' + function Export-ScheduledTask { 'Reviewed XML' } + Assert-Throws { Remove-CleanTask $entry } 'Startup task changed' + Assert-True ($script:unregistered -eq 0) 'A case-only task change was unregistered.' function Export-ScheduledTask { 'reviewed XML' } Remove-CleanTask $entry Assert-True ($script:unregistered -eq 1) 'The reviewed task was not unregistered.' } + Test-Case 'Gateway cleanup lock waits for a running worker and fails closed at its deadline' { + $directory = "$fixture\cleanup-lock\OpenClawFoundation.OpenClaw_rfcbke2p71se2" + $entry = [pscustomobject]@{ Name = 'fixture cleanup task'; Directory = $directory } + Assert-True ($null -eq (Enter-CleanGatewayCleanupLock $entry)) 'A missing cleanup folder needs no lock.' + New-Item -ItemType Directory -Path $directory -Force | Out-Null + $worker = [IO.File]::Open("$directory\cleanup.lock", 'OpenOrCreate', 'ReadWrite', 'None') + $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = '1' + try { + Assert-Throws { Enter-CleanGatewayCleanupLock $entry } 'cleanup worker is still running' + } finally { $worker.Dispose(); $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = $null } + $lock = Enter-CleanGatewayCleanupLock $entry + try { + Assert-Throws { [IO.File]::Open("$directory\cleanup.lock", 'OpenOrCreate', 'ReadWrite', 'None') } 'being used by another process' + } finally { $lock.Dispose() } + } + Test-Case 'Gateway cleanup task removal stops the task before unregistering it and ends only its waiting workers' { + $directory = "$fixture\cleanup-stop\OpenClawFoundation.OpenClaw_rfcbke2p71se2" + $task = [pscustomobject]@{ TaskName = 'fixture cleanup task'; TaskPath = '\' } + $entry = [pscustomobject]@{ Name = 'fixture cleanup task'; Key = '\'; Value = 'reviewed XML'; Directory = $directory } + $script:taskEvents = [Collections.Generic.List[string]]::new() + function Get-ScheduledTask { $task } + function Export-ScheduledTask { 'reviewed XML' } + function Stop-ScheduledTask { $script:taskEvents.Add('stop') } + function Unregister-ScheduledTask { $script:taskEvents.Add('unregister') } + function Get-CimInstance { + [pscustomobject]@{ ProcessId = 11; Name = "cleanup-host-$('A' * 64).exe"; ExecutablePath = "$directory\cleanup-host-$('A' * 64).exe"; CommandLine = '' } + [pscustomobject]@{ ProcessId = 12; Name = 'powershell.exe'; ExecutablePath = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'; CommandLine = "powershell.exe -File `"$directory\cleanup.ps1`" -Family x" } + [pscustomobject]@{ ProcessId = 13; Name = 'powershell.exe'; ExecutablePath = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'; CommandLine = 'powershell.exe -File C:\other\cleanup.ps1' } + [pscustomobject]@{ ProcessId = 14; Name = 'System'; ExecutablePath = $null; CommandLine = $null } + } + function Stop-Process { param($Id, [switch]$Force) $script:taskEvents.Add("kill:$Id") } + Remove-CleanGatewayCleanupTask $entry + Assert-True (($script:taskEvents -join ',') -eq 'stop,unregister,kill:11,kill:12') "Unexpected removal sequence: $($script:taskEvents -join ',')" + $script:taskEvents.Clear() + function Export-ScheduledTask { 'Reviewed XML' } + Assert-Throws { Remove-CleanGatewayCleanupTask $entry } 'Gateway cleanup task changed' + Assert-True ($script:taskEvents.Count -eq 0) 'A changed cleanup task was stopped or unregistered.' + } Test-Case 'tree inventory includes hidden files but refuses source checkout' { $tree = Join-Path $fixture 'tree' New-Item -ItemType Directory -Path $tree | Out-Null @@ -817,11 +860,17 @@ try { $script:cleanupTaskRemovedAfter = $null $script:cleanupTaskRemovalFails = $false function Get-CleanGatewayCleanupTasks { $script:cleanupTasks } - function Remove-CleanTask { + function Remove-CleanGatewayCleanupTask { param($Entry) + Assert-True (-not (Test-Path -LiteralPath $Entry.Directory) -or $script:cleanupLockHeld.Invoke($Entry.Directory)) 'Cleanup task was removed without holding its lock.' $script:cleanupTaskRemovedAfter = $script:events.Count if (-not $script:cleanupTaskRemovalFails) { $script:cleanupTasks = @() } } + $script:cleanupLockHeld = { + param($Directory) + try { [IO.File]::Open("$Directory\cleanup.lock", 'OpenOrCreate', 'ReadWrite', 'None').Dispose(); return $false } + catch [IO.IOException] { return $true } + } function Invoke-CleanTeardown { $script:events.Add('teardown') if ($script:teardownFails) { throw 'TEST native teardown failed' } @@ -914,12 +963,18 @@ try { New-Item -ItemType Directory -Path $directory -Force | Out-Null Set-Content -LiteralPath "$directory\owned.json" -Value '{}' } - $entry = [pscustomobject]@{ Kind = 'Task'; Name = 'fixture cleanup task'; Key = '\'; Value = 'fixture task XML' } + $entry = [pscustomobject]@{ Kind = 'Task'; Name = 'fixture cleanup task'; Key = '\'; Value = 'fixture task XML'; Directory = $store } $script:cleanupTasks = @($entry) Invoke-OpenClawClean -Apply $false -Dev $false -Models $false -Wsl $false -Extra @() Assert-True ($script:cleanupTasks.Count -eq 1 -and (Test-Path -LiteralPath $store)) 'Preview changed cleanup state.' $script:registered = $true $events.Clear() + $worker = [IO.File]::Open("$store\cleanup.lock", 'OpenOrCreate', 'ReadWrite', 'None') + $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = '1' + try { + Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-busy-reports" } 'cleanup worker is still running' + } finally { $worker.Dispose(); $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = $null } + Assert-True ($events.Count -eq 0 -and $script:cleanupTasks.Count -eq 1 -and (Test-Path -LiteralPath "$store\owned.json")) 'A busy cleanup worker did not stop the run before mutation.' Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-task-reports" Assert-True ($script:cleanupTaskRemovedAfter -eq 1) 'Cleanup task must be removed after teardown and before package removal.' Assert-True (($events -join ',') -eq 'teardown,package') 'Unexpected lifecycle order.' From 9d189ac6a469d29d832b809cf174c7bad657a4d9 Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Tue, 1 Dec 2026 21:10:36 -0800 Subject: [PATCH 3/6] fix(clean): lock every cleanup folder, recheck tasks before package removal, and kill only exact workers Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- scripts/clean-uninstall.ps1 | 37 +++++++++++++------- scripts/test-clean-uninstall.ps1 | 58 ++++++++++++++++++++++++++------ 2 files changed, 73 insertions(+), 22 deletions(-) diff --git a/scripts/clean-uninstall.ps1 b/scripts/clean-uninstall.ps1 index 4217836770..83861ab40b 100644 --- a/scripts/clean-uninstall.ps1 +++ b/scripts/clean-uninstall.ps1 @@ -678,15 +678,15 @@ function Get-CleanGatewayCleanupLockTimeoutSeconds { # The Gateway cleanup worker holds cleanup.lock for its whole run, including any WSL unregister. # Holding it here means no worker is mid-run, so the plan's preserved distros cannot be removed under us. -function Enter-CleanGatewayCleanupLock($Entry) { - if (-not (Test-Path -LiteralPath $Entry.Directory -PathType Container)) { return $null } - $lockPath = Join-Path $Entry.Directory 'cleanup.lock' +function Enter-CleanGatewayCleanupLock([string]$Directory) { + if (-not (Test-Path -LiteralPath $Directory -PathType Container)) { return $null } + $lockPath = Join-Path $Directory 'cleanup.lock' $deadline = [DateTimeOffset]::UtcNow.AddSeconds((Get-CleanGatewayCleanupLockTimeoutSeconds)) while ($true) { try { return [IO.File]::Open($lockPath, 'OpenOrCreate', 'ReadWrite', 'None') } catch [IO.IOException] { if ([DateTimeOffset]::UtcNow -ge $deadline) { - throw "A Gateway cleanup worker is still running. Nothing was removed; retry later: $($Entry.Name)" + throw "A Gateway cleanup worker is still running. Nothing was removed; retry later: $Directory" } Start-Sleep -Milliseconds 200 } @@ -701,13 +701,21 @@ function Remove-CleanGatewayCleanupTask($Entry) { Stop-ScheduledTask -InputObject $task[0] -ErrorAction Stop Unregister-ScheduledTask -InputObject $task[0] -Confirm:$false -ErrorAction Stop } - $worker = "$($Entry.Directory)\cleanup.ps1" - foreach ($process in Get-CimInstance Win32_Process -ErrorAction Stop) { + # Only the task's own action shapes match: the hosted exe, or legacy PowerShell running this folder's worker. + $powershell = Get-CleanFullPath (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe') + $legacySuffix = " -File `"$($Entry.Directory)\cleanup.ps1`" -Family $(Split-Path -Leaf $Entry.Directory)" + foreach ($process in @(Get-CimInstance Win32_Process -ErrorAction Stop)) { $path = [string]$process.ExecutablePath - $hosted = $path -and (Split-Path -Parent $path) -ieq $Entry.Directory - $script = $process.Name -ieq 'powershell.exe' -and - ([string]$process.CommandLine).IndexOf($worker, [StringComparison]::OrdinalIgnoreCase) -ge 0 - if ($hosted -or $script) { Stop-Process -Id $process.ProcessId -Force -ErrorAction Stop } + if (-not $path -or $process.ProcessId -eq $PID) { continue } + $hosted = (Split-Path -Parent $path) -ieq $Entry.Directory -and (Split-Path -Leaf $path) -match '^cleanup-host-[0-9A-Fa-f]{64}\.exe$' + $legacy = $path -ieq $powershell -and ([string]$process.CommandLine).EndsWith($legacySuffix, [StringComparison]::OrdinalIgnoreCase) + if (-not ($hosted -or $legacy)) { continue } + # Stop-CleanProcess revalidates the PID's path and creation time, so a reused PID is never killed. + try { Stop-CleanProcess $process } + catch { + $live = @(Get-CimInstance Win32_Process -Filter "ProcessId = $($process.ProcessId)" -ErrorAction Stop) + if ($live.Count -gt 0 -and $live[0].CreationDate -eq $process.CreationDate) { throw } + } } } @@ -1140,8 +1148,11 @@ function Invoke-OpenClawClean { Assert-CleanDistroStorage @(Get-CleanDistroRecords) $deletionTargets $selectedDistros foreach ($profile in $isolatedToRemove) { $null = Get-CleanIsolatedProfileForRemoval $profile } # Wait out any running cleanup worker before mutating; a failed run releases the locks and keeps tasks armed. - foreach ($entry in $cleanupTasks) { - $lock = Enter-CleanGatewayCleanupLock $entry + # Lock every selected cleanup folder, even one without a task, so no worker can start mid-run. + $lockDirectories = @(@($cleanupTasks | ForEach-Object { $_.Directory }) + @(Get-CleanGatewayCleanupProfiles $Dev) | + ForEach-Object { Get-CleanFullPath $_ } | Sort-Object -Unique) + foreach ($directory in $lockDirectories) { + $lock = Enter-CleanGatewayCleanupLock $directory if ($lock) { $cleanupLocks.Add($lock) } } foreach ($process in $processes) { Stop-CleanProcess $process } @@ -1151,6 +1162,8 @@ function Invoke-OpenClawClean { } # An armed task reacts to package removal: it could race this run or unregister a preserved distro. foreach ($entry in $cleanupTasks) { Remove-CleanGatewayCleanupTask $entry } + # A task registered after the plan was taken would still react to package removal. + if (@(Get-CleanGatewayCleanupTasks $Dev).Count -gt 0) { throw 'A Gateway cleanup task remains. Packages were not removed.' } foreach ($package in @($gateways) + @($packages | Where-Object { $_ -notin $gateways })) { Write-Host "UNINSTALL: $($package.PackageFullName)" Remove-AppxPackage -Package $package.PackageFullName -ErrorAction Stop diff --git a/scripts/test-clean-uninstall.ps1 b/scripts/test-clean-uninstall.ps1 index 5b3b7a4d5a..bcf980737b 100644 --- a/scripts/test-clean-uninstall.ps1 +++ b/scripts/test-clean-uninstall.ps1 @@ -350,15 +350,14 @@ try { } Test-Case 'Gateway cleanup lock waits for a running worker and fails closed at its deadline' { $directory = "$fixture\cleanup-lock\OpenClawFoundation.OpenClaw_rfcbke2p71se2" - $entry = [pscustomobject]@{ Name = 'fixture cleanup task'; Directory = $directory } - Assert-True ($null -eq (Enter-CleanGatewayCleanupLock $entry)) 'A missing cleanup folder needs no lock.' + Assert-True ($null -eq (Enter-CleanGatewayCleanupLock $directory)) 'A missing cleanup folder needs no lock.' New-Item -ItemType Directory -Path $directory -Force | Out-Null $worker = [IO.File]::Open("$directory\cleanup.lock", 'OpenOrCreate', 'ReadWrite', 'None') $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = '1' try { - Assert-Throws { Enter-CleanGatewayCleanupLock $entry } 'cleanup worker is still running' + Assert-Throws { Enter-CleanGatewayCleanupLock $directory } 'cleanup worker is still running' } finally { $worker.Dispose(); $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = $null } - $lock = Enter-CleanGatewayCleanupLock $entry + $lock = Enter-CleanGatewayCleanupLock $directory try { Assert-Throws { [IO.File]::Open("$directory\cleanup.lock", 'OpenOrCreate', 'ReadWrite', 'None') } 'being used by another process' } finally { $lock.Dispose() } @@ -372,16 +371,35 @@ try { function Export-ScheduledTask { 'reviewed XML' } function Stop-ScheduledTask { $script:taskEvents.Add('stop') } function Unregister-ScheduledTask { $script:taskEvents.Add('unregister') } + $ps = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' + $legacyArgs = "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$directory\cleanup.ps1`" -Family OpenClawFoundation.OpenClaw_rfcbke2p71se2" + $script:processes = @( + [pscustomobject]@{ ProcessId = 11; ExecutablePath = "$directory\cleanup-host-$('A' * 64).exe"; CommandLine = ''; CreationDate = 'c11' } + [pscustomobject]@{ ProcessId = 12; ExecutablePath = $ps; CommandLine = "`"$ps`" $legacyArgs"; CreationDate = 'c12' } + [pscustomobject]@{ ProcessId = 13; ExecutablePath = $ps; CommandLine = "`"$ps`" -File `"$directory\cleanup.ps1`" -Family x"; CreationDate = 'c13' } + [pscustomobject]@{ ProcessId = 14; ExecutablePath = $ps; CommandLine = "`"$ps`" -Command `"type '$directory\cleanup.ps1'`""; CreationDate = 'c14' } + [pscustomobject]@{ ProcessId = 15; ExecutablePath = "$directory\other.exe"; CommandLine = ''; CreationDate = 'c15' } + [pscustomobject]@{ ProcessId = $PID; ExecutablePath = $ps; CommandLine = "`"$ps`" $legacyArgs"; CreationDate = 'self' } + [pscustomobject]@{ ProcessId = 16; ExecutablePath = $null; CommandLine = $null; CreationDate = 'c16' } + ) + # The live view is what Stop-CleanProcess revalidates against just before killing. + $script:live = @{} + foreach ($p in $script:processes) { $script:live[[int]$p.ProcessId] = $p } function Get-CimInstance { - [pscustomobject]@{ ProcessId = 11; Name = "cleanup-host-$('A' * 64).exe"; ExecutablePath = "$directory\cleanup-host-$('A' * 64).exe"; CommandLine = '' } - [pscustomobject]@{ ProcessId = 12; Name = 'powershell.exe'; ExecutablePath = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'; CommandLine = "powershell.exe -File `"$directory\cleanup.ps1`" -Family x" } - [pscustomobject]@{ ProcessId = 13; Name = 'powershell.exe'; ExecutablePath = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'; CommandLine = 'powershell.exe -File C:\other\cleanup.ps1' } - [pscustomobject]@{ ProcessId = 14; Name = 'System'; ExecutablePath = $null; CommandLine = $null } + param($ClassName, $Filter) + if ($Filter -match 'ProcessId = (\d+)') { $hit = $script:live[[int]$Matches[1]]; if ($hit) { $hit } ; return } + $script:processes } function Stop-Process { param($Id, [switch]$Force) $script:taskEvents.Add("kill:$Id") } Remove-CleanGatewayCleanupTask $entry Assert-True (($script:taskEvents -join ',') -eq 'stop,unregister,kill:11,kill:12') "Unexpected removal sequence: $($script:taskEvents -join ',')" $script:taskEvents.Clear() + # PID 11 exited and was reused before the kill; PID 12 exited outright. Neither is killed and removal succeeds. + $script:live[11] = [pscustomobject]@{ ProcessId = 11; ExecutablePath = "$directory\cleanup-host-$('A' * 64).exe"; CommandLine = ''; CreationDate = 'reused' } + $script:live.Remove(12) + Remove-CleanGatewayCleanupTask $entry + Assert-True (($script:taskEvents -join ',') -eq 'stop,unregister') "A reused or exited PID was killed: $($script:taskEvents -join ',')" + $script:taskEvents.Clear() function Export-ScheduledTask { 'Reviewed XML' } Assert-Throws { Remove-CleanGatewayCleanupTask $entry } 'Gateway cleanup task changed' Assert-True ($script:taskEvents.Count -eq 0) 'A changed cleanup task was stopped or unregistered.' @@ -859,7 +877,9 @@ try { $script:cleanupTasks = @() $script:cleanupTaskRemovedAfter = $null $script:cleanupTaskRemovalFails = $false - function Get-CleanGatewayCleanupTasks { $script:cleanupTasks } + $script:lateTask = $null + # A late task appears only after teardown starts, as if Companion registered it after the plan was taken. + function Get-CleanGatewayCleanupTasks { $script:cleanupTasks; if ($script:lateTask -and $script:events -contains 'teardown') { $script:lateTask } } function Remove-CleanGatewayCleanupTask { param($Entry) Assert-True (-not (Test-Path -LiteralPath $Entry.Directory) -or $script:cleanupLockHeld.Invoke($Entry.Directory)) 'Cleanup task was removed without holding its lock.' @@ -991,9 +1011,27 @@ try { Remove-Item -LiteralPath (Split-Path -Parent $root) -Recurse -Force $script:cleanupTasks = @($entry) $script:cleanupTaskRemovalFails = $true - Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-remains-reports" } 'Gateway cleanup task remains' + $script:registered = $true + $events.Clear() + Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-remains-reports" } 'Packages were not removed' + Assert-True ($script:registered -and ($events -join ',') -eq 'teardown') 'A surviving cleanup task did not stop package removal.' $script:cleanupTaskRemovalFails = $false $script:cleanupTasks = @() + $script:lateTask = $entry + $events.Clear() + Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-late-reports" } 'Packages were not removed' + Assert-True ($script:registered -and ($events -join ',') -eq 'teardown') 'A late cleanup task did not stop package removal.' + $script:lateTask = $null + New-Item -ItemType Directory -Path $store -Force | Out-Null + Set-Content -LiteralPath "$store\owned.json" -Value '{}' + $worker = [IO.File]::Open("$store\cleanup.lock", 'OpenOrCreate', 'ReadWrite', 'None') + $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = '1' + $events.Clear() + try { + Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-taskless-reports" } 'cleanup worker is still running' + } finally { $worker.Dispose(); $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = $null } + Assert-True ($events.Count -eq 0 -and (Test-Path -LiteralPath "$store\owned.json")) 'A busy worker without a task did not stop the run before mutation.' + Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-final-reports" $events.Clear() } Test-Case 'WSL deletion is opt-in and exact, with dev distro preserved by default' { From 86fad9551b80ded4fbe761908a38ad016584d04d Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Tue, 1 Dec 2026 22:46:34 -0800 Subject: [PATCH 4/6] fix(clean): stop direct-launch cleanup workers in every locked folder and match the host's family Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- scripts/clean-uninstall.ps1 | 22 +++++++++++++++++----- scripts/test-clean-uninstall.ps1 | 29 +++++++++++++++++++++++++---- 2 files changed, 42 insertions(+), 9 deletions(-) diff --git a/scripts/clean-uninstall.ps1 b/scripts/clean-uninstall.ps1 index 83861ab40b..bc0c2b8e2a 100644 --- a/scripts/clean-uninstall.ps1 +++ b/scripts/clean-uninstall.ps1 @@ -701,15 +701,25 @@ function Remove-CleanGatewayCleanupTask($Entry) { Stop-ScheduledTask -InputObject $task[0] -ErrorAction Stop Unregister-ScheduledTask -InputObject $task[0] -Confirm:$false -ErrorAction Stop } - # Only the task's own action shapes match: the hosted exe, or legacy PowerShell running this folder's worker. + Stop-CleanGatewayCleanupWorkers $Entry.Directory +} + +# Call only while holding the folder's cleanup.lock. Ends workers still waiting for it: the hosted exe +# started for this family, or system PowerShell running this folder's cleanup.ps1 for this family, +# whether launched by a task, the host, or Companion directly (which appends -CleanupHostPath and other switches). +function Stop-CleanGatewayCleanupWorkers([string]$Directory) { + $family = Split-Path -Leaf $Directory $powershell = Get-CleanFullPath (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe') - $legacySuffix = " -File `"$($Entry.Directory)\cleanup.ps1`" -Family $(Split-Path -Leaf $Entry.Directory)" + $hostFamily = '\s' + [regex]::Escape($family) + '\s*$' + $script = '(?i)\s-File\s+"?' + [regex]::Escape("$Directory\cleanup.ps1") + '"?\s+-Family\s+(\S+)(?:\s|$)' foreach ($process in @(Get-CimInstance Win32_Process -ErrorAction Stop)) { $path = [string]$process.ExecutablePath if (-not $path -or $process.ProcessId -eq $PID) { continue } - $hosted = (Split-Path -Parent $path) -ieq $Entry.Directory -and (Split-Path -Leaf $path) -match '^cleanup-host-[0-9A-Fa-f]{64}\.exe$' - $legacy = $path -ieq $powershell -and ([string]$process.CommandLine).EndsWith($legacySuffix, [StringComparison]::OrdinalIgnoreCase) - if (-not ($hosted -or $legacy)) { continue } + $commandLine = [string]$process.CommandLine + $hosted = (Split-Path -Parent $path) -ieq $Directory -and + (Split-Path -Leaf $path) -match '^cleanup-host-[0-9A-Fa-f]{64}\.exe$' -and $commandLine -cmatch $hostFamily + $worker = $path -ieq $powershell -and $commandLine -match $script -and $Matches[1] -ceq $family + if (-not ($hosted -or $worker)) { continue } # Stop-CleanProcess revalidates the PID's path and creation time, so a reused PID is never killed. try { Stop-CleanProcess $process } catch { @@ -1162,6 +1172,8 @@ function Invoke-OpenClawClean { } # An armed task reacts to package removal: it could race this run or unregister a preserved distro. foreach ($entry in $cleanupTasks) { Remove-CleanGatewayCleanupTask $entry } + # Companion can start a worker directly, so a folder without a task can still have one waiting for its lock. + foreach ($directory in $lockDirectories) { Stop-CleanGatewayCleanupWorkers $directory } # A task registered after the plan was taken would still react to package removal. if (@(Get-CleanGatewayCleanupTasks $Dev).Count -gt 0) { throw 'A Gateway cleanup task remains. Packages were not removed.' } foreach ($package in @($gateways) + @($packages | Where-Object { $_ -notin $gateways })) { diff --git a/scripts/test-clean-uninstall.ps1 b/scripts/test-clean-uninstall.ps1 index bcf980737b..d27beee234 100644 --- a/scripts/test-clean-uninstall.ps1 +++ b/scripts/test-clean-uninstall.ps1 @@ -372,15 +372,23 @@ try { function Stop-ScheduledTask { $script:taskEvents.Add('stop') } function Unregister-ScheduledTask { $script:taskEvents.Add('unregister') } $ps = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' - $legacyArgs = "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$directory\cleanup.ps1`" -Family OpenClawFoundation.OpenClaw_rfcbke2p71se2" + $family = 'OpenClawFoundation.OpenClaw_rfcbke2p71se2' + $legacyArgs = "-NoProfile -NonInteractive -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$directory\cleanup.ps1`" -Family $family" + $hostExe = "$directory\cleanup-host-$('A' * 64).exe" $script:processes = @( - [pscustomobject]@{ ProcessId = 11; ExecutablePath = "$directory\cleanup-host-$('A' * 64).exe"; CommandLine = ''; CreationDate = 'c11' } + [pscustomobject]@{ ProcessId = 11; ExecutablePath = $hostExe; CommandLine = "`"$hostExe`" $family"; CreationDate = 'c11' } [pscustomobject]@{ ProcessId = 12; ExecutablePath = $ps; CommandLine = "`"$ps`" $legacyArgs"; CreationDate = 'c12' } [pscustomobject]@{ ProcessId = 13; ExecutablePath = $ps; CommandLine = "`"$ps`" -File `"$directory\cleanup.ps1`" -Family x"; CreationDate = 'c13' } [pscustomobject]@{ ProcessId = 14; ExecutablePath = $ps; CommandLine = "`"$ps`" -Command `"type '$directory\cleanup.ps1'`""; CreationDate = 'c14' } [pscustomobject]@{ ProcessId = 15; ExecutablePath = "$directory\other.exe"; CommandLine = ''; CreationDate = 'c15' } [pscustomobject]@{ ProcessId = $PID; ExecutablePath = $ps; CommandLine = "`"$ps`" $legacyArgs"; CreationDate = 'self' } [pscustomobject]@{ ProcessId = 16; ExecutablePath = $null; CommandLine = $null; CreationDate = 'c16' } + # Companion's direct launch appends switches after the family. + [pscustomobject]@{ ProcessId = 17; ExecutablePath = $ps; CommandLine = "`"$ps`" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$directory\cleanup.ps1`" -Family $family -CleanupHostPath `"$hostExe`" -Preserve"; CreationDate = 'c17' } + [pscustomobject]@{ ProcessId = 18; ExecutablePath = $hostExe; CommandLine = "`"$hostExe`" OpenClawFoundation.OpenClaw_otherfamily01"; CreationDate = 'c18' } + [pscustomobject]@{ ProcessId = 19; ExecutablePath = $ps; CommandLine = "`"$ps`" -File $directory\cleanup.ps1 -Family $family"; CreationDate = 'c19' } + [pscustomobject]@{ ProcessId = 20; ExecutablePath = $ps; CommandLine = "`"$ps`" -File `"$directory\cleanup.ps1.bak`" -Family $family"; CreationDate = 'c20' } + [pscustomobject]@{ ProcessId = 21; ExecutablePath = $ps; CommandLine = "`"$ps`" -File `"$directory\cleanup.ps1`" -Family $($family.ToUpperInvariant())"; CreationDate = 'c21' } ) # The live view is what Stop-CleanProcess revalidates against just before killing. $script:live = @{} @@ -392,11 +400,13 @@ try { } function Stop-Process { param($Id, [switch]$Force) $script:taskEvents.Add("kill:$Id") } Remove-CleanGatewayCleanupTask $entry - Assert-True (($script:taskEvents -join ',') -eq 'stop,unregister,kill:11,kill:12') "Unexpected removal sequence: $($script:taskEvents -join ',')" + Assert-True (($script:taskEvents -join ',') -eq 'stop,unregister,kill:11,kill:12,kill:17,kill:19') "Unexpected removal sequence: $($script:taskEvents -join ',')" $script:taskEvents.Clear() # PID 11 exited and was reused before the kill; PID 12 exited outright. Neither is killed and removal succeeds. - $script:live[11] = [pscustomobject]@{ ProcessId = 11; ExecutablePath = "$directory\cleanup-host-$('A' * 64).exe"; CommandLine = ''; CreationDate = 'reused' } + $script:live[11] = [pscustomobject]@{ ProcessId = 11; ExecutablePath = $hostExe; CommandLine = "`"$hostExe`" $family"; CreationDate = 'reused' } $script:live.Remove(12) + $script:live.Remove(17) + $script:live.Remove(19) Remove-CleanGatewayCleanupTask $entry Assert-True (($script:taskEvents -join ',') -eq 'stop,unregister') "A reused or exited PID was killed: $($script:taskEvents -join ',')" $script:taskEvents.Clear() @@ -886,6 +896,12 @@ try { $script:cleanupTaskRemovedAfter = $script:events.Count if (-not $script:cleanupTaskRemovalFails) { $script:cleanupTasks = @() } } + $script:workerScans = [Collections.Generic.List[string]]::new() + function Stop-CleanGatewayCleanupWorkers { + param($Directory) + Assert-True (-not (Test-Path -LiteralPath $Directory) -or $script:cleanupLockHeld.Invoke($Directory)) 'Cleanup workers were stopped without holding the lock.' + $script:workerScans.Add("$(Split-Path -Leaf $Directory)@$($script:events.Count)") + } $script:cleanupLockHeld = { param($Directory) try { [IO.File]::Open("$Directory\cleanup.lock", 'OpenOrCreate', 'ReadWrite', 'None').Dispose(); return $false } @@ -995,14 +1011,19 @@ try { Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-busy-reports" } 'cleanup worker is still running' } finally { $worker.Dispose(); $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = $null } Assert-True ($events.Count -eq 0 -and $script:cleanupTasks.Count -eq 1 -and (Test-Path -LiteralPath "$store\owned.json")) 'A busy cleanup worker did not stop the run before mutation.' + $script:workerScans.Clear() Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-task-reports" Assert-True ($script:cleanupTaskRemovedAfter -eq 1) 'Cleanup task must be removed after teardown and before package removal.' + Assert-True (($script:workerScans -join ',') -eq 'OpenClawFoundation.OpenClaw_rfcbke2p71se2@1') "Workers were not stopped after teardown and before package removal: $($script:workerScans -join ',')" Assert-True (($events -join ',') -eq 'teardown,package') 'Unexpected lifecycle order.' Assert-True (-not (Test-Path -LiteralPath $store)) 'Selected cleanup files remain.' Assert-True (Test-Path -LiteralPath "$dev\owned.json") 'Unselected Dev cleanup files were removed.' $plan = Get-Content -LiteralPath "$fixture\cleanup-task-reports\plan.json" -Raw | ConvertFrom-Json Assert-True (@($plan.gatewayCleanupTasks).Count -eq 1) 'Cleanup task was not recorded in the plan.' + $script:workerScans.Clear() Invoke-OpenClawClean -Apply $true -Dev $true -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-dev-reports" + # The Dev folder has no task, but Companion may have started a worker there directly. + Assert-True (@($script:workerScans -match '^OpenClawFoundation\.OpenClaw\.Dev_h1swxthnmjtwj@').Count -gt 0) "A cleanup folder without a task was not scanned for workers: $($script:workerScans -join ',')" Assert-True (-not (Test-Path -LiteralPath (Split-Path -Parent $root))) 'Empty Companion home remains.' New-Item -ItemType Directory -Path $root -Force | Out-Null Set-Content -LiteralPath "$(Split-Path -Parent $root)\unrelated.txt" -Value 'keep' From 20a32abdc795e55109531b0def962a42f9146ebd Mon Sep 17 00:00:00 2001 From: Copilot App <223556219+Copilot@users.noreply.github.com> Date: Tue, 1 Dec 2026 23:12:53 -0800 Subject: [PATCH 5/6] fix(clean-uninstall): retire owned.json under the lock, anchor worker matching, kill by held handle - Delete owned.json while the cleanup lock is still held, so a worker that starts after the scan has nothing to act on. - Anchor host and worker command-line matches at the executable token and an allowlisted option prefix, so script text inside another argument (for example -Command) is never treated as a worker. - Pin the PID with a process handle before the identity check and kill through that handle instead of Stop-Process -Id. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- scripts/clean-uninstall.ps1 | 37 ++++++++++++++++++------- scripts/test-clean-uninstall.ps1 | 46 +++++++++++++++++++++++++++++--- 2 files changed, 70 insertions(+), 13 deletions(-) diff --git a/scripts/clean-uninstall.ps1 b/scripts/clean-uninstall.ps1 index bc0c2b8e2a..4eb10dcdd2 100644 --- a/scripts/clean-uninstall.ps1 +++ b/scripts/clean-uninstall.ps1 @@ -476,14 +476,25 @@ function Get-CleanProcesses([string[]]$OwnedRoots) { } } +function Open-CleanProcessHandle([int]$Id) { + try { $process = [Diagnostics.Process]::GetProcessById($Id) } catch [ArgumentException] { return $null } + try { $null = $process.Handle } catch { $process.Dispose(); if ($_.Exception -is [InvalidOperationException]) { return $null }; throw } + $process +} + function Stop-CleanProcess($Expected) { - $current = @(Get-CimInstance Win32_Process -Filter "ProcessId = $($Expected.ProcessId)" -ErrorAction Stop) - if ($current.Count -eq 0) { return } - if ($current.Count -ne 1 -or $current[0].ExecutablePath -ne $Expected.ExecutablePath -or - $current[0].CreationDate -ne $Expected.CreationDate) { - throw "PID $($Expected.ProcessId) changed identity. Cleanup stopped." - } - Stop-Process -Id $Expected.ProcessId -Force -ErrorAction Stop + # An open handle pins the PID, so the identity checked below is the process that is killed. + $process = Open-CleanProcessHandle $Expected.ProcessId + if (-not $process) { return } + try { + $current = @(Get-CimInstance Win32_Process -Filter "ProcessId = $($Expected.ProcessId)" -ErrorAction Stop) + if ($current.Count -eq 0) { return } + if ($current.Count -ne 1 -or $current[0].ExecutablePath -ne $Expected.ExecutablePath -or + $current[0].CreationDate -ne $Expected.CreationDate) { + throw "PID $($Expected.ProcessId) changed identity. Cleanup stopped." + } + try { $process.Kill() } catch [InvalidOperationException] { if (-not $process.HasExited) { throw } } + } finally { $process.Dispose() } } function Invoke-CleanNativeCommand([string]$FilePath, [string]$Arguments, [int]$TimeoutMilliseconds = 240000) { @@ -710,8 +721,11 @@ function Remove-CleanGatewayCleanupTask($Entry) { function Stop-CleanGatewayCleanupWorkers([string]$Directory) { $family = Split-Path -Leaf $Directory $powershell = Get-CleanFullPath (Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe') - $hostFamily = '\s' + [regex]::Escape($family) + '\s*$' - $script = '(?i)\s-File\s+"?' + [regex]::Escape("$Directory\cleanup.ps1") + '"?\s+-Family\s+(\S+)(?:\s|$)' + # Anchored at the executable token so text inside another argument (e.g. -Command) never matches. + $hostFamily = '^(?:"[^"]*"|\S+)\s+' + [regex]::Escape($family) + '\s*$' + $scriptPath = [regex]::Escape("$Directory\cleanup.ps1") + $script = '(?i)^(?:"[^"]*"|\S+)(?:\s+-(?:NoProfile|NonInteractive|NoLogo|WindowStyle\s+Hidden|ExecutionPolicy\s+Bypass))*' + + '\s+-File\s+(?:"' + $scriptPath + '"|' + $scriptPath + ')\s+-Family\s+(\S+)(?:\s|$)' foreach ($process in @(Get-CimInstance Win32_Process -ErrorAction Stop)) { $path = [string]$process.ExecutablePath if (-not $path -or $process.ProcessId -eq $PID) { continue } @@ -1213,6 +1227,11 @@ function Invoke-OpenClawClean { } } foreach ($profile in $isolatedToRemove) { Remove-CleanIsolatedProfile $profile } + # A worker that started after the scan would act on owned.json once the lock is free, so retire it first. + foreach ($directory in $lockDirectories) { + $record = Join-Path $directory 'owned.json' + if (Test-Path -LiteralPath $record) { Remove-Item -LiteralPath $record -Force -ErrorAction Stop } + } # Tasks and their waiting workers are gone, so the lock files can be released and deleted with their folders. Close-CleanLocks $cleanupLocks foreach ($profile in $profiles) { diff --git a/scripts/test-clean-uninstall.ps1 b/scripts/test-clean-uninstall.ps1 index d27beee234..c11aeccc82 100644 --- a/scripts/test-clean-uninstall.ps1 +++ b/scripts/test-clean-uninstall.ps1 @@ -389,6 +389,9 @@ try { [pscustomobject]@{ ProcessId = 19; ExecutablePath = $ps; CommandLine = "`"$ps`" -File $directory\cleanup.ps1 -Family $family"; CreationDate = 'c19' } [pscustomobject]@{ ProcessId = 20; ExecutablePath = $ps; CommandLine = "`"$ps`" -File `"$directory\cleanup.ps1.bak`" -Family $family"; CreationDate = 'c20' } [pscustomobject]@{ ProcessId = 21; ExecutablePath = $ps; CommandLine = "`"$ps`" -File `"$directory\cleanup.ps1`" -Family $($family.ToUpperInvariant())"; CreationDate = 'c21' } + # Text inside another argument is not a -File launch, and a host takes only the family argument. + [pscustomobject]@{ ProcessId = 22; ExecutablePath = $ps; CommandLine = "`"$ps`" -Command `"Get-Item -File $directory\cleanup.ps1 -Family $family -Force`""; CreationDate = 'c22' } + [pscustomobject]@{ ProcessId = 23; ExecutablePath = $hostExe; CommandLine = "`"$hostExe`" --other $family"; CreationDate = 'c23' } ) # The live view is what Stop-CleanProcess revalidates against just before killing. $script:live = @{} @@ -398,7 +401,15 @@ try { if ($Filter -match 'ProcessId = (\d+)') { $hit = $script:live[[int]$Matches[1]]; if ($hit) { $hit } ; return } $script:processes } - function Stop-Process { param($Id, [switch]$Force) $script:taskEvents.Add("kill:$Id") } + function Stop-Process { throw 'TEST FAILURE: workers must be killed through a held handle' } + function Open-CleanProcessHandle { + param($Id) + if (-not $script:live.ContainsKey([int]$Id)) { return $null } + $handle = [pscustomobject]@{ Id = $Id; HasExited = $false } + $handle | Add-Member ScriptMethod Kill { $script:taskEvents.Add("kill:$($this.Id)") } + $handle | Add-Member ScriptMethod Dispose { } + $handle + } Remove-CleanGatewayCleanupTask $entry Assert-True (($script:taskEvents -join ',') -eq 'stop,unregister,kill:11,kill:12,kill:17,kill:19') "Unexpected removal sequence: $($script:taskEvents -join ',')" $script:taskEvents.Clear() @@ -502,10 +513,24 @@ try { Save-Receipt Assert-Throws { Get-CleanModels @((Get-Item $receiptFile)) } 'exact Hugging Face' } - Test-Case 'PID reuse never stops a replacement process' { - function Get-CimInstance { [pscustomobject]@{ ProcessId = 42; ExecutablePath = 'C:\other.exe'; CreationDate = 'new' } } - function Stop-Process { throw 'TEST FAILURE: a real stop was attempted' } + Test-Case 'PID reuse never stops a replacement process, and the PID is pinned before its identity is checked' { + $script:pidEvents = [Collections.Generic.List[string]]::new() + $script:liveIdentity = [pscustomobject]@{ ProcessId = 42; ExecutablePath = 'C:\other.exe'; CreationDate = 'new' } + function Get-CimInstance { $script:pidEvents.Add('check'); $script:liveIdentity } + function Stop-Process { throw 'TEST FAILURE: a stop by PID was attempted' } + function Open-CleanProcessHandle { + param($Id) + $script:pidEvents.Add("open:$Id") + $handle = [pscustomobject]@{ HasExited = $false } + $handle | Add-Member ScriptMethod Kill { $script:pidEvents.Add('kill') } + $handle | Add-Member ScriptMethod Dispose { $script:pidEvents.Add('close') } + $handle + } Assert-Throws { Stop-CleanProcess ([pscustomobject]@{ ProcessId = 42; ExecutablePath = 'C:\owned.exe'; CreationDate = 'old' }) } 'changed identity' + Assert-True (($script:pidEvents -join ',') -eq 'open:42,check,close') "A replacement was not refused through a held handle: $($script:pidEvents -join ',')" + $script:pidEvents.Clear() + Stop-CleanProcess $script:liveIdentity + Assert-True (($script:pidEvents -join ',') -eq 'open:42,check,kill,close') "The verified process was not killed through its held handle: $($script:pidEvents -join ',')" } Test-Case 'process ownership compares short and long paths without changing PID identity observations' { $fso = New-Object -ComObject Scripting.FileSystemObject @@ -593,6 +618,7 @@ try { function Get-CimInstance { param($ClassName) Assert-True ($ClassName -eq 'Win32_Process') 'Unexpected live inventory.'; $state.Processes } function Get-CleanDistroRecords { $state.Distros } function Stop-Process { throw 'Isolated mode must not stop any process.' } + function Open-CleanProcessHandle { throw 'Isolated mode must not stop any process.' } function Remove-Item { [CmdletBinding()] param([string[]]$LiteralPath, [switch]$Recurse, [switch]$Force) @@ -902,6 +928,15 @@ try { Assert-True (-not (Test-Path -LiteralPath $Directory) -or $script:cleanupLockHeld.Invoke($Directory)) 'Cleanup workers were stopped without holding the lock.' $script:workerScans.Add("$(Split-Path -Leaf $Directory)@$($script:events.Count)") } + # Records whether a late worker could still find owned.json at the moment the locks are released. + $script:ownedProbe = $null + $script:ownedAtRelease = [Collections.Generic.List[bool]]::new() + function Close-CleanLocks { + param($Locks) + if ($script:ownedProbe -and @($Locks).Count) { $script:ownedAtRelease.Add((Test-Path -LiteralPath $script:ownedProbe)) } + foreach ($lock in @($Locks)) { $lock.Dispose() } + $Locks.Clear() + } $script:cleanupLockHeld = { param($Directory) try { [IO.File]::Open("$Directory\cleanup.lock", 'OpenOrCreate', 'ReadWrite', 'None').Dispose(); return $false } @@ -1012,7 +1047,10 @@ try { } finally { $worker.Dispose(); $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = $null } Assert-True ($events.Count -eq 0 -and $script:cleanupTasks.Count -eq 1 -and (Test-Path -LiteralPath "$store\owned.json")) 'A busy cleanup worker did not stop the run before mutation.' $script:workerScans.Clear() + $script:ownedProbe = "$store\owned.json" Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-task-reports" + $script:ownedProbe = $null + Assert-True ($script:ownedAtRelease.Count -gt 0 -and -not $script:ownedAtRelease[0]) 'owned.json was still present when the cleanup locks were released.' Assert-True ($script:cleanupTaskRemovedAfter -eq 1) 'Cleanup task must be removed after teardown and before package removal.' Assert-True (($script:workerScans -join ',') -eq 'OpenClawFoundation.OpenClaw_rfcbke2p71se2@1') "Workers were not stopped after teardown and before package removal: $($script:workerScans -join ',')" Assert-True (($events -join ',') -eq 'teardown,package') 'Unexpected lifecycle order.' From 520cf4492e1c91e710de38475025d054c0c3254a Mon Sep 17 00:00:00 2001 From: Scott Hanselman Date: Tue, 1 Dec 2026 23:36:47 -0800 Subject: [PATCH 6/6] fix(clean): retire owned.json before package removal and recheck cleanup folders Retire owned.json under lock before any package removal so a run that fails after removal begins never releases the lock with the record intact. Refuse cleanup folders that appeared after the preview or are reparse points, and require a quoted worker script path when it contains whitespace. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- scripts/clean-uninstall.ps1 | 23 ++++++++---- scripts/test-clean-uninstall.ps1 | 63 ++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 7 deletions(-) diff --git a/scripts/clean-uninstall.ps1 b/scripts/clean-uninstall.ps1 index 4eb10dcdd2..046353d92e 100644 --- a/scripts/clean-uninstall.ps1 +++ b/scripts/clean-uninstall.ps1 @@ -724,8 +724,10 @@ function Stop-CleanGatewayCleanupWorkers([string]$Directory) { # Anchored at the executable token so text inside another argument (e.g. -Command) never matches. $hostFamily = '^(?:"[^"]*"|\S+)\s+' + [regex]::Escape($family) + '\s*$' $scriptPath = [regex]::Escape("$Directory\cleanup.ps1") + # An unquoted path containing whitespace would split into several arguments, so it is not this script. + $scriptArgument = if ("$Directory\cleanup.ps1" -match '\s') { '"' + $scriptPath + '"' } else { '(?:"' + $scriptPath + '"|' + $scriptPath + ')' } $script = '(?i)^(?:"[^"]*"|\S+)(?:\s+-(?:NoProfile|NonInteractive|NoLogo|WindowStyle\s+Hidden|ExecutionPolicy\s+Bypass))*' + - '\s+-File\s+(?:"' + $scriptPath + '"|' + $scriptPath + ')\s+-Family\s+(\S+)(?:\s|$)' + '\s+-File\s+' + $scriptArgument + '\s+-Family\s+(\S+)(?:\s|$)' foreach ($process in @(Get-CimInstance Win32_Process -ErrorAction Stop)) { $path = [string]$process.ExecutablePath if (-not $path -or $process.ProcessId -eq $PID) { continue } @@ -1174,7 +1176,13 @@ function Invoke-OpenClawClean { # Wait out any running cleanup worker before mutating; a failed run releases the locks and keeps tasks armed. # Lock every selected cleanup folder, even one without a task, so no worker can start mid-run. $lockDirectories = @(@($cleanupTasks | ForEach-Object { $_.Directory }) + @(Get-CleanGatewayCleanupProfiles $Dev) | - ForEach-Object { Get-CleanFullPath $_ } | Sort-Object -Unique) + ForEach-Object { Assert-CleanPath $_ } | Sort-Object -Unique) + foreach ($directory in $lockDirectories) { + # A folder found now but absent from the preview was never shown to the user. + if ((Test-Path -LiteralPath $directory) -and $directory -notin $profiles) { + throw "Gateway cleanup folders changed. Preview again before cleanup: $directory" + } + } foreach ($directory in $lockDirectories) { $lock = Enter-CleanGatewayCleanupLock $directory if ($lock) { $cleanupLocks.Add($lock) } @@ -1190,6 +1198,12 @@ function Invoke-OpenClawClean { foreach ($directory in $lockDirectories) { Stop-CleanGatewayCleanupWorkers $directory } # A task registered after the plan was taken would still react to package removal. if (@(Get-CleanGatewayCleanupTasks $Dev).Count -gt 0) { throw 'A Gateway cleanup task remains. Packages were not removed.' } + # Retire owned.json while still locked and before any removal: whether this run succeeds or fails, + # a worker that started after the scan then finds no record to act on once the locks are released. + foreach ($directory in $lockDirectories) { + $record = Join-Path $directory 'owned.json' + if (Test-Path -LiteralPath $record) { Remove-Item -LiteralPath $record -Force -ErrorAction Stop } + } foreach ($package in @($gateways) + @($packages | Where-Object { $_ -notin $gateways })) { Write-Host "UNINSTALL: $($package.PackageFullName)" Remove-AppxPackage -Package $package.PackageFullName -ErrorAction Stop @@ -1227,11 +1241,6 @@ function Invoke-OpenClawClean { } } foreach ($profile in $isolatedToRemove) { Remove-CleanIsolatedProfile $profile } - # A worker that started after the scan would act on owned.json once the lock is free, so retire it first. - foreach ($directory in $lockDirectories) { - $record = Join-Path $directory 'owned.json' - if (Test-Path -LiteralPath $record) { Remove-Item -LiteralPath $record -Force -ErrorAction Stop } - } # Tasks and their waiting workers are gone, so the lock files can be released and deleted with their folders. Close-CleanLocks $cleanupLocks foreach ($profile in $profiles) { diff --git a/scripts/test-clean-uninstall.ps1 b/scripts/test-clean-uninstall.ps1 index c11aeccc82..804522f6af 100644 --- a/scripts/test-clean-uninstall.ps1 +++ b/scripts/test-clean-uninstall.ps1 @@ -425,6 +425,37 @@ try { Assert-Throws { Remove-CleanGatewayCleanupTask $entry } 'Gateway cleanup task changed' Assert-True ($script:taskEvents.Count -eq 0) 'A changed cleanup task was stopped or unregistered.' } + Test-Case 'an unquoted cleanup script path containing spaces is not treated as the worker' { + $directory = "$fixture\cleanup stop\OpenClawFoundation.OpenClaw_rfcbke2p71se2" + $task = [pscustomobject]@{ TaskName = 'fixture cleanup task'; TaskPath = '\' } + $entry = [pscustomobject]@{ Name = 'fixture cleanup task'; Key = '\'; Value = 'reviewed XML'; Directory = $directory } + $script:taskEvents = [Collections.Generic.List[string]]::new() + function Get-ScheduledTask { $task } + function Export-ScheduledTask { 'reviewed XML' } + function Stop-ScheduledTask { } + function Unregister-ScheduledTask { } + $ps = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' + $family = 'OpenClawFoundation.OpenClaw_rfcbke2p71se2' + $script:processes = @( + [pscustomobject]@{ ProcessId = 31; ExecutablePath = $ps; CommandLine = "`"$ps`" -File `"$directory\cleanup.ps1`" -Family $family"; CreationDate = 'c31' } + # Windows would split this path at the space, so it runs some other script. + [pscustomobject]@{ ProcessId = 32; ExecutablePath = $ps; CommandLine = "`"$ps`" -File $directory\cleanup.ps1 -Family $family"; CreationDate = 'c32' } + ) + function Get-CimInstance { + param($ClassName, $Filter) + if ($Filter -match 'ProcessId = (\d+)') { $script:processes | Where-Object { $_.ProcessId -eq [int]$Matches[1] }; return } + $script:processes + } + function Open-CleanProcessHandle { + param($Id) + $handle = [pscustomobject]@{ Id = $Id; HasExited = $false } + $handle | Add-Member ScriptMethod Kill { $script:taskEvents.Add("kill:$($this.Id)") } + $handle | Add-Member ScriptMethod Dispose { } + $handle + } + Remove-CleanGatewayCleanupTask $entry + Assert-True (($script:taskEvents -join ',') -eq 'kill:31') "Unexpected workers killed: $($script:taskEvents -join ',')" + } Test-Case 'tree inventory includes hidden files but refuses source checkout' { $tree = Join-Path $fixture 'tree' New-Item -ItemType Directory -Path $tree | Out-Null @@ -913,6 +944,7 @@ try { $script:cleanupTasks = @() $script:cleanupTaskRemovedAfter = $null $script:cleanupTaskRemovalFails = $false + $script:packageRemovalFails = $false $script:lateTask = $null # A late task appears only after teardown starts, as if Companion registered it after the plan was taken. function Get-CleanGatewayCleanupTasks { $script:cleanupTasks; if ($script:lateTask -and $script:events -contains 'teardown') { $script:lateTask } } @@ -950,6 +982,7 @@ try { $script:events.Add('package') Assert-True ($script:events[0] -eq 'teardown') 'Package removed before native teardown.' $script:registered = $false + if ($script:packageRemovalFails) { throw 'TEST package removal failed' } } function Start-Transcript { } function Stop-Transcript { } @@ -1090,6 +1123,36 @@ try { Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-taskless-reports" } 'cleanup worker is still running' } finally { $worker.Dispose(); $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = $null } Assert-True ($events.Count -eq 0 -and (Test-Path -LiteralPath "$store\owned.json")) 'A busy worker without a task did not stop the run before mutation.' + # A failure after package removal began must not release the locks with owned.json intact. + $script:registered = $true + $script:packageRemovalFails = $true + $script:ownedAtRelease.Clear() + $script:ownedProbe = "$store\owned.json" + $events.Clear() + try { + Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-failed-removal-reports" } 'TEST package removal failed' + } finally { $script:packageRemovalFails = $false; $script:ownedProbe = $null } + Assert-True (($events -join ',') -eq 'teardown,package') "Unexpected lifecycle order: $($events -join ',')" + Assert-True ($script:ownedAtRelease.Count -gt 0 -and $script:ownedAtRelease -notcontains $true) 'owned.json survived a run that failed after package removal began.' + # A cleanup folder that appears after the preview was never shown, so the run stops before taking any lock. + $script:registered = $true + # Script-scoped names: the mocks run inside Invoke-OpenClawClean, whose locals would shadow test locals. + $script:lateFolder = "$root\OpenClawFoundation.OpenClaw_latefolder001" + function Start-Transcript { New-Item -ItemType Directory -Path $script:lateFolder -Force | Out-Null } + $events.Clear() + Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-late-folder-reports" } 'Preview again' + Assert-True ($events.Count -eq 0 -and $script:registered -and -not (Test-Path -LiteralPath "$script:lateFolder\cleanup.lock")) 'A cleanup folder added after the preview did not stop the run before mutation.' + Remove-Item -LiteralPath $script:lateFolder -Force + $script:junctionTarget = "$fixture\cleanup-junction-target" + New-Item -ItemType Directory -Path $script:junctionTarget -Force | Out-Null + Set-Content -LiteralPath "$script:junctionTarget\owned.json" -Value '{}' + $script:lateJunction = "$root\OpenClawFoundation.OpenClaw_latejunction1" + function Start-Transcript { New-Item -ItemType Junction -Path $script:lateJunction -Target $script:junctionTarget | Out-Null } + try { + Assert-Throws { Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-junction-reports" } 'reparse point' + } finally { if (Test-Path -LiteralPath $script:lateJunction) { [IO.Directory]::Delete($script:lateJunction) } } + Assert-True ($events.Count -eq 0 -and (Test-Path -LiteralPath "$script:junctionTarget\owned.json") -and -not (Test-Path -LiteralPath "$script:junctionTarget\cleanup.lock")) 'A junctioned cleanup folder was locked or changed.' + function Start-Transcript { } Invoke-OpenClawClean -Apply $true -Dev $false -Models $false -Wsl $false -Extra @() -Reports "$fixture\cleanup-final-reports" $events.Clear() }