Testing

Test-WinRE.ps1 diagnoses the current recovery configuration and tests driver downloads/extraction. It does not change WinRE registration, partitions, BitLocker or deployment state. Download tests create and clean scratch files; diagnostics report current observations rather than proving a later Repair will succeed. This document explains how to run it, what each menu option does, and what the results mean.

The harness exists to serve the project’s four design invariants, which architecture.md states in this order: never break Windows RE, never leave a machine without a working recovery route, minimize the reagentc /disable → reagentc /enable window, and do no work unless needed; prepare everything before touching anything. Two of those rules bear directly on the harness:

When to run the harness

Run Test-WinRE.ps1 in any of the following situations:

The harness requires no elevation and does not modify WinRE, partitions, BitLocker, drive letters, or the state file. All its work is confined to its working directory ($TestDir, default C:\Temp\WinRETest), where it creates and removes its own test artifacts. Use a dedicated scratch directory and keep concurrent harness runs in separate directories so their artifacts do not collide.

What the harness is

An interactive PowerShell script that:

It is the primary tool for pre-flight validation on an unfamiliar machine.

Current version: v40. The version history is:

See the .NOTES block at the top of scripts\Test-WinRE.ps1 for the complete per-version change list.

The harness has no mirror of v45 patch 1’s shrink-first pipeline. It reads the machine’s state and reports what production would do, but it does not simulate the destructive path or the plan. The shrink-first code paths are exercised on disposable VMs (see “v45 destructive-path regression” below), not through the harness.

v29 changes

Two changes, both closing the version-drift family that has required a manual $ProductionScriptVersion bump on five releases across the family (v21, v22, v23, v27, v28).

1. Version-drift family closed by Get-ProductionScriptVersion. A new reader extracts production’s $ScriptVersion from the adjacent WinRE.ps1 at call time, using a regex match against the source. Get-DesiredStateId’s $ProductionScriptVersion parameter is now [Nullable[int]] with a $null default; when the caller does not supply a value, the function invokes the reader; when the reader returns $null (production file absent, unparseable, or lacking the declaration), the function returns $null and the caller records State file parity as SKIP rather than substituting a stale default and reporting a false MISMATCH. This closes the version-drift family permanently: the harness no longer needs a manual bump whenever production bumps $ScriptVersion. The 49 default is retained as an explicit override path for the parser self-test (Check 15 passes 44 and 43 explicitly to prove version-sensitivity), but is no longer the load-bearing value on the live Option S path. When the DSI cannot be computed — the production file is not adjacent to the harness — Option S prints an explicit “place WinRE.ps1 beside Test-WinRE.ps1” hint.

2. Menu title and startup Rule bumped 28 -> 29.

The parser self-test count remains at eighteen — v29 adds no new checks.

v40 changes

Both adjacent-production readers now return unavailable when $PSScriptRoot is empty, so pasted/selection invocation can SKIP dependent source diagnostics instead of throwing at Join-Path. Parser checks 18–20 retain their names but inspect executable AST contracts for the VHDX, storage-controller and VM-detection mirrors. A matching comment or an unrelated -ErrorAction Stop no longer satisfies those contracts. Isolated mutation fixtures exercise the checks without invoking the live repair pipeline.

Check 2 uses the shared labelled-location reader and strict parser instead of a separate root-only regex. It recognizes valid drive-letter, GLOBALROOT and volume-GUID paths with their full folders, and cannot accept an unrelated recovery-image field as the WinRE location. An absent or invalid native location while Enabled is a FAIL; an absent location while Disabled is a SKIP. The unresolved-target diagnostic prints the observed status without claiming that resolution failure proves WinRE is unregistered.

The mirror policy explicitly documents omission of production’s DryRun-only download/extraction branches. Check 22 now exercises the vulnerable Math.Max form with both positive and negative Int64 variables, alongside the independent safe shrink and extend calculations. Casting directly inside the method call changes overload selection and would not reproduce the historical failure.

v39 changes

Four changes, all downstream of the production v50 patch 4 cycle.

1. Check 18 tightened. The Test-NativeBootVirtualTopology source-level mirror-binding assertion now requires the specific Get-Disk -ErrorAction Stop enumeration and its Where-Object { $_.Number -ne $osDisk.Number } filter, not just the presence of -ErrorAction Stop anywhere in the function. The prior form would have passed even if -ErrorAction Stop moved to an unrelated command in the same function.

2. Check 21 added (source-pattern). Asserts that Get-PartitionPlan contains the Int64-safe -gt comparison form (} elseif ($osSize -gt $plannedOSSize) { and } elseif ($plannedOSSize -gt $osSize) {) and does not contain the vulnerable [Math]::Max(0, ...) pattern. Guards against reintroduction of the v50 patch 4 Int32 overflow fix: the Surface Pro 3, 2026-10-16 field failure where the vulnerable [Math]::Max(0, ...) form threw on a ~4.9 GB extend delta and every subsequent invocation crashed identically. SKIP when WinRE.ps1 is not adjacent.

3. Check 22 added (behavioral). Reproduces both the safe shrink and safe extend forms with a delta of 3,000,000,000 bytes (greater than Int32.MaxValue) and confirms the correct value is returned without throwing; separately confirms the vulnerable Math.Max form still throws on the same input. Complementary to check 21: catches an off-by-one or wrong-direction rewrite that would still match check 21’s source pattern. The behavioral check does not read WinRE.ps1, so it does not SKIP on source absence.

4. Menu title and startup Rule bumped 38 -> 39.

The parser self-test count moves from twenty-one to twenty-three with the two new checks.

v38 changes

Three changes, all affecting the harness’s own behaviour rather than its mirrors of production.

1. Run logging added. Every Say / Rule / Write-Diag / Write-KV / Write-WarningBanner call and every Record call now appends a line to %TEMP%\WinRE-TestHarness.log in addition to its console output. The log captures the full narrative of the run, including every parser self-test result via Record, so an operator or CI consumer can review the run after the console output has scrolled off. The log is overwritten at the start of each run and its path is announced at startup via a Say line.

The log lives under %TEMP% rather than $TestDir because NonInteractive mode (and interactive mode with the default cleanup answer) deletes $TestDir at exit; a log inside $TestDir would be destroyed with it and would be unavailable for post-run triage. If $env:TEMP is not set, the log is not created; every Write-Log call is a no-op and the harness continues without it.

2. -NonInteractive now runs the parser self-test. Before v38, NonInteractive ran only Invoke-AllRelevant (the download/extraction tests) and never invoked Show-SystemDiagnostic, so the parser self-test - including the source-level mirror-binding assertions 18, 19, and 20 that were added specifically to catch production mirror drift - was not exercised by CI. A future production edit that dropped one of the asserted shapes would have passed CI silently. NonInteractive now runs Show-SystemDiagnostic first, then Invoke-AllRelevant, then the summary and cleanup. The v25 changelog promise (“CI and cron consumers can now treat the harness as a regression gate”) is now honored in full.

3. Menu title and startup Rule bumped 37 -> 38.

The parser self-test count remains at twenty-one - v38 adds no new checks.

v37 changes

Three changes, all downstream of the production v50 patch 2 cycle.

1. Empty-metadata fail-closed guard added to the Test-RunningInVirtualMachine mirror. Production v50 patch 2 treats a Win32_ComputerSystem query that succeeds but returns empty or whitespace-only Manufacturer and Model fields as indeterminate and returns $null; without that guard, the empty string falls through to the signature scan, matches nothing, and is classified as a physical machine. The harness mirror lacked the guard, so on such a machine the Option 1 sweep-suppression preview would have reported physical (sweep runs) while production would have reported indeterminate (sweep suppressed). v37 closes that mirror gap: the harness mirror now returns $null on empty metadata, matching production’s behavior.

2. Check 20 extended with an assertion that binds the guard. Before v37, check 20 verified the ten hypervisor signatures, the fail-closed $null return, the Win32_ComputerSystem query source, and the combined-string construction — but not the guard that makes the $null return reachable for the empty-metadata case. A future production edit that dropped the guard would have passed check 20 silently. v37 adds an IsNullOrWhiteSpace assertion to close that hole.

3. Menu title and startup Rule bumped 36 -> 37.

The parser self-test count remains at twenty-one — v37 extends check 20’s assertion without adding a new check.

v36 changes

Five changes, all downstream of the production v50 patch 2 cycle.

1. Closed a diagnostic gap exposed by v50 patch 2’s hypervisor-suppression boundary. The harness now mirrors production’s Test-RunningInVirtualMachine and adds a “Non-OS sweep suppression preview” section to Option 1. The preview reports the hypervisor-detection verdict (guest, physical, or indeterminate) that production’s Remove-StrayRecoveryPartitions will reach, and lists every non-OS recovery partition with its disposition under the sweep’s deletion rules (WOULD DELETE / WOULD PRESERVE / WOULD SKIP, with a one-line reason). The operator can now see, before running production, whether the sweep will run and what it would target.

2. Added source-level mirror-binding assertion check 20. Reads production’s Test-RunningInVirtualMachine and verifies the ten hypervisor signatures, the fail-closed $null return, the Win32_ComputerSystem query source, and the combined-string construction. Catches the same mirror-drift class that checks 18 and 19 guard against. SKIP when WinRE.ps1 is not adjacent.

3. Added Test-RunningInVirtualMachine to the “Mirrored from production” list in .DESCRIPTION.

4. No $ProductionScriptVersion bump is needed for v50 patch 2. Production’s $ScriptVersion remains 50 across the patch-level bump (only $ScriptPatchLevel moves 1 -> 2), and the harness reads the value directly from the adjacent WinRE.ps1 via Get-ProductionScriptVersion, so the DSI mirror remains correct.

5. Menu title and startup Rule bumped 35 -> 36.

The parser self-test count moves from twenty to twenty-one with the new check 20.

v35 changes

Two changes, both affecting the interactive cleanup path.

1. Interactive cleanup prompt inverted. v34 shipped the cleanup prompt as Keep test artifacts in $TestDir → (y/N) with y=keep and N=delete. The y-as-keep semantics were the reverse of what most operators read (“y to cleanup”), and an operator who answered y expecting deletion got the opposite: the keep branch returned before Remove-EmptyTestParent ran, so neither $TestDir nor its parent was removed. The prompt now reads Delete test artifacts from $TestDir → (Y/n) with y=delete (default) and n=keep. Empty input still deletes. The -Keep switch still short-circuits to keep, and the pre-existing-non-empty refusal is unchanged.

2. Menu title and startup Rule bumped 34 -> 35.

The parser self-test count remains at twenty — v35 adds no new checks.

v34 changes

Two changes: Remove-EmptyTestParent mirroring production’s v50 Remove-EmptyWorkspaceParent invariant, and a menu-title and Rule bump.

1. Added Remove-EmptyTestParent. After Invoke-HarnessCleanup removes $TestDir, the parent directory (typically C:\Temp for the default path) is checked and removed if and only if its leaf name is exactly Temp, it is completely empty, and it is not a drive root. Before this change the harness removed $TestDir recursively but left an empty C:\Temp behind on a machine where the harness had created C:\Temp itself. Removal is attempted via Remove-Item with a [System.IO.Directory]::Delete fallback for provider-layer disagreements, then verified: if the directory still exists afterward (typically because another process holds a handle, or because the invoking session’s working directory is inside it), a WARN is logged and the directory is left in place. A user-supplied -TestDir whose parent is not named Temp (for example C:\Users\Me\Desktop) is therefore never touched.

2. Menu title and startup Rule bumped 33 -> 34.

The parser self-test count remains at twenty — v34 adds no new checks.

v33 changes

Two changes: two source-level mirror-binding assertions added to the parser self-test, and a menu-title and Rule bump.

1. Added two source-level mirror-binding assertions (checks 18 and 19).

2. Menu title and startup Rule bumped 32 -> 33.

The parser self-test count moves from eighteen to twenty with the two new checks.

v32 changes

Three changes, all defensive or documentation-only.

1. Record’s -Ok parameter hardened with an explicit default. The parameter previously had no default and was not marked mandatory, so a future call site writing Record <name> -State <state> without -Ok would have silently bound $Ok = $false. The behavior was already correct (when -State is supplied it is authoritative), so the change is defensive only: it makes the implicit default explicit. No observable behavior change; every current call site supplies -Ok.

2. Design note added to Get-DriverManifest’s header. Explains why the function is called afresh by each of the four interactive entry points that need the manifest (Options 1, 2, 9, and S) rather than caching the result across the session. The choice is deliberate: production fetches once in Main and passes the manifest down, so there is no production function to mirror that would hold a cache; and a cached manifest would hide a mid-session network failure from a later entry point. Documentation only.

3. Menu title and startup Rule bumped 31 -> 32.

The parser self-test count remains at eighteen — v32 adds no new checks.

v31 changes

Four changes, all downstream of the v31 cycle.

1. Mirror-discipline principle documented in .DESCRIPTION. Every function named in the “Mirrored from production” list above, and every function under a “based on WinRE.ps1” section header, matches its production counterpart line-for-line in logic and functional calls. The only permitted differences are: (a) the log sink (Say vs Write-Log); (b) diagnostics layered around the mirror (observational, no control-flow change); (c) an explicit, documented functional difference; (d) an output-shape-aligned helper whose implementation may differ (Get-ThisMachineProfile, Get-HarnessPartitionRef). Any deviation outside these four is a mirror gap and is treated as a defect.

2. Mirror-gap correction: Invoke-CabExtraction’s 7-Zip argument list. The harness was missing -w"$DestinationDir", which production passes. Without it 7-Zip uses the process’s current directory for temporary files rather than the extraction destination. Not a functional defect in practice, but a genuine divergence from production that the newly-documented mirror discipline names as a defect class.

3. Parser self-test failure output enriched for the two English-language-dependent regexes. Check 1 (reagentc status, matching “Enabled”/”Disabled”) and check 2b (reagentc Windows RE Version, anchored on the label “Windows RE Version:”) now report the current OS locale and a two-cause hypothesis on a non-match: structural reagentc format drift, or a non-English OS. The recorded test result (FAIL) is unchanged; the added output is observational.

4. Menu title and startup Rule bumped 30 -> 31.

The parser self-test count remains at eighteen — v31 adds no new checks.

v30 changes

Four changes, all downstream of the v49 patch 2 cycle.

1. Get-StorageControllerDevices mirror corrected. The harness’s copy of the function carried the same defect as production’s — return @($result) collapsed an empty result to $null, so the caller in the Option 1 diagnostic mis-reported “INDETERMINATE (PnP enumeration failed)” for a successfully-empty enumeration, and the parser self-test at check 17 recorded FAIL instead of the intended SKIP. Both sites now use return ,$result and reach their intended branches.

2. Say line for filtered software/virtual devices. The harness now emits a Say line when a software or virtual storage device is filtered out of the SCSIAdapter-class enumeration, similar to production’s equivalent line but without production’s Storage applicability: prefix. Previously the harness dropped filtered devices silently, so an operator comparing the harness’s controller list against their own Get-PnpDevice -Query had no visible explanation for the difference.

3. NonInteractive exit-code effect documented. On a machine whose SCSIAdapter-class enumeration legitimately returns zero devices, check 17 now records SKIP instead of FAIL, so -NonInteractive returns exit code 0 for that case.

4. Menu title and startup Rule bumped 29 -> 30.

The parser self-test count remains at eighteen — v30 adds no new checks.

v28 changes

Six changes, all downstream of the v49 cycle.

Additionally, stale “v48” references in the architecture warning and the Get-DesiredStateId header comment were rewritten version-agnostically (they now say “production” rather than “production v48”); the over-indented try { in the Compare-WimServicingMetadata self-test was fixed; and the menu title and startup Rule were bumped to v28.

The parser self-test count moves from seventeen checks to eighteen with the Get-StorageControllerDevices check.

v27 changes

Four changes, all downstream of the v48 patch 1 cycle.

The parser self-test count is unchanged from v25 (seventeen checks).

v26 changes

One diagnostic addition, downstream of the production v47 patch 3 plan-rejection enrichment.

Plan adjacency preview. Option 1 now runs a read-only mirror of the geometric and partition-identity subset of production’s Get-PartitionPlan rejection checks against the current layout. On a clean layout the section prints two green lines confirming the layout would not be rejected on the checks evaluated; on a separated-recovery or oversized-recovery layout it prints the enriched rejection reason(s) that production would log. The preview does not compute a bucket size or a planned extent, so the rejections related to planned-extent sizing are not evaluated. A clean preview is not a claim that the full plan would succeed, and the section says so explicitly. A new Get-HarnessPartitionRef helper renders a partition the same way production’s Format-PartitionRef does.

The parser self-test count is unchanged. The preview is diagnostic and does not record a PASS/FAIL/SKIP result.

v25 changes

Six functional changes, one menu bump, and one comment set, all downstream of the production v47 patch 3 cycle. See the v47 patch 3 entry for the full context.

The parser self-test count moved from sixteen to seventeen with the Compare-WimServicingMetadata check.

v24 changes

Two changes, both downstream of the v47 patch 2 cycle.

1. The active-WIM diagnostic probe now matches production’s dual-path resolver. The prior code constructed <registered-location>\Recovery\WindowsRE\winre.wim unconditionally. That path is correct when reagentc /info returns a partition root, but doubles the path when it returns ...\Recovery\WindowsRE (producing ...\Recovery\WindowsRE\Recovery\WindowsRE\winre.wim and reporting the active WIM as missing when it is present). Production handles both forms via Ensure-RecoveryPartitionAccess, which returns a drive root or the subpath depending on which form the registered location was in. The harness now probes both forms in order (<location>\Recovery\WindowsRE\winre.wim, then <location>\winre.wim) and uses the first that resolves to a readable file.

2. Get-ThisMachineProfile trims Win32_ComputerSystemProduct.Version. Mirrors production’s Get-HardwareObject change in v47 patch 2. Some vendors pad the field with trailing whitespace (observed: ASUS sets it to "1.0 "); without trimming, the harness’s DSI mirror could compute a different HW component than production on such machines, causing a false Option-S mismatch.

v23 changes

Three changes, all downstream of the v47 patch 1 cycle.

1. $ProductionScriptVersion default bumped 46 → 47. The harness’s Get-DesiredStateId mirror carries this default to track production’s $ScriptVersion. Left at 46 it would report a false DSI MISMATCH for every state file v47 production writes, exactly the drift v21 and v22 corrected for earlier bumps. The parameter-header comment continues to name the tracking rule. The harness’s own parser self-test (Check 15) still deliberately passes 44 and 43 to prove version-sensitivity; those values are unchanged.

2. Show-StateFileParity now displays DeployedWinREMetadata. The state file’s DISM servicing metadata anchor (v47 patch 1’s DeployedWinREMetadata field, in <Version>|<SPBuild> form) renders in the parity output alongside PendingReboot, LastEnableResult, EnableFailureAttempts, and RepairAttempts. When present, it renders green. When absent (a v46-or-earlier state file), it renders yellow with a note that production v47 will force a rebuild on the next run because the drift detector has no anchor to compare against. Purely diagnostic; no production decision depends on the harness reading this field.

3. Harness version string bumped 22 → 23 in the menu title and the startup Rule.

v22 changes

Three changes, all downstream of the v46 patch 2 cycle.

1. Mirrored production v46 patch 2’s Get-WinREState version parsing. The harness’s Get-WinREState now extracts Windows RE Version from reagentc /info and returns it as Version. The parsed-state block in Option 1 reports the value alongside Status and Location, and a new “Build numbers” section renders the registered WinRE version, the active WIM build, and (when present) the backup WIM build at C:\Recovery\WindowsRE\winre.wim. This answers the operator’s question “what builds are we about to replace?” before any destructive operation.

2. New parser self-test check for the version regex. Parser: reagentc version reports [OK] when the version line matches, [FAIL] when WinRE is Enabled and the line is missing, and [SKIP] when WinRE is Disabled or reagentc suppressed the line. The self-test total moves from fifteen checks to sixteen. The check mirrors production v46 patch 2’s extraction logic: if the regex fails on a machine where WinRE is Enabled, the production log’s WinRE ... Version: line will read unknown, which is a signal that the reagentc output format has shifted under both the harness and production.

3. $ProductionScriptVersion default bumped 45 → 46. The harness’s Get-DesiredStateId mirror carries this default to track production’s $ScriptVersion. Left at 45 it would report a false DSI MISMATCH for every state file v46 production writes, exactly the drift v21 corrected for the 44 → 45 case. The parameter-header comment continues to name the tracking rule. The harness’s own parser self-test (Check 15) still deliberately passes 44 and 43 to prove version-sensitivity; those values are unchanged.

v21 changes

Two changes. This was a standalone harness correction not tied to a production release.

1. DSI-mirror drift corrected. The harness’s Get-DesiredStateId mirror carried [int]$ProductionScriptVersion = 44, while production v45 patch 1 ships $ScriptVersion = 45. Because the harness computes the same seven-field recipe production does, its default was one version behind, and every comparison against a v45-written state file returned DSI MISMATCH — production will treat the state file as stale for a state file that production would actually accept. The default is now 45, and the parameter-header comment names the version boundary explicitly: this default must be bumped whenever production’s $ScriptVersion is bumped. The harness’s own parser self-test (Check 15) still deliberately passes 44 and 43 to prove version-sensitivity; those values are unchanged.

2. Show-StateFileParity displays the state file’s RepairAttempts field. The v44 patch 6 state file carries RepairAttempts alongside PendingReboot, LastEnableResult, and EnableFailureAttempts; the harness’s parity display previously listed the other three but not this one. Purely additive; no existing display line changed.

v20 changes

Two changes.

1. The active-location classifier requires a type-coded partition on the OS disk for the DEDICATED verdict. Mirrors production’s active-location classifier change (patch 3 of the v44 patch 7 cycle). The previous harness logic computed a single $isRec flag from GptType-or-MbrType, and if that was $false it fell back to a Get-Volume -Partition label check that promoted a label-only match to $isRec = $true. The classifier now computes $isTypedRecovery and $isLabelRecovery separately, and the branches report:

The LABEL-ONLY verdict is new in v20. Before v20, a machine whose reagentc-registered WinRE location was a Basic Data partition labelled “Recovery” would have been reported as DEDICATED by the harness, while production would have taken the full-update path. This was a false positive that could have misled a field engineer. Production’s final-verification classifier (patch 4 of the v44 patch 7 cycle) has no direct harness equivalent and is not claimed; the harness classifies the reagentc-registered location, which is the active-location decision point.

2. Menu box alignment fixed. The menu box’s border is 66 columns wide interior (plus the two border characters and two leading spaces). The three content rows — title, working directory, and detected — were each padded to values that did not equal interior width minus the leading space, so the closing border character was misaligned on two of the three rows. All three rows now pad their content to exactly 65 columns, truncating with an ellipsis if content overflows. Purely cosmetic; no functional change.

The output format for every other section is unchanged from v16.

v19 changes

Two Option S corrections.

  1. Option S reports SKIP (not PASS) when the state file is absent and the VMD query is indeterminate. Before v19, Show-StateFileParity checked for the state file’s existence before consulting the VMD query result, and returned PASS with detail no state file (rebuild expected) whenever the file was missing. That was correct when VMD presence was determinable, but wrong when the VMD query had failed: production defers the entire run with EXIT_WARNING in that case rather than taking the full-update path, and the harness’s PASS disagreed with what a live run would do. The missing-state-file branch now checks $vmdQueryOk and records SKIP with detail No state file; VMD query indeterminate. The existing INDETERMINATE / SKIP handling for the state-file-present case is unchanged.
  2. Option S wording clarified. The header now reads “does the stored DesiredStateId match current inputs? This is not a full-flow simulation.” The DSI MATCH verdict reads “the stored deployment ID matches current inputs” followed by a note that production separately evaluates WinRE state/location, recovery-partition count, active WIM hash, pending-reboot/repair state, BitLocker, and other startup/flow gates before deciding what to do. The prior wording — “production will accept the state file” — implied that DSI equality alone was sufficient.

v18 changes

v18 is a combined mirror of production v44 patch 6 and a set of harness-specific fixes. The mirror changes keep the harness’s outputs in lockstep with production’s actual behavior; the harness-specific fixes close issues that the harness’s own review surfaced.

Mirror of production v44 patch 6:

  1. VMD query-failure handling. Options 1 and S now treat a PnP enumeration error as an indeterminate result rather than absence. Option 1’s VMD hardware presence section reports INDETERMINATE with the enumeration error message. Option S records SKIP in the results with reason VMD query indeterminate and prints an INDETERMINATE verdict instead of a DSI MATCH or DSI MISMATCH. Before v18, the harness could produce a “definitive” DSI that disagreed with what a live production run would compute, which is the opposite of what Option S is for.
  2. Lenovo map resolution status machine. Get-LenovoWinPEPack in the harness now sets $Script:LenovoPackResolution to the same five states as production. Test-OemMaps distinguishes malformed-entry (red, marks the test failed) from no-entry (gray, informational), and treats map-unavailable (yellow, marks the test failed) separately from both.

Harness-specific fixes:

  1. Get-DriverManifest extracted as a shared helper. Options 2, 9, and S now all use the same two-attempt / 2-second-sleep / WARN-log retry policy that production uses. Previously each option had its own fetch code, and they had drifted from each other and from production.
  2. Cleanup footgun closed. The harness refuses to delete $TestDir on exit when the directory pre-existed the run and already contained entries. The pre-existing state is captured before any directory work. This prevents Remove-Item $TestDir -Recurse -Force from wiping a user-supplied path like C:\Users\Me\Desktop.
  3. Stale extraction destinations are cleared before each extraction. Applies to Invoke-VendorExtraction, Invoke-CabExtraction, and the GitHub base-WIM test’s working directory. Before v18, a stale INF file left by an earlier run could satisfy a failed extraction’s INF-count success check. The Lenovo “non-zero exit but INFs present” branch was the sharpest case: it treats an INF-count greater than zero as success regardless of the extractor’s exit code, so a stale INF could mask a genuine extraction failure.
  4. Test-VmdDrivers records SKIP (not PASS) when the Intel CPU generation cannot be parsed. Driver applicability was not evaluated in that case, so a PASS would misrepresent what the harness actually checked. The raw CPU string is logged so the parser can be extended. The result detail reads Intel CPU generation could not be parsed.

Five new parser self-test checks (see “The parser self-test” below):

  1. DISM cmdlet availability. Verifies Mount-WindowsImage, Dismount-WindowsImage, Get-WindowsImage, Add-WindowsDriver, and Get-WindowsDriver are all present. Production hard-depends on all five; a missing cmdlet would only be discovered at injection time.
  2. Get-Disk shape. Verifies Number, FriendlyName, PartitionStyle, Size, BootFromDisk, IsSystem, and IsBoot are present.
  3. Get-Volume shape. Verifies DriveLetter, FileSystemLabel, FileSystem, Size, SizeRemaining, DriveType, HealthStatus, and UniqueId are present.
  4. CPU-generation parser regression table. Fourteen cases spanning 11th, 12th, 13th Gen, Core, Core Ultra, AMD, Celeron, Pentium, Xeon, and Atom CPU strings. Catches a Windows update or firmware rename that changes Win32_Processor.Name in a way that would silently desynchronise DesiredStateId.
  5. DesiredStateId determinism and input sensitivity. Same inputs must hash identically; flipping VMD presence must change the hash; flipping ProductionScriptVersion must change the hash; the output must be 64 hex characters. A silent change to the DSI recipe would be caught before it desynchronised every deployed state file.

Cosmetic fixes:

  1. Write-KV overflow handling. A key at or past $KeyWidth now gets a separating space before its value. Previously, Manifest VMD device IDs (23 chars, one over the 22-char key column) rendered flush against the value.
  2. Harness .NOTES block count “Four” → “Five” for the count of future-proofing checks (the v18 harness .NOTES block miscounted).
  3. Harness .NOTES block wording “in the detail” → “in the log line” for the Test-VmdDrivers SKIP path (the raw CPU string is logged via Say, not recorded in Record -Detail).

The output format is unchanged from v16 in every respect except the new colour tagging for the v18 checks, the five new parser self-test lines, and the new INDETERMINATE verdict colouring in Option S.

Running it

# Interactive
.\scripts\Test-WinRE.ps1

# Non-interactive: runs "all relevant for this machine" and exits
.\scripts\Test-WinRE.ps1 -NonInteractive

# Do not offer to delete the working directory on exit
.\scripts\Test-WinRE.ps1 -Keep

# Custom working directory
.\scripts\Test-WinRE.ps1 -TestDir D:\WinRETest

The default working directory is C:\Temp\WinRETest. All downloads and extractions go there.

Cleanup guard (v18; extended in v34 and v35). The harness refuses to delete $TestDir on exit when the directory pre-existed the run and already contained entries. This closes a footgun: before v18, passing -TestDir C:\Users\Me\Desktop and then choosing “no” at the cleanup prompt would have deleted the entire desktop directory. The pre-existing state is captured before any harness directory work; a directory that did not exist, or that existed but was empty, is deleted on exit as before. -Keep retains artifacts; it does not override the deletion refusal. Choose a separate dedicated scratch directory rather than removing unrelated content.

As of v34, when the harness does remove $TestDir, it also removes the parent directory (typically C:\Temp for the default path) if and only if its leaf name is exactly Temp, it is completely empty, and it is not a drive root — mirroring production’s v50 Remove-EmptyWorkspaceParent invariant. A user-supplied -TestDir whose parent is not named Temp (for example C:\Users\Me\Desktop) is therefore never touched.

As of v35, the interactive cleanup prompt reads Delete test artifacts from $TestDir → (Y/n) with y=delete (default) and n=keep. The v34 form was Keep test artifacts in $TestDir → (y/N) with y=keep, and operators read “y to cleanup” and answered y expecting deletion — the keep branch returned before Remove-EmptyTestParent ran. Empty input still deletes. The -Keep switch still short-circuits to keep, and the pre-existing-non-empty refusal is unchanged.

Output style (v16; extended in v17 through v38, with v20’s menu box alignment, v22’s new Build numbers section, v23’s Option S DeployedWinREMetadata display, v24’s dual-path active-WIM probe and Version trim, v25’s colour-tagged parser self-test additions and seven-component DSI-mismatch sentence, v26’s Plan adjacency preview section, v27’s Architecture line in the System Diagnostic and LocalInputsId in Option S, v28’s VMD storage-controller diagnostic section, v33’s two source-level mirror-binding assertions in the parser self-test, v34’s empty-test-parent cleanup, v35’s inverted cleanup prompt, v36’s Non-OS sweep suppression preview section, v37’s empty-metadata fail-closed guard in the sweep-suppression preview mirror, and v38’s run logging as the departures)

As of v16 the harness’s output is colour-coded and, in several sections, tabular. The changes are presentation-only: the checks, the menu structure, the arguments, and the read-only contract are unchanged. v17, v19, and v21 do not modify the output format. v20 changes only the menu box’s interior alignment; every other section’s output format is unchanged. v22 adds a Version line to the parsed-state block and a new “Build numbers” section. v23 adds a DeployedWinREMetadata line to Option S’s parity output. v27 adds an Architecture line to the Hardware section of the System Diagnostic and a LocalInputsId pair to the Option S parity output. v28 adds the VMD storage-controller diagnostic block to the VMD hardware presence section of Option 1. v39 adds two more rows to the parser self-test table (checks 21 and 22) and tightens check 18’s assertion; the row format itself is unchanged. The rest of the output format is unchanged from v16.

Run logging (v38)

Every Say, Rule, Write-Diag, Write-KV, and Write-WarningBanner call, and every Record call, appends a line to %TEMP%\WinRE-TestHarness.log in addition to its console output. The log is overwritten at the start of each run and its path is announced at startup.

The log lives under %TEMP% rather than $TestDir because NonInteractive mode (and interactive mode with the default cleanup answer) deletes $TestDir at exit; a log inside $TestDir would be destroyed with it and would be unavailable for post-run triage. If $env:TEMP is not set, the log is not created; every logging call is a no-op and the harness continues without it.

The log captures the full narrative of the run, including every parser self-test result via Record. A CI consumer running -NonInteractive can grep the log for [FAIL] or Summary: Passed=N Failed=M to find failures without parsing console output. An interactive operator can review the log after the console has scrolled.

Colour-coded values

Diagnostic values are rendered with a colour that reflects their state:

Tables

The All disks, All partitions, All volumes, and Recovery partitions sections of Option 1 render as aligned tables with fixed column headers. Each row is colour-coded by relevance: the OS partition and OS disk stand out in White, the reagentc-registered recovery partition stands out in Cyan, and other rows render Gray. Recovery-partition rows are further colour-coded green when the partition is both type-coded and on the OS disk, yellow when type-coded but on a secondary disk, and red when it is not type-coded at all.

The remaining sections — hardware, reagentc raw output, WinRE parsed state, OS partition / OS disk, OS partition supported sizes, bucket sizing preview, Build numbers, Windows Setup state, BitLocker on C:, target recovery partition state, VMD hardware presence (with the v28 storage-controller block), and the parser self-test — render as aligned key/value pairs or as free-form diagnostic lines. The parser self-test in particular is line-per-check: one [OK] / [FAIL] / [SKIP] line per check, with the state tag colour-coded.

Write-Diag and Write-KV

Diagnostic output in Option 1 and its sub-sections uses two helpers:

These replace direct Say calls in the diagnostic output. Download and extraction tests, the menu, and top-level banners continue to use Say and Rule.

Say colour-codes by -Level: INFO Gray, WARN Yellow, ERROR / FATAL Red, PASS / OK Green, FAIL Red, SKIP DarkGray, HEAD Cyan.

The menu

  1. System diagnostic (read-only info gathering)
  2. Driver manifest fetch
  3. OEM maps fetch + resolve (Dell, HP, Lenovo)
  4. GitHub base WIM - Win10 (download + extract + build check)
  5. GitHub base WIM - Win11 (download + extract + build check)
  6. HP WinPE pack (download + extract)
  7. Dell WinPE pack (prompts for OS)
  8. Lenovo WinPE pack (prompts for MT)
  9. VMD drivers (per manifest, filtered for this machine)
  S. State file parity check (production DSI vs on-disk state file)
  A. All relevant for this machine
  B. All of the above
  R. Print results summary
  Q. Quit

The menu renders the shortcut letter in colour, defaulting to Cyan. The state-file parity check (S) renders in Magenta, the aggregate runs (A, B) in Green, the summary (R) in Yellow, and quit (Q) in Red. The colour choice is a visual hint, not a semantic change to the option.

Option 1 — System diagnostic

Read-only information gathering. Dumps:

Then it runs the parser self-test (below).

BitLocker (C:) warnings (v12, updated in v14)

The BitLocker section of the diagnostic distinguishes two categories of state on C: that are relevant to the OS-fallback route. Both produce a warning block, in yellow.

Hazardous states. When the section reports ProtectionStatus not On together with a VolumeStatus of EncryptionInProgress, DecryptionInProgress, EncryptionPaused, or DecryptionPaused, the harness prints:

  WARNING: ProtectionStatus=Off, VolumeStatus=EncryptionInProgress
           Device Encryption is actively encrypting or decrypting C:.
           Production refuses the OS-fallback path in this state.
           The enable-only and dedicated-partition paths are still
           available because they target the recovery partition.

Ambiguous state. When the section reports ProtectionStatus not On together with VolumeStatus=FullyEncrypted, the harness prints a distinct block:

  WARNING: ProtectionStatus=Off, VolumeStatus=FullyEncrypted
           This state is ambiguous: legitimate suspension, OR
           Device Encryption Waiting-for-Activation.
           Production refuses the OS-fallback path in this state.

The wording of these warnings was updated in harness v14. The v12/v13 wording said production “will refuse destructive partition work” in these states, which described the removed OS-volume-gate policy and would have told a field engineer to defer a run that production would actually succeed on. Under the v43 patch 5 (further revision 5) policy, only the OS-fallback route depends on C:’s BitLocker state; the enable-only and dedicated-partition routes target the recovery partition directly and are not affected. As of v44 patch 6, the destructive partition path does not consult C:’s state either — only the OS-fallback route does.

Production fallback eligibility. C: must be confirmed FullyDecrypted before production can use it for OS-fallback. ProtectionStatus=On does not make an encrypted volume eligible, and an empty or unrecognized conversion status is not proof of decryption.

The harness warning blocks above are narrower diagnostics, not a complete mirror of production’s eligibility gate. They currently suppress these additional warnings when protection is On, and an unrecognized conversion status does not produce either block. Read the displayed VolumeStatus; absence of a warning does not authorize OS-fallback. Production checks the actual target again and refuses an indeterminate encryption state.

Target recovery partition state (v14)

The v43 patch 5 (further revision 5) policy is target-volume-based. reagentc’s BitLocker check is on the partition it is being asked to enable WinRE on, not on C:. The harness reports the BitLocker state of the partition reagentc is registered to. This is the state that determines whether the production script will need to run manage-bde -off on the target partition before calling reagentc /enable, and whether Set-RecoveryPartitionReadyForWinRE will find the partition already clean or need to prepare it.

The section header is drawn with a divider, then the details are printed as aligned key/value pairs. The diagnostic prints one of the following four classifications, depending on what manage-bde -status reports for the target partition.

Unmanaged by BitLocker. The partition is not managed by BitLocker — this is the expected state for a properly-typed recovery partition. The block reads:

  Target recovery partition state
  ────────────────────────────────
  Registered partition  Disk <n> Part <m>
  Querying              manage-bde -status <letter or volume GUID>
  Classification        unmanaged by BitLocker (reagentc /enable will accept this)

Fully decrypted. BitLocker manages the partition, but it is currently unencrypted. Also acceptable.

  Target recovery partition state
  ────────────────────────────────
  Registered partition  Disk <n> Part <m>
  Querying              manage-bde -status <letter or volume GUID>
  Classification        fully decrypted (reagentc /enable will accept this)

BitLocker-managed. The partition is encrypted or actively encrypting. Production’s preparation helper can attempt in-place decryption before reagentc /enable; success depends on the observed target and the command outcome. The harness prints the conversion status and a note about possible additional runtime.

  Target recovery partition state
  ────────────────────────────────
  Registered partition  Disk <n> Part <m>
  Querying              manage-bde -status <letter or volume GUID>
  Conversion Status     <value>
  Classification        BitLocker-managed - production will decrypt in place
                  Expect up to 300s of additional runtime on the next run.

Note: the final Expect up to 300s line uses a shallower indent than the value column above it. That is a known cosmetic quirk in harness v16 and does not indicate a problem with the diagnostic. A future harness version may tidy the alignment.

Could not parse. manage-bde -status produced output the harness did not recognise. Production’s helper retries the query at runtime.

  Target recovery partition state
  ────────────────────────────────
  Registered partition  Disk <n> Part <m>
  Querying              manage-bde -status <letter or volume GUID>
  Classification        could not parse manage-bde output

When WinRE is not registered to a partition at all — the common case on a machine where WinRE is Disabled and no registered location exists — the section prints:

  Target recovery partition state
  ────────────────────────────────
  WinRE is not registered to a partition (Disabled, or unresolved).
  If the plan is OS-fallback, production checks C: directly.

The harness remains read-only: it does not assign a drive letter. If the target partition already carries a drive letter, that letter is used for the manage-bde -status query. If it does not, manage-bde is invoked against the volume’s UniqueId (the \\?\Volume{...}\ form), which manage-bde accepts as a <volume> argument.

The block is informational, not a PASS/FAIL/SKIP record. It does not appear in the summary.

Build numbers (v22)

The “Build numbers” section renders immediately after the bucket sizing preview and before the Windows Setup state. It reports three values side by side:

  Build numbers
  ─────────────
  Registered WinRE      10.0.26100.9545
  Active WIM build      26100
  Backup WIM build      26100  C:\Recovery\WindowsRE\winre.wim

The three values are the harness’s read-only mirror of production v46 patch 2’s build-drift logging. A field engineer diagnosing whether a run is about to replace a newer registered WinRE with an older WIM reads these three values before running production. If the registered version is newer than the build of the WIM the harness sees at the reagentc location, that is a signal — but not necessarily a fault — and the harness reports the values without flagging.

The block does not produce a PASS/FAIL/SKIP record and does not appear in the summary.

VMD hardware presence (v18; extended v28)

The VMD section runs the same Get-PnpDevice query that production uses, with the same fail-closed semantics. As of v28 the section is preceded by a storage-controller enumeration block that closes the diagnostic gap the ASUS incident exposed: the machine had a controller (PCI\VEN_8086&DEV_7D0B) that the manifest did not recognize as VMD, the VMD detector reported “0 of 3 patterns matched”, and nothing in the previous output showed the operator which IDs to compare against.

Storage-controller enumeration (v28). The block runs first. It reports one of three outcomes:

Software and virtual controllers (InstanceId starting with {GUID}\ or SWD\) are skipped, mirroring production v49’s software-device filter.

Manifest VMD patterns. Immediately after the controller enumeration, the block prints the manifest’s requiredDevices patterns, one per line, under a Manifest VMD patterns N pattern(s) header. This is the operator’s side-by-side view: the machine’s controller IDs above, the manifest’s expected IDs below.

Match verdict. Then the VMD presence verdict:

ASUS-shape advisory (v28). When VMD is not present but SCSIAdapter-class devices are, an additional advisory block renders in yellow. It names the exact ASUS-incident shape and states that production v49’s storage-applicability gate — the last check before deployment — is what refuses a candidate that does not match the machine’s controller IDs. The advisory is operator-facing only; production does not depend on the operator to make the decision.

The INDETERMINATE outcome is v18; the storage-controller enumeration, the manifest-pattern display, and the ASUS-shape advisory are v28.

Windows Setup state (v13)

The diagnostic reads HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\State → ImageState and warns when the value is present and not IMAGE_STATE_COMPLETE. Production’s Audit Mode guard defers in that state before any state-modifying action. The diagnostic’s check mirrors the guard so that a field engineer pre-flighting a freshly imaged machine sees the deferral condition before running production.

Option S — State file parity check (v15; VMD handling and wording refined in v18, v19, and v21; DeployedWinREMetadata display added in v23; LocalInputsId display added in v27)

Read-only. Recomputes the DesiredStateId production would compute right now — reading the live driver manifest, resolving the OEM package for this machine’s vendor, and detecting VMD hardware presence — then reads the on-disk state file at C:\Recovery\OEM\winre_state.json and reports whether production would accept it or treat it as stale.

The output names the computed ID and the stored ID side by side, then prints one of three verdicts:

If the state file does not exist, the harness reports that production will take the full-update path (which is correct: needInject = $true when there is no state) — except when the VMD query is also indeterminate, in which case the harness records SKIP and explains that a live production run would defer rather than start the update (v19).

As of v21 the parity display also includes the state file’s RepairAttempts field alongside PendingReboot, LastEnableResult, and EnableFailureAttempts. Before v21 the display omitted this field even though the state file carries it; a field engineer diagnosing a pending-reboot loop had to read the JSON directly.

As of v23 the parity display also includes the state file’s DeployedWinREMetadata field. When present (a state file written by a v47 production run), it renders green. When absent (a v46-or-earlier state file), it renders yellow with a note that production v47 will force a rebuild on the next run because the drift detector has no anchor to compare against. Before v23 the field was silently absent from the display; a field engineer diagnosing a rebuild-on-first-v47-run had to read the JSON directly.

As of v27 the parity display also includes the state file’s LocalInputsId, alongside the computed value. Production writes the field (v48 patch 1) and consults it on offline fallback; the harness makes a mismatch visible before the machine goes offline. A stored LocalInputsId that differs from the current locally-computable value means a hardware or OS input has changed since the state file was written, and production’s offline fallback will defer rather than trust the stale DSI.

Option S is the field engineer’s tool for answering “is this machine about to rebuild?” without running the production script. It does not exercise the offline fallback (v44 patch 5): Option S always performs a live manifest fetch and a live VMD detection, so on an offline machine the harness reports the fetch failure rather than a DSI verdict.

Options 2 through 9 and A/B

Exercise the download and extraction paths. Each option:

Option A runs the subset relevant to the current machine (its OS, its vendor, its CPU). Option B runs everything.

The parser self-test

Twenty-three checks as of v39 (twenty-one as of v36 through v38, twenty as of v33, eighteen as of v28, seventeen as of v25, sixteen as of v22, fifteen as of v18, ten before v18); v19, v20, v21, v23, v24, v26, v27, v29, v30, v31, v32, v34, v35, and v38 did not change the count or the contents, and v37 extended check 20’s assertion without adding a new check. v28 added the Get-StorageControllerDevices shape check; v33 added the two source-level mirror-binding assertions (checks 18 and 19); v36 added check 20, the Test-RunningInVirtualMachine mirror-binding assertion; v39 tightened check 18’s assertion and added checks 21 (source-pattern) and 22 (behavioral) for the Int32-safe arithmetic fix. Each records PASS, FAIL, or SKIP in $Script:Results and prints one [OK] / [FAIL] / [SKIP] line. The state tags are colour-coded (green [OK], red [FAIL], dark gray [SKIP]); the line format itself is unchanged from earlier versions.

# Check What it verifies Since
1 reagentc status regex (Enabled\|Disabled) matches at least one line of reagentc /info output. v1
2 reagentc location parser The labelled native WinRE location passes the shared strict parser, including drive-letter, GLOBALROOT and volume-GUID forms. A missing or invalid reported location while Enabled fails; an absent Disabled location skips. v1 (updated v40)
2b reagentc version regex Windows RE Version: matches at least one line. SKIP when the line is absent (WinRE Disabled, or reagentc suppressed it). v22
3 manage-bde protection regex Protection On or Protection Off appears. v1
4 manage-bde conversion status regex A Conversion Status: value matches, or the string could not be opened by BitLocker appears. v1
5 Get-BitLockerVolume shape ProtectionStatus and VolumeStatus are non-null. SKIP if not elevated. v1
6 OS resolution Get-OSPartition and Get-OSDisk both resolve. v1
7 Get-Partition shape A sample partition exposes DiskNumber, PartitionNumber, Size, GptType, MbrType, IsBoot, IsSystem, IsActive. v1
8 WinRE location resolution The reagentc location resolves to a partition. SKIP if location is empty. v1
9 Get-RecoveryPartitions Returns at least one partition. v1
10 Get-PartitionSupportedSize Returns SizeMin and SizeMax. SKIP if no OS partition. v1
11 DISM cmdlets Mount-WindowsImage, Dismount-WindowsImage, Get-WindowsImage, Add-WindowsDriver, Get-WindowsDriver, Remove-WindowsDriver are all present. v18 (extended v25)
12 Get-Disk shape Number, FriendlyName, PartitionStyle, Size, BootFromDisk, IsSystem, IsBoot, BusType are present. v18 (extended v25)
13 Get-Volume shape DriveLetter, FileSystemLabel, FileSystem, Size, SizeRemaining, DriveType, HealthStatus, UniqueId are present. SKIP if no lettered volume to sample. v18
14 CPU generation parser Fourteen regression cases: 11th/12th/13th Gen, Core, Core Ultra, and negative cases for AMD/Celeron/Pentium/Xeon/Atom return the expected values. v18
15 DesiredStateId 64-hex, deterministic across repeat calls, VMD-sensitive, ScriptVersion-sensitive. v18
16 Compare-WimServicingMetadata Eight regression cases covering the DISM servicing-metadata comparison rules. v25
17 Get-StorageControllerDevices shape Handles the enumeration’s three outcomes: a NULL return (indeterminate PnP enumeration) records FAIL, an empty array records SKIP, and a populated array is verified to have objects each carrying FriendlyName, InstanceId, and Ids. v28
18 VHDX gate fail-closed Production’s Test-NativeBootVirtualTopology retains the v49 patch 2 fail-closed shape: the unfiltered Get-Disk enumeration uses -ErrorAction Stop, the gate sets IsNativeBootVirtual = $true on the corresponding catch path, and the indeterminate-topology reason text is present. As of v39 the assertion additionally requires the specific Where-Object { $_.Number -ne $osDisk.Number } filter, not just the presence of -ErrorAction Stop anywhere in the function. SKIP when WinRE.ps1 is not adjacent. v33 (tightened v39)
19 StorageControllerDevices mirror binding Production’s Get-StorageControllerDevices retains the unary-comma return (return ,$result) and both software-device filter regexes ({GUID}\ and SWD\). SKIP when WinRE.ps1 is not adjacent. v33
20 Test-RunningInVirtualMachine mirror binding Production’s Test-RunningInVirtualMachine retains the ten hypervisor signatures, the fail-closed $null return, the Win32_ComputerSystem query source, the empty-metadata fail-closed guard (IsNullOrWhiteSpace), and the combined-string construction ($combined = "$mfg $mdl"). SKIP when WinRE.ps1 is not adjacent. v36 (extended v37)
21 Get-PartitionPlan Int64-safe arithmetic (source pattern) Production’s Get-PartitionPlan contains the Int64-safe -gt comparison form (} elseif ($osSize -gt $plannedOSSize) { and } elseif ($plannedOSSize -gt $osSize) {) and does not contain the vulnerable [Math]::Max(0, ...) form. Guards against reintroduction of the v50 patch 4 Int32 overflow fix. SKIP when WinRE.ps1 is not adjacent. v39
22 Int64 arithmetic (behavioral) Reproduces the safe shrink and safe extend forms with a delta of 3,000,000,000 bytes (greater than Int32.MaxValue) and confirms the safe forms return the correct value without throwing; separately confirms the vulnerable Math.Max form still throws on the same input. Complementary to check 21: catches an off-by-one or wrong-direction rewrite that would still match the source pattern. Does not read WinRE.ps1; does not SKIP on source absence. v39

What a FAIL means

A FAIL means the machine’s Windows tooling no longer matches an assumption the production script relies on. The production script may silently misclassify state on this machine and must be adapted before deploying to it.

The most likely FAILs and their implications:

What a SKIP means

A SKIP means the check could not run in the current context. The reasons:

A SKIP does not indicate a defect.

Result states

Every test records a result via Record:

Record -Test "<name>" -Ok $true   -Detail "<description>"                        # PASS
Record -Test "<name>" -Ok $false  -Detail "<description>"                        # FAIL
Record -Test "<name>" -Ok $false  -State "SKIP" -Detail "<reason>"               # SKIP

The legacy -Ok boolean is still supported: when -State is not supplied, the state is derived from -Ok. When -State is supplied it is authoritative, and OK is $true only for PASS.

Show-Summary prints each result, then the totals. The per-result state tags are colour-coded: green for [PASS], red for [FAIL], dark gray for [SKIP]. The totals on the last line are colour-coded: the pass count green when non-zero, the fail count red when non-zero else green, the skip count yellow when non-zero else dark gray.

Passed 8, failed 1, skipped 1 (of 10)

The BitLocker, target-partition, ImageState, Build numbers, storage-controller, and Option S outputs are informational — Option S records a result for the parity check itself but its intermediate verdict output is a separate thing. The BitLocker, target-partition, Build numbers, storage-controller, and ImageState blocks do not produce PASS/FAIL/SKIP records and do not appear in Show-Summary.

Non-interactive mode

.\scripts\Test-WinRE.ps1 -NonInteractive

Runs Show-SystemDiagnostic, then Invoke-AllRelevant, prints the summary, exits (v38). Before v38, NonInteractive ran only Invoke-AllRelevant.

-NonInteractive runs the full System Diagnostic (Option 1), including the parser self-test, mirror-binding assertions (checks 18–20), the Int64 source-pattern check (21) and behavioral regression (22), and then the download and extraction tests. It does not run the State file parity check (Option S). So the BitLocker warnings, the target-partition state block, the ImageState check, the Build numbers block, the storage-controller block, the sweep-suppression preview, and the parser self-test are printed; the DSI comparison is not. If you need the DSI comparison, run the harness interactively and choose Option S.

The exit code is 0 when no FAIL results were recorded, and 1 when at least one FAIL was recorded (v25+). SKIPs do not affect the exit code. The summary remains the authoritative view of what ran. The behavior was introduced in v25 so that CI and cron consumers can treat the harness as a regression gate rather than a reporter.

What the harness does not test

The harness is deliberately narrow. It does not and cannot test:

Those paths are covered by field testing on representative hardware. See the “Field-tested hardware” table in the README.

Differences from production

The harness shares code paths with production in the download, extraction, and CPU-generation helpers. It is documented in the file’s own docstring which functions are “based on” the production versions and which are harness-specific.

Fourteen known differences:

The harness has no mirror of the v45 shrink-first pipeline. Option 1 and Option S report the machine’s current state and the DSI comparison, but they do not simulate the plan, the pre-shrink, the extension path, or the whole-layout assertion. That is by design: those paths are destructive and cannot be simulated read-only.

v50 patch 5 validation

This development revision needs two distinct kinds of evidence. Parser checks and isolated regressions can establish the contracts below without executing the production repair pipeline. A disposable Windows VM is needed to exercise actual partition, BitLocker, reagentc and reboot transitions. The v50.4 field logs and the existing harness success counts are baseline evidence, not v50.5 test results.

Isolated regressions

An isolated test result applies to the exercised fixture and extracted functions. It does not establish that Windows will accept a particular resize or that the resulting WinRE will boot.

Recorded isolated results

The following suites passed under Windows PowerShell 5.1 and PowerShell 7 during local patch 5 implementation on 2026-10-23–24. They extract the relevant functions/AST and use isolated fixtures; they do not execute a live Repair deployment, the full hardware/network harness or recovery boot.

Suite Result Scope
Test-BackupCleanup.ps1 29 PASS Backup allowlist, ancestry/child junctions, read-only files, relative paths, no-mutation listing and nonrecursive empty-directory removal.
Test-RestoreCleanup.ps1 29 PASS All seven production call sites and preparation abort; rollback allowlist, actual junctions, read-only files and replacement/new-child race fixtures.
Test-HarnessBindings.ps1 60 PASS Production contracts, mutation fixtures, scriptless readers, exact location-helper mirrors, full-directory state extraction and actual diagnostic Check 2 execution; Enabled blank/absent location refusal in both readers.
Test-DeploymentSafety.ps1 131 PASS Actual main predicates and extracted layout/journal/deployment contracts with mocked storage, DISM, registration, lock and state providers; ownership, interruption, backoff and failure fixtures, including route loss before last-resort fallback and actual target-selector enumeration failures that must not enter replacement.
Test-DeploymentProviders.ps1 25 PASS Exact UTC timestamp parsing, BitLocker-provider fallback, deployment ACL construction and ownership-scoped mount/workspace cleanup; native tools and ACL writes mocked.
Test-PartitionPreparation.ps1 15 PASS Actual preparation helper with mocked storage: journal-before-shrink, prepare-before-disable, source drift, reserve checks, geometry restoration and post-deletion failure reporting.
Test-WinRELocations.ps1 51 PASS Real parser, resolver, state reader, matcher, fingerprint and deployment flow; directory aliases, nested decoy WIMs, stale registry masking (including Enabled blank/absent native locations), copy-after-disable, custom-folder Restore/rollback and native path quoting. All providers mocked; proven missing folders remain repairable and missing volume roots refuse.
Test-OemPackHashes.ps1 72 PASS Actual production/harness downloaders and Lenovo/Dell builder checksum publication; surrounding whitespace, malformed/blank supplied digests, mismatches, dual hashes, failed requests and empty downloads; selected Dell packs, supplied XML whitespace and single-pack Current alias on both runtimes. All network/filesystem providers mocked.
Test-MaintenanceInstall.ps1 65 PASS Actual wrapper install control flow and shared trust policy; owner/ACE/reparse checks, protected descriptors, creation races, hash/registration failure and retained staging after partial publication. Filesystem/task providers are instrumented or mocked; actual nonprivileged CMD export, launcher JSON and command-length checks run.
Test-VirtualDiskSafety.ps1 23 PASS Actual source with mocked providers: ordinary guest OS-disk eligibility, non-OS sweep suppression and file-backed/unsupported-bus preservation, plus the unchanged native-boot topology refusal. These fixtures do not validate native boot or real partition operations.
Test-InfHardwareIds.ps1 14 PASS Actual INF parser, controller enumerator and applicability chain: the observed Hyper-V VMBUS model line, legacy prefixes, case/duplicate handling and multiple IDs; wrong or missing IDs, comment/unreferenced decoys, unreadable INFs and provider failures remain refused. All PnP/filesystem providers mocked.

The location suite imports and reruns the deployment-safety fixtures as prerequisites; those 131 checks are counted once in the 514-check total across eleven suites. Separate read-only probes on the workspace volume confirmed actual DOS/volume-GUID directory resolution and metadata access under both runtimes. They did not inspect or modify WinRE and are not recovery-boot evidence.

Follow-up review reproduced two pre-fix behaviors in isolated source-extracted fixtures: last-resort fallback disabled an enabled route that became unresolvable after a creation failure, and diagnostic Check 2 falsely failed a valid drive-letter location. The added tests reject those behaviors while retaining fallback recovery for a known partition with an unreadable WIM. These are mocked-provider results, not reports of the inconsistent native state occurring on Windows hardware.

The current eleven-suite/514-check rerun, including the Restore reporting clarification, is retained under v50.5\Isolated Regression 2026-10-24_112509, with all 22 runtime/suite invocations exiting zero. The preceding VMBUS-fix run remains under v50.5\Isolated Regression 2026-10-24_020021. Earlier nine-suite/477-check evidence remains under v50.5\Isolated Regression 2026-10-23_211654; the intermediate ten-suite/500-check record references the additional virtual-disk logs under v50.5\Final Verification 2026-10-24_013703. These results use Windows PowerShell 5.1.26100.9711 and PowerShell 7.6.8. A native fresh maintenance-installation core run is recorded below; the isolated failure fixtures do not inject real filesystem failures or register an actual task.

No passing isolated count closes the VM gate below. The deployment suite does not perform actual partition, WinRE/DISM, protected-journal or deployment-lock operations, and does not boot WinRE.

Recorded prerelease field results — 2026-10-23

The eight logs supplied on 2026-10-23 covered four machines, with every recorded manager run ending in a SUCCESS summary. Their numbered folders under v50.5\Prerelease Test Run were subsequently reused for the 24 October batch below; this table retains the earlier review rather than describing the files currently there. The staged production-script SHA256 in the earlier Repair/Restore runs was A30A3F8767453AE089FC57DC91E9A1FCEA161CAA8DDB9B4A1D27DF8B437CE1E8; it matched the repository script before the checksum and work-summary corrections described below. These results apply to that snapshot. The harness logs identify v40 but do not record their source-file hash.

Folder / machine Observed production work Harness evidence
1 — ASUS, i5-11400 Two successful fast paths; successful DryRun; 756.4 MiB WIM backup with hash/sidecar verification; Restore verified that the target already matched and performed no replacement. User-owned OEM-parent warning and USB-disk preservation behaved as documented. Option S state-file parity: 1 PASS, 0 FAIL, 0 SKIP.
2 — Dell Pro 16 PC16250, Ultra 5 235U Serviced deployment in 5m41s; C: shrank 101 MiB before disable; recovery replaced from 1000 to 1100 MiB. Dell A10 injection verified 64 new packages and 49/49 package-INF matches. One later fast path succeeded. System diagnostic: 23 PASS, 0 FAIL, 0 SKIP; recovery free space 272.9 MiB.
3 — HP EliteBook 840 G9, i7-1255U Serviced deployment in 6m44s; C: shrank 301 MiB before disable; recovery replaced from 1000 to 1300 MiB. SoftPaq exit 1168 produced 195 INFs; injection verified 190 new packages and 153/153 package-INF matches. One later fast path succeeded. System diagnostic: 23 PASS, 0 FAIL, 0 SKIP; recovery free space 349.2 MiB.
4 — Lenovo 21MW / ThinkBook 16 G7 ARP, Ryzen 7 7735HS Serviced deployment in 3m00s; C: shrank 101 MiB before disable; recovery replaced from 1000 to 1100 MiB. No OEM-map entry or VMD injection; all three storage controllers matched candidate INFs. Three later fast paths succeeded. System diagnostic: 23 PASS, 0 FAIL, 0 SKIP; recovery free space 306.1 MiB.

The three full deployments classified their starting image as Foreign-No-Drivers, then serviced it. All three observed C: encryption state True before replacement; the later diagnostics showed EncryptionInProgress with ProtectionStatus Off. Those observations establish successful dedicated replacement despite OS encryption, not encrypted-target reuse. Copy hashes, Enabled registration, saved state, LKG refresh and cleanup were verified in the logs. Checks 18–22 passed on all three diagnostic machines. Dell’s first manifest timeout recovered; the HP extractor’s nonzero exit was accepted only after usable output was verified. ASUS DryRun reported an unknown source build while retaining the correct metadata/hash and fast-path decision.

These logs exposed an inaccurate empty Work performed summary after real work; the follow-up reporting fix records actual completed copies and verification without inventing servicing on copy-only runs. Generated Dell/HP/Lenovo maps also parsed successfully (6/5/926 entries). One Lenovo 20JV / DS121687 checksum had leading whitespace; the builder and both downloaders now normalize edges and refuse supplied malformed hashes. Those edge cases retain isolated regression coverage. The 24 October field runs below exercise populated deployment summaries and an ordinary hash-verified Lenovo download, not the whitespace case or builder publication. The existing generated maps were left untouched.

Those runs do not establish recovery boot, transactional Restore replacement/rollback, preserved-foreign relocation, OS-fallback migration, encrypted dedicated-target reuse, missing-location refusal on hardware, or interrupted/post-deletion failure recovery. The ASUS Restore was a verified no-op. The scope concern about Restore’s local workspace was independently disproved using the actual deployment function with mocked providers on both runtimes; it does not require a live different-image Restore merely to settle PowerShell scope semantics.

Recorded prerelease field results — 2026-10-24

Six new logs in v50.5\Prerelease Test Run\1 through 3 contain seven Repair invocations: three serviced deployments and four subsequent fast paths, all with SUCCESS summaries. Every invocation staged production SHA256 9CD1EE4D247F21546EAFD4BA7304234CD600B2BB21637B4B2C00B3BB3CFC89B6, matching the tested production snapshot. Hash-verified copies of these logs and their manifest are retained under v50.5\Field Validation 2026-10-24_152641. Harness logs identify v40 without a source-file hash.

Folder / machine Observed production work Harness evidence
1 — HP ProBook 4 G1i 16, Ultra 5 225U Serviced deployment in 5m44s; C: shrank 301 MiB before disable; recovery replaced from 1000 to 1300 MiB. HP sp173204 produced 195 INFs despite extractor exit 1168; injection verified 190 new packages and 153/153 package-INF matches. One later fast path succeeded. Diagnostic: 23 PASS, 0 FAIL, 0 SKIP; recovery free space 349.8 MiB.
2 — Lenovo ThinkPad L15 Gen 4, MT 21H4, i7-1355U Serviced deployment in 2m56s; C: shrank 101 MiB before disable; recovery replaced from 1000 to 1100 MiB. No OEM-map entry or VMD injection; all three storage controllers matched candidate INFs. Two later fast paths succeeded. Diagnostic: 23 PASS, 0 FAIL, 0 SKIP; recovery free space 306.7 MiB.
3 — Lenovo ThinkPad L16 Gen 1, MT 21L3, Ultra 7 155U Serviced deployment in 3m39s; C: shrank 101 MiB before disable; recovery replaced from 1000 to 1100 MiB. Lenovo package SHA256 verified; injection added 14 packages with 14/14 package-INF matches. One later fast path succeeded. Diagnostic repeated twice: 46 cumulative PASS, 0 FAIL, 0 SKIP; 23 checks per repetition, recovery free space 303.2 MiB.

All three starting images were Foreign-No-Drivers and were serviced. Each deployment verified candidate storage-ID matches, the new unencrypted recovery partition, copied WIM hashes, Enabled registration, saved state and the LKG copy. Later fast paths accepted matching state and reported no byte drift. C: was reported encrypted before replacement; subsequent diagnostics showed EncryptionInProgress with protection off. The logs establish successful dedicated replacement during OS encryption, not encrypted-target reuse or recovery boot. HP’s download had no supplied integrity digest; Lenovo’s supplied SHA256 was verified. No secondary disks were present, so these runs do not test the non-OS sweep exclusions.

The deployment Work performed summaries now include completed copies and final verification. The diagnostic wording has since been clarified to include the existing USB/unsupported-bus sweep exclusions, remove stale current-version references and avoid implying that an INF match proves bootability; no partition or driver policy changed. The 60-check harness-binding suite passed again on both PowerShell runtimes after that wording change; those logs are retained with this field record. The recorded 92 diagnostic passes are four repetitions of the 23-check diagnostic across three machines, separate from the 514 isolated checks above. Native manager-process exit codes were not captured independently.

These runs do not establish preserved-image relocation, OS-fallback migration, encrypted dedicated-target reuse, transactional Restore replacement/rollback, missing-location refusal, malformed-checksum rejection, maintenance installation, interrupted/post-deletion failure recovery or actual WinRE boot. The disposable-VM gates below remain open.

Disposable Windows transitions

Use a snapshot or full disk image before each destructive exercise. Record the original layout, BitLocker conversion/protection state, registered route and WIM SHA256; retain the complete resulting logs.

Starting condition or injected failure Expected evidence
Accepted foreign WinRE on decrypted C:; safe dedicated target available Byte-identical image on an adequately sized dedicated partition; registration checked; foreign ownership remains separate.
Accepted foreign WinRE on encrypted C: Safe dedicated preparation is attempted without decrypting C:; failures before switching retain the old registration and verified source. Do not assume the old OS-fallback route is bootable.
Current manager-owned image; layout alone is inadequate Copy-only transition; no strip, injection, ResetBase, provenance write or export.
Adequate dedicated foreign image No unnecessary partition work; observed status and preservation are reported separately.
Adequately sized encrypted dedicated target Healthy-layout exit refused; reuse and in-place preparation attempted where safe, without requiring repartitioning solely because of encryption. Unknown state does not prove eligibility.
Active dedicated route expressed by drive letter or alternate volume spelling Active target identified before any WIM replacement; disable precedes active-target copying, and the exact registered folder is retained.
Shrink or pre-delete verification fails Old route and recoverable image remain; accurate deferral/retry behavior.
Active recovery partition is deleted, then creation, format, attributes or drive-letter assignment fails Retained independent source and durable operation record; no false rollback or healthy-route claim; fatal failure when no acceptable route can be verified.
Deployment, /setreimage or /enable fails Verify the actual post-failure destination/registration, retain recovery material and task where unresolved, and report the correct code.
Dedicated creation actually fails; C: fully decrypted, geometry verified, no acceptable existing route A last-resort OS route is accepted only after location/hash/enable/state checks; warning 2, retained Registered journal/candidate/task and one-hour retry delay. Preflight deferral and encrypted C: do not authorize it.
State persistence fails after a valid dedicated route is established Keep the valid route; retain the source and operation record; report the persistence failure.
Process kill or reboot between persisted phases Next Repair run inspects current layout and expected bytes before acting; no blind replay of old partition numbers.
Recovery boot after successful registration Actually enter WinRE and verify that the OS disk and expected inputs are usable. Enabled and matching SHA256 alone do not establish this.

On 2026-10-24, PowerShell Direct verified the disposable Windows (x64) guest: Windows 11 Pro build 26300, one GPT virtual disk, C: already fully encrypted with protection off, and an Enabled WinRE route on a 917 MiB recovery partition. Both the original post-OOBE checkpoint and a powered-off authenticated baseline were saved. Baseline inventory is retained under v50.5\Hyper-V Baseline 2026-10-24_012341; test records are under v50.5\VM Validation 2026-10-24. Some starts initially failed with host-memory error 0x8007000E; later starts succeeded at the unchanged 4096 MiB setting.

The first actual Repair used E905E53D0C1749559E80A77DFD3252F638B3960368425C66D82AAEF3CCEE84CC and exited 2 before partition work: the applicability check falsely rejected the Hyper-V SCSI controller. Registration, geometry and the registered WIM hash remained unchanged. A read-only probe found its required VMBUS ID in wstorvsc.inf line 35; the parser fix has 14 isolated cases. The subsequent A3E758… ControlFixed attempt failed inside the external test runner because its Storage module could not load, before production ran. It is not a production deployment result. Completed results for that tested production snapshot follow.

Recorded Hyper-V validation

Recorded on 2026-10-24. Evidence: v50.5\VM Validation 2026-10-24_155531, including verified-VM-results.md, per-case logs, runner/post-state records and boot screenshots. Production remained SHA256 9CD1EE4D247F21546EAFD4BA7304234CD600B2BB21637B4B2C00B3BB3CFC89B6 throughout these cases.

Case Recorded outcome
ControlCurrent Production/runner 0; real 917→1100 MiB recovery replacement, Enabled registration and saved state. Original outer exit field is null, not independently measured 0.
Control recovery boot WinRE menus and X:\Windows command prompt captured; guest OS disk and SYSTEM hive readable. Returning to Windows retained Enabled registration and exact AC5E080A… WIM hash.
NewPartitionCurrent → NewPartitionRetry Three injected creation failures after actual old-recovery deletion: fatal 3, C: size restored, WinRE Disabled; candidate/journal/task retained. Normal retry exited 0 and deployed that exact FECAA125… candidate.
FormatVolumeCurrent → FormatVolumeRetry One injected format failure after real partition creation: orphan removed, C: size restored, fatal 3 with recovery material retained. Normal retry exited 0 with the exact 06871360… candidate.
InterruptedCurrent PID 4904 forcibly killed during a 30-second test-provider hold after deletion; exit -1, no runner-finally result. Journal/candidate/task survived, C: remained shrunk. After reboot, the actual task ran as SYSTEM, 16:43:08–16:45:50, with Scheduler event 201 result 0 and event 102 completion. No manual Repair launch; no additional shrink. Registered/saved hash matched retained 0DE3F537…; pending material/task removed.
ForeignPreserveCurrent Fourteen actual non-inbox drivers classified Foreign-With-Drivers; unchanged 817429179-byte WIM relocated 917→1100 MiB. Production/runner/outer exit 2, PRESERVED-DEDICATED, Enabled; deployed/accepted hash 4AE2BD8F…, CurrentImageHash empty. Pending material/task/staging removed.
MaintenanceNativeCurrent Actual install core/native providers exited 0. Trusted installed 9CD1… copy, SYSTEM principal and boot+5m / every-30-days-at-03:00 triggers verified. The exact newly registered task was then removed; installed file retained. Full menu/UAC and scheduled task execution were not tested.

After these runs, source comments were corrected and only the summary renderer changed executable production code: empty lists on unresolved outcomes now say (none recorded; see detailed log). Extracted-renderer checks verify that correction separately; the native results above remain bound to 9CD1…. Final source SHA256: 1995348FF178BF0F1FD3B48740519475D4C66511FAFCC56FB2FB8CBB22FF48E9; eight renderer checks pass under each PowerShell runtime, and the other 124 executable function bodies and executable tokens outside the renderer are identical.

The foreign fixture was prepared separately from a verified baseline WIM and an official Lenovo 14-driver WinPE pack. Production then preserved those completed fixture bytes; this was not a captured vendor field image.

Scope: one adjacent C: Recovery GPT guest, encrypted/unlocked C: with protection Off. Process-local fault overrides did not persist across reboot. The two immediate manual retries removed only the archived execution-deferral marker, preserving journal/candidate; no clock change or cooldown-expiry test. Restoring C: size did not restore deleted recovery content. The interruption case separately proves automatic boot-task recovery.

This records specific live post-deletion failures and recovery, not an atomic transaction or a completed transition matrix. These cases do not deliberately exercise all four historical v46 hardenings. Intervening-anchor/MBR failures, fully decrypted last-resort fallback, protection-On/locked BitLocker, native boot, encrypted-target reuse and other failure sites remain unverified. The accepted-foreign fast-path repeat and booting the preserved WIM were not run. Control boot proves that candidate’s boot and storage access, not every recovery tool or physical-device driver. Retain the failure-test procedure and gate for unexercised scope.

The v45 patch 1 changes to Ensure-AdequateRecoveryPartition are the largest rework of the destructive path since v43. The reorder moves the shrink into the reversible window; the geometry model changes from deficit-plus-slack to single-boundary; the plan gains several validity checks; the deletion loop reorders the active partition last; a post-delete extension path with a safe fallback replaces the pre-delete extend; and a whole-layout assertion verifies the created partition’s geometry. The happy path through these code paths has been exercised end-to-end on a disposable Hyper-V VM (2026-10-02 08:56).

The v46 patch 1 cycle added three physical-hardware exercises on top of the VM run: two clean-path runs on different vendors, and the plan-rejection exercise on the machine that motivated the fix.

Assert-RecoveryPartitionLayout has been exercised in the passing case. The Dell Latitude 3540 and the HP EliteBook 6 G1i 16” both took the v46 patch 1 destructive path on 2026-10-02 and both logged Verified recovery partition layout: disk 0 partition 4, offset O MiB, size S MiB before reaching DEDICATED. Both runs also confirmed the C:-to-recovery gap and the disk-end trailing reserve were within tolerance, which is what the assertion exists to verify. This is the first physical-hardware exercise of the whole-layout assertion on the v45/v46 pipeline.

The plan-rejection check has been exercised in the rejecting case. The Lenovo IdeaPad 3 15IAU7 that motivated v46 patch 1 took the v45 patch 1 pipeline on physical hardware and the post-delete geometry check in Ensure-AdequateRecoveryPartition ($plannedEnd -gt ($diskSizeNow - 1MB)) correctly rejected the plan: Get-PartitionPlan had computed tailEnd from a factory-provided partition ending exactly 1 MiB past the disk-end reserve, AlignedManagedExtentEnd landed 1 MiB past the reserve, and the post-delete check refused to proceed. The machine fell into OS-fallback with a state file that matched the failing DesiredStateId, so subsequent scheduled runs accepted the state and did not retry — the machine stayed in OS-fallback until an operator manually deleted the state file. Under v46 patch 1’s clamp the same layout produces a valid plan; the second full-update run (after the state-file reset) reached DEDICATED. This is the first physical-hardware failure of the v45 destructive path, and the first time the post-delete check fired outside a test harness.

v47 patch 1 destructive-path coverage (historical)

This subsection records coverage at v47 patch 1; the patch 5 results above supersede later claims about current coverage. At v47 patch 1 the ASUS PRIME H510M-D covered the non-destructive paths; the gaps then were:

The v45 destructive-path VM test documented below remains the recommended next step before broad rollout under v47. It should be followed by a canary on a machine with an OEM driver pack so the strip-and-reinject loop runs against a non-empty set. These paths are covered by inspection, by the earlier F1/F2/F3 strip experiment, and by the mocked-geometry test plan documented below.

v48 patch 1 coverage (historical). The intervening-anchor happy path is field-verified on the AMD Ryzen 7 5825U machine that motivated it (2026-10-06), on the exact C: | D: | Recovery layout. The v48-specific code paths that remain unexercised on any storage are: the intervening-anchor post-deletion failure behaviour (the same class of residual documented for the non-intervening path); the v48 multi-intervening rejection and surplus rejection; the transactional WIM replacement’s rollback branch (a copy failure mid-replacement); the architecture gate on ARM64 hardware; and, from v48 patch 2, the source-WIM hash cache fix on the enable-only fallthrough path. The remaining v47 gaps also stand: the strip stage against a non-zero third-party driver set, the OEM pack or VMD injection paths, the metadata-triggered rebuild branch, the pre-/disable race-detector abort branch, and the WIM_READY checkpoint save/resume round trip. The deliberate post-deletion failure test remains the gate for future changes to the post-deletion segment. See the “v48 patch 1 destructive-path coverage” section below.

v48 patch 1 destructive-path coverage

The v48 patch 1 release introduces five changes: intervening-partition handling, the architecture gate, LocalInputsId, LKG-by-hash at any discovered recovery location, and transactional WIM replacement. The four that are covered below are listed first; the fifth (LKG-by-hash) is a source-selection change and is not covered here. Two additional sub-case gaps of the intervening-partition handling are listed after the four.

v49 destructive-path coverage

The v49 release introduces several pre-deployment gates, post-run persistence features, and the backup / restore actions. The happy path for the interim features (backup, restore, resume task on clean completion) is exercised by the wrapper’s own smoke tests. The gates and the interruption paths below are the v49 coverage that remains.

Each of these tests should be recorded with the same data the v45 / v46 tests record: the VM setup, the branch that fired (with the log line), the machine’s end state, the exit code, and any divergence from the documented behavior.

v46 patch 2 hardenings (inside the post-deletion gate)

The v46 patch 2 cycle added four post-review hardenings of Ensure-AdequateRecoveryPartition. Per CONTRIBUTING.md, they are treated as inside the post-deletion gate — no future change to the post-deletion segment of the destructive sequence should ship until the post-deletion failure test below runs and its result is recorded. The four hardenings:

None of the four has been exercised in the field. They were code-review hardenings in the v46 patch 2 cycle, not field-driven fixes. They are covered by parser and mocked-geometry tests, and by the same post-deletion failure test that gates the rest of the post-deletion segment. When that test runs, its recorded result must list which of the four hardenings it exercised and which it did not; that is the right moment to revisit the gate’s scope.

The post-deletion failure test (gating)

The original v45 failure case remains the motivating test: an active recovery partition is deleted, every subsequent creation or formatting attempt fails, and encrypted C: prevents OS-fallback. Restoring the size of C: cannot recreate the deleted recovery partition. Patch 5 adds an independent protected WIM and pending-operation record, accurate fatal reporting, and a resumable fresh assessment; it does not make partition replacement atomic.

No change to the post-deletion segment may ship until this deliberate failure test runs and its result is recorded. The isolated suites above exercise mocked providers and do not close this gate. See CONTRIBUTING.

Setup.

Procedure and expected evidence.

  1. Run the patch 5 Repair action and retain its complete log and actual process exit code.
  2. Before any partition mutation, verify that the protected independent candidate and its journal exist, that the expected SHA256 matches, and that the recorded OS identity matches the VM. Capture the journal again after failure.
  3. Verify shrink-before-disable sequencing and actual deletion of the active recovery partition. If failure occurs earlier, the test has not reached the gated case.
  4. For creation failure, verify the bounded three attempts. For formatting failure, verify orphan removal. Check whether restoring the resize target to its original size actually succeeds; record partial restoration as such.
  5. Verify that encrypted C: prevents fallback and that an unverified or missing recovery route returns 3 (fatal). Warning 2 is insufficient for the loss of the active route. The protected WIM, journal and resume task must remain.
  6. Reboot with the injection still active. Verify that the pending operation is read before ordinary servicing/network preparation and that current topology is reassessed without replaying stale partition numbers. Record any retry delay.
  7. Remove the injection and retry. Verify a single adequate dedicated partition, the registered destination’s exact expected hash, Enabled status, ownership fields and durable state read-back. Only then may the journal and candidate be retired.
  8. Boot the resulting WinRE and verify storage access. Registration and hash checks alone do not prove recovery boot.

Repeat on a fully decrypted OS volume to exercise the constrained last-resort fallback: actual dedicated creation failure, verified geometry and no acceptable route to retain are required. A verified OS-fallback returns warning 2 and keeps the Registered journal, candidate and task for a later dedicated retry. Capacity/preflight deferral must never trigger fallback.

Also repeat on the supported intervening-anchor layout. Record the anchor’s original and final geometry separately from C:. A successful size restore is not proof that a deleted partition or its contents were restored.

Record the Windows build, script version, injection point/method, partition inventories, hashes, native-tool results, persisted phases, exit code, task state, and recovery-boot result. Investigate any divergence before release; update the documentation from observed evidence rather than accepting the expected result as proof.

Paths that need coverage

Each of these tests exists to protect a specific invariant from architecture.md. The pre-shrink and deletion-failure tests are direct exercises of Rule 2 — a failing pre-shrink must leave the old recovery route intact, and a failing deletion must attempt to restore it. The whole-layout assertion and the plan-validation edge cases are Rule 1 tests — the destructive sequence must refuse to proceed on a layout it cannot prove safe. The deferral marker lifecycle is a Rule 4 test — the marker is the mechanism by which “do no work unless needed” is enforced across a run that has deferred. The MBR test confirms Rule 1 on a partition style that has not yet seen a field exercise.

How to run these tests

Each test needs a different starting state. Use a snapshot-restorable VM; the destructive path is only safe in a disposable context.

What to record when a test is run

For each test, record:

If a divergence is found, report it as a bug with the test setup and the full log. The fix ships as its own patch, gated on the test that found it. For the post-deletion failure test, the fix is the gate the CHANGELOG entry describes.

Adding a test

The harness is a single file. To add a test:

  1. Write a function that follows the existing pattern: log via Say, record the result via Record.
  2. Add a menu entry in Show-Menu using the MenuItem helper and pick a shortcut-letter colour from the palette already in use.
  3. Add a case to the switch in the main loop.
  4. If the test should run as part of “all relevant for this machine,” add it to Invoke-AllRelevant.
  5. If the test downloads anything, apply -TimeoutSec $NetworkTimeoutSeconds to every network call. The harness’s $NetworkTimeoutSeconds is declared at the top of the file and matches production’s value.

For diagnostic output added to Option 1 or its sub-sections, use Write-Diag for free-form lines and Write-KV for aligned key/value pairs. The caller chooses the colour in both cases; there is no automatic severity mapping. For values inside tables, follow the pattern of the surrounding table and pick a colour from the restricted palette (Gray, DarkGray, Cyan, Green, Yellow, Red, Magenta, White).

When adding a check to the parser self-test, use the pattern of the existing checks: enumerate the object’s expected properties, compare against the observed shape, record PASS when all are present, FAIL when one is missing, and SKIP when the state the check inspects is legitimately absent. A check that a machine can be in without fault should SKIP rather than FAIL — for example, the Get-StorageControllerDevices shape check (v28) SKIPs on zero devices because a VM with no SCSIAdapter-class devices is a valid configuration.

Do not add tests that modify the machine’s state. The harness may manage its own scratch artifacts, but must not modify the live WinRE configuration, partitions, BitLocker, drive letters or deployment state.