Files
leleka/scripts/laptop/win/test_state.ps1
T

366 lines
24 KiB
PowerShell

<#
.SYNOPSIS
Dry tests of scripts\laptop\win\state.ps1 (STRA-319): CPU only, no GPU query, no owner precondition.
.DESCRIPTION
Every test runs state.ps1 as a CHILD powershell process whose PATH starts with a directory of fake
`powercfg` and `nvidia-smi` shims (.cmd files) and whose environment variable LELEKA_STATE_FIXTURE_DIR points at
the same directory, which holds the data files that stand in for Get-CimInstance / Get-Process / Get-WinEvent.
The real tools are never reached: each shim logs its arguments to calls.log, and the tests assert that only
query forms were called. Nothing here touches a system setting.
Usage (from the repository root):
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\laptop\win\test_state.ps1
... -OutDir C:\Users\pavel\work\leleka\artifacts\runs\stra-319\test (scratch directory; default is
<repository root>\artifacts\runs\stra-319-test, which is ignored by Git)
Exit 0 and the last line 'ALL TESTS PASSED' when every assertion holds; otherwise exit 1.
#>
[CmdletBinding()]
param([string]$OutDir)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$here = $PSScriptRoot
$stateScript = Join-Path $here 'state.ps1'
$repoRoot = (Resolve-Path (Join-Path $here '..\..\..')).Path
if (-not $OutDir) { $OutDir = Join-Path $repoRoot 'artifacts\runs\stra-319-test' }
$stamp = (Get-Date).ToUniversalTime().ToString('yyyyMMddTHHmmssZ')
$work = Join-Path $OutDir $stamp
[void][System.IO.Directory]::CreateDirectory($work)
$script:Total = 0
$script:Failed = 0
function Assert-That([string]$Name, [bool]$Condition, [string]$Detail = '') {
$script:Total++
if ($Condition) { Write-Host (" ok {0}" -f $Name) }
else { $script:Failed++; Write-Host (" FAIL {0} {1}" -f $Name, $Detail) }
}
function Write-TextFile([string]$Path, [string]$Text, [bool]$Crlf = $false) {
if ($Crlf) { $Text = ($Text -replace "`r`n", "`n") -replace "`n", "`r`n" }
[System.IO.File]::WriteAllText($Path, $Text, (New-Object System.Text.ASCIIEncoding))
}
# ------------------------------------------------------------------ fake tool output
$SchemeGuid = '6fecc5ae-f350-48a5-b669-b472cb895ccf'
function New-SleepDump([string]$SleepAc, [string]$HibAc) {
@"
Power Scheme GUID: $SchemeGuid (Turbo)
Subgroup GUID: 238c9fa8-0aad-41ed-83f4-97be242c8f20 (Sleep)
GUID Alias: SUB_SLEEP
Power Setting GUID: 29f6c1db-86da-48c5-9fdb-f2b67b1f44da (Sleep after)
GUID Alias: STANDBYIDLE
Current AC Power Setting Index: $SleepAc
Current DC Power Setting Index: 0x000000f0
Power Setting GUID: 94ac6d29-73ce-41a6-809f-6363ba21b47e (Allow hybrid sleep)
GUID Alias: HYBRIDSLEEP
Possible Setting Index: 000
Possible Setting Index: 001
Current AC Power Setting Index: 0x00000001
Current DC Power Setting Index: 0x00000001
Power Setting GUID: 9d7815a6-7ee4-497e-8888-515a05f02364 (Hibernate after)
GUID Alias: HIBERNATEIDLE
Current AC Power Setting Index: $HibAc
Current DC Power Setting Index: 0x00000000
"@
}
function New-VideoDump([string]$VideoAc, [bool]$WithConLock, [string]$ConLockAc) {
$t = @"
Power Scheme GUID: $SchemeGuid (Turbo)
Subgroup GUID: 7516b95f-f776-4464-8c53-06167f40cc99 (Display)
GUID Alias: SUB_VIDEO
Power Setting GUID: 3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e (Turn off display after)
GUID Alias: VIDEOIDLE
Current AC Power Setting Index: $VideoAc
Current DC Power Setting Index: 0x000000f0
"@
if ($WithConLock) {
$t += @"
Power Setting GUID: 8ec4b3a5-6868-48c2-be75-4f3044be88a7 (Console lock display off timeout)
GUID Alias: VIDEOCONLOCK
Current AC Power Setting Index: $ConLockAc
Current DC Power Setting Index: 0x0000001e
"@
}
$t += @"
Power Setting GUID: aded5e82-b909-4619-9949-f5d71dac0bcb (Display brightness)
GUID Alias: VIDEONORMALLEVEL
Current AC Power Setting Index: 0x0000004a
Current DC Power Setting Index: 0x0000004a
"@
return $t
}
$PowercfgCmd = @'
@echo off
echo %* >> "%~dp0calls.log"
if /i "%~1"=="/getactivescheme" (type "%~dp0powercfg_active.txt" & exit /b 0)
if /i "%~1"=="/q" (
if /i "%~3"=="SUB_SLEEP" (type "%~dp0powercfg_sleep.txt" & exit /b 0)
if /i "%~3"=="SUB_VIDEO" (type "%~dp0powercfg_video.txt" & exit /b 0)
)
if /i "%~1"=="/qh" (if /i "%~3"=="SUB_VIDEO" (type "%~dp0powercfg_video_qh.txt" & exit /b 0))
echo shim: unexpected arguments 1>&2
exit /b 9
'@
$NvidiaSmiCmd = @'
@echo off
echo %* >> "%~dp0calls.log"
echo %* | findstr /i /c:"--query-compute-apps" >nul && (type "%~dp0apps.txt" & exit /b 0)
echo %* | findstr /i /c:"--query-gpu=" >nul && (type "%~dp0gpu.txt" & exit /b 0)
echo shim: unexpected arguments 1>&2
exit /b 9
'@
# a shim that never returns (a hung driver call)
$NvidiaSmiHangCmd = @'
@echo off
echo %* >> "%~dp0calls.log"
ping -n 61 127.0.0.1 >nul
exit /b 0
'@
function New-Scenario {
param([string]$Name, [hashtable]$Over = @{})
$d = @{
gpu = 'NVIDIA GeForce RTX 3080 Laptop GPU, 138.94 W, 140.00 W, 1695 MHz, 7001 MHz, P0, 0x0000000000000000, 61'
apps = ''
sleepAc = '0x00000000'; hibAc = '0x00000000'; videoAc = '0x00000000'; conLockAc = '0x00000000'
conLockInQ = $false
battery = '{"BatteryStatus": 2}'
os = '{"LastBootUpTime": "2026-10-28T08:00:00Z"}'
events = '[]'
processes = '[{"Name":"chrome","Id":100,"CpuPercent":12.5},{"Name":"code","Id":101,"CpuPercent":30.0},{"Name":"idle-app","Id":102,"CpuPercent":0.0}]'
hang = $false
}
foreach ($k in $Over.Keys) { $d[$k] = $Over[$k] }
$dir = Join-Path $work $Name
[void][System.IO.Directory]::CreateDirectory($dir)
Write-TextFile (Join-Path $dir 'powercfg.cmd') $PowercfgCmd $true
if ($d.hang) { Write-TextFile (Join-Path $dir 'nvidia-smi.cmd') $NvidiaSmiHangCmd $true }
else { Write-TextFile (Join-Path $dir 'nvidia-smi.cmd') $NvidiaSmiCmd $true }
Write-TextFile (Join-Path $dir 'powercfg_active.txt') ("Power Scheme GUID: $SchemeGuid (Turbo)`r`n")
Write-TextFile (Join-Path $dir 'powercfg_sleep.txt') (New-SleepDump $d.sleepAc $d.hibAc)
Write-TextFile (Join-Path $dir 'powercfg_video.txt') (New-VideoDump $d.videoAc $d.conLockInQ $d.conLockAc)
Write-TextFile (Join-Path $dir 'powercfg_video_qh.txt') (New-VideoDump $d.videoAc $true $d.conLockAc)
Write-TextFile (Join-Path $dir 'gpu.txt') ($d.gpu + "`r`n")
Write-TextFile (Join-Path $dir 'apps.txt') $(if ($d.apps) { $d.apps + "`r`n" } else { '' })
if ($d.battery) { Write-TextFile (Join-Path $dir 'battery.json') $d.battery }
Write-TextFile (Join-Path $dir 'os.json') $d.os
Write-TextFile (Join-Path $dir 'events.json') $d.events
Write-TextFile (Join-Path $dir 'processes.json') $d.processes
return $dir
}
function Invoke-State {
param([string]$ShimDir, [string[]]$StateArgs = @(), [int]$TimeoutMs = 90000)
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = (Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe')
$quoted = ($StateArgs | ForEach-Object { if ($_ -match '\s') { '"' + $_ + '"' } else { $_ } }) -join ' '
$psi.Arguments = ('-NoProfile -ExecutionPolicy Bypass -File "{0}" {1}' -f $stateScript, $quoted).Trim()
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.CreateNoWindow = $true
# the shims go on the CHILD's PATH only; this test process keeps its own PATH
$psi.EnvironmentVariables['PATH'] = $ShimDir + ';' + $env:PATH
$psi.EnvironmentVariables['LELEKA_STATE_FIXTURE_DIR'] = $ShimDir
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$p = [System.Diagnostics.Process]::Start($psi)
$o = $p.StandardOutput.ReadToEndAsync()
$e = $p.StandardError.ReadToEndAsync()
if (-not $p.WaitForExit($TimeoutMs)) { & taskkill.exe /PID $p.Id /T /F 2>&1 | Out-Null; throw "state.ps1 did not finish in $TimeoutMs ms" }
$p.WaitForExit()
$sw.Stop()
$json = $null
try { $json = $o.Result | ConvertFrom-Json } catch { }
$r = [pscustomobject]@{ Exit = $p.ExitCode; Out = $o.Result; Err = $e.Result; Json = $json; Ms = $sw.ElapsedMilliseconds }
Write-TextFile (Join-Path $ShimDir 'last-output.json') $o.Result
$p.Dispose()
return $r
}
function Test-IsUnreadable($v) { return (($v -is [string]) -and $v -ceq 'unreadable') }
function Get-CallLog([string]$Dir) {
$f = Join-Path $Dir 'calls.log'
if (Test-Path $f) { return @(Get-Content $f | ForEach-Object { $_.Trim() } | Where-Object { $_ }) }
return @()
}
$testStart = [System.Diagnostics.Stopwatch]::StartNew()
Write-Host "work directory: $work"
# ------------------------------------------------------------------ 1. good laptop
Write-Host "[1] good shims"
$dGood = New-Scenario 'good'
$r = Invoke-State $dGood
$j = $r.Json
Assert-That 'good: exit 0' ($r.Exit -eq 0) "exit=$($r.Exit) err=$($r.Err)"
Assert-That 'good: one JSON document, source fixture, read_only' ($null -ne $j -and $j.source -eq 'fixture' -and $j.read_only -eq $true)
Assert-That 'good: power scheme guid and name' ($j.settings.power_scheme_guid -eq $SchemeGuid -and $j.settings.power_scheme_name -eq 'Turbo')
Assert-That 'good: sleep, hibernate, display AC timeouts are 0' ($j.settings.timeouts_s.sleep.ac -eq 0 -and $j.settings.timeouts_s.hibernate.ac -eq 0 -and $j.settings.timeouts_s.display_off.ac -eq 0)
Assert-That 'good: DC sleep timeout 240 s (0xf0) parsed' ($j.settings.timeouts_s.sleep.dc -eq 240)
Assert-That 'good: console-lock timeout read through the hidden-settings dump' ($j.settings.timeouts_s.console_lock_display_off.ac -eq 0 -and $j.settings.timeouts_s.console_lock_display_off.dc -eq 30)
Assert-That 'good: AC status on_ac (code 2)' ($j.settings.ac_status.state -eq 'on_ac' -and $j.settings.ac_status.battery_status_code -eq 2)
Assert-That 'good: enforced_power_limit 138.94 W' ($j.settings.enforced_power_limit -eq 138.94)
Assert-That 'good: power_max_limit_w 140 W (shimmed power.max_limit)' ($j.settings.power_max_limit_w -eq 140)
Assert-That 'good: owner_attestation lists unlocked_screen, sign_in_requirement, oem_turbo' (@($j.settings.owner_attestation) -contains 'unlocked_screen' -and @($j.settings.owner_attestation) -contains 'sign_in_requirement' -and @($j.settings.owner_attestation) -contains 'oem_turbo')
Assert-That 'good: pstate, throttle reasons, temperature, clocks' ($j.gpu.pstate -eq 'P0' -and $j.gpu.throttle_reasons_active -eq '0x0000000000000000' -and $j.gpu.temperature_c -eq 61 -and $j.gpu.clocks_sm_mhz -eq 1695 -and $j.gpu.clocks_mem_mhz -eq 7001)
Assert-That 'good: boot time carried' ($j.boot_time_utc -eq '2026-10-28T08:00:00.000Z')
Assert-That 'good: no unreadable fields, no post_abort block' (@($j.unreadable_fields).Count -eq 0 -and $null -eq $j.PSObject.Properties['post_abort'])
Assert-That 'good: top-process snapshot sorted by CPU' ($j.top_processes[0].name -eq 'code' -and $j.top_processes[1].name -eq 'chrome' -and @($j.top_processes).Count -le 5)
$calls = Get-CallLog $dGood
Assert-That 'good: the shims were used (the real tools were not reached)' (@($calls | Where-Object { $_ -match '^/getactivescheme' }).Count -ge 1 -and @($calls | Where-Object { $_ -match '--query-gpu=name,enforced\.power\.limit,power\.max_limit' }).Count -eq 1)
Assert-That 'good: only query forms were called' (@($calls | Where-Object { $_ -notmatch '^(/getactivescheme|/q |/qh |--query-gpu=)' }).Count -eq 0) ($calls -join ' | ')
Assert-That 'good: no write form of powercfg was called' (@($calls | Where-Object { $_ -match '/(setactive|change|x|setacvalueindex|setdcvalueindex)' }).Count -eq 0)
Assert-That 'good: state mode does not query compute apps' (@($calls | Where-Object { $_ -match 'compute-apps' }).Count -eq 0)
# ------------------------------------------------------------------ 2. enforced limit unreadable (fail closed)
Write-Host "[2] enforced.power.limit unreadable"
$bad = [ordered]@{
'na' = 'NVIDIA GeForce RTX 3080 Laptop GPU, [N/A], 140.00 W, 1545 MHz, 7151 MHz, P5, 0x0000000000000001, 47'
'empty' = 'NVIDIA GeForce RTX 3080 Laptop GPU, , 140.00 W, 1545 MHz, 7151 MHz, P5, 0x0000000000000001, 47'
'unparsable' = 'NVIDIA GeForce RTX 3080 Laptop GPU, abc W, 140.00 W, 1545 MHz, 7151 MHz, P5, 0x0000000000000001, 47'
'notsupported' = 'NVIDIA GeForce RTX 3080 Laptop GPU, [Not Supported], 140.00 W, 1545 MHz, 7151 MHz, P5, 0x0000000000000001, 47'
'zero' = 'NVIDIA GeForce RTX 3080 Laptop GPU, 0.00 W, 140.00 W, 1545 MHz, 7151 MHz, P5, 0x0000000000000001, 47'
}
foreach ($k in $bad.Keys) {
$d = New-Scenario ("enforced-$k") @{ gpu = $bad[$k] }
$r = Invoke-State $d
Assert-That "enforced $k`: exit 4" ($r.Exit -eq 4) "exit=$($r.Exit)"
Assert-That "enforced $k`: enforced_power_limit is 'unreadable', max limit still read" ((Test-IsUnreadable $r.Json.settings.enforced_power_limit) -and $r.Json.settings.power_max_limit_w -eq 140)
Assert-That "enforced $k`: listed in unreadable_fields" (@($r.Json.unreadable_fields) -contains 'enforced_power_limit')
}
# power.limit populated but the enforced field missing from the line (7 fields): the whole sample is unusable
$d = New-Scenario 'enforced-missing-field' @{ gpu = 'NVIDIA GeForce RTX 3080 Laptop GPU, 140.00 W, 1545 MHz, 7151 MHz, P5, 0x0000000000000001, 47' }
$r = Invoke-State $d
Assert-That 'enforced field missing (power.limit populated only): exit 4, both limits unreadable' ($r.Exit -eq 4 -and (Test-IsUnreadable $r.Json.settings.enforced_power_limit) -and (Test-IsUnreadable $r.Json.settings.power_max_limit_w))
# ------------------------------------------------------------------ 3. max limit unreadable
Write-Host "[3] power.max_limit unreadable"
$badMax = [ordered]@{
'na' = 'NVIDIA GeForce RTX 3080 Laptop GPU, 138.94 W, [N/A], 1545 MHz, 7151 MHz, P5, 0x0000000000000001, 47'
'empty' = 'NVIDIA GeForce RTX 3080 Laptop GPU, 138.94 W, , 1545 MHz, 7151 MHz, P5, 0x0000000000000001, 47'
'unparsable' = 'NVIDIA GeForce RTX 3080 Laptop GPU, 138.94 W, 14O.00 W, 1545 MHz, 7151 MHz, P5, 0x0000000000000001, 47'
}
foreach ($k in $badMax.Keys) {
$d = New-Scenario ("max-$k") @{ gpu = $badMax[$k] }
$r = Invoke-State $d
Assert-That "max limit $k`: exit 4, power_max_limit_w 'unreadable', enforced limit still read" ($r.Exit -eq 4 -and (Test-IsUnreadable $r.Json.settings.power_max_limit_w) -and $r.Json.settings.enforced_power_limit -eq 138.94)
}
# ------------------------------------------------------------------ 4. a shim that never returns
Write-Host "[4] hung nvidia-smi"
$dHang = New-Scenario 'hang' @{ hang = $true }
$r = Invoke-State $dHang
$sec = [math]::Round($r.Ms / 1000.0, 1)
Write-Host (" hung nvidia-smi: total run time {0} s (limit 15 s, the call is abandoned after 5 s)" -f $sec)
Assert-That 'hang: total run time < 15 s' ($r.Ms -lt 15000) "ms=$($r.Ms)"
Assert-That 'hang: the call was not abandoned before the 5 s timeout' ($r.Ms -ge 4800) "ms=$($r.Ms)"
Assert-That 'hang: exit 4, sample status timeout, both limits unreadable (missing sample)' ($r.Exit -eq 4 -and $r.Json.gpu.sample_status -eq 'timeout' -and (Test-IsUnreadable $r.Json.settings.enforced_power_limit) -and (Test-IsUnreadable $r.Json.settings.power_max_limit_w))
Start-Sleep -Milliseconds 500
$stuck = @(Get-CimInstance Win32_Process -Filter "Name='cmd.exe'" -ErrorAction SilentlyContinue | Where-Object { $_.CommandLine -and $_.CommandLine -like "*$($dHang)*" })
Assert-That 'hang: the hung shim process tree was killed' ($stuck.Count -eq 0) "left=$($stuck.Count)"
# ------------------------------------------------------------------ 5. static read-only check on state.ps1
Write-Host "[5] static read-only check"
$pattern = 'powercfg\s+/(setactive|change|x|setacvalueindex)|Set-ExecutionPolicy|Set-ItemProperty|Stop-Computer|Restart-Computer|bash'
$hits = @(Select-String -Path $stateScript -Pattern $pattern)
Assert-That 'static: no write form, no execution-policy change, no WSL launcher in state.ps1' ($hits.Count -eq 0) (($hits | ForEach-Object { $_.Line.Trim() }) -join ' | ')
$more = @(Select-String -Path $stateScript -Pattern '/setdcvalueindex|powercfg\s+/(s|d|restoredefaultschemes|import|duplicatescheme|hibernate)\b|Set-Service|Set-Item\b|New-Item|Remove-Item|reg\s+add|Start-Service|Stop-Service|nvidia-smi\s+(-pl|--power-limit|-lgc|-ac)|-pm\b')
Assert-That 'static: no other setting-changing command in state.ps1' ($more.Count -eq 0) (($more | ForEach-Object { $_.Line.Trim() }) -join ' | ')
# ------------------------------------------------------------------ 6. settings stable across volatile changes
Write-Host "[6] settings stable"
$dA = New-Scenario 'stable-a'
$dB = New-Scenario 'stable-b' @{
gpu = 'NVIDIA GeForce RTX 3080 Laptop GPU, 138.94 W, 140.00 W, 1230 MHz, 6800 MHz, P5, 0x0000000000000024, 74'
processes = '[{"Name":"zzz","Id":9,"CpuPercent":99.0}]'
os = '{"LastBootUpTime": "2026-10-27T01:02:03Z"}'
}
$ra = Invoke-State $dA
$rb = Invoke-State $dB
$sa = ConvertTo-Json -InputObject $ra.Json.settings -Depth 8 -Compress
$sb = ConvertTo-Json -InputObject $rb.Json.settings -Depth 8 -Compress
$stable = ($sa -ceq $sb)
Write-Host (" settings stable: {0}" -f $stable)
Assert-That 'stable: the two settings objects are identical' $stable "$sa <> $sb"
Assert-That 'stable: the volatile fields differ (clocks, pstate, throttle, temperature, top processes, boot time)' ($ra.Json.gpu.clocks_sm_mhz -ne $rb.Json.gpu.clocks_sm_mhz -and $ra.Json.gpu.pstate -ne $rb.Json.gpu.pstate -and $ra.Json.gpu.throttle_reasons_active -ne $rb.Json.gpu.throttle_reasons_active -and $ra.Json.gpu.temperature_c -ne $rb.Json.gpu.temperature_c -and $ra.Json.top_processes[0].name -ne $rb.Json.top_processes[0].name -and $ra.Json.boot_time_utc -ne $rb.Json.boot_time_utc)
Assert-That 'stable: throttle mask 0x24 decodes to sw_power_cap and sw_thermal_slowdown' (@($rb.Json.gpu.throttle_reason_names) -contains 'sw_power_cap' -and @($rb.Json.gpu.throttle_reason_names) -contains 'sw_thermal_slowdown')
# ------------------------------------------------------------------ 7. post-abort check
Write-Host "[7] -PostAbort"
$dClean = New-Scenario 'post-clean'
$r = Invoke-State $dClean @('-PostAbort')
Assert-That 'post-abort clean: no leleka-/strata- process, empty compute-app list -> clean, exit 0' ($r.Exit -eq 0 -and $r.Json.mode -eq 'post_abort' -and $r.Json.post_abort.clean -eq $true -and @($r.Json.post_abort.reasons).Count -eq 0) "exit=$($r.Exit) $($r.Out)"
Assert-That 'post-abort clean: compute apps were queried (query form only)' (@(Get-CallLog $dClean | Where-Object { $_ -match '^--query-compute-apps=pid,process_name,used_memory' }).Count -eq 1)
$dProc = New-Scenario 'post-proc' @{ processes = '[{"Name":"leleka-serve","Id":4242,"CpuPercent":1.0},{"Name":"chrome","Id":100,"CpuPercent":2.0}]' }
$r = Invoke-State $dProc @('-PostAbort')
Assert-That 'post-abort leftover leleka-serve: not clean, named, exit 5' ($r.Exit -eq 5 -and $r.Json.post_abort.clean -eq $false -and $r.Json.post_abort.leftover_processes[0].name -eq 'leleka-serve' -and $r.Json.post_abort.leftover_processes[0].id -eq 4242 -and ($r.Json.post_abort.reasons -join ' ') -match 'leleka-serve')
$dStrata = New-Scenario 'post-strata' @{ processes = '[{"Name":"strata-engine","Id":77,"CpuPercent":0.0}]' }
$r = Invoke-State $dStrata @('-PostAbort')
Assert-That 'post-abort leftover strata-engine: not clean, named' ($r.Exit -eq 5 -and $r.Json.post_abort.clean -eq $false -and $r.Json.post_abort.leftover_processes[0].name -eq 'strata-engine')
$dApp = New-Scenario 'post-app' @{ apps = '1234, C:\work\x\engine.exe, 2048 MiB' }
$r = Invoke-State $dApp @('-PostAbort')
Assert-That 'post-abort one compute app listed: not clean, names the app, exit 5' ($r.Exit -eq 5 -and $r.Json.post_abort.clean -eq $false -and @($r.Json.post_abort.compute_apps).Count -eq 1 -and $r.Json.post_abort.compute_apps[0].process_name -eq 'C:\work\x\engine.exe' -and ($r.Json.post_abort.reasons -join ' ') -match 'engine\.exe')
# ------------------------------------------------------------------ 8. crash evidence
Write-Host "[8] Kernel-Power 41 / BugCheck evidence"
$evKp = '{"Id":41,"ProviderName":"Microsoft-Windows-Kernel-Power","TimeCreated":"2026-10-28T10:30:00Z","Message":"The system has rebooted without cleanly shutting down first.\nLine two."}'
$evBc = '{"Id":1001,"ProviderName":"Microsoft-Windows-WER-SystemErrorReporting","TimeCreated":"2026-10-28T10:30:20Z","Message":"The computer has rebooted from a bugcheck. 0x0000019c"}'
$evOld = '{"Id":41,"ProviderName":"Microsoft-Windows-Kernel-Power","TimeCreated":"2026-10-20T10:30:00Z","Message":"old"}'
$evOther = '{"Id":41,"ProviderName":"Some-Other-Provider","TimeCreated":"2026-10-28T10:31:00Z","Message":"not kernel power"}'
$dEv = New-Scenario 'events' @{ events = "[$evKp,$evBc,$evOld,$evOther]" }
$r = Invoke-State $dEv @('-ReferenceTime', '2026-10-28T09:00:00Z')
Assert-That 'events: Kernel-Power 41 dated after the reference time is listed (only that one)' (@($r.Json.crash_evidence.kernel_power_41).Count -eq 1 -and $r.Json.crash_evidence.kernel_power_41[0].time_utc -eq '2026-10-28T10:30:00.000Z' -and $r.Json.crash_evidence.kernel_power_41[0].message_first_line -eq 'The system has rebooted without cleanly shutting down first.') ($r.Out)
Assert-That 'events: BugCheck after the reference time is listed; other providers are ignored; count 2' (@($r.Json.crash_evidence.bugcheck).Count -eq 1 -and $r.Json.crash_evidence.count -eq 2 -and $r.Json.crash_evidence.reference_time_source -eq 'parameter')
$dEvOld = New-Scenario 'events-old' @{ events = "[$evOld]" }
$r = Invoke-State $dEvOld @('-ReferenceTime', '2026-10-28T09:00:00Z')
Assert-That 'events: only events dated before the reference time -> none listed' ($r.Json.crash_evidence.count -eq 0 -and @($r.Json.crash_evidence.kernel_power_41).Count -eq 0)
$r = Invoke-State $dEv
Assert-That 'events: default reference time is the boot time (08:00Z): the 10:30 event is listed, the 10-20 one is not' ($r.Json.crash_evidence.reference_time_source -eq 'boot_time' -and $r.Json.crash_evidence.reference_time_utc -eq '2026-10-28T08:00:00.000Z' -and @($r.Json.crash_evidence.kernel_power_41).Count -eq 1)
$r = Invoke-State $dEv @('-ReferenceTime', 'not-a-time')
Assert-That 'events: an invalid -ReferenceTime exits 3 without a JSON document' ($r.Exit -eq 3 -and $null -eq $r.Json)
# ------------------------------------------------------------------ 9. WSL / Docker, battery
Write-Host "[9] WSL / Docker presence, AC status"
$dWsl = New-Scenario 'wsl' @{ processes = '[{"Name":"vmmemWSL","Id":55,"CpuPercent":3.0},{"Name":"com.docker.backend","Id":56,"CpuPercent":1.0}]' }
$r = Invoke-State $dWsl
Assert-That 'wsl_docker: vmmemWSL and Docker present are reported' ($r.Json.wsl_docker.vmmemWSL_present -eq $true -and $r.Json.wsl_docker.docker_present -eq $true -and @($r.Json.wsl_docker.found).Count -eq 2)
Assert-That 'wsl_docker: absent in the good scenario' ($ra.Json.wsl_docker.vmmemWSL_present -eq $false -and $ra.Json.wsl_docker.docker_present -eq $false)
$dBat = New-Scenario 'battery' @{ battery = '{"BatteryStatus": 1}' }
$r = Invoke-State $dBat
Assert-That 'ac_status: BatteryStatus 1 -> on_battery' ($r.Json.settings.ac_status.state -eq 'on_battery' -and $r.Json.settings.ac_status.battery_status_code -eq 1)
$dNoBat = New-Scenario 'nobattery' @{ battery = '' }
$r = Invoke-State $dNoBat
Assert-That 'ac_status: no Win32_Battery instance -> no_battery_instance (owner attestation only)' ($r.Json.settings.ac_status.state -eq 'no_battery_instance' -and $null -eq $r.Json.settings.ac_status.battery_status_code)
# ------------------------------------------------------------------ 10. non-zero timeouts and the output file
Write-Host "[10] timeouts and -OutFile"
$dTo = New-Scenario 'timeouts' @{ sleepAc = '0x00000708'; hibAc = '0x00000e10'; videoAc = '0x0000012c'; conLockAc = '0x0000003c'; conLockInQ = $true }
$outFile = Join-Path $work 'timeouts-out.json'
$r = Invoke-State $dTo @('-OutFile', $outFile)
Assert-That 'timeouts: non-zero AC values parsed (1800 s, 3600 s, 300 s, 60 s)' ($r.Json.settings.timeouts_s.sleep.ac -eq 1800 -and $r.Json.settings.timeouts_s.hibernate.ac -eq 3600 -and $r.Json.settings.timeouts_s.display_off.ac -eq 300 -and $r.Json.settings.timeouts_s.console_lock_display_off.ac -eq 60)
Assert-That 'timeouts: the console-lock setting found in the plain dump needs no hidden-settings query' (@(Get-CallLog $dTo | Where-Object { $_ -match '^/qh' }).Count -eq 0)
Assert-That '-OutFile: the file holds the same JSON as stdout' ((Test-Path $outFile) -and (($r.Json | ConvertTo-Json -Depth 8 -Compress) -ceq ((Get-Content $outFile -Raw) | ConvertFrom-Json | ConvertTo-Json -Depth 8 -Compress)))
# ------------------------------------------------------------------ result
$testStart.Stop()
Write-Host ("{0} assertions, {1} failed, {2} s" -f $script:Total, $script:Failed, [math]::Round($testStart.Elapsed.TotalSeconds, 1))
if ($script:Failed -eq 0 -and $script:Total -ge 8) {
Write-Host 'ALL TESTS PASSED'
exit 0
}
Write-Host 'TESTS FAILED'
exit 1