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..046353d92e 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. @@ -475,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) { @@ -570,6 +582,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 +612,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 +622,144 @@ 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, with exactly these arguments. + $legacy = $execute -ieq $powershell -and + $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) + 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]) -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([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: $Directory" + } + 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 + } + 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') + # 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+' + $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 } + $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 { + $live = @(Get-CimInstance Win32_Process -Filter "ProcessId = $($process.ProcessId)" -ErrorAction Stop) + if ($live.Count -gt 0 -and $live[0].CreationDate -eq $process.CreationDate) { throw } + } + } +} + +function Close-CleanLocks($Locks) { + foreach ($lock in @($Locks)) { $lock.Dispose() } + $Locks.Clear() +} + +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 +1045,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 +1090,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 +1110,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" @@ -976,6 +1137,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 @@ -988,6 +1150,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 @@ -1010,11 +1173,37 @@ 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. + # 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 { 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) } + } 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-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.' } + # 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 @@ -1030,11 +1219,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) { @@ -1056,6 +1241,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) { @@ -1063,6 +1250,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 +1266,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) { @@ -1097,6 +1286,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 f1aab950bd..804522f6af 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,180 @@ 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 = "-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 }) + 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' } + 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" + 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 $directory } 'cleanup worker is still running' + } finally { $worker.Dispose(); $env:OPENCLAW_CLEAN_CLEANUP_LOCK_TIMEOUT_SECONDS = $null } + $lock = Enter-CleanGatewayCleanupLock $directory + 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') } + $ps = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' + $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 = $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' } + # 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 = @{} + foreach ($p in $script:processes) { $script:live[[int]$p.ProcessId] = $p } + function Get-CimInstance { + param($ClassName, $Filter) + if ($Filter -match 'ProcessId = (\d+)') { $hit = $script:live[[int]$Matches[1]]; if ($hit) { $hit } ; return } + $script:processes + } + 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() + # 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 = $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() + 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 '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 @@ -368,10 +544,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 @@ -459,6 +649,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) @@ -750,6 +941,39 @@ try { } function Get-CleanProcesses { } function Get-CleanStartup { } + $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 } } + 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: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)") + } + # 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 } + catch [IO.IOException] { return $true } + } function Invoke-CleanTeardown { $script:events.Add('teardown') if ($script:teardownFails) { throw 'TEST native teardown failed' } @@ -758,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 { } @@ -834,6 +1059,103 @@ 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'; 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.' + $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.' + 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' + 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 + $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.' + # 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() + } 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"