diff --git a/Start-SystemCleanup.ps1 b/Start-SystemCleanup.ps1 index d631232..a847b56 100644 --- a/Start-SystemCleanup.ps1 +++ b/Start-SystemCleanup.ps1 @@ -20,6 +20,7 @@ function Get-SystemCleanupDefaults { CleanupDiagnosticDays = 30 CleanupBackupDays = 30 CleanupSystemTemp = $true + CleanupOfficeStaging = $true CleanupUserTemp = $true CleanupServiceTemp = $true CleanupCBSArchives = $true @@ -183,7 +184,9 @@ function Get-SystemCleanupChildren { Write-SystemCleanupMessage "Skipping linked or unsafe path: $Root" return } - Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop | Where-Object { -not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) } + # Office staging has its own mutex/identity/retention rules. Generic temp scans + # must not bypass them or remove deferred user-cleanup helpers. + Get-ChildItem -LiteralPath $Root -Force -ErrorAction Stop | Where-Object { -not ($_.Attributes -band [IO.FileAttributes]::ReparsePoint) -and $_.Name -ne 'EmberkomOfficeDeployment' } } function Get-SystemCleanupFiles { @@ -201,6 +204,7 @@ function Get-SystemCleanupFiles { function Remove-SystemCleanupFile { param($Context, [string]$Category, [string]$Root, [string]$Path, [datetime]$Cutoff) + if ($Category -ne 'OfficeStaging' -and $Path -match '(?i)(^|[\\/])EmberkomOfficeDeployment([\\/]|$)') { return } if (-not (Test-SystemCleanupPath $Path $Root)) { return } $file = Get-Item -LiteralPath $Path -Force -ErrorAction Stop if ($file.PSIsContainer -or $file.LastWriteTimeUtc -ge $Cutoff) { return } @@ -533,6 +537,100 @@ function Remove-SystemCleanupBundle { } } +function Get-SystemCleanupOfficeStagingRoots { + param([string[]]$Profiles) + @( + (Join-Path ([IO.Path]::GetTempPath()) 'EmberkomOfficeDeployment') + (Join-Path $env:SystemRoot 'Temp\EmberkomOfficeDeployment') + (Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment') + (Join-Path $env:ProgramData 'EmberkomOfficeDeployment') + foreach ($profile in $Profiles) { Join-Path $profile 'AppData\Local\Temp\EmberkomOfficeDeployment' } + ) | Sort-Object -Unique +} + +function New-SystemCleanupOfficeMutex { + return New-Object Threading.Mutex($false, 'Global\EmberkomOfficeDeployment') +} + +function Clear-SystemCleanupOfficeStaging { + param($Context, [string[]]$Roots, [datetime]$Cutoff) + $rootsPresent = @($Roots | Select-Object -Unique | Where-Object { Test-Path -LiteralPath $_ }) + if (-not $rootsPresent.Count) { return } + $mutex = New-SystemCleanupOfficeMutex + $acquired = $false; $retained = 0 + try { + try { $acquired = $mutex.WaitOne(0) } catch [Threading.AbandonedMutexException] { $acquired = $true } + if (-not $acquired) { Set-SystemCleanupSkipped $Context 'OfficeStaging' 'Office deployment is running; staging retained.'; return } + $processes = @(Get-CimInstance Win32_Process -ErrorAction Stop) + if (@($processes | Where-Object { $_.Name -in @('setup.exe', 'odt.exe', 'msiexec.exe', 'OfficeC2RClient.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe', 'MicrosoftEdgeWebview2Setup.exe') }).Count) { + Set-SystemCleanupSkipped $Context 'OfficeStaging' 'An installer is running; staging retained.'; return + } + # Match Install-MicrosoftOffice365's disposable artifact allowlist. Never delete + # options, logs, XML, user helpers, task markers, locks or the workspace itself. + $names = @('ODT', 'odt.exe', 'odt-download-page.html', 'GetHelp', 'GetHelp.zip', 'media-cache.json', + 'MicrosoftEdgeWebview2Setup.exe', 'teamsbootstrapper.exe', 'OutlookSetup.exe', 'OneDriveSetup.exe') + foreach ($root in $rootsPresent) { + if (-not (Test-SystemCleanupPath $root $root)) { $retained++; continue } + foreach ($folder in @(Get-ChildItem -LiteralPath $root -Directory -Force -ErrorAction Stop | Where-Object { $_.Name -match '^[a-f0-9]{32}$' })) { + try { + if (-not (Test-SystemCleanupPath $folder.FullName $root)) { throw 'Linked or unsafe workspace.' } + $markerPath = Join-Path $folder.FullName 'options.json' + if (-not (Test-Path -LiteralPath $markerPath -PathType Leaf)) { throw 'Missing deployment identity.' } + if (-not (Test-SystemCleanupPath $markerPath $root)) { throw 'Linked deployment identity.' } + $marker = Get-Item -LiteralPath $markerPath -Force -ErrorAction Stop + if ($marker.Length -gt 64KB) { throw 'Oversized deployment identity.' } + $options = Get-Content -LiteralPath $markerPath -Raw -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop + if ($options.ProductId -notin @('O365BusinessRetail','O365BusinessEEANoTeamsRetail','O365ProPlusRetail','O365ProPlusEEANoTeamsRetail') -or + $options.OfficeArchitecture -notin @('32','64') -or $options.UpdateChannel -notin @('Current','MonthlyEnterprise','SemiAnnual')) { throw 'Unrecognized deployment identity.' } + if ($folder.LastWriteTimeUtc -ge $Cutoff -or $marker.LastWriteTimeUtc -ge $Cutoff) { throw 'Recent deployment.' } + foreach ($process in $processes) { + foreach ($value in @($process.CommandLine, $process.ExecutablePath)) { + if ($value -and $value.IndexOf($folder.FullName, [StringComparison]::OrdinalIgnoreCase) -ge 0) { throw 'Workspace is referenced by a running process.' } + } + } + $items = New-Object 'System.Collections.Generic.List[object]' + $pending = New-Object 'System.Collections.Generic.Stack[string]' + foreach ($name in $names) { + $target = Join-Path $folder.FullName $name + if (Test-Path -LiteralPath $target) { $pending.Push($target) } + } + while ($pending.Count) { + $target = $pending.Pop() + if (-not (Test-SystemCleanupPath $target $folder.FullName)) { throw 'Linked staging artifact.' } + $item = Get-Item -LiteralPath $target -Force -ErrorAction Stop + if ($item.LastWriteTimeUtc -ge $Cutoff) { throw 'Recent staging artifact.' } + $items.Add($item) + if ($item.PSIsContainer) { + foreach ($child in @(Get-ChildItem -LiteralPath $target -Force -ErrorAction Stop)) { $pending.Push($child.FullName) } + } else { + # Probe in preview too; in-use data is not an eligible estimate. + $probe = [IO.File]::Open($item.FullName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::None) + $probe.Dispose() + } + } + foreach ($file in @($items | Where-Object { -not $_.PSIsContainer })) { + Remove-SystemCleanupFile $Context 'OfficeStaging' $folder.FullName $file.FullName $Cutoff + } + if (-not $Context.Options.ReportOnly) { + foreach ($directory in @($items | Where-Object PSIsContainer | Sort-Object { $_.FullName.Length } -Descending)) { + if ((Test-SystemCleanupPath $directory.FullName $folder.FullName) -and @(Get-ChildItem -LiteralPath $directory.FullName -Force -ErrorAction Stop).Count -eq 0) { + [IO.Directory]::Delete($directory.FullName, $false) + } + } + } + } catch { + $retained++ + Write-SystemCleanupMessage "Office staging retained at $($folder.FullName): $($_.Exception.Message)" -Detail + } + } + } + if ($retained) { $Context.Stats.OfficeStaging.Notes = "$retained folder(s) retained: recent, active, unrecognized or unsafe; see verbose." } + } finally { + if ($acquired) { $mutex.ReleaseMutex() } + $mutex.Dispose() + } +} + function Get-SystemCleanupRecycleDate { param([string]$MetadataPath) if ((Get-Item -LiteralPath $MetadataPath -Force -ErrorAction Stop).Length -gt 1MB) { throw 'Oversized Recycle Bin metadata.' } @@ -700,9 +798,14 @@ function Invoke-SystemCleanup { # Generic temp cleaning must not bypass the AutoCAD process check or dump retention. $tempExclusions = @('*.ac$', '*.sv$', '*.dmp') Invoke-SystemCleanupCategory $context 'SystemTemp' { - Clear-SystemCleanupTree $context 'SystemTemp' (Join-Path $env:SystemRoot 'Temp') $tempCutoff -Exclude $tempExclusions -Recurse + foreach ($relative in @('Temp', 'SystemTemp')) { + Clear-SystemCleanupTree $context 'SystemTemp' (Join-Path $env:SystemRoot $relative) $tempCutoff -Exclude $tempExclusions -Recurse + } # Includes .evtx, computer-name logs, AppxErrorReport files, and Chocolatey temp. } + Invoke-SystemCleanupCategory $context 'OfficeStaging' { + Clear-SystemCleanupOfficeStaging $context (Get-SystemCleanupOfficeStagingRoots $allProfiles) $tempCutoff + } Invoke-SystemCleanupCategory $context 'UserTemp' { $acadRunning = Test-SystemCleanupAppRunning @('acad') foreach ($profile in $profiles) { diff --git a/docs/SystemCleanup.md b/docs/SystemCleanup.md index 151c66d..8ade2cc 100644 --- a/docs/SystemCleanup.md +++ b/docs/SystemCleanup.md @@ -120,10 +120,11 @@ selections, and mixtures of presets with other values also fail before cleanup. | Variable | Default | Purpose | | --- | --- | --- | | `CleanupReportOnly` | true | Assess all categories versus apply enabled categories only | -| `CleanupTempDays` | 7 | Temp files, installers, browser cache, Apple downloads | +| `CleanupTempDays` | 7 | Temp files, installers, abandoned Office staging, browser cache, Apple downloads | | `CleanupDiagnosticDays` | 30 | CBS, WER archives, dumps, Revit journals | | `CleanupBackupDays` | 30 | Downloads, backups, time spent in Recycle Bin | -| `CleanupSystemTemp` | true | Windows Temp, including EVTX, misc logs, AppxErrorReport, Chocolatey | +| `CleanupSystemTemp` | true | Windows Temp and SystemTemp, including EVTX, misc logs, AppxErrorReport, Chocolatey; excludes Office staging | +| `CleanupOfficeStaging` | true | Recognized abandoned Office deployment media, using CleanupTempDays; preserves diagnostics and deferred-user helpers | | `CleanupUserTemp` | true | Registered user profiles' Local Temp; AutoCAD `.ac$` only with AutoCAD closed | | `CleanupServiceTemp` | true | LocalService, NetworkService, SYSTEM profile temp folders | | `CleanupCBSArchives` | true | `CbsPersist_*.log` and `CbsPersist_*.cab` | @@ -218,6 +219,22 @@ termination can leave a temporary slot behind; future runs skip occupied slots. ## Deletion and operational boundaries +- `OfficeStaging` checks the execution account's temp directory, Windows Temp and + SystemTemp, registered user/service profile temp directories, and legacy + ProgramData, under `EmberkomOfficeDeployment`. It runs on clients and servers. + The deployment mutex must be available, process inventory must succeed, and no + recognized installer may be running. Each workspace must have a GUID name and a + bounded, recognizable `options.json`; its directory, identity and every payload + artifact must be older than `CleanupTempDays`. Recent, linked, locked, unrecognized + or process-referenced workspaces are retained, including in report-only estimates. +- Office cleanup deletes only named payload artifacts (ODT, companion installers, + old GetHelp downloads and cache manifests). It preserves logs, options, XML, + helper scripts, locks, task markers, unknown files and the workspace itself. + Generic temp scans exclude this subtree, so they cannot bypass the dedicated + option, retention or active-deployment checks. Report-only lists eligible media + even when `CleanupOfficeStaging=false`; apply skips that disabled category. + Process and mutex skips remain visible in the compact report; per-folder + retention reasons are available through verbose output. - Inspect each file's modification time; an old parent never authorizes deletion of newer children. Ordinary cache/temp directories are retained. - Use literal local paths, verify containment, and skip reparse points and linked @@ -262,13 +279,17 @@ Coverage includes disabled-category estimates, separate report groups, unique totals for overlapping categories, and disabled categories remaining untouched in apply mode. Preset tests verify exact handler membership, cumulative selections, RMM scope preservation, None disabling native work, and the server exclusions. -Output tests cover the duplicate-object regression, a 22-category preview under +Output tests cover the duplicate-object regression, a 23-category preview under 4 KiB including diagnostics, separate enabled/disabled sections, and preservation of diagnostic notes. Regression checks ensure DISM analysis is absent and report diagnostics launch no native programs. Hibernation/VSS tests cover usage in category MiB columns, zero for absence, unknown sizes after access failures, cross-drive storage, server exclusions, no duplicate diagnostic lines, and usage staying out of savings totals. +Office staging tests cover Windows SystemTemp and legacy ProgramData, complete +artifact selection, identity/age/link/lock/process guards, deployment mutex +contention, disabled categories, server support, generic-temp exclusion, and +preservation of diagnostics and deferred-user files. References: [OS ProductType](https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-operatingsystem), [Disk Cleanup](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/cleanmgr), diff --git a/rmm/Start-SystemCleanup.ps1 b/rmm/Start-SystemCleanup.ps1 index 365dcc8..32ce5f8 100644 --- a/rmm/Start-SystemCleanup.ps1 +++ b/rmm/Start-SystemCleanup.ps1 @@ -2,6 +2,7 @@ # Configure these [string] Dropdown variables in Syncro, each with true/false choices: # [string]$CleanupReportOnly - true (default: assess all), false (apply enabled only) # [string]$CleanupSystemTemp - true (default), false +# [string]$CleanupOfficeStaging - true (default), false; uses CleanupTempDays # [string]$CleanupUserTemp - true (default), false # [string]$CleanupServiceTemp - true (default), false # [string]$CleanupCBSArchives - true (default), false @@ -48,6 +49,8 @@ # Verbose output can exceed Syncro's output limit. No new Syncro variables are needed. # Server-blocked categories are listed without assessment. Native savings may be unknown. # Server exclusions cannot be overridden by these variables. No reboot is initiated. +# OfficeStaging checks Windows Temp/SystemTemp, execution/profile temp and legacy ProgramData. +# Only recognized, aged installer media is eligible; active deployments and user helpers are protected. $ErrorActionPreference = 'Stop' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 diff --git a/tests/Start-SystemCleanup.Tests.ps1 b/tests/Start-SystemCleanup.Tests.ps1 index 2dfcd55..14b018f 100644 --- a/tests/Start-SystemCleanup.Tests.ps1 +++ b/tests/Start-SystemCleanup.Tests.ps1 @@ -34,6 +34,8 @@ try { foreach ($definition in $core.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst]}, $false)) { . ([scriptblock]::Create($definition.Extent.Text)) } + # Never contend with a real deployment on the test host. + function New-SystemCleanupOfficeMutex { return [Threading.Mutex]::new($false) } $messageWriter = ${function:Write-SystemCleanupMessage} $script:messages = @(); $script:details = @() function Write-SystemCleanupMessage { @@ -209,7 +211,7 @@ try { $o.ReportOnly=$true foreach ($name in $blocked) { if ($name -ne 'DiskCleanup') { $o[$name]=$true } } $result = @(Invoke-SystemCleanup $o) - Assert-Cleanup ($result.Count -eq 22 -and @($result | Where-Object Status -eq 'Blocked on server').Count -eq $blocked.Count) 'Server report must list every blocked category.' + Assert-Cleanup ($result.Count -eq 23 -and @($result | Where-Object Status -eq 'Blocked on server').Count -eq $blocked.Count) 'Server report must list every blocked category.' Assert-Cleanup (@($script:assessed | Where-Object { $_ -in $blocked }).Count -eq 0) 'Server report must not assess blocked categories.' } @@ -329,6 +331,96 @@ try { Assert-Cleanup ($d.Count -eq 0 -and $script:fileReads -eq 0 -and $script:storageReads -eq 0 -and $script:diagnosticProcesses -eq 0) 'Apply mode must not run report diagnostics.' } + # Abandoned Office payloads: report/apply, disabled options, server support, + # identity, retention, process/lock/link protection, and durable helper survival. + & { + $officeAst=Read-CleanupAst 'Install-MicrosoftOffice365.ps1' + foreach ($definition in $officeAst.FindAll({param($n) $n -is [Management.Automation.Language.FunctionDefinitionAst] -and $n.Name -in @('Get-OfficeDeploymentDefinitions','Get-OfficeStagingNames')},$false)) { + . ([scriptblock]::Create($definition.Extent.Text)) + } + $names=@(Get-OfficeStagingNames) + $script:officeProcesses=@(); $script:officeInventoryFails=$false + function Get-CimInstance { if ($script:officeInventoryFails) { throw 'Synthetic process inventory failure' }; $script:officeProcesses } + function New-StageFixture { + param($Parent,$Id) + $relative=$Parent+'\'+($Id*32) + $null=New-CleanupFixture ($relative+'\options.json') '{"ProductId":"O365BusinessRetail","OfficeArchitecture":"64","UpdateChannel":"Current"}' + foreach ($name in $names) { + $leaf=if ($name -in @('ODT','GetHelp')) { $name+'\payload.dat' } else { $name } + $null=New-CleanupFixture ($relative+'\'+$leaf) + } + foreach ($name in @('Office-UserCleanup.ps1','user-cleanup.lock','install.xml','office-install.stdout.log','unknown.exe')) { $null=New-CleanupFixture ($relative+'\'+$name) } + $folder=Join-Path $testRoot $relative + foreach ($dir in @(Get-ChildItem -LiteralPath $folder -Recurse -Directory)+@(Get-Item -LiteralPath $folder)) { [IO.Directory]::SetLastWriteTimeUtc($dir.FullName,[datetime]::UtcNow.AddDays(-60)) } + return $folder + } + function Test-StageCleanup { + param([bool]$ReportOnly=$true,[bool]$Enabled=$true,[bool]$Server=$false) + $c=New-CleanupContext -ReportOnly $ReportOnly -Server $Server; $c.Options.OfficeStaging=$Enabled + Invoke-SystemCleanupCategory $c 'OfficeStaging' { Clear-SystemCleanupOfficeStaging $c $stageRoots ([datetime]::UtcNow.AddDays(-7)) } + return $c + } + $folder=New-StageFixture 'office-fixture\Windows\SystemTemp\EmberkomOfficeDeployment' 'a' + $legacy=New-StageFixture 'office-fixture\ProgramData\EmberkomOfficeDeployment' 'b' + $stageRoots=@((Split-Path -Parent $folder),(Split-Path -Parent $legacy)) + Assert-Cleanup ((Get-SystemCleanupOfficeStagingRoots @()) -contains (Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment')) 'SystemTemp must be a supported Office staging root.' + $c=Test-StageCleanup -Enabled $false + Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq (2*$names.Count) -and !$c.Stats.OfficeStaging.Enabled -and (Test-Path -LiteralPath (Join-Path $folder 'ODT\payload.dat'))) 'Disabled report must measure every installer artifact without deleting it.' + $c=Test-StageCleanup -Server $true + Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq (2*$names.Count) -and $c.Errors -eq 0) 'Owned staging cleanup must support server OSes.' + $c=New-CleanupContext + Invoke-SystemCleanupCategory $c 'SystemTemp' { Clear-SystemCleanupTree $c 'SystemTemp' (Split-Path -Parent $stageRoots[0]) ([datetime]::UtcNow.AddDays(-7)) -Recurse } + Assert-Cleanup ($c.Stats.SystemTemp.CandidateFiles -eq 0) 'Generic temp traversal must exclude Office staging entirely.' + $c=Test-StageCleanup -ReportOnly $false -Enabled $false + Assert-Cleanup ((Test-Path -LiteralPath (Join-Path $folder 'ODT\payload.dat')) -and !$c.Stats.Count) 'Disabled apply must preserve staged media.' + $script:officeProcesses=@([pscustomobject]@{Name='setup.exe'}) + $c=Test-StageCleanup + Assert-Cleanup ($c.Stats.OfficeStaging.Status -eq 'Skipped' -and $c.Stats.OfficeStaging.EstimateStatus -eq 'Not assessed') 'An installer without a workspace path must block staging cleanup.' + $script:officeProcesses=@([pscustomobject]@{Name='worker.exe'; ExecutablePath=(Join-Path $folder 'ODT\worker.exe')}) + $c=Test-StageCleanup + Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count -and $c.Stats.OfficeStaging.Notes -match 'retained') 'A running process must retain its workspace while allowing other abandoned media.' + $script:officeProcesses=@(); $script:officeInventoryFails=$true + $c=Test-StageCleanup -ReportOnly $false + Assert-Cleanup ($c.Errors -eq 1 -and (Test-Path -LiteralPath (Join-Path $folder 'ODT\payload.dat'))) 'Failed process inventory must prevent deletion.' + $script:officeInventoryFails=$false + & { + function New-SystemCleanupOfficeMutex { + $m=[pscustomobject]@{} + $m | Add-Member ScriptMethod WaitOne { param($Timeout) return $false } + $m | Add-Member ScriptMethod Dispose { } + return $m + } + $c=Test-StageCleanup -ReportOnly $false + Assert-Cleanup ($c.Stats.OfficeStaging.Status -eq 'Skipped' -and (Test-Path -LiteralPath (Join-Path $folder 'odt.exe'))) 'Active deployment mutex must block cleanup.' + } + $payload=Join-Path $folder 'ODT\payload.dat' + $handle=[IO.File]::Open($payload,[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::None) + try { $c=Test-StageCleanup; Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count) 'Locked media must not count as reclaimable.' } finally { $handle.Dispose() } + [IO.File]::SetLastWriteTimeUtc($payload,[datetime]::UtcNow) + $c=Test-StageCleanup + Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count) 'A fresh payload must retain the whole workspace media set.' + [IO.File]::SetLastWriteTimeUtc($payload,[datetime]::UtcNow.AddDays(-60)) + $outside=New-CleanupFixture 'office-outside\keep.dat' + $junction=Join-Path $folder 'ODT\linked' + $null=New-Item -ItemType Junction -Path $junction -Target (Split-Path -Parent $outside) + try { + [IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $junction),[datetime]::UtcNow.AddDays(-60)) + $c=Test-StageCleanup + Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count -and (Test-Path -LiteralPath $outside)) 'Linked artifacts must retain the whole media set without traversing the link.' + } finally { [IO.Directory]::Delete($junction,$false); [IO.Directory]::SetLastWriteTimeUtc((Split-Path -Parent $junction),[datetime]::UtcNow.AddDays(-60)) } + $marker=Join-Path $folder 'options.json'; [IO.File]::WriteAllText($marker,'{}'); [IO.File]::SetLastWriteTimeUtc($marker,[datetime]::UtcNow.AddDays(-60)) + $c=Test-StageCleanup + Assert-Cleanup ($c.Stats.OfficeStaging.CandidateFiles -eq $names.Count) 'Unrecognized folders must not be deleted based only on their names.' + [IO.File]::WriteAllText($marker,'{"ProductId":"O365BusinessRetail","OfficeArchitecture":"64","UpdateChannel":"Current"}'); [IO.File]::SetLastWriteTimeUtc($marker,[datetime]::UtcNow.AddDays(-60)) + $c=Test-StageCleanup -ReportOnly $false + Assert-Cleanup ($c.Errors -eq 0 -and $c.Stats.OfficeStaging.RemovedFiles -eq (2*$names.Count) -and !(Test-Path -LiteralPath (Join-Path $folder 'ODT')) -and !(Test-Path -LiteralPath (Join-Path $legacy 'ODT'))) 'Apply must remove known aged media from SystemTemp and legacy ProgramData.' + foreach ($workspace in @($folder,$legacy)) { + foreach ($name in @('options.json','Office-UserCleanup.ps1','user-cleanup.lock','install.xml','office-install.stdout.log','unknown.exe')) { + Assert-Cleanup (Test-Path -LiteralPath (Join-Path $workspace $name)) "Office staging cleanup removed protected data: $name" + } + } + } + # File ages, literal brackets, nested fresh files, no changes in preview. $root=Join-Path $testRoot 'temps' $old=New-CleanupFixture 'temps\old[1].tmp' @@ -558,6 +650,7 @@ try { } } function Test-SystemCleanupAppRunning { return $false } + function Get-SystemCleanupOfficeStagingRoots { return (Join-Path $env:SystemRoot 'SystemTemp\EmberkomOfficeDeployment') } function Get-Service { [pscustomobject]@{Status='Stopped'} } function Remove-Item { throw 'PREVIEW MUTATION: Remove-Item' } function New-ItemProperty { throw 'PREVIEW MUTATION: registry write' } @@ -569,13 +662,13 @@ try { $o=Get-SystemCleanupOptions $script:messages=@(); $script:details=@() $result=@(Invoke-SystemCleanup $o) - Assert-Cleanup ($result.Count -eq 22 -and @($result | Where-Object Status -ne 'Preview').Count -eq 0) "Full preview did not cover every category (count=$($result.Count))." + Assert-Cleanup ($result.Count -eq 23 -and @($result | Where-Object Status -ne 'Preview').Count -eq 0) "Full preview did not cover every category (count=$($result.Count))." Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'DownloadedExecutables' -and -not $_.Enabled -and $_.CandidateFiles -eq 1 }).Count -eq 1) 'Default-disabled downloads were not assessed by the entry point.' Assert-Cleanup (@($result | Where-Object { $_.Category -eq 'ComponentStore' -and -not $_.Enabled -and $null -eq $_.CandidateBytes -and $_.EstimateStatus -eq 'Not estimated' }).Count -eq 1) 'Unknown native savings must not be reported as zero.' Assert-Cleanup (Test-Path -LiteralPath (Join-Path $env:SystemRoot 'Temp\old.tmp')) 'Full preview removed a fixture.' $compactOutput = ($script:messages | ForEach-Object { '[SystemCleanup] ' + $_ }) -join "`r`n" $script:compactReportBytes = [Text.Encoding]::UTF8.GetByteCount($compactOutput) - Assert-Cleanup ($script:compactReportBytes -lt 4096) "22-category preview exceeded the 4 KiB regression budget ($script:compactReportBytes bytes)." + Assert-Cleanup ($script:compactReportBytes -lt 4096) "23-category preview exceeded the 4 KiB regression budget ($script:compactReportBytes bytes)." foreach ($row in $result) { Assert-Cleanup ([regex]::Matches($compactOutput, ('(?m)^\[SystemCleanup\] ' + [regex]::Escape($row.Category) + '\s')).Count -eq 1) "Compact report lost or repeated category $($row.Category)." } @@ -604,7 +697,7 @@ try { Assert-Cleanup ($c.Errors -eq 1 -and $report -match 'CrashDumps.*Failed; incomplete.*Synthetic failure.*see verbose' -and $report.Length -lt 1600) 'A long multiline error must retain its failure status without flooding the summary.' Assert-Cleanup (($script:details -join "`n").Contains(('long diagnostic ' * 300))) 'Compacted errors must remain complete in verbose diagnostics.' } - Write-Host "Compact 22-category preview: $script:compactReportBytes UTF-8 bytes." + Write-Host "Compact 23-category preview: $script:compactReportBytes UTF-8 bytes." Write-Host "PASS: $script:assertions offline cleanup assertions ($($PSVersionTable.PSVersion))." } finally { # Only this test's generated directory; links are removed non-recursively above.