Merge claude/stra-319 into Train A (STRA-245)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-28 20:31:12 +01:00
co-authored by Claude Sonnet 5.5
2 changed files with 853 additions and 0 deletions
+488
View File
@@ -0,0 +1,488 @@
<#
.SYNOPSIS
READ-ONLY state and precondition reader for the Windows laptop (STRA-319, S3.10 of STRA-245).
.DESCRIPTION
Prints ONE JSON document on stdout and changes nothing. It never changes a power, display, lock, sleep,
execution-policy or any other system setting; the owner-run SETTER is scripts\dev\laptop-turbo.ps1 and is
not used or cited here as a reader. The commands used are query-only:
powercfg (the active-scheme query and the settings-dump query for one scheme and subgroup)
nvidia-smi --query-gpu=... / --query-compute-apps=... (query only, no GPU load)
Get-CimInstance (Win32_Battery, Win32_OperatingSystem), Get-Process, Get-WinEvent (System log, read only)
Windows PowerShell 5.1, standard library only, no WSL launcher and no other shell is started.
Usage (from the repository root):
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\laptop\win\state.ps1
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\laptop\win\state.ps1 -ReferenceTime 2026-10-28T08:00:00Z
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\laptop\win\state.ps1 -PostAbort
... -OutFile C:\Users\pavel\work\leleka\artifacts\runs\<series>\state-before.json (also writes the JSON there;
the artifacts\ directory is ignored by Git, keep outputs there and never commit them)
Parameters
-PostAbort also run the post-abort check: no leleka-* / strata-* process is left and the nvidia-smi
compute-app list is empty. Note: on a WDDM (Windows display driver) GPU the compute-app
list can be empty even while a process uses the GPU, so the process-name check is the
primary evidence and the compute-app list is a second, weaker one.
-ReferenceTime instant (ISO 8601, give 'Z' or an offset; without one UTC is assumed) from which
Kernel-Power 41 and BugCheck (System log event 1001) events are listed. Default: the last
boot time (a crash is logged by the boot that follows it), reference_time_source says which.
-OutFile optional path; the same JSON is also written there (UTF-8 without BOM).
Output (stable `settings` object first, then the volatile fields; compare two reads by `settings` alone):
settings.power_scheme_guid / power_scheme_name, settings.timeouts_s (sleep, hibernate, display_off,
console_lock_display_off; each {ac, dc} in seconds, 0 = never), settings.ac_status,
settings.enforced_power_limit (W; the field is enforced.power.limit because power.limit is N/A on this GPU),
settings.power_max_limit_w (W, from power.max_limit), settings.owner_attestation (items with NO read-only
command, printed as required, never guessed: unlocked_screen, sign_in_requirement, oem_turbo).
gpu (name, clocks, pstate, throttle reasons, temperature), boot_time_utc, crash_evidence (Kernel-Power 41 and
BugCheck since the reference time), wsl_docker, top_processes (CPU over a 1 s window), post_abort (with -PostAbort),
unreadable_fields, exit_code.
Exit codes
0 read done; 4 = fail closed: enforced_power_limit or power_max_limit_w is empty, N/A, unparsable, or the
nvidia-smi sample is missing (each nvidia-smi / powercfg call is abandoned after 5 s and counts as a
missing sample); 5 = -PostAbort found something left over (or could not prove nothing is left);
3 = unexpected error. Any other field that could not be read is the string 'unreadable' and is listed in
`unreadable_fields`; a consumer must check that list.
Test hook: when the environment variable LELEKA_STATE_FIXTURE_DIR names a directory, the cmdlet-based sources
(battery.json, os.json, events.json, processes.json in that directory) are read from those data files instead of
the live system; the JSON then carries "source": "fixture". powercfg and nvidia-smi are always resolved through the
process PATH, so the tests put shims of them first on the CHILD process PATH only (scripts\laptop\win\test_state.ps1).
#>
[CmdletBinding()]
param(
[switch]$PostAbort,
[string]$ReferenceTime,
[string]$OutFile
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$Unreadable = 'unreadable'
$ToolTimeoutSec = 5
$Inv = [System.Globalization.CultureInfo]::InvariantCulture
$FixtureDir = $env:LELEKA_STATE_FIXTURE_DIR
$UseFixture = $false
if ($FixtureDir -and (Test-Path -LiteralPath $FixtureDir -PathType Container)) { $UseFixture = $true }
$UnreadableFields = New-Object System.Collections.Generic.List[string]
function Add-Unreadable([string]$Name) { if (-not $UnreadableFields.Contains($Name)) { $UnreadableFields.Add($Name) } }
# ---------------------------------------------------------------- tool runner (5 s per call, kills only its own child)
function Invoke-QueryTool {
param([string]$Name, [string[]]$ToolArgs, [int]$TimeoutSec = $ToolTimeoutSec)
$res = [ordered]@{ status = 'ok'; exit_code = $null; text = '' }
$cmd = Get-Command -Name $Name -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $cmd) { $res.status = 'missing'; return $res }
$p = $null
try {
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $cmd.Source
$psi.Arguments = ($ToolArgs -join ' ')
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.CreateNoWindow = $true
try {
$oem = [System.Globalization.CultureInfo]::CurrentCulture.TextInfo.OEMCodePage
$psi.StandardOutputEncoding = [System.Text.Encoding]::GetEncoding($oem)
} catch { }
$p = [System.Diagnostics.Process]::Start($psi)
$outTask = $p.StandardOutput.ReadToEndAsync()
$errTask = $p.StandardError.ReadToEndAsync()
if (-not $p.WaitForExit($TimeoutSec * 1000)) {
# abandon the call: kill the tool this script started (and its children), nothing else
& taskkill.exe /PID $p.Id /T /F 2>&1 | Out-Null
try { [void]$p.WaitForExit(2000) } catch { }
$res.status = 'timeout'
return $res
}
$p.WaitForExit()
$res.exit_code = $p.ExitCode
$res.text = [string]$outTask.Result
if ($p.ExitCode -ne 0) { $res.status = 'error' }
} catch {
$res.status = 'error'
$res.text = $_.Exception.Message
} finally {
if ($p) { $p.Dispose() }
}
return $res
}
function Test-Unreadable($Value) { return (($Value -is [string]) -and ($Value -ceq 'unreadable')) }
function ConvertTo-PositiveNumber([string]$Text) {
# '138.94 W', '140.00', ' 1545 MHz ' -> double; '[N/A]', '', 'x', '0', '-1' -> $null
if ($null -eq $Text) { return $null }
$m = [regex]::Match($Text, '^\s*([0-9]+(\.[0-9]+)?)\s*[A-Za-z%]*\s*$')
if (-not $m.Success) { return $null }
$v = [double]::Parse($m.Groups[1].Value, $Inv)
if ($v -le 0) { return $null }
return $v
}
function ConvertTo-NonNegativeNumber([string]$Text) {
if ($null -eq $Text) { return $null }
$m = [regex]::Match($Text, '^\s*([0-9]+(\.[0-9]+)?)\s*[A-Za-z%]*\s*$')
if (-not $m.Success) { return $null }
return [double]::Parse($m.Groups[1].Value, $Inv)
}
function Read-FixtureJson([string]$File) {
$path = Join-Path $FixtureDir $File
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { return $null }
$raw = Get-Content -LiteralPath $path -Raw -ErrorAction Stop
if ([string]::IsNullOrWhiteSpace($raw)) { return $null }
return ($raw | ConvertFrom-Json)
}
function ConvertTo-UtcDate($Value) {
if ($null -eq $Value) { return $null }
if ($Value -is [datetime]) { return $Value.ToUniversalTime() }
$dto = [DateTimeOffset]::MinValue
$styles = [System.Globalization.DateTimeStyles]::AssumeUniversal
if ([DateTimeOffset]::TryParse([string]$Value, $Inv, $styles, [ref]$dto)) { return $dto.UtcDateTime }
return $null
}
function Format-Utc($Value) {
if ($null -eq $Value) { return $null }
return $Value.ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ss.fffZ', $Inv)
}
# ---------------------------------------------------------------- power scheme and timeouts (powercfg, query forms only)
$SettingGuids = [ordered]@{
sleep = '29f6c1db-86da-48c5-9fdb-f2b67b1f44da' # STANDBYIDLE, subgroup SUB_SLEEP
hibernate = '9d7815a6-7ee4-497e-8888-515a05f02364' # HIBERNATEIDLE, subgroup SUB_SLEEP
display_off = '3c0bc021-c8a8-4e07-a973-6b14cbcb2b7e' # VIDEOIDLE, subgroup SUB_VIDEO
console_lock_display_off = '8ec4b3a5-6868-48c2-be75-4f3044be88a7' # VIDEOCONLOCK, subgroup SUB_VIDEO
}
function Get-SettingIndexes([string]$Dump, [string]$SettingGuid) {
# Parse by the setting GUID (not by the localized name): the first two 'Power Setting Index: 0x..' lines after
# the setting GUID that are not 'Possible' are AC then DC.
$lines = $Dump -split "`r?`n"
$found = $false
$vals = @()
foreach ($line in $lines) {
if (-not $found) {
if ($line -match 'Power Setting GUID:\s*([0-9a-fA-F-]{36})' -and $Matches[1].ToLowerInvariant() -eq $SettingGuid) { $found = $true }
continue
}
if ($line -match 'Power Setting GUID:') { break }
if ($line -match '^\s*Current\b.*Power Setting Index:\s*0x([0-9a-fA-F]+)') {
$vals += [Convert]::ToInt64($Matches[1], 16)
}
if ($vals.Count -ge 2) { break }
}
if ($vals.Count -lt 2) { return $null }
return [ordered]@{ ac = $vals[0]; dc = $vals[1] }
}
$schemeGuid = $Unreadable
$schemeName = $Unreadable
$timeouts = [ordered]@{}
foreach ($k in $SettingGuids.Keys) { $timeouts[$k] = $Unreadable }
$active = Invoke-QueryTool -Name 'powercfg' -ToolArgs @('/getactivescheme')
if ($active.status -eq 'ok') {
$m = [regex]::Match($active.text, '([0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12})\s*(\(([^)]*)\))?')
if ($m.Success) {
$schemeGuid = $m.Groups[1].Value.ToLowerInvariant()
if ($m.Groups[4].Success) { $schemeName = $m.Groups[4].Value.Trim() }
}
}
if ($schemeGuid -eq $Unreadable) { Add-Unreadable 'power_scheme_guid' }
if ($schemeName -eq $Unreadable) { Add-Unreadable 'power_scheme_name' }
if ($schemeGuid -ne $Unreadable) {
$dumps = @{}
foreach ($sub in 'SUB_SLEEP', 'SUB_VIDEO') {
$r = Invoke-QueryTool -Name 'powercfg' -ToolArgs @('/q', $schemeGuid, $sub)
$dumps[$sub] = if ($r.status -eq 'ok') { $r.text } else { '' }
}
$map = @{ sleep = 'SUB_SLEEP'; hibernate = 'SUB_SLEEP'; display_off = 'SUB_VIDEO'; console_lock_display_off = 'SUB_VIDEO' }
foreach ($k in $SettingGuids.Keys) {
$idx = Get-SettingIndexes $dumps[$map[$k]] $SettingGuids[$k]
if (-not $idx -and $k -eq 'console_lock_display_off') {
# this setting is a hidden one on some builds: the dump that includes hidden settings is also a query
$r2 = Invoke-QueryTool -Name 'powercfg' -ToolArgs @('/qh', $schemeGuid, 'SUB_VIDEO')
if ($r2.status -eq 'ok') { $idx = Get-SettingIndexes $r2.text $SettingGuids[$k] }
}
if ($idx) { $timeouts[$k] = $idx } else { Add-Unreadable ("timeouts_s." + $k) }
}
} else {
foreach ($k in $SettingGuids.Keys) { Add-Unreadable ("timeouts_s." + $k) }
}
# ---------------------------------------------------------------- AC / charger status
$acStatus = [ordered]@{ battery_status_code = $null; state = $Unreadable }
try {
$bat = $null
if ($UseFixture) { $bat = Read-FixtureJson 'battery.json' }
else { $bat = Get-CimInstance -ClassName Win32_Battery -ErrorAction Stop | Select-Object -First 1 }
if ($null -eq $bat) {
$acStatus.state = 'no_battery_instance' # owner attestation only (P3)
} else {
$code = [int]$bat.BatteryStatus
$acStatus.battery_status_code = $code
if (@(2, 3, 6, 7, 8, 9) -contains $code) { $acStatus.state = 'on_ac' }
elseif (@(1, 4, 5) -contains $code) { $acStatus.state = 'on_battery' }
else { $acStatus.state = 'unknown' }
}
} catch { Add-Unreadable 'ac_status' }
# ---------------------------------------------------------------- GPU line (nvidia-smi --query-gpu, 5 s timeout)
$gpuFields = 'name,enforced.power.limit,power.max_limit,clocks.sm,clocks.mem,pstate,clocks_throttle_reasons.active,temperature.gpu'
$enforced = $Unreadable
$maxLimit = $Unreadable
$gpu = [ordered]@{
sample_status = 'missing'; name = $Unreadable; clocks_sm_mhz = $Unreadable; clocks_mem_mhz = $Unreadable
pstate = $Unreadable; throttle_reasons_active = $Unreadable; throttle_reason_names = @(); temperature_c = $Unreadable
}
$g = Invoke-QueryTool -Name 'nvidia-smi' -ToolArgs @("--query-gpu=$gpuFields", '--format=csv,noheader')
$gpu.sample_status = $g.status
if ($g.status -eq 'ok') {
$line = ($g.text -split "`r?`n" | Where-Object { $_.Trim() } | Select-Object -First 1)
$parts = @()
if ($line) { $parts = @($line -split ',' | ForEach-Object { $_.Trim() }) }
if ($parts.Count -eq 8) {
if ($parts[0] -and $parts[0] -notmatch '^\[') { $gpu.name = $parts[0] }
$v = ConvertTo-PositiveNumber $parts[1]; if ($null -ne $v) { $enforced = $v }
$v = ConvertTo-PositiveNumber $parts[2]; if ($null -ne $v) { $maxLimit = $v }
$v = ConvertTo-NonNegativeNumber $parts[3]; if ($null -ne $v) { $gpu.clocks_sm_mhz = $v }
$v = ConvertTo-NonNegativeNumber $parts[4]; if ($null -ne $v) { $gpu.clocks_mem_mhz = $v }
if ($parts[5] -match '^P\d+$') { $gpu.pstate = $parts[5] }
if ($parts[6] -match '^0[xX]([0-9a-fA-F]+)$') {
$mask = [Convert]::ToUInt64($Matches[1], 16)
$gpu.throttle_reasons_active = ('0x{0:X16}' -f $mask)
$names = @()
$bits = @(
@(1, 'gpu_idle'), @(2, 'applications_clocks_setting'), @(4, 'sw_power_cap'), @(8, 'hw_slowdown'), @(16, 'sync_boost'),
@(32, 'sw_thermal_slowdown'), @(64, 'hw_thermal_slowdown'), @(128, 'hw_power_brake_slowdown'), @(256, 'display_clock_setting')
)
foreach ($b in $bits) { if (($mask -band [uint64]$b[0]) -ne 0) { $names += $b[1] } }
$gpu.throttle_reason_names = $names
}
$v = ConvertTo-NonNegativeNumber $parts[7]; if ($null -ne $v) { $gpu.temperature_c = $v }
}
}
foreach ($f in 'name', 'clocks_sm_mhz', 'clocks_mem_mhz', 'pstate', 'throttle_reasons_active', 'temperature_c') {
if ((Test-Unreadable $gpu[$f])) { Add-Unreadable ("gpu." + $f) }
}
if (Test-Unreadable $enforced) { Add-Unreadable 'enforced_power_limit' }
if (Test-Unreadable $maxLimit) { Add-Unreadable 'power_max_limit_w' }
# ---------------------------------------------------------------- process list (CPU over a 1 s window) and WSL / Docker presence
function Get-ProcessSnapshot {
$out = [ordered]@{ status = 'ok'; processes = @() }
try {
if ($UseFixture) {
$fx = Read-FixtureJson 'processes.json'
$list = @()
foreach ($p in @($fx)) {
if ($null -eq $p) { continue }
$list += [pscustomobject]@{ name = [string]$p.Name; id = [int]$p.Id; cpu_percent = [double]$p.CpuPercent }
}
$out.processes = $list
return $out
}
$first = @{}
foreach ($p in (Get-Process -ErrorAction SilentlyContinue)) {
$cpu = $null
try { $cpu = $p.CPU } catch { }
$first[$p.Id] = @{ name = $p.Name; cpu = $cpu }
}
$sw = [System.Diagnostics.Stopwatch]::StartNew()
Start-Sleep -Milliseconds 1000
$list = @()
foreach ($p in (Get-Process -ErrorAction SilentlyContinue)) {
$cpu = $null
try { $cpu = $p.CPU } catch { }
$pct = 0.0
if ($null -ne $cpu -and $first.ContainsKey($p.Id) -and $null -ne $first[$p.Id].cpu -and $first[$p.Id].name -eq $p.Name) {
$pct = [math]::Round((($cpu - $first[$p.Id].cpu) / ($sw.Elapsed.TotalSeconds)) * 100.0, 1)
if ($pct -lt 0) { $pct = 0.0 }
}
$list += [pscustomobject]@{ name = $p.Name; id = $p.Id; cpu_percent = $pct }
}
$out.processes = $list
} catch {
$out.status = $Unreadable
}
return $out
}
$snap = Get-ProcessSnapshot
$procs = @($snap.processes)
if ($snap.status -ne 'ok') { Add-Unreadable 'top_processes'; Add-Unreadable 'wsl_docker' }
$wslDockerNames = @('vmmemWSL', 'vmmem', 'wslhost', 'Docker Desktop', 'com.docker.backend', 'dockerd')
$wslFound = @($procs | Where-Object { $wslDockerNames -contains $_.name } | ForEach-Object { [ordered]@{ name = $_.name; id = $_.id } })
$wslDocker = [ordered]@{
status = $snap.status
vmmemWSL_present = [bool](@($procs | Where-Object { $_.name -ieq 'vmmemWSL' }).Count -gt 0)
docker_present = [bool](@($procs | Where-Object { $_.name -match '^(Docker Desktop|com\.docker\.backend|dockerd)$' }).Count -gt 0)
found = $wslFound
}
$top = @($procs | Where-Object { $_.name -ne 'Idle' -and $_.name -ne '_Total' } | Sort-Object cpu_percent -Descending |
Select-Object -First 5 | ForEach-Object { [ordered]@{ name = $_.name; id = $_.id; cpu_percent = $_.cpu_percent } })
# ---------------------------------------------------------------- boot time and crash evidence (Get-WinEvent, read only)
$bootUtc = $null
try {
if ($UseFixture) {
$os = Read-FixtureJson 'os.json'
if ($os) { $bootUtc = ConvertTo-UtcDate $os.LastBootUpTime }
} else {
$bootUtc = ConvertTo-UtcDate (Get-CimInstance -ClassName Win32_OperatingSystem -ErrorAction Stop).LastBootUpTime
}
} catch { }
if ($null -eq $bootUtc) { Add-Unreadable 'boot_time_utc' }
$refUtc = $null
$refSource = 'boot_time'
if ($ReferenceTime) {
$refUtc = ConvertTo-UtcDate $ReferenceTime
if ($null -eq $refUtc) { [Console]::Error.WriteLine("state.ps1: -ReferenceTime is not a valid ISO 8601 instant: $ReferenceTime"); exit 3 }
$refSource = 'parameter'
} elseif ($null -ne $bootUtc) {
$refUtc = $bootUtc
} else {
$refUtc = (Get-Date).ToUniversalTime().AddHours(-24)
$refSource = 'last_24h_fallback'
}
function Get-RawEvents([datetime]$SinceUtc) {
# returns @{ status; events = list of @{id; provider; time (UTC); message} }
$res = @{ status = 'ok'; events = @() }
try {
if ($UseFixture) {
$fx = Read-FixtureJson 'events.json'
foreach ($e in @($fx)) {
if ($null -eq $e) { continue }
$res.events += @{ id = [int]$e.Id; provider = [string]$e.ProviderName; time = (ConvertTo-UtcDate $e.TimeCreated); message = [string]$e.Message }
}
return $res
}
$since = $SinceUtc.ToLocalTime()
$queries = @(
@{ LogName = 'System'; ProviderName = 'Microsoft-Windows-Kernel-Power'; Id = 41; StartTime = $since },
@{ LogName = 'System'; ProviderName = 'Microsoft-Windows-WER-SystemErrorReporting'; Id = 1001; StartTime = $since }
)
foreach ($q in $queries) {
try {
foreach ($e in @(Get-WinEvent -FilterHashtable $q -ErrorAction Stop)) {
$res.events += @{ id = [int]$e.Id; provider = [string]$e.ProviderName; time = $e.TimeCreated.ToUniversalTime(); message = [string]$e.Message }
}
} catch {
if ($_.FullyQualifiedErrorId -notlike '*NoMatchingEventsFound*') { throw }
}
}
} catch {
$res.status = $Unreadable
}
return $res
}
function ConvertTo-EventRecord($E) {
$first = ($E.message -split "`r?`n" | Select-Object -First 1)
if ($null -eq $first) { $first = '' }
if ($first.Length -gt 300) { $first = $first.Substring(0, 300) }
return [ordered]@{ id = $E.id; provider = $E.provider; time_utc = (Format-Utc $E.time); message_first_line = $first }
}
$raw = Get-RawEvents $refUtc
$kp = @(); $bc = @()
if ($raw.status -eq 'ok') {
$after = @($raw.events | Where-Object { $null -ne $_.time -and $_.time -ge $refUtc } | Sort-Object { $_.time })
$kp = @($after | Where-Object { $_.id -eq 41 -and $_.provider -eq 'Microsoft-Windows-Kernel-Power' } | ForEach-Object { ConvertTo-EventRecord $_ })
$bc = @($after | Where-Object { $_.id -eq 1001 -and $_.provider -match 'WER-SystemErrorReporting|BugCheck' } | ForEach-Object { ConvertTo-EventRecord $_ })
} else {
Add-Unreadable 'crash_evidence'
}
$crash = [ordered]@{
query_status = $raw.status
reference_time_utc = (Format-Utc $refUtc)
reference_time_source = $refSource
kernel_power_41 = $kp
bugcheck = $bc
count = ($kp.Count + $bc.Count)
}
# ---------------------------------------------------------------- post-abort check
$paDoc = $null
$postAbortClean = $true
if ($PostAbort) {
$reasons = @()
$left = @($procs | Where-Object { $_.name -like 'leleka-*' -or $_.name -like 'strata-*' } | ForEach-Object { [ordered]@{ name = $_.name; id = $_.id } })
if ($snap.status -ne 'ok') { $reasons += 'process_list_unreadable' }
if ($left.Count -gt 0) { $reasons += ('leftover_process:' + (($left | ForEach-Object { $_.name }) -join ',')) }
$apps = @()
$ca = Invoke-QueryTool -Name 'nvidia-smi' -ToolArgs @('--query-compute-apps=pid,process_name,used_memory', '--format=csv,noheader')
if ($ca.status -eq 'ok') {
foreach ($l in ($ca.text -split "`r?`n")) {
if (-not $l.Trim()) { continue }
$f = @($l -split ',' | ForEach-Object { $_.Trim() })
$apps += [ordered]@{ pid = $f[0]; process_name = $(if ($f.Count -gt 1) { $f[1] } else { '' }); used_memory = $(if ($f.Count -gt 2) { $f[2] } else { '' }) }
}
if ($apps.Count -gt 0) { $reasons += ('compute_app:' + (($apps | ForEach-Object { $_.process_name + '(pid ' + $_.pid + ')' }) -join ',')) }
} else {
$reasons += 'compute_apps_unreadable'
Add-Unreadable 'post_abort.compute_apps'
}
$postAbortClean = ($reasons.Count -eq 0)
$paDoc = [ordered]@{
clean = $postAbortClean
leftover_processes = $left
compute_apps_status = $ca.status
compute_apps = $apps
reasons = $reasons
}
}
# ---------------------------------------------------------------- assemble and print
$exitCode = 0
if ((Test-Unreadable $enforced) -or (Test-Unreadable $maxLimit)) { $exitCode = 4 }
elseif ($PostAbort -and -not $postAbortClean) { $exitCode = 5 }
$doc = [ordered]@{
schema_version = 1
tool = 'scripts/laptop/win/state.ps1'
read_only = $true
source = $(if ($UseFixture) { 'fixture' } else { 'live' })
mode = $(if ($PostAbort) { 'post_abort' } else { 'state' })
settings = [ordered]@{
power_scheme_guid = $schemeGuid
power_scheme_name = $schemeName
timeouts_s = $timeouts
ac_status = $acStatus
enforced_power_limit = $enforced
power_limit_unit = 'W'
power_max_limit_w = $maxLimit
owner_attestation = @('unlocked_screen', 'sign_in_requirement', 'oem_turbo')
owner_attestation_status = 'required'
}
gpu = $gpu
boot_time_utc = (Format-Utc $bootUtc)
crash_evidence = $crash
wsl_docker = $wslDocker
top_processes = $top
time_utc = (Format-Utc ((Get-Date).ToUniversalTime()))
unreadable_fields = @($UnreadableFields)
exit_code = $exitCode
}
if ($PostAbort) { $doc['post_abort'] = $paDoc }
$json = ConvertTo-Json -InputObject $doc -Depth 8
Write-Output $json
if ($OutFile) {
$dir = Split-Path -Parent $OutFile
if ($dir -and -not (Test-Path -LiteralPath $dir)) { [void][System.IO.Directory]::CreateDirectory($dir) }
[System.IO.File]::WriteAllText($OutFile, $json + "`r`n", (New-Object System.Text.UTF8Encoding($false)))
}
exit $exitCode
+365
View File
@@ -0,0 +1,365 @@
<#
.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