WinRE Manager is a single-file production script, an interactive command-line wrapper that launches it, a read-only test harness, and three map builders. This document explains the design — why the script makes the choices it does, what invariants it maintains, and what state it carries between runs. The wrapper (scripts/WinRE-Manager.cmd) is a launcher, not a fifth control-flow path: it runs the production script or the harness in response to a menu selection and does not itself participate in the pipeline described here. As of v49 the wrapper also exposes backup and restore actions, a stable install location for the permanent maintenance task, and a reordered menu; v49 patch 2 adds a cleanup helper (Cleanup-Backups.ps1), an update check (Check-Update.ps1), and three conditionally-visible menu entries ([8] Restore, [C] Cleanup, [U] Open releases page). v50 patch 1 makes [8] and [C] unconditional (the screens themselves now explain when no backup exists, and require an explicit path rather than defaulting to a nonexistent one), removes the update checker’s local cache, and adds a machine-wide manager config file at C:\ProgramData\OEM\WinRE-Manager\manager.json that carries the backup-root catalogue read by the cleanup helper. v50 patch 2 adds a hypervisor-aware suppression boundary to the non-OS-disk recovery-partition sweep, a per-disk protection for mounted VHD/VHDX disks inside that sweep, a per-driver diagnostic loop in the source-ownership classifier, the SCSI bus entry in the workspace allowlist (admitted for the guest’s OS volume only), and the Win10/x64 URL-builder fix for the restructured GitHub base-WIM repository. v50 patch 3 replaces the v50 patch 1 resume-task protected-path guard with a resume-script staging design, extends the manager config trust gate with the shared Test-PathTrustedForSystem helper (owner plus effective-DACL mask, split by object class) and a file-level check, and closes the correctness gaps across the production script and the wrapper. A follow-up revision in the same cycle added further corrections: the Test-PathTrustedForSystem ACE loop now fails closed on an unresolvable SID rather than silently skipping the ACE (with the same fix ported to the duplicated trust helper in Cleanup-Backups.ps1 and to the compressed inline trust check in WinRE-Manager.cmd’s Restore TARGET_COMMAND), and Invoke-RestoreAction’s WIM-deployment-failure branch now captures the target WIM’s SHA256 before and after the failure so the state file, checkpoint, and deferral marker are preserved only when the target can be proven unchanged. All of these are documented separately in deployment.md, troubleshooting.md, and the CHANGELOG as the wrapper’s concerns, not as pipeline stages.
If you are new to the project, start with the README. That page explains what the tool does, who it is for, and how to run it. This document assumes you already know those things and want to understand how the tool works under the hood.
Windows’ recovery environment is fragile. The seven common failure modes are:
winre.wim with a newer, larger one; the recovery partition no longer has room for it plus the Microsoft-documented servicing margin.Device Encryption auto-encrypts newly created partitions, including recovery partitions. reagentc /enable then refuses with “Windows RE cannot be enabled on a volume with BitLocker Drive Encryption enabled.”VolumeStatus=EncryptionInProgress) while ProtectionStatus reads Off. In that state the encryption service is running and will claim any new partition created on the disk, before the recovery type GUID can be applied. This is the failure mode fixed in v43 patch 5; the pre-patch-5 code treated ProtectionStatus=Off as sufficient evidence that BitLocker was not a factor, and two machines were damaged by it on the same day. See troubleshooting.md for the recovery procedure.Manufacturer / Model / MachineType. Under the v43 DesiredStateId, the machine would take the fast path with a stale driver set. The v44 patch 1 revision adds CPU vendor/generation and VMD presence to the DesiredStateId inputs so the machine rebuilds automatically. The v44 patch 6 revision makes the VMD hardware presence check itself fail-closed: if the check cannot be completed, the run defers rather than guessing that VMD is absent. The v49 pre-deployment storage-applicability gate closes the remaining gap: a candidate in which any present SCSIAdapter-class device has no matching INF is refused rather than deployed, even if the manifest’s VMD patterns did not flag the mismatch.reagentc operation leaves the registration pointing at a partition that no longer exists. Windows might instead register C:\Recovery\WindowsRE (OS-fallback). That is a layout-remediation condition; an Enabled report does not establish recovery boot, especially when the image is on an encrypted OS volume.reagentc /enable is blocked with ERROR_CANCELLED (0x4c7, 1223) regardless of the correctness of the deployed WIM. The v43 patch 5 (further revision) startup guard detects this and defers — the script does not repair Audit Mode, it steps back from it. Without the guard, the deployment ran successfully, failed at /enable, wrote a state file recording the deployment as complete, and looped on every subsequent run.WinRE Manager addresses all seven idempotently. The two hard requirements are:
reagentc registered to it.Everything below is designed around those two requirements.
Image ownership and recovery placement answer different questions. A foreign image can require relocation without authorizing any change to its bytes. A current manager-owned image can require a larger partition without needing another rebuild. Patch 5 assesses the actual registered layout and the existing-partition capacity rule before ordinary fast-path, enable-only and pending-reboot exits.
Both unchanged-image relocation and deployment of a newly serviced image use the pending-deployment workflow. Before partition mutation, the selected bytes are copied to the protected %ProgramData%\OEM\WinRE-Manager\PendingDeployment\pending.wim, independently hash-verified, and bound to a trusted record at %ProgramData%\OEM\WinRE-Manager\pending-deployment.json. The record pins that candidate path and expected source hash; its modes are Managed and Preserved. These are deployment dispositions, not additional ownership classes.
The persisted phases are Prepared, MutationStarted, Copied, Registered and Verified. They describe what has been recorded, not instructions to replay old partition numbers. A resumed Repair validates current topology and expected bytes before proceeding. Pending recovery is loaded before ordinary dispatch and cleanup, then resumed after the hardware/topology gates and before network or DSI-dependent preparation. A DSI change does not make an unfinished operation disposable.
Where the active route lies outside the partition deletion set, the dedicated target can be prepared and its image copied and verified before disabling the previous registration. When the active recovery partition itself must be replaced, an interruption window remains; the independent source and record make that failure recoverable without claiming an atomic partition transaction. Source integrity is rechecked around mutation and deployment. A restored old route is evidence only when its own expected image bytes and observed registration match.
Active-route identity must be resolved before preparing or copying to a selected target. Drive-letter, GLOBALROOT and volume-GUID locations retain the registered folder; comparison requires the same partition and normalized folder, so two folders on one partition are not interchangeable. An unresolved enabled route cannot be treated as an independent target merely because partition resolution returned no result. When reagentc reports Enabled without a location, the reader leaves the route unresolved rather than substituting a possibly stale registry value. Disabled-state registry fallback remains available.
Successful retirement requires verification of the actual registered target, expected WIM hash and partition suitability, plus state persistence and read-back. A failed or interrupted operation retains its protected source, pending record and recovery task as appropriate. An unreadable, untrusted or malformed existing record is a refusal condition, not an absent operation. See state and idempotency and the validation matrix.
OS-fallback remains constrained to cases where the dedicated path cannot currently complete safely. An encrypted C: does not veto a safe transition to a separate unencrypted recovery partition, and the manager does not decrypt C:. An encrypted OS-fallback route is never an accepted healthy endpoint. Enabled and matching bytes are registration/integrity observations; a successful WinRE boot requires a boot test.
Last-resort fallback after an actual creation failure. A preflight Deferred result preserves the old route; it does not trigger fallback. If dedicated creation actually fails, Invoke-LastResortOSFallback proceeds only when geometry restoration is verified, C: is fully decrypted, and neither an intact acceptable previous route nor a readable enabled new route can be retained. It rechecks the current route at its own entry: if WinRE is enabled but its location cannot be resolved, fallback refuses before changing the journal or disabling WinRE. An earlier caller check cannot establish the route after a later observation changes. With these conditions met, it copies the expected bytes to the OS route, registers/enables them, checks the actual location and hash, and persists/read-backs fallback state. Failure to verify those conditions remains a failed transition.
A verified fallback returns warning 2 and reports OS-FALLBACK / DEGRADED FALLBACK. It is temporary, not convergence: the journal remains in Registered, the protected candidate and resume task remain, and execution retry is delayed one hour. Only a later verified dedicated commit retires the pending owner.
The production script runs one of four control-flow paths. Three of them are short-circuits; the full-update path is the long one.
Before any of those paths is chosen, the following run in order: the run-summary initialisation, the elevation guard, the log-directory creation, the startup banner and invocation-context log, the program lock, the -Action Backup dispatcher, the Audit Mode guard, the temporary resume-task registration, the -Action Restore dispatcher, the hardware identity and architecture resolution, the architecture gate, the native-boot VHDX fail-closed gate (v49), the LocalInputsId computation, the driver-manifest fetch, the OEM pack resolution, VMD detection, the required-VMD-driver-set resolution, the DesiredStateId computation, and the recovery-volume drive-letter cleanup. Of these, the elevation guard, the program lock, the -Action Backup dispatcher, the Audit Mode guard, the -Action Restore dispatcher, the architecture gate, the native-boot VHDX gate, and the VMD fail-closed guard can exit the run early with their own exit codes; the remaining steps are preparations and normalisations that do not terminate the run by themselves. The -Action Backup dispatcher runs before the Audit Mode guard (backup is state-independent); the -Action Restore dispatcher runs after resume-task registration (so an interrupted Restore is recoverable). The manifest fetch, VMD detection, and required-driver resolution are described in their own sections below; they run between the LocalInputsId computation and the drive-letter cleanup.
The elevation guard (v48 patch 2) is the first gate that runs, inside the outer try block (immediately after Initialize-RunSummary), before the program lock, before hardware probes, and before any network fetch. On refusal it creates the log directory itself, solely so its FATAL message has somewhere to be written. It checks whether the current process has the Administrator role via [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator). If not, it writes a single FATAL log line and exits EXIT_FATAL in milliseconds. The guard exists because an unelevated launch would otherwise proceed through hardware detection, manifest fetch, VMD detection, and the multi-minute GitHub base-WIM download before failing at Mount-WindowsImage with “The requested operation requires elevation” — a failure mode that burned roughly four minutes per run across the 2026-10-05 field logs. The check accepts both interactive Administrator sessions and the SYSTEM context used by the scheduled task. Under -DryRun the guard still fires: DryRun avoids destructive operations but still reads partition tables, calls reagentc /info, and reads DISM metadata, all of which require elevation on some machines, and refusing unelevated DryRun keeps the behavior unambiguous.
The program lock is acquired next, immediately after the startup banner and the log-directory creation, before the Audit Mode guard and before any state-modifying action. WinRE.ps1 opens C:\ProgramData\OEM\Logs\WinREManager.lock with an exclusive handle via [System.IO.File]::Open($path, [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None). The Windows kernel enforces the exclusive handle, so cross-session and cross-privilege exclusion are guaranteed by the OS. The handle is released automatically when the process exits, cleanly or after a crash — there is no stale-lock recovery logic. The lock is not acquired under -DryRun, because a dry run is read-only and safe to run concurrently with a live deployment. A second instance that encounters an IOException while opening the lock logs Another WinRE Manager instance is already running (program lock file is exclusively held) and exits EXIT_WARNING (code 2). For another setup failure the script logs a warning; Backup may continue, but live Repair and Restore require the exclusive handle and refuse to proceed without it. The temporary resume task invokes the production script with the default -Action Repair and acquires the lock normally.
The Audit Mode / OOBE / sysprep guard runs after the program lock and after the -Action Backup dispatcher, and before the resume-task registration, the -Action Restore dispatcher, and the hardware check. It reads HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\State → ImageState and defers with EXIT_WARNING when the value is present and is not IMAGE_STATE_COMPLETE. During Audit Mode, OOBE, sysprep generalize, and sysprep specialize, reagentc /enable is blocked by the OS regardless of what the script has done; running the destructive partition path in these states accomplishes nothing and leaves a state file that would loop on every subsequent run. The guard is deliberately conservative: any value other than IMAGE_STATE_COMPLETE defers, and absence of the key is treated as safe (some SKUs omit it). Under -DryRun the guard logs Would defer … and continues.
The native-boot VHDX fail-closed gate (v49) runs on the default Repair path after the architecture gate and before LocalInputsId. It refuses a File Backed Virtual OS disk when any other disk is nonvirtual, and refuses indeterminate topology. A guest backed by a VHDX is not refused merely because of that file format. The gate returns EXIT_WARNING before Repair reaches partition or WinRE changes; logging, pending-store checks and resume staging can already have occurred. Backup and Restore dispatch before it and are not covered by this refusal. Patch 5 retains the existing native-boot policy, without claiming that native partition APIs are unreliable or that native WinRE is supported. DryRun applies the same Repair topology check.
The hardware identity and architecture are resolved next (v48). Get-HardwareObject produces the same Manufacturer / Model / MachineType / CPUGeneration fields it always did, and additionally reports the actual OS architecture, normalized to x64, ARM64, x86, or unknown. The token is derived from PROCESSOR_ARCHITECTURE with PROCESSOR_ARCHITEW6432 taking precedence when present, because Win32_OperatingSystem.OSArchitecture reports only 32-bit or 64-bit and cannot distinguish ARM64 from x64.
The architecture gate (v48 patch 1) runs immediately after the hardware object is resolved, before the manifest fetch and before any state mutation. WinRE.ps1 refuses to run on any architecture other than x64; the refusal is a stable, named deferral that exits EXIT_WARNING. ARM64 support is not claimed; a future fleet requirement would be a separate change. The gate exists because the pipeline has not been validated on non-x64 targets. Pre-v48, the hardware object hardcoded the architecture token, so a non-x64 machine would have proceeded into partition and WIM work under an architecture assumption the pipeline does not honor — the strip stage, the injection stage, and the base-WIM selection rules have not been exercised on ARM64, and the architecture token was never a DesiredStateId component, so nothing upstream would have flagged the mismatch. The gate makes the refusal explicit and named rather than letting the machine reach a pipeline stage that has not been built for it. ARM64 support would be a separate, tested change.
The LocalInputsId computation (v48 patch 1) runs immediately after the native-boot VHDX gate. It hashes the three deployment inputs observable on the local machine without a network fetch: hardware identity (Manufacturer|Model|MachineType), OS build, and CPU vendor/generation. VMD presence is deliberately excluded because its detection is driven by the manifest’s requiredDevices patterns, which is precisely the input the offline fallback does not have. The value is stored in the state file on every write and compared against the stored value on the offline fallback path.
The drive-letter cleanup then runs: any volume labelled Recovery or WINRE whose partition is not the boot or system partition and whose root does not contain a Windows directory has its drive letter removed. This is a defensive normalisation — those letters should never be persistent — and it is a no-op on a healthy machine.
BitLocker decisions follow the actual target volume. An encrypted OS volume does not veto safe dedicated recovery-partition work. The layout assessment requires a confirmed unencrypted dedicated volume, and deployment preparation checks that target again. An adequately sized recovery partition can be reused and decrypted in place; encryption alone does not require repartitioning or driver servicing. An indeterminate read is not proof of an unencrypted target. C: must be confirmed fully decrypted before the constrained OS-fallback helper can use it. A failed pre-shrink preserves the old route and defers; it does not authorize fallback. If an active recovery partition is deleted and later creation fails, the independent source and journal remain, but geometry restoration alone cannot recreate that partition. See the Step 5 discussion and the VM release gate.
Entered when WinRE is enabled, the deployment inputs and image checks pass, and exactly one type-coded recovery partition on the OS disk holds the active image and meets the established reuse requirements. A recorded foreign acceptance permits unchanged bytes; it does not waive partition capacity or grant manager ownership. A suitable preserved image reports PRESERVED-DEDICATED.
The fast path does not mount a WIM, change OS-disk geometry or issue a reagentc mutation. It can perform the existing scoped non-OS stray scan and clear stale runtime counters. OS-fallback and an undersized dedicated partition proceed to layout assessment/remediation rather than being accepted as converged.
The same layout requirements apply during offline fallback. A successful offline check still reports EXIT_WARNING because the manifest could not be fetched; see state and idempotency for the local-input and metadata checks and their limits.
Entered when WinRE is disabled, the current WIM is already correct, and the active dedicated partition passes the reuse requirements. Layout remediation takes precedence when the image is on C: or the dedicated partition is inadequate.
Effect: prepare the target recovery partition first via Set-RecoveryPartitionReadyForWinRE. This is the v43 patch 5 (further revision 5) change: reagentc’s BitLocker check is on the target volume, not on C:, so the target must be unencrypted by the time /enable runs. The helper decrypts the target in place with manage-bde -off and polls for completion if needed, up to a 300-second timeout. It does not touch C:’s BitLocker state.
If the target cannot be made unencrypted, the enable-only path records the failure, increments the state file’s EnableFailureAttempts counter, writes LastEnableResult = "failed", removes the checkpoint file, and exits EXIT_WARNING. Otherwise it proceeds to reagentc /setreimage followed by reagentc /enable. Four possible outcomes from that call:
"ok" — enable succeeded, no reboot required. Exit EXIT_SUCCESS (or EXIT_WARNING if a non-fatal warning was set)."reboot" — enable succeeded but requires a reboot. Write the state file with PendingReboot = true and exit EXIT_REBOOT_REQUIRED (code 1)."failed" — generic hard failure. Increment the state file’s EnableFailureAttempts counter, write LastEnableResult = "failed", remove the checkpoint file, and exit EXIT_WARNING (code 2). The enable-only path deliberately does not fall through to full update on this outcome. The deployment is already current; a rebuild would not change the outcome of the enable step. The next run will retry enable-only. After three consecutive failures the loop-breaker fires (see below)."bitlocker" — reagentc refused because the target volume is BitLocker-protected, even after the helper prepared it. Increment the counter with LastEnableResult = "bitlocker", remove the checkpoint file, and exit EXIT_WARNING. This is rare under the new policy: it means either the Device Encryption service re-claimed the volume between preparation and /enable, or the target reagentc is checking is not the partition the helper prepared. The loop-breaker counts this alongside "failed".Entered when: anything has changed — new Windows build, new driver manifest version, new OEM pack version, no state, a change in CPU generation or VMD presence that has moved the DesiredStateId, a registered WinRE image whose servicing metadata has drifted from the DeployedWinREMetadata anchor (v47), a classifier-detected problem such as a recovery partition on a secondary disk, or a label-only recovery partition on the OS disk that no longer qualifies as DEDICATED.
Effect: the servicing pipeline prepares and verifies the candidate, then the common pending-deployment flow owns partition preparation, registration and final state persistence. Patch 5 writes completed deployment state only after verifying the dedicated route, exact expected WIM hash and current capacity. Unresolved deployment or enable failures retain the journal, independent source and recovery task; bounded retries and execution backoff apply. The ordinary enable-only path retains its existing enable-failure counter. Candidate hash and servicing metadata are captured before source access can be lost and remain bound to the protected copy.
v49 adds three refinements inside the full-update path. The source-ownership classification runs after source selection, before the strip stage, and decides whether the strip-and-reinject pipeline applies. The never-downgrade storage-driver check runs after injection, comparing each storage-class driver in the final image against the pre-strip inventory by INF basename. The pre-deployment storage-applicability gate runs inside Step 3, after injection is confirmed complete, before ResetBase and before the dismount. A fourth v49 addition — the native-boot VHDX fail-closed gate — is a startup refusal that runs before any path is chosen, not a refinement inside the full-update path. The v49 backup and restore actions are not inside this pipeline either: they are standalone -Action Backup / -Action Restore invocations that do not participate in the repair control flow. The v49 refinements are described in their own section below.
Entered at the top of the run when the state file says PendingReboot = true and the state file’s DesiredStateId matches the current one.
Effect: prepare the target recovery partition via Set-RecoveryPartitionReadyForWinRE, then re-run reagentc /enable against the WIM path recorded in the state file. If the target cannot be prepared, defer with EXIT_WARNING. If reagentc /enable succeeds, clear the flag and exit. If it fails, increment RepairAttempts and either retry (up to 3 attempts) or exit fatally. The pending-reboot path resets the enable-failure counter to 0 on every write, because it represents a different failure mode tracked by a separate counter. The two counters are independent.
A target-preparation failure on the pending-reboot path does not increment EnableFailureAttempts. The exclusion is deliberate. Immediately after a reboot, the target partition’s encryption state may be transiently indeterminate: the BitLocker service may not have finished enumerating the volume, the Device Encryption service may still be arming protection, or manage-bde may not yet report a stable state. A preparation failure that would resolve on its own within one poll cycle must not be counted against the enable-failure threshold, because the loop-breaker’s purpose is to catch machines that are stuck on a genuine /enable failure, not machines that were polled a moment too early. The pending-reboot path is tracked exclusively by RepairAttempts; a preparation failure there defers the run and leaves the state file’s enable-failure counter untouched.
A separate check runs after the pending-reboot block and before the classifier. When the state file records EnableFailureAttempts >= 3 and LastEnableResult is "failed" or "bitlocker" and WinRE is still Disabled, the script logs a “manual intervention required” message, removes the checkpoint file, and exits EXIT_FATAL (code 3). The state file is left in place; the log message names it and instructs the operator to delete it to reset the counter, once the underlying cause is resolved.
The predicate is deliberately narrow. "bitlocker" is included because a machine that keeps failing the enable step on the BitLocker error — even after the helper prepared the target — is in the same kind of loop as a machine failing generically, and the same manual intervention is required. "blunsafe" no longer exists as a return value; the fail-closed check that produced it is now the helper’s job, and a failure to prepare the target is recorded as "failed".
Under -DryRun the loop-breaker logs Would refuse to retry … and continues, matching the pattern used by the Audit Mode guard.
When the manifest fetch fails after its retry budget, the script engages the offline fallback (v44 patch 5). It reads the state file’s stored DesiredStateId, sets $Script:offlineFallback = $true, and skips the OEM pack resolution, the VMD detection, and the required-driver resolution, because all three depend on the manifest.
If the fast path fires under the offline fallback, the machine is validated and the run exits EXIT_WARNING. If the fast path does not fire — because the state file indicates a full update is needed — the run exits EXIT_WARNING before the full-update pipeline, having done nothing. If there is no state file at all, the run throws and exits EXIT_FATAL; a first deployment requires the live manifest.
The offline fallback trusts the state file’s stored DesiredStateId without recomputing it from cached inputs. Until v48 patch 1, that trust extended to the machine’s local hardware: on a machine whose hardware changed while offline — a CPU swap, a BIOS update that flipped VMD, or a motherboard replacement that changed Manufacturer / Model / MachineType — the offline run could take the fast path with a stale DSI. As of v48 patch 1, the residual is closed by the LocalInputsId field: the state file records a hash over the three deployment inputs observable on the local machine without a network fetch (hardware identity, OS build, CPU vendor/generation), and the offline fallback recomputes that hash and defers with EXIT_WARNING when the stored and current values disagree. VMD presence is deliberately excluded because its detection depends on the manifest’s requiredDevices patterns, which the offline fallback does not have. Under v47 the offline fast path additionally requires a DeployedWinREMetadata anchor matching the currently-registered image’s servicing metadata, so the offline path is metadata-based from the second v47 run onward. See state-and-idempotency.md for the full discussion.
v49 does not add offline-path conditions. The v49 pipeline refinements — source-ownership classification, never-downgrade check, storage-applicability gate — all run inside the full-update path, which the offline fallback does not reach. The native-boot VHDX gate precedes offline fallback on the default Repair path. Backup and Restore dispatch before that gate; an ordinary VHDX-backed guest is not the refused topology by file format alone.
When the manifest is available, the script determines VMD hardware presence by enumerating present PnP devices that match the union of the manifest’s requiredDevices patterns. As of v44 patch 6 the enumeration is fail-closed: if Get-PnpDevice reports an error during the query, the run treats VMD presence as indeterminate rather than as absent.
An indeterminate result means the correct driver set cannot be determined. Proceeding on a guess would risk selecting a driver set that omits the VMD package on a machine that has VMD hardware; the resulting WinRE would not be able to see the OS disk, which is exactly the failure mode the v44 patch 1 DesiredStateId change was designed to prevent. The run logs the enumeration error, sets $Script:nonFatalWarning = $true, removes the checkpoint file, and exits EXIT_WARNING before committing any state. No WIM is deployed, no partition is touched, no reagentc call is made. The next run retries the enumeration.
Under -DryRun the check logs the enumeration error and continues; the exit is not predicted. See troubleshooting.md for the resolution.
The servicing path. A layout-only repair can use the same deployment machinery without performing Steps 1–4; a pending operation is handled before normal scratch cleanup.
Scope note (v50 patch 5). The step numbers below describe the logical pipeline. The ordinary servicing path logs Steps 2 through 4; copy-only and preserved paths can skip these stages. The common deployment flow then reports preparation, native-tool results, verification and cleanup without the former Step 5/6/7 numbered headers. Its durable phases are Prepared, MutationStarted, Copied, Registered and Verified. Use the actual phase and operation evidence when reading a log rather than assuming that a numbered heading proves a transition completed.
Step 1 — Wipe WorkDir.
Delete <WorkDir>\mount and <WorkDir>\base.wim under the workspace selected in this run. Checkpoint as Step=1.
Step 2 — Obtain base WIM.
Source selection (v47). The base WIM is sourced from one of three places, in preference order: the currently-registered WinRE image, the manager’s last-known-good copy discovered by content hash (v48 patch 1), or the GitHub repository. The registered image wins unless the LKG is provably newer by DISM servicing metadata (Version + SPBuild + SPLevel, with Architecture required to match); the LKG is trusted only when its SHA256 matches state.CurrentImageHash; GitHub is the last resort. A WIM found by the loose fallback-discovery path is no longer a source-selection candidate. Copy the selected source to WorkDir\base.wim; record the source’s SHA256 for the Step 3 and Step 4 checkpoints. Immediately after the copy, the destination is hashed and compared against the selected source’s SHA256; a mismatch or an unreadable destination rejects the candidate (v47 patch 2). Checkpoint as Step=2.
As of v44 patch 6, the GitHub download path removes any stale winre.wim at $WorkDir\winre.wim before invoking 7-Zip, verifies that 7-Zip produced winre.wim after extraction, and removes any stale base.wim at $WorkDir\base.wim before the Rename-Item call. Before patch 6, an interrupted previous run could leave a base.wim in place at the moment the next run reached the rename; the rename would fail and the machine would not progress past Step 2 until an operator deleted WorkDir by hand.
Step 3 — Mount, classify source, strip, inject, dismount.
Mount base.wim with Mount-WindowsImage.
Classify the source’s ownership class (v49). Every candidate source WIM is classified into one of four ownership classes before the strip stage runs: Manager-Owned, Manager-Lineage, Foreign-No-Drivers, or Foreign-With-Drivers. The classification decides whether the strip-and-reinject pipeline applies. A Foreign-With-Drivers source is preserved as-is: the strip stage is skipped and the current recipe is not injected. The other three classes proceed through the strip and injection as in v47/v48. The classification gate narrows the v47 strip-everything policy to sources the manager itself deployed or in-box images with no third-party drivers; see “The v49 pipeline refinements” below for the full rationale.
Strip every third-party driver (v47; skipped when the source classified as Foreign-With-Drivers in v49). Remove-AllThirdPartyDrivers enumerates the mounted image with Get-WindowsDriver -Path $MountDir (no -All, no provider filter), removes each published OEM#.inf one at a time with Remove-WindowsDriver, and re-enumerates after every removal because the published numbering can change as packages are removed. The loop terminates only when a fresh enumeration returns zero entries. Every failure mode rejects the candidate: enumeration failure, removal failure, a missing Driver field on an enumeration entry, or budget exhaustion. Enumeration failure is never interpreted as zero drivers. On rejection the caller dismounts with -Discard, rolls the checkpoint back to Step 2, removes base.wim and any stale winre_optimized.wim, and exits EXIT_WARNING — no injection, no export, no partition work, no reagentc call. The pre-strip inventory is logged as one line per package (published INF name, provider, version, original filename) for field evidence.
Then capture the pre-injection third-party driver count via Get-WindowsDriver — expected to be zero after the strip. Download the OEM pack (vendor-specific: CAB for Dell, EXE for Lenovo, SoftPaq EXE for HP), extract to a temp dir, Add-WindowsDriver -Recurse. Then, if VMD hardware is present and manifest VMD drivers match the CPU generation, download each VMD pack, extract, Add-WindowsDriver. The v49 never-downgrade storage-driver check runs during this step — after injection completes, each storage-class driver in the final image is compared against the pre-strip inventory by INF basename; if any post-injection driver would be older than the source’s version of the same basename, the entire candidate is discarded. See “Never-downgrade storage-driver check” below. Success gate: the package’s INF basenames must appear in the mounted image’s third-party drivers after injection, OR the pre/post delta must be > 0. See driver-injection.md.
Lenovo OEM pack resolution distinguishes five states as of v44 patch 6: unknown-mt, map-unavailable, no-entry, malformed-entry, and resolved. unknown-mt and no-entry are legitimate “no pack available for this machine” answers and let the run proceed with OEMPACK=NONE. map-unavailable and malformed-entry mark the run with $Script:ImageInjectionComplete = $false.
Pre-deployment storage-applicability gate (v49). The gate runs inside Step 3, after injection is confirmed complete and after the never-downgrade check, before ResetBase and before the dismount. The manager verifies that every present SCSIAdapter-class device on the machine has at least one INF in the mounted candidate image whose HardwareID or CompatibleID prefix-matches one of the device’s IDs. A candidate that does not match is refused rather than deployed. The run exits EXIT_WARNING before the dismount commits the candidate; no partition is touched, WinRE is not disabled. The gate is the last refusal before deployment; it has never fired in the field. See “The v49 pipeline refinements” below.
Once injection is confirmed complete ($Script:ImageInjectionComplete = $true), run dism /image:<MountDir> /cleanup-image /StartComponentCleanup /ResetBase on the mounted image. ResetBase removes superseded components from the WinSxS store inside the image; the size reduction it represents does not appear in the .wim file on disk until the image is re-exported in Step 4. ResetBase failure is non-fatal.
Dismount with -Save to commit the strip, the injected drivers, and the ResetBase changes on a serviced candidate. Preserved candidates use -Discard and the unchanged-image path instead. Checkpoint as Step=3 only if $Script:ImageInjectionComplete is $true; the Step 3 checkpoint is bound to the source-content hash (v47 patch 2), so a later resume can prove the staged artifact was built from the source the current selection rules would choose. After this block, if $Script:ImageInjectionComplete is $false, the pipeline exits with EXIT_WARNING before Step 4 (the v44 patch 1 pipeline gate), and the abort branch removes both winre_optimized.wim and base.wim from WorkDir.
Step 4 — Optimize.
dism /Export-Image /Compress:max to winre_optimized.wim. This is where the ResetBase savings from Step 3 are materialised on disk as a smaller file. The exit code is checked; a non-zero exit is fatal. Checkpoint as Step=4 only if $Script:ImageInjectionComplete is $true. The v47 checkpoint additionally records the source-content hash that produced this WIM (from Step 2, or recovered from base.wim when this execution resumed at Step 3), so a later resume can prove the staged WIM was prepared from a source that is still available with the same bytes.
Step 5 — Ensure a suitable recovery partition.
The selected deployment bytes are first protected by the pending-deployment workflow above. Find-SuitableRecoveryPartition reuses only one type-coded OS-disk recovery partition whose total size, measured effective free space and 2048 MiB ceiling meet the established reuse rule. The creation bucket is a separate rule; see sizing policy.
If no candidate passes, Ensure-AdequateRecoveryPartition uses the existing read-only planner and shrink-first sequence. -ExpectedSourceHash binds the protected source to the accepted bytes, and -PrepareBeforeDisable permits target preparation ahead of disabling when the active route is outside the deletion set. The source partition must be outside that set. A pre-delete refusal preserves the old route; a post-delete failure retains the independent candidate and pending record and reports the actual recoverability.
The existing single-intervening-anchor support, plan limits and 2 GiB protection remain. Patch 5 introduces no rightmost-data-partition or disk-tail placement policy. Geometry restoration alone cannot recreate a deleted partition or restore its WIM. The post-deletion failure release gate remains documented in Testing.
Step 6 — Deploy and verify the WIM.
Prepare the dedicated target as unencrypted using the target-volume policy. Where possible, copy and hash-verify a target independent of the active route before switching registration. Deploy-WimTransactional still protects replacement of an existing target file; the pending candidate protects the selected source across interruption. These are separate guarantees.
Register the chosen target and attempt enablement. Verify the observed registered location, expected image hash, dedicated layout and available servicing space before declaring completion. Managed and preserved state writes remain distinct: acceptance of a foreign WIM does not populate CurrentImageHash. Persist and read back the state before retiring the pending record and releasing its source.
Failures retain recovery material until the operation can be resolved. If no acceptable recovery route can be verified after a failed transition, report fatal failure and retain the recovery task. A state-write failure after establishing a valid route does not justify undoing that route. The script’s exit-code convention remains 0 success, 1 reboot required, 2 warning and 3 fatal.
Step 7 — Enforce the single-recovery-partition invariant.
Remove-StrayRecoveryPartitions applies the existing VM/topology suppression, internal-bus allowlist, per-disk virtual-media protection and 2 GiB ceiling before deleting a type-coded recovery partition on a non-OS disk. A Recovery label alone never authorizes deletion. Protected disks and oversized partitions can therefore remain; the desired single-partition layout does not override those safety boundaries. Patch 5 does not broaden the sweep.
Step 8 — Final verification.
Re-read WinRE state. Classify the registered location: DEDICATED (recovery partition on OS disk), OS-FALLBACK (on the OS partition), or UNEXPECTED (neither). A partition detected only by a Recovery / WINRE volume label — with no matching type code — does not reach DEDICATED; it falls through to UNEXPECTED. If dedicated, remove any temporary drive letter that the script assigned during the pipeline. If OS-fallback, report a constrained fallback requiring dedicated remediation; do not describe it as verified recovery-boot success.
| Artifact | Path | Purpose | Lifetime |
|---|---|---|---|
| State file | C:\Recovery\OEM\winre_state.json |
Records the deployment identity and its observed companions. Identity fields: DesiredStateId, CurrentImageHash, InjectedDriverSetVersion, DeployedWinREMetadata (v47), LocalInputsId (v48 patch 1). Route and target fields: DeployedDiskNumber, DeployedPartitionNumber, UsedOSFallback, PendingReboot. Runtime counters: LastEnableResult, EnableFailureAttempts, RepairAttempts. Metadata: LastUpdated (write timestamp, used by the offline-fallback log line). v49 additions: ForeignSourceAcceptedHash (set only when a Foreign-With-Drivers source was preserved) and LineageId (the persistent lineage identifier written into the provenance marker). |
Persists across runs. |
| Checkpoint file | C:\ProgramData\OEM\Logs\winre_checkpoint.txt |
Records the highest completed step of the current pipeline; Steps 3 and 4 also record the source-content hash of the WIM that produced the staged candidate (v47 patch 2). | Deleted at end of run. |
| Log file | C:\ProgramData\OEM\Logs\WinRE-Manager.log |
Append-only event log. | Rotated by the operator, not by the script. |
| Program lock file | C:\ProgramData\OEM\Logs\WinREManager.lock |
Exclusive-handle target for the single-instance guarantee (v44 patch 4). | Persists across runs; the file’s existence is not the lock, the open handle is. |
| Partition deferral marker | C:\Recovery\OEM\winre_partition_deferred.json |
Records reason/category and bounded execution backoff; capacity is freshly assessed (patch 5). | Separate from the pending-operation owner; an obsolete marker can be cleared without discarding the protected candidate. |
| Pending deployment | %ProgramData%\OEM\WinRE-Manager\pending-deployment.json, with %ProgramData%\OEM\WinRE-Manager\PendingDeployment\pending.wim. |
Binds the selected deployment disposition, expected bytes and protected candidate to an unfinished operation; handled before ordinary DSI/checkpoint cleanup. | Retained until the actual route and persisted state are verified; not cleared by DSI mismatch. |
| WorkDir | Selected at run time from an eligible fixed NTFS volume on an allowlisted internal/virtual bus; recorded in the checkpoint. | Scratch space for mounts, downloads, and intermediate WIMs. | Deleted after deployment, before the stray-partition cleanup. |
| Backup sidecar | Operator-supplied <backup-dir>\<timestamp>\backup.json, alongside the same directory’s winre.wim copy. Each -Action Backup run creates a new timestamped subdirectory (yyyy-MM-dd_HHmmss). |
Records the captured WIM’s source hash, size, and DISM servicing metadata, for a future -Action Restore. |
Persists in the operator’s backup directory; not touched by the repair pipeline. |
| Manager config file | C:\ProgramData\OEM\WinRE-Manager\manager.json. |
Durable machine-wide settings that are not operational state: the backup-root catalogue read by Cleanup-Backups.ps1, and any future setting that must survive across runs. Writes are atomic via the existing Write-FileAtomically. The v50 patch 1 trust check verified the ACL owner of the containing directory and its immediate parent; the v50 patch 3 extension replaces this with the shared Test-PathTrustedForSystem helper (owner plus effective-DACL mask, split by object class) and additionally checks the config file itself. An untrusted, unreadable, or unparseable config is treated as the empty default. |
Persists across runs; created on first successful backup. |
The v49 and v50 additions do not change the deployment-identity artifact model: the backup sidecar is a standalone action artifact and is not part of the deployment identity, the manager config file holds durable settings but not deployment identity, and the temporary WinRE Manager - Resume task is a scheduled task, not a file. However, v49 does extend the state file schema with two optional fields — ForeignSourceAcceptedHash and LineageId — as noted in the “Rationale for the ScriptVersion bump” section. See state-and-idempotency.md for the schemas and the crash-consistency model. One further piece of persistent state is carried inside the deployed WIM rather than as a top-level file: the provenance marker written by Write-ProvenanceMarker at Sources\Recovery\WinRE-Manager\provenance.json, which embeds the state file’s LineageId so the source-ownership classifier can recognize a manager-lineage source on a subsequent run. It is not listed in the table because it is not a file the script reads or writes at the filesystem level; it is a content-carrying mechanism inside the WIM.
DesiredStateId is a SHA256 over a deterministic set of inputs:
HW=<Manufacturer>|<Model>|<MachineType>
OS=<Build>
CPU=<vendor>|<generation or N>
VMD=<True|False>
MANIFEST=<manifest.version>
OEMPACK=<resolved OEM pack version or NONE>
SCRIPT=<ScriptVersion>
Any change to any of those seven fields changes the ID. When the ID differs from the stored state file’s ID, the state file is treated as stale and the script rebuilds. When the ID matches, the fast path can fire.
The CPU and VMD inputs were added in v44 patch 1. They capture the two hardware inputs that determine VMD driver selection, which the v43 ID did not cover. The CPU field is vendor|generation, with the literal string N when the generation cannot be parsed (AMD, Intel Celeron/Pentium/Atom/Xeon, N/J-series). The VMD field is True or False (the .NET Boolean string form of the machine-wide presence check), computed from the union of manifest requiredDevices matched against present PnP devices.
The design deliberately excludes things that change frequently but should not trigger a rebuild: the current date, the current WIM hash at the registered location (that’s a separate check), and the machine’s serial number. As of v47 the WIM hash is also no longer a rebuild trigger at all — the drift detector compares servicing metadata (Version + SPBuild) instead. The WIM hash remains in use for copy verification, deployment verification, LKG validation, and the pre-/disable race detector, but it does not enter the DesiredStateId and does not force a rebuild on its own. The DeployedWinREMetadata field plays the drift-detection role.
LastEnableResult and EnableFailureAttempts are not part of the DesiredStateId — they are runtime counters that affect the control-flow decision, not the identity of the deployment. A machine with a non-zero counter is still “the current deployment” as far as the state-file comparison is concerned; the counter tracks the enable step’s history, not the deploy step’s identity.
DeployedWinREMetadata (v47) is also not part of the DesiredStateId. It records what the last successful deployment actually produced, so the next run’s drift detector has a baseline to compare the currently-registered image against. It is an observed value, not a desired input; the same reasoning that keeps the WIM hash out of DesiredStateId applies to it.
The deferral marker (v45 patch 1) is also not part of the DesiredStateId. Its DesiredStateId field records the DSI under which the deferral was written, but the marker’s presence does not change the DSI.
The v49 pipeline refinements are not DSI inputs. The source-ownership classification, the never-downgrade check, and the storage-applicability gate are parts of the WIM production recipe — what the script does to a base image and how it decides whether the candidate is deployable — not deployment inputs. The v49 ScriptVersion bump from 48 to 49 is what converges the fleet on the new pipeline; future recipe refinements that do not bump ScriptVersion would not change the DSI, and a machine whose inputs do not otherwise change would keep its earlier-recipe WIM until a natural DSI change triggered its next rebuild.
LocalInputsId is a separate hash from DesiredStateId, computed over a strict subset of the DSI inputs:
HW=<Manufacturer>|<Model>|<MachineType>
OS=<Build>
CPU=<vendor>|<generation or N>
VMD presence and the three network-derived inputs (MANIFEST, OEMPACK, SCRIPT) are deliberately excluded. The three included inputs are the ones observable on a machine with no network access, which is precisely the situation the offline fallback exists for. VMD presence is excluded because its detection depends on the manifest’s requiredDevices patterns; hashing an input that cannot be recomputed offline would make the offline comparison meaningless.
The field is consulted on exactly one path: the offline fallback. On that path, the run recomputes LocalInputsId from the current machine and compares it against the stored value. A mismatch defers with EXIT_WARNING rather than trusting a stored DesiredStateId that describes a machine whose hardware or OS has since changed. On every other path the field is written but not read. It does not enter DesiredStateId, does not affect the fast-path decision, and does not force a rebuild when it changes; it bounds the offline trust model.
The offline fallback (v44 patch 5) does not recompute DesiredStateId from cached inputs; it trusts the state file’s stored value and relies on LocalInputsId to detect hardware or OS drift. The v48 patch 1 field closes the residual hardware-drift risk documented in state-and-idempotency.md.
Every decision in WinRE Manager is subordinate to four rules, in this order.
reagentc /disable → reagentc /enable window.Rules 1–3 are invariants: they hold for every run, and no code change may weaken them. Rule 4 is the working rule: it is the discipline by which rules 1–3 are mostly enforced. It is subordinate in authority but not in importance — it is the mechanism.
The control-flow invariants list that follows is the detailed enforcement, one entry per guarantee. The wrong-question narrative at the end of the document is the reasoning behind each of them.
Every guarantee that a WinRE Manager run cannot make the recovery environment worse than it found it. A read-only plan cannot break anything. A failed pre-shrink in the reversible window cannot break anything. A fail-closed guard cannot break anything. A sequence that requires every preparation to complete before destruction begins never starts a partition operation it cannot finish.
| Guarantee | Enforced by |
|---|---|
| The destructive sequence refuses to begin if the layout cannot be proved safe. | Get-PartitionPlan rejection — the plan’s refusal conditions, all logged with a reason. |
| A volume label alone never authorizes deletion or reuse. | Type-code gate in the delete loop, in Find-SuitableRecoveryPartition, and in Remove-StrayRecoveryPartitions. |
| The currently-active recovery partition is deleted last. | Delete ordering in Ensure-AdequateRecoveryPartition. |
| The sequence refuses to begin if the active WinRE route cannot be resolved to a partition. | v46 patch 2 pre-deletion resolver guard. |
| The layout assertion fails closed if the OS partition cannot be resolved for the adjacency check. | v46 patch 2 fail-closed branch in Assert-RecoveryPartitionLayout. |
| Recovery-typed partitions over 2 GiB are never deleted or reused. | Ceiling enforced in the plan, in Find-SuitableRecoveryPartition, and in Remove-StrayRecoveryPartitions. |
| The extension-failure fallback never creates a partition larger than the 2 GiB managed-recovery ceiling. | v47 patch 2 ceiling-fill in the fallback branch: min(AvailableSize, 2 GiB). |
| Failed transitions attempt to restore the resize target and expose incomplete restoration. | Restore-OSPartitionSize and $Script:GeometryRestoreFailed; size restoration is not a deleted-partition rollback. |
| A failed injection never reaches deployment. | Step 3 → Step 4 pipeline gate on $Script:ImageInjectionComplete. |
| A candidate image never reaches injection without first being normalized to zero third-party drivers, unless the source-ownership classification deliberately preserves a foreign-with-drivers source. | v47 strip stage as a hard gate; v49 source-ownership classification decides whether the strip runs. |
| A newly created partition has no window where it is a plain Basic Data partition. | Recovery type code applied at New-Partition time. |
The target recovery partition is unencrypted before reagentc /enable is called. |
Set-RecoveryPartitionReadyForWinRE before every reagentc invocation. |
| Two runs never collide on the same machine. | FileShare.None program lock held for the process lifetime. |
| An intervening-anchor layout is validated before the anchor is touched. | v48 anchor validation: on the OS disk, not C:, not a recovery-typed partition, not EFI/MSR/system/reserved, NTFS, accessible for resize, sufficiently large, shrinkable from the right, with no unexpected intervening geometry. |
| The transactional WIM replacement preserves the existing WIM as a rollback copy before deleting it. | v48 Deploy-WimTransactional: hash source, copy target to workspace, hash-verify rollback, delete target, copy source, hash-verify target, restore rollback on failure. |
| An unelevated launch is refused before any resource is consumed. | v48 patch 2 elevation guard: millisecond refusal before the program lock, hardware probes, or any network fetch. The only file-system operation on the refusal path is the creation of the log directory that the FATAL line is written into. |
| The manager refuses to run on any architecture it was not built for. | v48 architecture gate; any value other than x64 exits EXIT_WARNING before any state mutation. |
| Default Repair refuses a file-backed virtual OS disk with another nonvirtual disk, or an indeterminate topology. | v49 native-boot gate; warning before Repair partition/WinRE changes. Backup and Restore dispatch earlier. |
| A candidate image that does not match the machine’s storage controllers is never written to the active route. | v49 pre-deployment storage-applicability gate; the last refusal before the WIM is written. |
| A storage driver that would be a version downgrade against one already present in the image is never injected. | v49 never-downgrade storage-driver check; the whole candidate is discarded, the source is preserved; patch 5 still assesses dedicated layout repair. |
| An interrupted Repair or Restore leaves a resumable state behind. | v49 temporary WinRE Manager - Resume scheduled task, registered on every Repair or Restore run, deleted on clean completion, preserved on interruption. |
| A safety check whose underlying query fails is refused rather than treated as a safe result. | v49 patch 2 fail-closed principle; the four corrected guards are the native-boot VHDX disk enumeration, the post-deletion partition verification (two call sites), the WinRE status determination (two call sites), and the storage-controller enumeration. |
| The non-OS-disk recovery-partition sweep is suppressed under a detected or indeterminate hypervisor, and mounted VHD/VHDX disks are preserved individually. | v50 patch 2 Test-RunningInVirtualMachine gate at the top of Remove-StrayRecoveryPartitions, plus the per-disk File Backed Virtual preservation inside the sweep’s disk loop. |
The v50 patch 3 additions to Rule 1 enforcement — the post-deletion verification on the non-OS sweep, the empty-parts guard in Get-GitHubBaseWinRE, the fail-closed drive-letter normalization, the fail-closed workspace enumeration, and the volume-root preservation in Add-ManagerBackupRoot — are listed under the Control-flow invariants below. The table above is not extended because those additions are refinements to existing gates rather than new gates.
Rule 1 is about not damaging what is there. Rule 2 is about what happens after a failure: the machine should end in a state that still has a usable recovery environment, or should fail in a way that leaves the previous route intact.
| Guarantee | Enforced by |
|---|---|
A pre-shrink failure leaves the old recovery route Enabled and untouched. |
Shrink-first ordering (v45 patch 1); Restore-OSPartitionSize restores the pre-attempt C: size. |
| A deletion failure attempts to restore the previous route. | Restore-PreviousWinRERoute — restores C:, re-registers the previous partition, verifies the location matches. |
| A deferral marker suppresses identical retries only while the old route is verified functional. | Test-DeferredWinRERouteFunctional gate on the marker. |
| When the dedicated-partition route cannot complete, the OS-fallback route is attempted as a last resort. | Main-flow OS-fallback fall-through, guarded by the OS-fallback gate for encrypted C:. |
The fallback WIM at C:\Recovery\WindowsRE\winre.wim is refreshed on every successful deploy. |
Deployment-tail copy, guarded against self-reference. |
| The state file is invalidated when C: geometry cannot be verified, forcing a clean retry from scratch. | $Script:GeometryRestoreFailed → state-file deletion in Write-WinREState. |
| A strip failure preserves the machine’s existing recovery route. | v47 strip hard gate — candidate rejection happens before any partition work or reagentc call. |
| A failed WIM copy on the active recovery route restores the previous WIM. | v48 transactional replacement — the old WIM is preserved as a rollback copy in the workspace before the target is deleted; on any failure the rollback copy is restored and hash-verified. |
| An intervening-anchor layout with an unresolvable active route or an unvalidatable anchor defers before any mutation. | v48 fail-closed anchor validation and active-route resolution moved before the resize. |
| A verified resume task can retry an interrupted Repair or Restore at boot or within the hour. | The finally block merges $Script:ResumeTaskShouldPersist with [WinRECancelKeyProbe]::ShouldPersist. Pending deployment and covered failure paths retain the task; verified completion permits cleanup. A hard kill or reboot bypasses finally. Registration can fail, so verify the actual task and staged script. See persist signals. |
| The wrapper’s backup action captures a byte-for-byte copy of the active WinRE WIM, so a failed repair can be rolled back by a subsequent restore. | v49 -Action Backup; non-destructive; does not modify the state file. Rollback requires the operator to run -Action Restore. |
| The wrapper’s restore action writes a captured WIM back to the active route transactionally, with the same rollback protections as the deploy step. | v49 -Action Restore; uses the existing transactional deployment machinery. |
The residual corner, named honestly. Rule 2 cannot be guaranteed in the case where the old recovery partition has already been deleted, a later step fails, and C: is encrypted — the OS-fallback gate refuses on encrypted C:, so the machine ends with neither a dedicated partition nor a working route until the next run. The v45 shrink-first reorder narrowed this corner without closing it: the shrink is no longer the trigger, but a failure of any post-deletion step — New-Partition, Format-Volume, the whole-layout assertion (Assert-RecoveryPartitionLayout), drive-letter availability, drive-letter assignment, in-place decryption of the new partition, the post-delete extension fallback, the post-delete geometry verification, the planned-extent-available re-check, or the deletion itself when the previous route cannot be restored — can still reach it. The gating post-deletion failure test documented in testing.md must establish the failure handling; passing it cannot make partition replacement atomic.
The intervening-anchor residual, updated for v48. The non-adjacent-recovery-partition layout that v47 deferred unconditionally is now handled by v48 within a deliberately narrow scope: exactly one intervening data partition, no partition-moving, no extension of the anchor. Multi-intervening layouts (C: | D: | E: | Recovery) and the surplus case (recovery partition being reclaimed is larger than the new bucket size) still defer stably with named reasons. The manual path remains available for both; automating them was floated as a v49 candidate, but v49 shipped without it, so it remains a candidate for a future release. The 2026-10-06 field run on the motivating AMD Ryzen 7 5825U machine confirms the intervening-anchor path works end-to-end on the exact layout that motivated it.
The v48 residual on the intervening-anchor post-deletion segment. The intervening-anchor handling was developed under the project’s deliberate decision to accept the risk that the post-deletion segment (unchanged code, different parameters) has not been exercised under a deliberate failure on the intervening path. The 2026-10-06 field run confirmed the happy path. The deliberate post-deletion failure test remains the gate for future changes to the segment.
The Restore residual. A failed WIM copy attempts to restore and verify the previous bytes; rollback can itself fail. Later /setreimage or /enable failures occur after the replacement WIM is in place and do not undo that copy. Unresolved paths preserve the resume task when available so a later Repair can reassess the route; the task is a recovery attempt, not a completion guarantee. These failure paths have not been exercised in the field.
reagentc /disable → reagentc /enable windowFor the duration of that window, WinRE is not registered: reagentc /info reads Disabled, and reagentc will refuse to hand off to a recovery image. The script therefore runs everything that does not strictly require a disabled WinRE before the disable, and only the operations that require a disabled WinRE inside the window.
Before the window:
WIM_READY checkpoint, base.wim cleanup.Inside the window:
/disable. The fingerprint recheck is the last operation before the window opens; it runs immediately before the /disable call itself, so it is the boundary between the reversible window and the disable→enable window.)reagentc /disable and verify disabled.isWinRELocation flag).New-Partition, Format-Volume, Set-RecoveryPartitionAttributes, drive-letter assignment.reagentc /setreimage and reagentc /enable.After the window:
The longest operation inside the window is the WIM copy — typically 700–1000 MiB onto a freshly created partition. It cannot be moved out: the partition being replaced is the one the WIM is being deployed to. Everything else that can be moved out has been. The v47 source fingerprint recheck is a bounded addition to the window’s entry — one SHA256 of a ~750 MiB WIM, roughly 1–3 seconds — and it runs only once per actual rebuild. The v49 source-ownership classification, the never-downgrade check, and the pre-deployment applicability gate all run before the window opens; none of them extend the window.
Why this matters operationally. If the machine loses power, blue-screens, or is forced off inside the window, reagentc is left disabled and the recovery partition is in whatever state the interruption left it. The shorter the window, the smaller the exposure. The single-run recovery story is: Restore-PreviousWinRERoute on delete failure; Remove-OrphanPartition plus Restore-OSPartitionSize on create failure; the enable-only path on a clean-but-disabled state; and, as of v49, the temporary resume task that re-invokes the script on the next boot or within the hour. The crash-inside-the-window case is not fully covered today — the same post-deletion failure test that gates the eventual fix for Rule 2’s residual also gates the eventual fix for this one.
This is the working rule. It is subordinate to 1–3 in that any conflict resolves in favor of 1–3, but it is the mechanism through which 1–3 are enforced on the fast path and the enable-only path, and through which the destructive path is made to fail safe.
“Do no work unless needed” — three tiers:
reagentc call. Runtime is dominated by Windows’ own CIM and PnP enumeration.reagentc /enable. No partition geometry change, no rebuild, no C: shrink.“Prepare everything before touching anything” — the mandatory ordering inside Tier 3:
WIM_READY.The failure semantics of Rule 4. If driver download fails, or OEM pack extraction produces zero INFs, or the VMD package cannot be resolved for the CPU generation, or the base WIM cannot be verified, or the strip stage cannot prove zero third-party drivers remain, or the applicability gate refuses the candidate — the script stops before it touches the recovery partition. The old recovery route stays intact. The run exits EXIT_WARNING with a named reason in the log. Nothing is destroyed in the service of a rebuild that could not have succeeded anyway.
This is exactly how Rule 4 reinforces Rules 1 and 2: the destructive sequence is only reachable through a chain of successful preparations, so no partition operation is ever performed as preparation for another partition operation that might fail. Every failure point has been moved into the reversible window or excluded from the pipeline entirely.
“Drivers go into a clean base” is a corollary of Rule 4 for the image-servicing step. The recovery image on a machine that has ever run the script carries our previously injected OEM and VMD drivers. Before new drivers are injected, the image is normalised so the injection targets a clean baseline rather than a stale one with our own prior layers still present. Without that normalisation, the effective driver set is a function of the image’s own prior history, and the deployment identity stops being a reliable fingerprint of the image contents. The mechanism is the v47 strip stage: the mounted image is stripped to zero third-party drivers, proven by re-enumeration, before the current recipe is injected. The strip is a hard gate — a candidate that cannot be proven clean is discarded. The v49 source-ownership classification narrows this corollary to sources that are not Foreign-With-Drivers: a WIM that a vendor populated with its own drivers is preserved rather than stripped and re-injected, because the vendor’s driver set — not the manager’s recipe — is the correct one for that source. See “The v47 rebuild pipeline” and “The v49 pipeline refinements” below.
The v47 release changes the way a rebuild selects and prepares its seed image. It does not change the four design invariants, the four control-flow paths, or the eight-step pipeline shape; it changes what happens inside Step 2 (source selection) and Step 3 (image servicing), and it adds a pre-/disable recheck that runs before whichever reagentc /disable an execution reaches first.
The change was driven by an architectural problem in the pre-v47 design. Every rebuild seeded from the currently-registered WinRE image, so rebuild N depended on rebuild N−1 and third-party drivers injected by prior runs accumulated silently inside the registered image. The deployment identity (DesiredStateId) remained a fingerprint of the inputs that produced the image, but the image’s contents drifted as a function of the machine’s rebuild history. Two consequences followed: the fleet could not be externally proven to hold a normalized driver set, and a machine that had been rebuilt many times carried more driver packages than a freshly-provisioned one under the same recipe.
The fix is to strip every third-party driver from the mounted image — proving by re-enumeration that zero remain — and then inject only the current recipe. The resulting image is a deterministic function of the current recipe plus Microsoft’s current WinRE base, with no memory of prior rebuilds.
Step 2 now selects the base WIM from one of three sources, in preference order:
Version, SPBuild, SPLevel, with Architecture required to match) is at least as new as the manager’s last-known-good copy.Get-LKGWinREImagePath scans every type-coded recovery partition on the OS disk for a winre.wim whose SHA256 matches state.CurrentImageHash, in addition to the canonical C:\Recovery\WindowsRE\winre.wim path (v48 patch 1). Used when it is provably newer than the registered image, when the registered image’s metadata cannot be read, or when the registered image is not usable.The regression guard is the point of the ordering. Without it, a machine whose registered WinRE had been rolled back — by a failed WU servicing operation, a disk-level restore, or an operator action — would seed its next rebuild from the older image, and the manager would have no way to know the source had regressed. The comparison is metadata-based (Version first, SPBuild as the tiebreak, SPLevel as a secondary tiebreak) because Microsoft documents that an LCU bumps SPBuild while the base Version can remain unchanged; a Version-only comparison would tie across an LCU and select the wrong source. An indeterminate comparison (metadata shape mismatch, unparseable field) defers to the LKG: the registered image is not proven at least as new as the LKG, so the hash-validated copy wins.
The LKG is trusted only when its SHA256 matches state.CurrentImageHash. In patch 5, a verified dedicated deployment persists and reads back the ownership state before attempting a transactional refresh of the manager-owned LKG. A failed refresh produces a warning without undoing the good dedicated route. Any stale or damaged fallback whose hash differs from the saved manager-owned hash is not promoted. Preserved foreign bytes never refresh the manager-owned LKG.
A WIM found by the loose fallback-discovery path is no longer a source-selection candidate. The old v46 discovery could populate $ActiveLocationImage with a fallback file when the registered location yielded nothing readable; that path is now excluded from source selection. If the registered location yields no readable WIM, the LKG is the next candidate; only if the LKG is also unusable does the GitHub cold-start fire.
Get-LKGWinREImagePath returns a @{ Path; Hash } pair when the LKG is valid, $null otherwise. The validity test has two parts:
state.CurrentImageHash.v48 patch 1 added LKG-by-hash at any discovered recovery location. When the canonical path is missing or its hash does not match, the helper scans every type-coded recovery partition on the OS disk for a winre.wim whose SHA256 matches state.CurrentImageHash. The canonical path remains preferred when its hash is valid; the discovery scan runs only when it is not. A discovered WIM whose hash matches is accepted as LKG — provenance is content, not pathname. Discovery may assign temporary drive letters to recovery partitions; those letters are added to $Script:tempDriveLetters and cleaned up at end of run under the existing temp-drive-letter cleanup.
The second condition is what makes the copy “known good”. A stale file, a partially-written file from a crashed prior run, or a file that has been tampered with all fail the equality and are not promoted. The helper logs a WARN on each failure so a fleet-wide hash mismatch is visible in the logs.
Step 3 inserts a strip between mount and injection, subject to the v49 source-ownership classification described in the next section. Remove-AllThirdPartyDrivers takes the mounted image and removes every third-party driver from it:
Get-WindowsDriver -Path $MountDir. No -All. No provider filter. This is the form Microsoft documents as the third-party inventory of a mounted image.OEM#.inf, call Remove-WindowsDriver -Path $MountDir -Driver <published name>.oem5.inf may renumber oem7.inf to oem5.inf, and so on). The loop terminates only when a fresh enumeration returns zero entries.The strip is a hard gate, not a best-effort operation. Every failure mode rejects the candidate:
| Failure | Result |
|---|---|
| Initial enumeration fails | Candidate rejected. |
| Re-enumeration fails at any iteration | Candidate rejected. |
| Enumeration entry is missing its published INF name | Candidate rejected. |
Remove-WindowsDriver fails for any entry |
Candidate rejected. |
| Iteration budget exhausted without reaching zero | Candidate rejected. |
| Final enumeration returns a non-zero count | Candidate rejected. |
Enumeration failure is never interpreted as zero drivers. There is no catch {} that swallows an error and returns success. On rejection the caller dismounts with -Discard, rolls the checkpoint back to Step 2, removes base.wim and any stale winre_optimized.wim, and exits EXIT_WARNING. No injection, no export, no partition work, and no reagentc call occurs. Under v49 this abort is only reached when the source-ownership classification is not Foreign-With-Drivers — a foreign-with-drivers source skips the strip, so the strip-failure abort is not reachable on such a source.
The pre-strip inventory is logged as one line per third-party package, with the published INF name, provider, version, and original filename. This is diagnostic: it records what the source image contained before the strip, and over time the fleet logs answer whether Microsoft’s WU servicing ever delivers a WinRE image with third-party driver packages already present.
Rule 4 says “prepare everything before touching anything”. The strip is a preparation step in the fullest sense: it produces a candidate image that is provably what the current recipe says it should be, before any partition work begins. The order matters:
base.wim. Verify the copy.base.wim.WIM_READY.If step 5 cannot be proven, steps 6–11 never run. The candidate is discarded; the machine’s existing recovery route is untouched. That is the “prepare everything” discipline applied to the image itself: no state-modifying operation runs against a candidate that has not first been proven to match the current recipe. The v49 classification determines whether step 5 runs at all — for a Foreign-With-Drivers source, the recipe is not applied and the servicing pipeline is bypassed; patch 5 separately evaluates unchanged-image relocation and its read-only applicability check.
/disable race detectorWindows Update can service or replace the registered WinRE while the script is preparing a candidate. The preparation takes minutes; a WU servicing pass is smaller but can complete in that window. If the registered image is replaced between source capture and the first /disable, the script would deploy a candidate based on a source that no longer exists and would overwrite a newer Microsoft image with one derived from the previous one.
The race detector narrows that window from minutes to microseconds:
reagentc /disable this execution reaches first: re-read all three./disable. Discard the candidate, invalidate the checkpoint, defer.Both /disable sites are wrapped — the Ensure-AdequateRecoveryPartition site (which runs after the pre-shrink, so an abort restores C: to its captured size first) and the Step 5 deployment site (which runs with the old route intact, so an abort is a clean defer). Only one fires per execution; whichever fires first performs the recheck. The helper handles three capture states: 'captured' (full fingerprint, all three fields re-read and compared), 'unreadable' (WinRE was Enabled with a registered location but the WIM could not be read at capture time — the recheck verifies location and version are unchanged and the WIM is still unreadable before allowing the repair path to proceed), and 'none' (WinRE was not Enabled or had no registered location — the recheck verifies no registered source has appeared since).
The detector is named honestly as a race detector, not a lock. Microsoft does not document reagentc /disable as atomic with respect to Windows Update. The microseconds between the final re-read and /disable returning cannot be closed without moving the re-read inside the disable→enable window, which would lengthen that window and violate Rule 3. The detector reduces the exposure window from minutes to a residual that is not addressable without violating a higher-priority invariant.
The WIM_READY checkpoint is the entry point for a resumed execution that skipped Step 2 (resumed at Step 3, then completed the export at Step 4). Under v47 the checkpoint records a fifth field: the SHA256 of the source WIM from which the staged candidate was prepared. On resume, the checkpoint validator compares the recorded hash against the currently available sources (the registered WIM and the LKG). If the recorded hash no longer matches either available source, the checkpoint is invalidated and the candidate is discarded — the source it was prepared from is no longer present with the same bytes, so the staged WIM’s lineage cannot be trusted.
Legacy four-field checkpoints written by a pre-v47 build have no source binding and are invalidated on first resume. Checkpoints prepared from a GitHub cold-start also have no source binding (there is no on-disk source to bind to) and are invalidated on first resume as a conservative rebuild. This is not a problem in practice: GitHub cold-start is rare, and the rebuild cost is the same as any other rebuild.
When the source-selection path is skipped because the execution resumed at Step 3, the source hash is recovered at Step 4 by hashing base.wim and matching against the registered WIM hash and the LKG hash. If base.wim matches neither, the source identity is left unbound and the checkpoint is written without the fifth field, which is the conservative outcome.
v49 does not change the checkpoint format or the source-hash binding. The source-ownership classification is a downstream decision that runs after source selection; it does not change what the checkpoint binds to. A checkpoint staged under a v49 run records the same source hash it would have recorded under v48 — the hash of the WIM the source-selection chain chose — and a resume under v49 evaluates the same Select-BaseWinRESource result.
ScriptVersion bumpScriptVersion moves from 46 to 47. The four-rule hierarchy permits this without compromising any invariant: the bump is not a gratuitous rebuild trigger, it is the mechanism that converges the fleet on a rebuild the recipe change has already made necessary. Every managed machine performs one full update on its next scheduled run because the SCRIPT component of the DesiredStateId changed; that is the intended effect, not a side effect.
The rule is: ScriptVersion bumps when a change modifies the deployed WIM bytes, the partition layout that gets created, or the DesiredStateId inputs. The strip changes the WIM bytes whenever a rebuild happens. On a machine that is already on the current recipe, the strip is a no-op — the image is already normalized — and the deployed WIM is byte-identical to what v46 would have produced. On a machine that would carry accumulated drivers under v46, the strip produces a different WIM. The two cases cannot be distinguished from the fleet without the version boundary.
Without the bump, the fleet ends heterogeneous: machines rebuilt under v46 (or earlier) retain whatever driver packages the lineage had accumulated, and machines rebuilt under v47 carry a stripped image. The DesiredStateId is the same string under both cases, so the state file cannot distinguish them, and the deployment identity stops being a reliable fingerprint of the deployed artifact’s contents. The v47 bump is the version boundary that forces every machine onto a common footing: every managed machine performs one full update on its next scheduled run, converges on the strip-normalized driver set, and returns to the fast path.
The bump also serves a second purpose: every machine’s first v47 run writes a DeployedWinREMetadata anchor, so the metadata-based drift detector has a baseline. Without the bump, machines whose existing inputs happened to produce the same DSI would keep running without an anchor.
The original design brief flagged a residual concern: Microsoft documents that WinRE servicing can migrate certain boot-critical or input drivers from the OS into the WIM. If Microsoft’s WU servicing ever delivered a WinRE image that already contained third-party driver packages, the strip would remove them, and on the machine’s next rebuild the recipe would decide what to reinstall — potentially producing a WinRE that lacks a driver Microsoft had intentionally migrated in.
The design accepts this as a named residual rather than designing around a hypothetical. The observation that closed the concern is empirical, not documentary: across the project’s actual collection of WU-serviced WinRE images, no third-party driver packages have been observed in the WIMs. That is evidence, not proof — Microsoft could begin delivering such packages in a future servicing change — and the pre-strip inventory logging is the mechanism by which the project accumulates the field data that would surface a change if it occurred. If future data shows Microsoft-serviced WinRE images containing third-party packages, the strip stage is revisited. The v49 source-ownership classification is orthogonal to this concern: the empirical observation is about in-box WIMs that the strip sees as Foreign-No-Drivers; the classification narrows the strip to those sources and to manager-owned or manager-lineage sources, and preserves Foreign-With-Drivers sources as-is.
Four residuals are carried forward under v47:
The WU race remains a race. The pre-/disable recheck narrows the exposure window from minutes to microseconds. It does not close it. Closing it would require holding a lock that Microsoft does not provide; the correct posture is to detect the change and defer, which is what the recheck does.
DesiredStateId does not encode the strip. The strip is part of the WIM production recipe, not an input to the deployment identity. A machine whose current recipe is unchanged will rebuild under v47 (because SCRIPT changed from 46 to 47) and produce a strip-normalized image; a machine whose current recipe would change next month will rebuild once under v47 (from the strip change) and once again under the next DesiredStateId change (from the recipe change). The two rebuilds are separate. DesiredStateId answers “what recipe should the deployed image reflect?”; the strip answers “what should the base image contain before the recipe is applied?” — the second is not a deployment input in the DSI sense.
Metadata-neutral Dynamic Update drift is undetected as a rebuild trigger. Microsoft documents that a Dynamic Update may change the contents of a serviced WinRE image without changing its Version or SPBuild. The v47 drift detector compares servicing metadata, so a DU delivered in that manner will not trigger a rebuild. The WIM_READY checkpoint’s source-content-hash binding catches it for an in-flight rebuild — a staged candidate whose source is no longer available with the same bytes is invalidated on resume — but a completed prior deployment with no in-flight checkpoint will not be flagged by a metadata-neutral DU. In practice a machine whose registered WinRE was serviced by a DU-only update will continue on the fast path until some other deployment input (manifest version, OEM pack version, Windows build, CPU vendor/generation, VMD presence) changes. The pre-strip inventory logging is the field-evidence mechanism by which a wider fleet impact would be recognised.
LocalInputsId was not shipped in v47. The offline fallback’s residual (a machine whose hardware changed while offline taking the fast path with a stale DSI) remained open through v47 and was closed in v48 patch 1. The v47 release made the offline fast path metadata-based rather than WIM-hash-based by requiring a DeployedWinREMetadata anchor that matches the currently-registered image’s metadata, so a v46-or-earlier state file forces a rebuild on the first v47 run regardless of network state. That was a change to which signal gates the fast path, not a closure of the hardware-drift residual; the closure came one release later.
The v49 release is the largest single release since v48. It does not change the four design invariants, the four control-flow paths, or the eight-step pipeline shape. It narrows what the full-update pipeline will deploy by adding three pre-deployment decisions, closes the standing gap on the native-boot VHDX topology, and exposes a standalone backup and restore action pair. It also rewrites the interactive wrapper (scripts/WinRE-Manager.cmd) and adds a temporary crash-recovery scheduled task. This section covers the pipeline-relevant pieces.
The change was driven by the ASUS-incident field case. A machine’s controller (PCI\VEN_8086&DEV_7D0B) was not in the manifest’s VMD patterns, the VMD detector classified the machine as having no VMD hardware, and the earlier pipeline would have deployed a candidate with no driver for the machine’s actual storage controller — a recovery environment that boots but cannot see the OS disk. The v49 pre-deployment storage-applicability gate is the direct response: the last refusal before the WIM is written to the active route is a check that every present SCSIAdapter-class device on the machine has at least one INF in the candidate image whose HardwareID or CompatibleID prefix-matches one of the device’s IDs.
The release also responds to a class of source images the v47 strip-and-reinject policy was never designed for. The v47 policy assumed every source was either a manager-deployed image, a manager-lineage image, or an in-box WIM. That assumption held for the shipped source chain, but not for a machine whose registered WinRE had been populated by a vendor servicing tool with third-party drivers. Under v47 the strip would have removed those drivers and injected the manager’s recipe; on a machine whose hardware depended on the vendor drivers, that would have regressed the recovery environment. The v49 source-ownership classification preserves such a source.
The four classes decide whether normal servicing is authorized:
Manager-Owned — the staged hash matches a positively owned current or historically bridged CurrentImageHash.Manager-Lineage — a valid in-image provenance marker matches known manager lineage.Foreign-No-Drivers — no positive ownership evidence, but no third-party driver packages are present.Foreign-With-Drivers — no positive ownership evidence and third-party drivers are present; preserve the source bytes.The first three permit the normal strip-and-inject recipe when an update is needed. They do not force image servicing merely because layout repair is needed. Foreign-With-Drivers is dismounted with -Discard and skips stripping, injection, ResetBase, provenance writes and export.
Patch 5 makes placement independent of those decisions. A preserved source can be copied unchanged to an adequate dedicated partition after a read-only applicability check. An already adequate dedicated source avoids partition work. ForeignSourceAcceptedHash records acceptance; it does not grant ownership, and the same hash must not be written into CurrentImageHash merely because it was copied.
Normal servicing source selection still precedes classification: the registered image wins unless a positively hash-validated LKG is provably newer by compatible servicing metadata. An already accepted foreign source selected for relocation is pinned to its accepted hash, rather than silently replaced by another candidate. Deleting state does not make a source positively owned; classification considers bytes, historical ownership evidence and lineage.
After injection and before ResetBase, the manager compares storage-class drivers against the pre-strip inventory by INF basename. If any candidate driver would be older than the corresponding source driver, the whole servicing candidate is discarded with -Discard. The check is conservative; it does not establish a general driver coexistence or ranking policy.
The check applies to OEM and VMD package drivers when the servicing recipe runs. It does not run when a foreign image is preserved before injection, or during unchanged-image relocation. Its purpose is to prevent an older manifest/vendor package from silently replacing a newer driver already present in the source.
The log names each downgrade’s INF basename and source/candidate versions. Patch 5 preserves the original bytes, records acceptance separately from ownership, and still evaluates dedicated layout repair. The final outcome is determined by actual route/capacity verification or a reported pending-operation failure, not by the preservation message alone.
The manager verifies that every present SCSIAdapter-class device on the machine has at least one INF in the mounted candidate image whose HardwareID or CompatibleID prefix-matches one of the device’s IDs. The gate runs inside Step 3, after injection is confirmed complete, before ResetBase and before the dismount.
The gate is the last refusal before deployment. A candidate that does not match the machine’s controller is refused rather than deployed; the run exits EXIT_WARNING before the WIM is written to the active route. No partition is touched, WinRE is not disabled.
Why it exists. The manifest’s VMD patterns are an incomplete signal. The ASUS-incident field case demonstrated the gap: a machine’s controller was not in the manifest, the VMD detector classified the machine as having no VMD hardware, and the earlier pipeline would have deployed a candidate with no driver for the machine’s actual storage controller. The gate closes the gap by verifying the actual outcome — does the candidate’s INF set match the machine’s actual controllers?
What the gate reads. The gate enumerates the candidate image’s driver INFs and extracts each one’s HardwareID and CompatibleID entries; it enumerates the machine’s present SCSIAdapter-class devices and extracts each device’s HardwareID and CompatibleID; and it requires every device to have at least one matching INF. Software and virtual controllers (InstanceId starting with {GUID}\ or SWD\) are excluded from the device enumeration, mirroring the v28 harness diagnostic.
Preserved-image relocation (patch 5). The Step 3 servicing gate is bypassed when a source is preserved. Before relocating a preserved image, the pending-deployment workflow mounts its independently verified candidate read-only, runs the storage-applicability check and discards the mount. No servicing is committed. Applicability is a consistency check, not proof of successful recovery boot.
Field status. The gate has never fired in the field. A field log of the refusal is high-signal; the harness Option 1 “Storage controllers” block (v28) surfaces the machine’s controller IDs alongside the manifest’s VMD patterns, which is what a bug report should include.
The manager refuses to run destructive operations when the OS disk’s bus type is File Backed Virtual and at least one other disk is on a physical bus — the native-boot VHD/VHDX topology, where the running OS disk is a VHD/VHDX stored on a host physical disk. A hypervisor guest whose entire storage stack is virtual (every other disk on Virtual or File Backed Virtual) is not refused. This gate identifies a file-backed OS disk with visible nonvirtual disks; it does not refuse ordinary Hyper-V or VirtualBox guests merely because their backing storage is a VHDX or another virtual-disk file. Native-boot support remains a separate policy decision; patch 5 retains the existing refusal.
The gate exits EXIT_WARNING before any partition or WinRE change; the state file is unchanged. It is a stable deferral: a genuinely VHDX-boot machine will continue to exit 2 on every run until the topology is supported or the machine is converted. The gate has no -DryRun carve-out — the topology is a property of the machine, not of the run mode.
The v49 release adds two standalone actions to the production script:
-Action Backup -BackupPath <dir> — captures a byte-for-byte copy of the currently registered WinRE WIM plus a sidecar backup.json recording the source hash, size, and DISM servicing metadata.-Action Restore -BackupPath <dir> — writes a previously captured WIM back to the currently registered route transactionally.Backup is non-destructive. It does not rebuild, replace, or reconfigure the active WinRE route, and it does not write to the state file. It may temporarily assign a drive letter to access a WIM registered through a GLOBALROOT/volume path, and cleans the letter up under the existing temporary-drive-letter machinery.
Restore is transactional. It validates the backup, resolves the current registered route, handles dedicated and OS-fallback targets, uses the existing deployment machinery, re-registers WinRE, and re-enables it. Restore does not create a new partition or invent a replacement route — a usable current WinRE route must already exist. The three mid-transformation failure paths - the WIM-deployment failure when the re-enable attempt after the failure does not return ok (v50 patch 3), /setreimage failing after the WIM has been replaced, and /enable returning failed/bitlocker after the WIM is in place - preserve the temporary resume task so the operation is resumed on the next boot or within the hour.
A separate branch on the same WIM-deployment failure path (v50 patch 3 follow-up) handles the state-carrying artifacts differently from the success case. The branch captures the target WIM’s SHA256 before the deploy attempt and again after the failure. When the two hashes are equal, the target is provably unchanged (untouched, or the transactional rollback restored and hash-verified it), and the branch preserves the state file, checkpoint, and deferral marker because those files still describe the target content. When the two hashes differ, or either hash is unavailable (Get-LiveWimHash returns $null for both absent and unreadable), the target’s content cannot be proven unchanged, and the branch invalidates the three markers so the next run does not trust stale state; the resume-task persist flag is set unconditionally in the invalidate branch, because reagentc /enable returning ok establishes only that reagentc reports Enabled, not that the target WIM’s bytes are intact.
Neither action participates in the repair pipeline. They are standalone commands invoked by the wrapper’s menu (Backup under SAFETY, Restore under RECOVERY) or by a direct -Action invocation. The backup action does not write to the state file and does not change the DesiredStateId; the restore action deletes the state file, checkpoint file, and partition deferral marker on success so the next repair run re-evaluates the machine from a clean state. Neither action enters the fast-path or full-update control flow. The backup sidecar lives in the operator’s backup directory and is not part of the deployment identity.
Live Repair and Restore attempt to register a scheduled task named WinRE Manager - Resume when a script path is available and staging checks pass. The task fires at boot+1m and as a one-shot at T+1h; it is deleted on clean completion and preserved on interruption. The persist decision is made by OR-merging two independent signals in the finally block. $Script:ResumeTaskShouldPersist is armed while reading or executing a pending deployment and by covered failure/cleanup paths, including Restore and the outer catch; verified deployment completion clears it. The persist-signal contract describes the current lifecycle. [WinRECancelKeyProbe]::ShouldPersist is set by a compiled ConsoleCancelKeyPress delegate that the v49 patch 1 fix introduced — the load-bearing Ctrl+C case, because PowerShell runs finally blocks but bypasses catch blocks on Ctrl+C, and because the event callback runs on a thread-pool thread that cannot safely mutate PowerShell session state. The compiled delegate replaces the pre-fix [Console]::CancelKeyPress += { ... } scriptblock subscription, which failed at runtime on PowerShell 5.1 with The property 'CancelKeyPress' cannot be found on this object — so the handler was never registered, the finally block read $false, and the task was deleted on exactly the Ctrl+C interruption it existed for. If the Add-Type or Register() step fails, the pipeline logs a WARN and continues; the Ctrl+C signal is unavailable. Ctrl+C alone cannot retain the task in that case; other persist conditions still apply. Two further interruption classes leave the task registered without setting either signal, because the finally block never runs to consult them: a hard kill (e.g. taskkill /F) and a reboot mid-run (the OS terminates PowerShell). See troubleshooting.md.
The task is a per-run safety net, not machine state. It invokes the default Repair action, which acquires the program lock normally. Its presence can indicate interruption or retained pending work; a completed healthy run normally removes it.
Under $PSCommandPath-less invocation — gist bootstrap via Invoke-RestMethod | Invoke-Expression, or paste-into-console — the guard in Register-ResumeTask logs at INFO and does not register the task. This is by design: those invocation modes have no $PSCommandPath, and a run initiated from such an invocation cannot be resumed by the task.
The task profile is SYSTEM / highest run level, startup+1m and one-shot T+1h, StartWhenAvailable, battery-allowed, no idle requirement, network not required, 24-hour execution limit. The same profile as the primary scheduled task’s conservative settings, so a resume run behaves identically to a scheduled run for the purposes of the offline fallback and the fast-path gates.
The scripts\WinRE-Manager.cmd wrapper’s install option (menu option 5 — Install automatic maintenance) does not register the task against the operator’s local WinRE.ps1. It copies the local script to a stable install location at:
C:\ProgramData\OEM\WinRE-Manager\WinRE.ps1
and registers the task against that copy. Patch 5 checks destination ancestry and permissions, stages a protected copy, verifies its SHA256 and holds the installed file against writes/deletion through task registration. Existing untrusted paths are refused. See deployment for installation and publication-failure behavior. The task survives deletion or relocation of the operator’s original files.
The wrapper’s removal option (menu option 6 — Remove automatic maintenance) unregisters the task and leaves the installed copy in place. Reinstallation checks and refreshes that copy.
The stable install location does not participate in the repair pipeline. It is a wrapper-managed artifact, not a state-file field, and it does not affect the DesiredStateId.
ScriptVersion bumpScriptVersion moves from 48 to 49. The four-rule hierarchy permits this for the same reason as the v47 bump: the bump is not a gratuitous rebuild trigger, it is the mechanism that converges the fleet on a rebuild the recipe change has already made necessary. Every managed machine performs one full update on its next scheduled run because the SCRIPT component of the DesiredStateId changed.
The rule is: ScriptVersion bumps when a change modifies the deployed WIM bytes, the partition layout that gets created, or the DesiredStateId inputs. The v49 refinements satisfy the first branch:
Foreign-With-Drivers: the WIM is deployed with its own driver set rather than the manager’s recipe.On a machine whose source, manifest, and OEM pack are unchanged from v48 and whose candidate matches the machine’s controllers, the pass produces the same output as v48’s pass did — the gates’ decisions are the same. On a machine whose source classifies as Foreign-With-Drivers, or whose manifest resolves a downgrade driver, or whose candidate does not match its controllers, the pass produces a different outcome. The two cases cannot be distinguished from the fleet without the version boundary.
Without the bump, the fleet ends heterogeneous: machines rebuilt under v48 retain whatever the v48 pipeline deployed, and machines rebuilt under v49 carry whatever the v49 pipeline’s decisions produced. The DesiredStateId is the same string under both cases, so the state file cannot distinguish them.
The bump also ensures every machine exercises the v49 pipeline once and every subsequent rebuild produces an image that is a function of the current recipe only.
The bump adds two optional state-file fields. v49 introduces ForeignSourceAcceptedHash (set when a Foreign-With-Drivers source is preserved, so the next run’s fast path accepts the registered hash) and LineageId (the persistent lineage identifier written into the provenance marker and carried forward across runs). Both are absent on state files written by v48 or earlier; their absence is handled as any other missing field. The DeployedWinREMetadata field (v47) and the LocalInputsId field (v48) are unchanged. The backup and restore actions write a backup.json sidecar in the operator-supplied backup directory; they do not touch the state file. The temporary resume task is a scheduled task, not a state-file field.
Four residuals are carried forward under v49:
The applicability gate has never fired in the field. The gate is a v49 addition and no logged run has reached it. The gate is exercised by inspection, by the harness’s v28 storage-controller diagnostic, and by the test plan in testing.md. The false-negative rate is unknown — a machine whose present storage controller is not enumerated (hidden by policy, in an error state, or transiently unreadable during the PnP query) would not be checked by the gate and could pass with a candidate that lacks that controller’s INF. The gate is a narrowing, not a proof.
The Foreign-With-Drivers preservation depends on the classification being correct. A WIM that a vendor populated with drivers the manager should have replaced — because the manager’s recipe is the correct one for the hardware — is preserved as-is. The classification is a set-membership test against the source’s driver inventory and the state file’s DeployedWinREMetadata anchor; it does not consult the machine’s hardware. A misclassified source is deployed as-is, and the failure mode is a recovery environment whose driver set is not the manager’s recipe. The operator’s remedy is to make a manager-owned source available.
The never-downgrade check does not compare against Windows Update’s own version policy. The check compares the driver’s version against any matching driver already present in the mounted image. If Windows Update delivers a driver with a version that the manager’s manifest also carries but at a different revision number, the check will treat the manifest’s version as the candidate and compare it against the WU-delivered version. If the manifest’s version is older than the source’s, the check fires and the candidate is discarded; if it is newer or equal, no downgrade is detected and the injection proceeds. The check assumes a monotonically-increasing version scheme, which is the vendor’s convention but not a documented guarantee.
The v49 restore mid-transformation failure paths have not been exercised in the field. The three paths - the WIM-deployment failure when the re-enable attempt after the failure does not return ok (v50 patch 3; a reboot result does not confirm WinRE is enabled), /setreimage failing after the WIM has been replaced, and /enable returning failed/bitlocker after the WIM is in place - are the primary v49 restore coverage gap. All three set the resume task’s persist flag and leave the machine with the newly restored WIM on the active route but an incomplete registration. The transactional helper’s rollback behaviour on real storage has not been exercised either.
The v50 patch 1 release does not change the four design invariants, the four control-flow paths, or the eight-step pipeline shape. It hardens the manager’s durable state — the config file, the ownership classification, the resume task — against a property of the stock Windows ACL that the earlier releases had not had to consider: a non-administrator can create a directory under C:\ProgramData and become its owner. The v50 patch 1 release assumes that property explicitly and defends against it in four places.
The v50 patch 3 release extends two of those defenses. The manager config ownership gate is replaced by the shared Test-PathTrustedForSystem helper, which checks the owner and the effective DACL mask (split by object class: on a directory the mask is Delete | DeleteSubdirectoriesAndFiles | TakeOwnership | ChangePermissions; on a file it adds WriteData | AppendData) and additionally checks the config file itself, so a non-admin cannot pre-create manager.json inside a SYSTEM-owned directory and supply hostile content. The v50 patch 1 resume-task protected-path guard is replaced by a resume-script staging design: the running script is staged to C:\Recovery\OEM\Resume\WinRE.ps1 under an explicit DACL (SYSTEM and Administrators FullControl, inheritance disabled), byte-verified against the source, re-verified with Test-PathTrustedForSystem, and the task is registered against the staged copy. The staging design preserves the security property the guard aimed at (the SYSTEM task’s execution target cannot be modified by a non-admin after staging) without the guard’s false positive on every development checkout. It also closes the correctness gaps: Remove-StrayRecoveryPartitions positively verifies each deletion with a terminating re-query; Get-GitHubBaseWinRE rejects an empty archive-parts list with a named reason; recovery-volume drive-letter normalization is scoped to the OS disk and fails closed on a provider error; Add-ManagerBackupRoot preserves volume roots (E:\ no longer truncates to E:); and Get-WorkDirCandidates fails closed on a volume-enumeration error.
The single durable settings file at C:\ProgramData\OEM\WinRE-Manager\manager.json holds the backup-root catalogue read by Cleanup-Backups.ps1. Both the read path (Get-ManagerConfig) and the write path (Set-ManagerConfig) verify that the directory containing manager.json and its immediate parent are owned by SYSTEM (S-1-5-18) or Administrators (S-1-5-32-544).
The two-level check is not belt-and-braces. The stock ACL on C:\ProgramData grants Authenticated Users the ability to create subdirectories, and a directory created by a non-admin principal is owned by that principal. An attacker who pre-creates C:\ProgramData\OEM\WinRE-Manager under their own account and populates it with a manager.json whose BackupCatalog.Roots points at an attacker-chosen path could redirect a later Cleanup helper’s deletions, or a later Restore’s file reads, to a location the operator does not control. The two-level check catches the initial pre-creation attack. It also catches the delete-and-recreate swap: an attacker who owns the parent can delete-and-recreate the child directory between runs to steal ownership of the recreated directory, so a check that validates only the immediate parent is bypassable on a subsequent run. Checking both levels means the delete-and-recreate swap fails the check at the parent level before any operation the child could redirect.
The write path additionally runs the checks before creating the directory, so a pre-created attacker-owned parent is caught before the manager adds a child to it. An untrusted, unreadable, or unparseable config is treated as absent: the caller gets the empty default, an operator-initiated backup still completes without catalogue registration, and an attacker who swapped the directory cannot inject roots for a later restore or cleanup to use. Writes are atomic via the existing Write-FileAtomically.
v50 patch 3 extension. The v50 patch 3 release extends the check by replacing the v50 patch 1 owner-only test with the shared Test-PathTrustedForSystem helper. The helper verifies the ACL owner (SYSTEM or Administrators) and that no Allow ACE grants a modify-capable right to a principal outside SYSTEM, Administrators, or TrustedInstaller. The modify-capable mask is split by object class (on a directory: Delete | DeleteSubdirectoriesAndFiles | TakeOwnership | ChangePermissions; on a file: those plus WriteData | AppendData), because on a directory WriteData means only create-new-file and AppendData means only create-new-subdirectory, not modify-existing. The v50 patch 3 release also adds a file-level check on manager.json itself, closing a pre-creation attack a directory-only check would not catch: a non-admin who pre-created the file inside a SYSTEM-owned directory would pass the directory check but is refused by the file-level check, because the planted file is owned by the attacker, not SYSTEM. The stock C:\ProgramData ACL passes the extended check exactly as it passed the v50 patch 1 owner-only check, confirmed by the v50 patch 3 field verification. See SECURITY.md under “Manager config trust gate” for the full security posture.
Cleanup-Backups.ps1 performs the same two-level trust check on the config directory it reads from, and additionally checks the config file itself, matching Get-ManagerConfig. The check is duplicated rather than imported from WinRE.ps1 because dot-sourcing the production script would execute the production pipeline; the duplication is deliberate.
The temporary crash-recovery task registered by every Repair or Restore run invokes the production script as SYSTEM. If the script lives in a directory writable by a non-admin principal, that principal could modify the script before the task fires and gain SYSTEM-level code execution on the next boot.
The v50 patch 1 protected-path guard refused to register the task when the script directory granted any write-capable right to Everyone, BUILTIN\Users, Authenticated Users, or INTERACTIVE. That guard (and the v50 patch 3 first-revision three-path Test-PathTrustedForSystem check that replaced it) shipped a false positive on every development checkout: any script running from a path a non-admin could write was refused, so an interrupted run (WinRE disabled, old recovery partition deleted, deployment incomplete) had no automatic recovery hook.
The v50 patch 3 design replaces both. Initialize-ResumeScriptStaging stages the running script to C:\Recovery\OEM\Resume\WinRE.ps1 under an explicit DACL (SYSTEM and Administrators FullControl, inheritance disabled), byte-verifies the copy against the source, and re-verifies the staged file and its directory with Test-PathTrustedForSystem before the task is registered against the staged copy. The staging directory is created with [System.IO.Directory]::CreateDirectory($StagedDir, $sec) where $sec is built with SetAccessRuleProtection($true, $false) and two explicit Allow-ACEs, so there is no window in which the directory exists with an inherited permissive ACL.
The staging directory and the temporary resume task share a lifetime: Remove-ResumeScriptStaging is called from the finally block at the same point Unregister-ResumeTask is, under the same persist guard. A self-staging case (the resume task itself firing and re-invoking the script from the staged path) is detected by comparing the running script’s full path to the staged path and is short-circuited: the file is reused in place after its DACL is verified.
The staging design preserves the security property the guard aimed at - the SYSTEM task’s execution target cannot be modified by a non-admin after staging - without the false positive. The residual - a non-admin who modifies the running script before this elevated process stages it - is not a new exposure: the process is already executing that script elevated.
Staging failure at any step (staging-directory creation, stale-directory clear, script copy, hash verification, or the final trust check) is non-fatal: Register-ResumeTask logs the specific failure line, adds a Changes NOT made entry to the run summary, and returns $false. The repair pipeline proceeds without the self-healing hook. A machine whose script lives in the standard C:\ProgramData\OEM\ location with default ACLs stages successfully and registers the task.
Remove-EmptyWorkspaceParent removes the now-empty parent directory left behind by workspace cleanup. The workspace convention is <volume>:\Temp\WinREWork; after the workspace is removed, <volume>:\Temp is left empty. The cleanup removes the parent only when its leaf name is exactly Temp, it is completely empty, and it is not a drive root. An arbitrary empty parent directory is never removed. Called from four sites in Main.
Cleanup-Backups.ps1 applies the same pattern to the backup hierarchy: C:\Backup\WindowsRE is removed if it is empty, and C:\Backup is then removed if it too is empty. The child’s leaf must match the timestamped-backup convention (yyyy-MM-dd_HHmmss) before removal, and the same safety rules apply — never a drive root, never a reparse point, never a non-empty directory. Remove-IfEmptyDirectory is the single gate for the cleanup helper’s empty-directory removals; the function refuses an empty path, a drive root, a non-container, a reparse point, an unreadable directory, a non-empty directory, or an unremovable directory.
Invoke-BackupAction verifies that the destination volume has room for the WIM plus a 100 MiB margin before creating the destination directory or starting the copy. The check runs after the source WIM’s size and hash are known.
If the destination drive letter resolves to a local volume, Get-Volume provides the free-space value. If the drive is not an MSFT_Volume — a mapped network drive is the common case — Get-PSDrive provides it. If neither resolves, the check is skipped and the copy proceeds with any space-related failure surfaced by Copy-Item. A drive letter that resolves to nothing is a genuine error and the backup aborts before any file is written.
Add-ManagerBackupRoot resolves a mapped drive-letter path to its UNC form via Get-PSDrive.DisplayRoot before writing the root to manager.json. A mapped drive is a session-specific DOS device mapping; a later run may map the same letter to a different share, making the catalogue entry point at the wrong location. The UNC form is stable. If DisplayRoot is empty — a local drive, a subst, or a mapping not visible to the elevated process — the drive-letter path is kept, which is no worse than the pre-v50 behaviour.
Get-SourceOwnershipClassification now takes -HistoricalImageHash and -HistoricalLineageId. The Manager-Owned classification matches the staged source hash against the current state.CurrentImageHash or a historical CurrentImageHash read from a stale state file across a version boundary. The Manager-Lineage classification requires the marker’s LineageId to match a known current or historical lineage identifier; a marker whose LineageId matches no known value is treated as absent.
The bridge is deliberately narrow. It uses a new Get-StaleWinREStateFields function that reads the stale state file in isolation and returns both the historical image hash and the historical lineage identifier. It does not make the stale state operationally authoritative, does not enter any gate other than the source-ownership classifier, and does not affect the fast path’s DesiredStateId check.
The bridge exists because the v50 ScriptVersion bump (49 → 50) is itself the reason a machine’s previously-recorded CurrentImageHash no longer matches the current run’s expectation. Without the bridge, the first v50 run on a machine whose state file was written by v49 would read the stale state file, reject it as DSI-mismatched, and classify its own prior deployment as Foreign-With-Drivers — preserving a source the v49 manager had deployed and normalized. The bridge restores Manager-Owned recognition across exactly the version boundary the release introduces. Get-StaleWinREStateImageHash is replaced by Get-StaleWinREStateFields.
ScriptVersion bumpScriptVersion moves from 49 to 50. The rule is the same one that has governed every previous bump: ScriptVersion bumps when a change modifies the deployed WIM bytes, the partition layout that gets created, or the DesiredStateId inputs. The v50 patch 1 change does not itself alter the deployed WIM bytes or the partition layout — the pipeline’s decisions on an unchanged machine are the same as they were under v49 — but it does change the SCRIPT component of DesiredStateId (49 → 50), and it does so deliberately: the version boundary is what triggers the ownership migration bridge on machines whose state file was written by v49 or earlier, and what ensures the newly added manager config helpers, protected-path guard, and empty-parent cleanup are exercised on every machine.
Without the bump, the migration bridge would not fire on the machines it exists for, and the fleet would be split between machines whose ownership classifier had run against the current state file (post-bump machines) and machines whose ownership classifier had run against a state file the current process could not fully read (pre-bump machines still on the old fast path). The bump converges both onto the same pipeline.
ScriptPatchLevel resets to "1" in the v50 generation. It is not a DesiredStateId input, so it does not force a second rebuild.
v50 patch 3 does not bump ScriptVersion. The v50 patch 3 release hardens the manager config trust gate, replaces the v50 patch 1 resume-task protected-path guard with a resume-script staging design, and closes six correctness gaps. None of those changes the deployed WIM bytes, the partition layout, or the DesiredStateId inputs. A machine that ran v50 patch 2 continues on the fast path.
Three residuals are carried forward under the v50 generation:
The manager config ownership gate’s TOCTOU window. Between the two-level owner check and the actual file read or write, a hostile actor with the ability to delete-and-recreate directories under C:\ProgramData could theoretically swap the directory again. Perfect closure would require holding a directory handle open across the check-and-read sequence, using Windows primitives PowerShell does not expose cleanly. The residual impact is bounded: the attacker would need continuous control of the parent directory, which the parent-level check is specifically there to prevent, and the effect of a successful attack is bounded to redirecting the backup-root catalogue — not arbitrary code execution.
The resume-script staging design does not cover a post-staging replacement. If the staging directory’s DACL is verified at registration time but the staged file is later modified by a principal with the rights to modify it, or if the SYSTEM task’s execution target at C:\Recovery\OEM\Resume\WinRE.ps1 is swapped for a different file after the final trust check but before the task fires, the staging design does not catch it. The check is a registration-time verification, not a continuous protection. The mitigation is the same as the general design’s: the task is a per-run safety net, and a machine whose administrator cannot be trusted not to modify files under C:\Recovery\OEM\ is a machine whose trust model the resume task’s protections were never going to hold up against. The v50 patch 1 protected-path guard had a different residual (a script in a non-admin-writable directory that a non-admin could replace after the ACL check); the staging design narrows it by placing the execution target under a SYSTEM/Administrators-owned directory whose DACL is set at creation and re-verified before registration.
The ownership migration bridge’s Manager-Lineage half is limited to v49-and-later state files. The bridge works for Manager-Owned across any state file generation that carries a CurrentImageHash — the field has been part of the state file schema since well before v49 — so a v48-or-earlier state file also supplies a historical image hash, and a machine whose registered WinRE image is unchanged from its prior deployment is recognized as Manager-Owned. Only the Manager-Lineage half is limited to v49-and-later state files, because v48 and earlier did not write the LineageId field. The practical outcome is unchanged: a state file written by v48 or earlier already fails the v50 DesiredStateId comparison, so such a machine rebuilds from source regardless of the classification. Get-StaleWinREStateFields reads whichever stale state file is currently on disk, so its historical value tracks the last version that wrote it.
A safety check that cannot complete is never interpreted as a safe result. Every safety guard either positively confirms the safe state or refuses.
The principle was made explicit in v49 patch 2 after a peer review identified the same defect shape in four separate guards. In each case, the guard’s underlying query could fail — through a thrown exception, an enumeration error, an unreadable property, or a PowerShell pipeline-enumeration collapse of an empty array — and the failure produced the same in-memory result as a successful but negative query. The guard then proceeded as if the safe state had been positively confirmed.
The four corrected sites:
The native-boot VHDX disk enumeration (Test-NativeBootVirtualTopology). The unfiltered disk inventory previously used -ErrorAction SilentlyContinue; a thrown Get-Disk was indistinguishable from “no other disks present,” and the function fell through to the hypervisor-guest verdict that permits destructive partition operations. The enumeration is now wrapped in a try/catch with -ErrorAction Stop; a thrown error marks the topology indeterminate and refuses. An unreadable BusType on any other disk is treated symmetrically.
The post-deletion partition verification (two call sites: Ensure-AdequateRecoveryPartition’s deletion loop and Remove-OrphanPartition). The prior form queried the specific partition with -ErrorAction SilentlyContinue and treated $null as “partition deleted.” A thrown query, suppressed by -ErrorAction SilentlyContinue, produced the same $null result and was indistinguishable from the “gone” case. Both sites now enumerate the target disk with a terminating query and confirm the target partition is not among the results; a query failure is treated as “not-confirmed-removed (fail closed)” and the corresponding failure branch runs.
The WinRE status determination (two call sites: the destructive sequence in Ensure-AdequateRecoveryPartition and the transactional replacement in Invoke-RestoreAction). The prior form treated any status other than Enabled as the “no disable step required” case. An indeterminate status — reagentc output the parser could not classify, such as a non-English OS — would have skipped both the location-resolution guard and the reagentc /disable block, allowing the destructive sequence to proceed without the normal assurance that the active route had been identified and WinRE disabled. Both sites now refuse on any status that is neither Enabled nor Disabled.
The storage-controller enumeration (Get-StorageControllerDevices). The function’s terminal return was @($result). PowerShell enumerates a returned empty array into zero pipeline objects, so the caller received $null and could not distinguish “successfully empty” from “enumeration failed” (the function’s other return path returns literal $null). The applicability gate’s if ($null -eq $controllers) branch then fired for a successfully-empty enumeration, causing the candidate image to be rejected on a machine with no SCSIAdapter-class devices. The function now uses return ,$result (the unary comma operator), which preserves the empty array as a single object; the caller’s .Count -eq 0 branch handles it as the documented “nothing to verify” case.
The first three sites are cases where a failed query could authorize destructive work. The fourth is a case where a successful-but-empty query caused a spurious refusal — a false negative rather than a false positive — but the fix is the same shape: the function now returns a value that its caller can classify, rather than a value that collapses under PowerShell’s pipeline-enumeration rules.
The four corrections do not change the pipeline’s control-flow shape, the eight steps, the four design invariants, or any of the control-flow invariants that follow. They tighten the behaviour of existing guards under transient failure conditions. The corrected behaviour is what those guards were always intended to produce; the pre-patch behaviour was a defect that the review surfaced.
A fifth instance of the same class was closed in v50 patch 4. The former inline Step 5 block in Main disabled WinRE only for the exact status Enabled, allowing an unclassified status to reach deployment. Patch 4 added a known-status guard with fatal exit and resume-task retention. Patch 5 replaces that inline deployment block: Main refuses an indeterminate status before fast-path, enable-only or servicing decisions, and Invoke-PendingWinREDeployment checks again before target preparation and route switching. Its direct status guards return fatal 3; later caught failures report according to the verified route and mutation phase. The pending executor arms task retention on entry. This preserves the fail-closed property without retaining the old Step 5 variable or log signature.
These are the invariants the script maintains, in the order they are enforced. Each one has a real field failure behind it, except where explicitly noted; the .NOTES block in scripts/WinRE.ps1 carries the “Critical lessons (do not regress)” list. They are the detailed enforcement of Rules 1–4 above.
A single adequate type-coded recovery partition on the OS disk is the target layout. Fast-path and enable-only decisions require current layout assessment. Cleanup retains the existing VM/topology, bus, virtual-media and 2 GiB safety boundaries, so protected secondary-disk partitions may remain. A Recovery/WINRE label alone never authorizes reuse or deletion. OS-fallback remains a constrained remediation state.
Failed transitions attempt size restoration and report partial rollback honestly. Post-shrink failures use Remove-OrphanPartition or Restore-OSPartitionSize as appropriate. A failed restore sets $Script:GeometryRestoreFailed; the operation cannot claim a verified final layout. The pending journal and independent WIM survive. Restoring C: or an anchor’s size cannot recreate a deleted recovery partition or its contents.
Deployment state never invents manager ownership. A newly serviced managed candidate requires successful injection and verification. Copy-only relocation of an already positively owned current image can retain its ownership without servicing. Preserved foreign bytes use ForeignSourceAcceptedHash and never become CurrentImageHash through acceptance or relocation. Completion verifies the actual route, bytes and capacity before persisting completed state.
The pipeline stops before deployment when injection fails. If $Script:ImageInjectionComplete = $false after Step 3, the script exits with EXIT_WARNING before Step 4 (dism /Export-Image), before Step 5 (partition work), before Step 6 (deployment), and before any reagentc call. The abort branch also removes base.wim and winre_optimized.wim from WorkDir so the next run’s Step 2 can rename cleanly; this is the v44 patch 3 fix.
Component cleanup runs on the mounted image before export, and is non-fatal. dism /cleanup-image /StartComponentCleanup /ResetBase runs inside Step 3 after successful injection and before the dismount, gated on $Script:ImageInjectionComplete. The size benefit is not realised until Step 4’s dism /Export-Image writes a fresh .wim. ResetBase failure is logged and the pipeline continues. ResetBase makes the image unserviceable for rollback, which is acceptable for a recovery image that is rebuilt from source whenever the DesiredStateId changes. This is the v44 patch 2 addition.
BitLocker is never assumed Off, and the target volume is prepared before reagentc is called. This is the v43 patch 5 (further revision 5) policy. It replaces the OS-volume-gate policy of the earlier further revision, which the 2026-09-29 field test disproved: reagentc’s BitLocker check is on the target volume, not on C:. The invariant is now:
The target recovery partition must be unencrypted by the time reagentc /enable runs. Set-RecoveryPartitionReadyForWinRE enforces this. It queries the target’s BitLocker state with Test-VolumeEncrypted (the tri-state classifier). If the target is confirmed unencrypted, it returns immediately. If it is encrypted or actively encrypting, it runs manage-bde -off against the target and polls at 5-second intervals up to a 300-second timeout. It is called at every point where reagentc will be invoked.
The OS-fallback path is the only path that depends on C:’s BitLocker state. In the OS-fallback case the target volume is the OS volume, and reagentc will refuse to enable WinRE on an encrypted OS volume. The OS-fallback gate therefore checks C:’s VolumeStatus before deploying the WIM and defers with EXIT_WARNING unless it is FullyDecrypted. It never modifies C:’s state. The gate uses Test-VolumeEncrypted (not Get-BitLockerVolume directly) and requires the result to be exactly $false.
Suspension is not used. The v43 patch 5 function Suspend-BitLockerForWinRE was deleted. Suspension does not prevent Device Encryption from claiming a newly created partition. Decrypting the target in place is the mechanism the policy uses; the 2026-09-29 test confirmed that a partition claimed by Device Encryption does not re-encrypt after manage-bde -off completes.
The target may be an existing encrypted recovery partition. Find-SuitableRecoveryPartition no longer rejects encrypted candidates, because the helper will decrypt them.
New recovery partitions are created with the recovery type code already applied. New-Partition passes -GptType {de94bba4-06d1-4d40-a16a-bfd50179d6ac} (GPT) or -MbrType 0x27 (MBR) at creation time (v43 patch 5). This closes the window between New-Partition and Set-RecoveryPartitionAttributes during which the partition is a plain Basic Data partition. Set-RecoveryPartitionAttributes still runs after format to apply the GPT attributes (0x8000000000000001 — PLATFORM_REQUIRED + NO_DRIVE_LETTER); it is idempotent on the type code.
Self-referential file operations are guarded. Any block that deletes a file and then writes to the same path (or copies another file onto it) checks first that the source and destination are not the same file (by [System.IO.Path]::GetFullPath). This guards against the v42 “fallback copy ate its own source” bug.
Checkpoint advancement requires injection success. A checkpoint that says “step 3 completed” is only written when image injection actually completed. This is v43 patch 4’s fix.
The Audit Mode / OOBE / sysprep guard runs before any state-modifying action. The guard reads ImageState at startup and defers unless the value is absent or IMAGE_STATE_COMPLETE. This is the highest-priority guard in the script after the program lock and the elevation guard, and it runs before the drive-letter cleanup, the pending-reboot block, the classifier, and any partition work.
A reagentc /enable failure on the enable-only path does not fall through to full update, and does not loop forever. When the deployment is current and only the enable step fails, the enable-only path increments the state-file counter and exits EXIT_WARNING without attempting a rebuild. After three consecutive failures the loop-breaker fires and exits EXIT_FATAL, requiring manual intervention.
The state file never records DeployedDiskNumber or DeployedPartitionNumber as 0 for OS-fallback states. The Write-WinREState parameters are [object] typed and the conditional that populates the state file checks $null -ne before the integer comparison, so a $null argument does not coerce to 0 and write a misleading "DeployedDiskNumber": 0 into the state file. This is the v44 patch 1 fix.
The script holds an exclusive program lock for its entire duration, from just after the startup banner to the last cleanup step in the finally block. The lock is a FileShare.None handle on C:\ProgramData\OEM\Logs\WinREManager.lock, enforced by the Windows kernel. The handle is released automatically when the process exits. The lock is deliberately not acquired under -DryRun. Failure to acquire the lock for any reason other than contention is non-fatal. The lock is released last in the finally block. This is the v44 patch 4 addition. The v49 temporary resume task does not participate in the lock directly; a resume run acquires the lock normally and is serialized against a scheduled run by the same lock.
The offline fallback trusts the state file’s stored DesiredStateId directly, without recomputing it from cached inputs. When the manifest fetch fails after its retry budget, the script sets $Script:offlineFallback = $true, reads the state file’s stored DesiredStateId, and skips the OEM pack resolution, VMD detection, and required-driver resolution. The local safety checks remain fully enforced. The v44 patch 5 residual — a machine whose hardware changed while offline could take the fast path with a stale DSI — was closed in v48 patch 1 by the LocalInputsId field, which the offline path recomputes from the current machine and compares against the stored value. This is the v44 patch 5 addition, updated by v48 patch 1.
VMD hardware presence detection is fail-closed. When the manifest is available, the script determines VMD hardware presence by enumerating present PnP devices that match the union of the manifest’s requiredDevices patterns. If Get-PnpDevice reports an error during the query, the run treats VMD presence as indeterminate rather than as absent, and defers with EXIT_WARNING before committing any state. This is the v44 patch 6 addition.
Only a type-coded recovery partition on the OS disk is authoritative. Every decision the script makes about recovery partitions — reuse, fast-path counting, active-location classification, final verification, deletion authorization, stray cleanup — reads from a single rule: the partition must carry the recovery GPT type GUID {de94bba4-06d1-4d40-a16a-bfd50179d6ac} or the MBR type code 0x27. This is the v44 patch 7 addition.
The shrink runs in the reversible window, before route destruction. The v45 patch 1 reorder moves the pre-shrink (with its sleep and defrag retries) ahead of reagentc /disable and ahead of any partition deletion. A shrink failure at this point returns Deferred with the old route intact. The pre-shrink free-space check is fail-closed: if the resize target’s volume cannot be read, the run defers rather than proceeding on the assumption that the partition supported-size preflight is sufficient. As of v48 patch 1 the resize target is C: on the ordinary path, or the validated intervening anchor — typically D: — on the C: | D: | Recovery path; the deferral reason names which (OS partition (C:) or anchor partition (disk X part Y)).
The plan computes a single boundary; the recovery partition fills exactly the space between that boundary and C:’s end. The usable extent end is diskSize − 1 MiB; tailEnd is clamped to that value before aligning, on both branches (v46 patch 1). AlignedManagedExtentEnd = floor(tailEnd / 1 MiB) × 1 MiB; TargetRecoveryStart = AlignedManagedExtentEnd − B. C: is resized so it ends exactly at TargetRecoveryStart, and the recovery partition of size exactly B fills the space up to AlignedManagedExtentEnd. The whole-layout assertion (Assert-RecoveryPartitionLayout) re-queries the newly created partition and confirms identity, exact offset, size within one alignment block, no overlap with C:, C:-to-recovery gap within one alignment block, boundary-to-recovery gap within one alignment block (the boundary is C: on the ordinary path, the shrunk anchor on the intervening-anchor path), and end at the current plan’s own end ($plannedEnd), which equals AlignedManagedExtentEnd on the normal path and reflects the fallback geometry when the extension-failure fallback ran.
Post-delete extension has a safe fallback that prioritizes WinRE deployability over exact geometry. When the plan calls for extending C: into the space the old recovery partitions occupied, the extension runs after deletion. If extension fails, the script re-queries C:’s current end, computes the largest recovery partition that fits between the current C: end and AlignedManagedExtentEnd, and places the recovery partition there with a non-fatal warning. The v47 patch 2 addition sizes that partition to min(AvailableSize, 2 GiB): it fills the available extent in the common case (the surplus after a failed extension is typically a few hundred MiB, well under the ceiling) and only leaves a trailing unallocated extent when the surplus exceeds 2 GiB. The ceiling is what matters, not the plan’s bucket size.
The pre-shrink deferral marker suppresses retries only while the old route is verified functional. When Ensure-AdequateRecoveryPartition returns Deferred with RetrySuppressible = $true, the main flow writes C:\Recovery\OEM\winre_partition_deferred.json. On the next run, the marker is honored only if the old route is verified functional and the fast path would not fire.
A deletion failure restores the previous route when possible. The currently active recovery partition is deleted last, so a mid-loop failure leaves it available. On any deletion failure, the script restores C: to its original size and attempts Restore-PreviousWinRERoute. As of v46 patch 2, the two restores are reported separately: when the resize target’s geometry did not verify, the distinct reason recovery partition deletion failed; previous route restored but <resize-target label> geometry restore unverified is returned (the label is OS partition (C:) on the non-intervening path and anchor partition (disk X part Y) on the intervening-anchor path; v48 patch 1) and $Script:GeometryRestoreFailed is set.
The destructive sequence fails closed if the active WinRE route or the OS partition cannot be resolved. Two guards, both v46 patch 2. The pre-deletion resolver guard refuses the sequence if WinRE was Enabled and its registered location cannot be resolved to a partition. The layout-assertion fail-closed branch refuses the layout if Get-OSPartition returns nothing. Both refuse to proceed when the state cannot be established, rather than proceeding on the assumption that the missing state is benign.
Build numbers are logged for evidence; one of the three is also read by the force-upgrade detection. Every run logs three values: the registered WinRE version, the source WIM’s build, and the post-deploy WIM build. None of the three enters the DesiredStateId. The registered WinRE version and the post-deploy WIM build are logged-only. The source WIM’s build is also read by the force-upgrade detection, which compares the WIM’s build number against the running OS’s family (Win10 vs Win11) and forces a rebuild when the deployed image is from the wrong OS family; that decision point is the reason the source WIM’s build is captured on every pass, not only when a rebuild is already known to be required. The purpose of the log lines themselves is empirical: over time the fleet logs answer whether Windows Update is updating the registered WinRE between runs, and whether any rebuild replaces a newer registered image with an older one. This is the v46 patch 2 addition.
The rebuild seed is normalized to zero third-party drivers before the current recipe is injected, unless the source-ownership classification preserves it as a foreign-with-drivers source. The strip stage runs between mount and injection, and it is a hard gate: any failure to enumerate, remove, or re-verify rejects the candidate before any injection, export, partition work, or reagentc call. Enumeration failure is never interpreted as zero drivers. The pre-strip inventory is logged for field evidence. This is the v47 addition, extended by the v49 classification.
The base WIM is sourced by a regression-guarded preference order. Registered wins only when its servicing metadata is at least as new as the LKG; the LKG wins when it is provably newer or when the registered image is unusable; GitHub is the last resort. The LKG is trusted only when its SHA256 matches state.CurrentImageHash, whether the file is at the canonical path or discovered by hash on a type-coded recovery partition (v48 patch 1). An indeterminate metadata comparison defers to the LKG. A WIM found by the loose fallback-discovery path is not a source-selection candidate. This is the v47 addition, extended by v48 patch 1’s LKG-by-hash discovery.
The registered-source fingerprint is re-read immediately before whichever reagentc /disable this execution reaches first. A change in location, version, or WIM hash aborts before /disable. The detector is a race detector, not a lock. Both /disable sites are wrapped. This is the v47 addition.
The WIM_READY checkpoint is bound to the source-content hash that produced the staged WIM. On resume, the recorded source hash must still match an available source (the registered WIM or the LKG) or the checkpoint is invalidated. Legacy four-field checkpoints, and checkpoints prepared from a GitHub cold-start, are invalidated on first resume. When a resume from Step 3 needs to bind the source at Step 4, the source hash is recovered from base.wim. This is the v47 addition.
The needInject trigger is metadata-based, not WIM-hash-based. The currently-registered WinRE’s DISM servicing metadata (Version + SPBuild) is compared against a DeployedWinREMetadata field recorded in the state file at the end of every successful deployment. Drift forces a rebuild; stability stays on the fast path. The WIM hash is no longer a rebuild trigger, though it remains in use for LKG validation, copy verification, and the pre-/disable race detector. A registered image whose metadata cannot be read forces a rebuild. A state file whose DeployedWinREMetadata is absent forces a rebuild. This is the v47 addition.
Every source image carries an ownership class, and the strip-and-reinject pipeline runs only when the class permits. The four classes are Manager-Owned, Manager-Lineage, Foreign-No-Drivers, and Foreign-With-Drivers. A Foreign-With-Drivers source is preserved as-is: the strip stage is skipped and the current recipe is not injected. The other three classes proceed through the strip and injection as in v47/v48. The classification gate narrows the v47 strip-everything policy to sources the manager itself deployed or in-box images with no third-party drivers. This is the v49 addition.
A candidate image that would inject a storage driver older than one already present in the mounted image is discarded. The never-downgrade check runs after injection is confirmed complete, before ResetBase and before the applicability gate. Each storage-class driver in the final image is compared against the pre-strip inventory by INF basename; if any post-injection driver would be older, the whole candidate is discarded — the mounted image is dismounted with -Discard, the source is preserved, the state file records ForeignSourceAcceptedHash, and patch 5 independently evaluates layout remediation. The check does not apply to a source classified as Foreign-With-Drivers, where the recipe is not injected. This is the v49 addition.
A candidate image in which any present SCSIAdapter-class device has no matching INF is refused rather than deployed. The pre-deployment storage-applicability gate runs inside Step 3, after injection is confirmed complete, before ResetBase and before the dismount. It is the last refusal before deployment. Software and virtual controllers (InstanceId starting with {GUID}\ or SWD\) are excluded from the device enumeration. The gate has never fired in the field. This is the v49 addition.
The manager refuses to run destructive operations under the native-boot VHD/VHDX topology. The native-boot VHDX fail-closed gate refuses when the OS disk’s bus type is File Backed Virtual and at least one other disk is on a physical bus — the topology in which the running OS disk is a VHD/VHDX stored on a host physical disk. A hypervisor guest whose entire storage stack is virtual is not refused. The gate runs as a startup refusal, before any partition or WinRE change. It is a stable deferral, and it has no -DryRun carve-out. This is the v49 addition.
A verified resume task can retry an interrupted Repair or Restore at boot or within the hour. Live Repair and Restore attempt registration when a script path and safe staging are available. The finally block merges the script persist flag with the compiled Ctrl+C probe; pending work and covered failures retain the hook, while verified completion permits task/staging cleanup. A hard kill or reboot bypasses finally, leaving an already registered task in place. Registration and cleanup are checked operations, not guarantees that a task exists on every machine. See the current persist contract.
The backup and restore actions do not modify the deployment identity. -Action Backup captures a byte-for-byte copy of the currently registered WinRE WIM plus a sidecar backup.json; it does not write to the state file and does not change the DesiredStateId. -Action Restore writes a previously captured WIM back to the currently registered route transactionally; it does not create a new partition or invent a replacement route. It deletes the state file, checkpoint file, and partition deferral marker on success, so the next repair run re-evaluates the machine from a clean state. Both actions are standalone commands, not pipeline stages. This is the v49 addition.
A safety check that cannot complete is never interpreted as a safe result. Every safety guard either positively confirms the safe state or refuses. This is the v49 patch 2 addition; it was made explicit after a review identified the same defect shape in four separate guards: the native-boot VHDX disk enumeration, the post-deletion partition verification (two call sites), the WinRE status determination (two call sites), and the storage-controller enumeration. Each guard’s underlying query could fail in a way that produced the same in-memory result as a successful-but-negative query, and the guard then proceeded as if the safe state had been positively confirmed. Each site was corrected to fail closed independently. The principle is stated in the production script’s .NOTES block as the “Fail-closed principle”, so future safety checks are written against it from the start.
The manager config file is trusted only when its containing directory, that directory’s immediate parent, and the config file itself all pass Test-PathTrustedForSystem. The check verifies the ACL owner (SYSTEM or Administrators) and that no Allow ACE grants a modify-capable right to a principal outside SYSTEM, Administrators, or TrustedInstaller. The modify-capable mask is split by object class (on a directory: Delete | DeleteSubdirectoriesAndFiles | TakeOwnership | ChangePermissions; on a file: those plus WriteData | AppendData). Both the read path (Get-ManagerConfig) and the write path (Set-ManagerConfig) perform the check and fail closed on ambiguity - a missing directory, an unreadable ACL, an unknown owner, or an unresolvable owner SID. An untrusted or unparseable config is treated as the empty default, so a config read failure never blocks a backup and never causes a restore or cleanup to assume a root exists. The write path additionally checks the ancestors before creating the directory, so a pre-created attacker-owned parent is caught before the manager adds a child to it. Two levels of directory are checked, not one: an attacker who owns the parent can delete-and-recreate the child to steal ownership of that child between runs. The file-level check closes a pre-creation attack a directory-only check would not. The v50 patch 1 form checked only the owner; the v50 patch 3 form extends the check to the effective DACL mask and the config file itself. The v50 patch 4 form additionally skips InheritOnly ACEs: those apply only to children, not to the object being checked, and treating them as effective on the object itself is a false-positive source on the stock C:\ProgramData ACL, which carries an inherited CREATOR OWNER ACE with (OI)(CI)(IO)(F). CREATOR OWNER (S-1-3-0) and CREATOR GROUP (S-1-3-1) are deliberately not added to the trusted SID list — the fix is to skip ACEs that do not apply, not to trust their principals generally. The identical logic exists in three copies (WinRE.ps1’s Test-PathTrustedForSystem, Cleanup-Backups.ps1’s local copy, and the shared _T helper in WinRE-Manager.cmd’s elevated payload), and any future change to the helper — owner SIDs, trusted ACE SIDs, per-Kind modify-capable mask, the InheritOnly skip, or the fail-closed behaviour on unresolvable SIDs — must land in all three copies in the same PR. The three-copy invariant is restated as a maintenance commitment in CONTRIBUTING.md.
The temporary resume task executes a staged copy of the running script, placed in a SYSTEM/Administrators-owned location. Register-ResumeTask stages the running script to C:\Recovery\OEM\Resume\WinRE.ps1 under an explicit DACL (SYSTEM and Administrators FullControl, inheritance disabled), byte-verifies the copy against the source, re-verifies the staged file and its directory with Test-PathTrustedForSystem, and registers the task against the staged copy. Staging failure at any step (staging-directory creation, stale-directory clear, script copy, hash verification, or the final trust check) is non-fatal: the repair pipeline proceeds without the self-healing hook. The staging directory is removed on clean terminal exit, at the same point the task is unregistered, so the two share a lifetime. A self-staging case (the resume task firing and re-invoking the script from the staged path) is detected and short-circuited. The residual - a non-admin who modifies the running script before this elevated process stages it - is not a new exposure: the process is already executing that script elevated. This is the v50 patch 3 replacement for the v50 patch 1 protected-path guard (and for the v50 patch 3 first-revision three-path check that briefly replaced it), both of which shipped a false positive on every development checkout. The v50 patch 4 release hardens the staging lifecycle in three ways. First, Initialize-ResumeScriptStaging and Remove-ResumeScriptStaging now call Remove-StagingDirectorySafely, which refuses reparse points, subdirectories, unexpected content, or a non-directory path; enumerates the expected children; and deletes them individually rather than calling Remove-Item -Recurse on the tree. This avoids recursive deletion of an unexpected tree; isolated Windows PowerShell 5.1 junction probes preserved their target files and did not establish the proposed target-deletion exploit. Second, a warn-only parent-chain trust check logs a WARN when C:\Recovery\OEM or C:\Recovery fails Test-PathTrustedForSystem but does not refuse registration; a strict check would disable self-healing on machines where the parent ACL is imperfect. The residual risk — a local user with Modify on the parent chain can replace the staged directory between task registration and task execution — is documented in SECURITY.md and accepted rather than closed. Third, two script-scope flags track staging safety: $Script:ResumeStagingTaskInvalid (set at entry to the staging touch-region, cleared only on a verified success return) and $Script:ResumeTaskCompromiseUnresolved (set only when $Script:ResumeStagingTaskInvalid is set and the existing task’s removal cannot be positively confirmed via Get-ScheduledTask enumeration); when $Script:ResumeTaskCompromiseUnresolved = $true, Main exits $EXIT_FATAL before any destructive repair work. Registration failure on an otherwise-safe staging path preserves the verified staged copy so a prior task is not orphaned.
The empty parent directory left behind by workspace cleanup is removed, but only when its leaf name matches the workspace convention. After Remove-EmptyWorkspaceParent removes <volume>:\Temp\WinREWork, the parent <volume>:\Temp is removed only when its leaf name is exactly Temp, it is completely empty, and it is not a drive root. An arbitrary empty parent directory is never removed. Cleanup-Backups.ps1 applies the same pattern to the backup hierarchy (C:\Backup\WindowsRE and its parent C:\Backup), with the additional constraint that the child’s leaf must match the timestamped-backup convention (yyyy-MM-dd_HHmmss) before removal. Remove-IfEmptyDirectory is the single gate for the cleanup helper’s empty-directory removals: it refuses an empty path, a drive root, a non-container, a reparse point, an unreadable directory, a non-empty directory, or an unremovable directory. This is the v50 patch 1 addition.
The backup destination is preflighted for free space before the destination directory is created. Invoke-BackupAction verifies that the destination volume has room for the WIM plus a 100 MiB margin before creating the destination directory or starting the copy. The check runs after the source WIM’s size and hash are known. If the destination drive letter resolves to a local volume, Get-Volume provides the free-space value; if it is a mapped network drive (an MSFT_Volume the Storage module cannot see), Get-PSDrive provides it. If neither resolves, the check is skipped and the copy proceeds with any space-related failure surfaced by Copy-Item. A drive letter that resolves to nothing is a genuine error and the backup aborts before any file is written. This is the v50 patch 1 addition.
A mapped drive-letter backup path is resolved to its UNC form before being written to the manager config. Add-ManagerBackupRoot resolves a mapped drive-letter path to its UNC form via Get-PSDrive.DisplayRoot before storing the root in manager.json. A mapped drive is a session-specific DOS device mapping; a later run may map the same letter to a different share, making the catalogue entry point at the wrong location. The UNC form is stable. If DisplayRoot is empty — a local drive, a subst, or a mapping not visible to the elevated process — the drive-letter path is kept, which is no worse than the pre-v50 behaviour. This is the v50 patch 1 addition.
The source-ownership classifier accepts a historical image hash and a historical lineage identifier read from a stale state file across a version boundary. The Manager-Owned classification matches the staged source hash against the current state.CurrentImageHash or a historical CurrentImageHash obtained via the new Get-StaleWinREStateFields helper. The Manager-Lineage classification requires the marker’s LineageId to match a known current or historical lineage identifier; a marker whose LineageId matches no known value is treated as absent. The historical read does not make the stale state operationally authoritative, does not enter any gate other than the source-ownership classifier, and does not affect the fast path’s DesiredStateId check. Without the bridge, the ScriptVersion bump from 49 to 50 would break the source-ownership classification for exactly the machines the bump is meant to reach: a machine whose state file was written by v49 would have a CurrentImageHash that no longer matches the v50 run’s expectation, and its own prior deployment would be reclassified as foreign. Get-StaleWinREStateImageHash is replaced by Get-StaleWinREStateFields. This is the v50 patch 1 addition.
The non-OS-disk recovery-partition sweep is suppressed under a detected or indeterminate hypervisor, and mounted VHD/VHDX disks are preserved individually. Remove-StrayRecoveryPartitions calls Test-RunningInVirtualMachine before its disk loop. When the helper returns $true (a known hypervisor signature matched against Win32_ComputerSystem Manufacturer/Model) or $null (indeterminate; fail closed), the entire sweep is skipped and any recovery partitions on non-OS disks are preserved. When the sweep does run — physical machine, no hypervisor signature — any non-OS disk whose BusType is File Backed Virtual is preserved individually: a mounted VHD/VHDX may contain another installation’s recovery environment. The OS-disk repair path is unaffected by either suppression: it operates only on the OS disk. This is the v50 patch 2 addition.
SCSI is admitted to the workspace bus allowlist only for the running OS volume. Get-WorkDirCandidates accepts the running OS volume’s SCSI bus (the common topology inside a Hyper-V guest) while continuing to exclude non-OS SCSI volumes, because a host physical disk passed through to a guest can also report SCSI and the workspace holds temporary servicing files rather than deletion targets. This is the v50 patch 2 addition.
The non-OS-disk recovery-partition sweep positively verifies each deletion with a terminating re-query. After Remove-Partition returns, the function re-queries the target disk with Get-Partition -DiskNumber $disk.Number -ErrorAction Stop and confirms the target partition is absent before recording the deletion as confirmed. A query failure is treated as not-confirmed-deleted (fail closed): the partition is added to the failed list, $Script:nonFatalWarning is set, and the function returns $false. This closes the same class of fail-open the v49 patch 2 changes closed on the main destructive deletion loop, extended to the non-OS sweep. This is the v50 patch 3 addition.
The GitHub base-WIM cold-start rejects an empty archive-parts list with a named reason. Get-GitHubBaseWinRE enumerates the folder’s contents and filters for the Winre.7z.NNN parts. If the folder is reachable but its contents no longer match the expected filename pattern, the function logs Get-GitHubBaseWinRE: no winre.7z.NNN archive parts found at <url> and returns $false rather than indexing $parts[0] on an empty array. This is the v50 patch 3 addition.
Recovery-volume drive-letter normalization is scoped to the OS disk and fails closed on a provider error. The block that removes drive letters from volumes labelled Recovery or WINRE requires the volume’s partition to be on the OS disk, matching the same OS-disk scope the v50 patch 2 sweep suppression boundary uses. The \Windows presence check is wrapped in a try/catch that logs the failure and skips removal for that volume; an indeterminate result is treated as “do not remove” rather than “not a system volume”. Adding -ErrorAction SilentlyContinue would have been worse than the try/catch: $false on error would pass the -not check and remove the letter on a volume whose contents were never verified. This is the v50 patch 3 addition.
Add-ManagerBackupRoot preserves volume roots and does not append a trailing separator when the relative path is empty. [System.IO.Path]::GetFullPath('E:\').TrimEnd('\\') returns E:, which is drive-relative in PowerShell and does not match the mapped-drive resolution regex (which requires a backslash after the colon). The function preserves a path whose full form is exactly a volume root (X:\ or X:) and trims trailing separators only from ordinary directory paths. The mapped-drive UNC conversion appends the relative path only when the relative path is non-empty, so a bare volume root stores \\server\share rather than \\server\share\. This is the v50 patch 3 addition.
Workspace volume enumeration is fail-closed with a named reason. Get-WorkDirCandidates wraps its Get-Volume call in a try/catch that logs a named reason and returns an empty candidate list, so the caller defers cleanly with the standard “no eligible fixed NTFS workspace” message rather than aborting FATAL. The log line makes the enumeration failure distinguishable from “enumeration succeeded but found nothing eligible”. This is the v50 patch 3 addition.
Partition-plan size arithmetic uses -gt comparisons on [int64] operands, never [Math]::Max/Min with mixed Int32/Int64 arguments. PowerShell binds the literal 0 in [Math]::Max(0, $delta) as Int32 and selects the Max(Int32, Int32) overload, then converts $delta to Int32 for the val2 parameter — which throws before Max can run when $delta is outside the Int32 range (about 2.1 GB in either direction). The field failure: Surface Pro 3, 2026-10-16, three type-coded recovery partitions on disk 0, about 4.9 GB extend delta, fatal Cannot convert argument "val2", with value "-5262802944", for "Max" to type "System.Int32". Every subsequent invocation crashed identically, defeating the self-healing resume task. The fix in Get-PartitionPlan replaces [Math]::Max(0, ($osSize - $plannedOSSize)) and [Math]::Max(0, ($plannedOSSize - $osSize)) with explicit if ($x -gt $y) { [int64]($x - $y) } else { [int64]0 } forms. The harness guards the fix with a source-pattern assertion (check 21) and a behavioral Int64 regression test (check 22). This is the v50 patch 4 addition.
The twenty-seven most consequential decisions in the whole script, presented without any ranked order, are:
Shrink-first replacement (v45 patch 1). The risky operation — the shrink — runs in the reversible window, before any partition is destroyed. A failed shrink now returns Deferred with the old route intact, closing the v44 residual for the shrink trigger. What changed is when each step runs and what happens if it fails.
Single-boundary geometry with whole-layout assertion (v45 patch 1). The planner computes a target boundary rather than a shrink amount, and the post-creation assertion re-queries the partition to confirm it landed exactly where the plan intended.
The plan clamps tailEnd to the disk-end reserve before aligning (v46 patch 1). The disk-end reserve is a fixed Windows convention: the last 1 MiB of the disk is not addressable for partition layout. The clamp moves the plan to the boundary the post-delete check would accept on the same layout.
Post-delete extension uses a safe fallback (v45 patch 1; ceiling-fill in v47 patch 2). When the plan calls for extending C: into the space the old recovery partitions occupied, extension runs after deletion. If extension fails, the safe fallback places the recovery partition at the current C: end, sized to min(AvailableSize, 2 GiB), and continues. Exact geometry is a goal, not a reason to leave WinRE disabled.
Dedicated recovery partition is the primary objective; OS-fallback is a last resort. Read-only plan and capacity checks precede mutation. A failed pre-shrink preserves the old route and defers. Only actual dedicated creation failure, verified geometry, fully decrypted C: and no acceptable retained route permit checked OS-fallback; that returns warning and keeps the pending operation.
Retries follow present conditions rather than DSI alone. A Capacity marker is diagnostic and does not suppress fresh assessment. Execution failures receive a bounded one-hour delay. Matching deployment inputs never make OS-fallback a healthy final layout, and clearing a marker does not discard an unresolved operation’s protected image.
The BitLocker policy targets the volume reagentc will enable, not the OS volume. The enable-only and dedicated-partition paths proceed regardless of C:’s BitLocker state, because reagentc does not care about C: — it cares about the volume it is being asked to enable WinRE on. The only path that gates on C:’s state is the OS-fallback path, and it does so for a specific reason: there the target volume is C:.
The Audit Mode guard takes priority over everything except the program lock and the elevation guard, including the BitLocker decision. When ImageState is not IMAGE_STATE_COMPLETE, the script defers before it has fetched the manifest, resolved the OEM pack, computed the DesiredStateId, or read the state file.
The enable-failure counter introduces a bounded retry for the enable failure. Before the counter, a generic /enable failure on the enable-only path fell through to full update and eventually exited EXIT_FATAL at the final-verification block. That is a silent loop. The counter turns it into a bounded retry.
The DesiredStateId is a deployment-input fingerprint, not a hardware fingerprint. The ID should change whenever the inputs that determine the deployed WinRE artifact change, and should not change merely because unrelated machine state changes.
Component cleanup is applied to the mounted image, not to the export output. ResetBase reduces the WinSxS component store inside the mounted image; the existing export is what materialises the savings on disk.
The single-instance guarantee uses a file handle, not a named mutex. A FileShare.None handle has no DACL dependency, is released on process termination regardless of how the process terminated, and the file’s presence on disk is not the lock — the open handle is.
Offline fallback uses stored DSI with separate local checks. Recomputing the full DSI would require unavailable manifest/OEM-map inputs. The locally computable LocalInputsId detects hardware/OS/CPU drift when the stored field is present, while live registration, image metadata and dedicated-layout checks still apply. A legacy state without LocalInputsId logs that limitation; offline completion reports warning.
VMD hardware presence detection is fail-closed. The alternative — treat an enumeration error as “no VMD hardware” — was the pre-patch-6 behavior. It is a wrong-question problem: the check was answering “did the enumeration return any matching devices?”, but the downstream decision needed the answer to “does this machine have VMD hardware?”.
The type code is the recovery partition’s identity; the volume label is only a hint. Before v44 patch 7, the classifier and the fast-path count accepted either the type code or the volume label as evidence that a partition was a recovery partition. That was a wrong-question problem: the destructive path’s delete authorization had always required the type code, but the count and the classifier used the label OR the type code. Patch 7 unifies the question across all consumers.
The strip stage is a hard gate, and the fallback for a strip failure is deferral, not best-effort. If the strip cannot prove zero third-party drivers remain, the candidate is discarded and the machine’s existing recovery route is preserved. The alternative — inject on top of a partial strip, or accept enumeration failure as zero — would produce a WIM whose driver set is a function of the source image’s history rather than the current recipe, which is the lineage problem the strip is designed to solve. The candidate is disposable; the recovery route is not.
Source selection prefers the registered image; the LKG is the regression guard, not the default. The registered image is what Windows Update serviced most recently, so in the ordinary case it is the better source. The LKG is preferred only when it is provably newer by servicing metadata, or when the registered image cannot be read. This is the reverse of what a naive “always use the known-good copy” design would do, and it is the correct preference because the registered image is more current by construction; the LKG’s role is to catch the case where the registered image has regressed.
The pre-/disable recheck is a race detector, and it is not called a lock. Naming matters: a “lock” implies atomicity that the script does not have. The recheck detects a WU servicing event and defers; it does not prevent one. The residual microseconds between the recheck and /disable returning are accepted, because closing them would require moving the recheck inside the disable→enable window and lengthening that window, in violation of Rule 3.
The source-ownership classification preserves a foreign-with-drivers WIM as-is. The v47 strip-and-reinject policy assumed every source was either a manager-deployed image, a manager-lineage image, or an in-box WIM. The v49 classification narrows that assumption: a WIM that a vendor populated with its own third-party drivers is not normalized by the manager, because the vendor’s driver set — not the manager’s recipe — is the correct one for that source. The classification combines a third-party driver count (from the pre-strip inventory of the mounted image), a staged-source hash exact-match against state.CurrentImageHash for Manager-Owned, and a valid provenance marker whose LineageId matches the state file’s for Manager-Lineage. It does not consult the machine’s hardware. A misclassified source is deployed as-is, and the operator’s remedy is to make a manager-owned source available.
The never-downgrade storage-driver check compares versions after injection. A Windows Update-delivered storage driver can be newer than what the manifest or OEM pack resolves. The check prevents the manager from silently regressing the recovery environment’s ability to see the OS disk. It assumes a monotonically-increasing version scheme, which is the vendor’s convention but not a documented guarantee; a vendor that reverses or resets version numbering would defeat the check.
The pre-deployment storage-applicability gate is the last refusal before deployment. The gate reads the candidate image’s INFs and the machine’s present SCSIAdapter-class devices, and requires every device to have at least one matching INF. It runs on every candidate the pipeline is prepared to deploy; it does not run on a preserved Foreign-With-Drivers source, inside the servicing pipeline; patch 5 separately checks applicability before preserved-image relocation. The gate is a narrowing, not a proof — a machine whose present storage controller is not enumerated (hidden by policy, in an error state, or transiently unreadable during the PnP query) would not be checked by the gate and could pass with a candidate that lacks that controller’s INF.
The native-boot VHDX fail-closed gate refuses destructive operations under a topology the pipeline was not built for. The alternative — proceed and hope the partition operations work — would leave the machine without a working recovery route on a failed partial sequence. The gate is a stable deferral, and it has no -DryRun carve-out.
The temporary resume task is a per-run safety net, not machine state. Every Repair or Restore run registers it; it is deleted on clean completion and preserved on interruption. The task does not participate in the program lock directly — a resume run acquires the lock normally. Under $PSCommandPath-less invocation, the task is not registered. The alternative — rely on the operator to re-run the script after an interruption — leaves an interrupted partition sequence in whatever state the interruption left it, which is exactly the corner Rule 2 cannot guarantee.
A safety check that cannot complete is refused rather than interpreted as a safe result. The fail-closed principle was made explicit in v49 patch 2 after a peer review identified the same defect shape in four separate guards. Each guard’s underlying query could fail in a way that produced the same in-memory result as a successful-but-negative query, and the guard then proceeded as if the safe state had been positively confirmed. The alternative — treat a failed query as a permissive result — was the pre-patch behaviour. The corrective principle is stated in the production script’s .NOTES block so future safety checks are written against it from the start.
The manager config file, its containing directory, and that directory’s immediate parent are trusted only when the ACL owner is SYSTEM or Administrators and no Allow ACE grants a modify-capable right to a principal outside SYSTEM, Administrators, or TrustedInstaller. The stock ACL on C:\ProgramData grants Authenticated Users the ability to create subdirectories, and a directory created by a non-admin principal is owned by that principal. Without the two-level directory check plus the file-level check, an attacker could pre-create C:\ProgramData\OEM\WinRE-Manager\manager.json under their own account and inject a BackupCatalog.Roots catalogue that points at a location the operator does not control; a later Cleanup helper invoked under SYSTEM would delete files under the attacker’s chosen path, or a later Restore would read from an attacker-supplied location. The two-level directory check catches both the initial pre-creation attack and the delete-and-recreate swap: an attacker who owns the parent can delete-and-recreate the child to steal ownership of the recreated directory between runs, so checking only the immediate parent is bypassable. The file-level check closes the case a directory-only check would not: a non-admin who pre-created the file inside a SYSTEM-owned directory. The mask is split by object class (on a directory WriteData means only create-new-file and AppendData means only create-new-subdirectory, not modify-existing; on a file both are content-modify rights), so including them on directories would false-positive on the stock C:\ProgramData ACL that grants BUILTIN\Users a container-inherited (I)(CI)(WD,AD,WEA,WA) ACE. This is the v50 patch 3 form of the check.
A mapped drive letter in the backup catalogue is a session-scoped alias, not a location. A mapped drive is registered with the Lanman redirector and lives in the DOS Devices namespace, not in the Storage module’s volume list. A subsequent logon may map the same letter to a different share, or not map it at all, and a mapped letter is never visible to a different user or a different session. The UNC form is stable across logons and share remappings. Storing the UNC form in manager.json means a Restore or Cleanup on a machine where the mapped letter has moved still resolves the location the operator originally chose.
The resume task executes a staged copy of the running script, not the script’s original path. The v50 patch 1 protected-path guard refused to register the task whenever the script lived in a directory a non-admin could write. That guard (and the v50 patch 3 first-revision three-path Test-PathTrustedForSystem check that replaced it) shipped a false positive on every development checkout: any script running from a path a non-admin could write was refused, so an interrupted run (WinRE disabled, old recovery partition deleted, deployment incomplete) had no automatic recovery hook. The v50 patch 3 staging design preserves the security property the guard aimed at - the SYSTEM task’s execution target cannot be modified by a non-admin after staging - without the false positive. The running script is staged to C:\Recovery\OEM\Resume\WinRE.ps1 under an explicit DACL (SYSTEM and Administrators FullControl, inheritance disabled), byte-verified against the source, re-verified with Test-PathTrustedForSystem, and the task is registered against the staged copy. The staging directory is removed on clean terminal exit, at the same point the task is unregistered. The residual - a non-admin who modifies the running script before this elevated process stages it - is not a new exposure: the process is already executing that script elevated.
The v43 patch 5 change was driven by two field failures on the same day, both on Windows 11 build 26200 with Device Encryption mid-encryption:
VolumeStatus=EncryptionInProgress at 73.6% when the script ran.Both machines lost their dedicated recovery partition and had WinRE disabled. The recovery procedure is documented in troubleshooting.md.
After the further revision landed, two more Dell machines ran against a mid-encryption state:
The further revision 5 change to target-volume-based preparation was driven by a different field observation, made on the same day:
FullyEncrypted/no-protectors state, reagentc /enable against a dedicated recovery partition succeeded while reagentc /enable against the OS volume failed on the same machine in the same session. This is the observation that inverted the policy.The further revision’s Audit Mode guard was motivated by a separate field case:
reagentc /enable failed with 0x4c7 on two consecutive runs, and the state file recorded the deployment as complete. After the user completed OOBE and ran reagentc /enable manually it succeeded on the first attempt with the same WIM.The v44 patch 4 field observation:
WinRE.ps1 processes ran simultaneously on the same machine, one exiting on Cannot rename because item at 'C:\Temp\WinREWork\winre.wim' does not exist.The v44 patch 5 field observation:
FATAL ERROR: The remote name could not be resolved: 'gist.github.com' on a transient DNS failure.The v45 patch 1 field runs:
The v46 patch 1 fix was driven by the first v45 destructive-path failure on physical hardware, and verified by clean-path runs on two more machines:
DEDICATED.The v46 patch 2 changes were exercised on:
The v47 non-destructive paths were field-verified on:
Find-SuitableRecoveryPartition accepted the existing type-coded recovery partition and no partition work occurred; the pre-/disable race detector fired at the Step 5 site and confirmed the source was unchanged; reagentc /disable exit 0; WIM deployed with SHA256 verified; reagentc /setreimage exit 0; reagentc /enable exit 0; DeployedWinREMetadata: 10.0.26100.9545|9545 recorded; Operating mode: DEDICATED. Two subsequent fast-path runs on the same machine confirmed the metadata-based drift detector: Registered WinRE metadata: 10.0.26100.9545|9545; last deployed: 10.0.26100.9545|9545 — the anchor matched, $registeredSourceChanged stayed false, $needInject stayed false, no partition touched, no WIM mounted, no reagentc call. Runtime dominated by the driver-manifest fetch and Windows CIM/PnP enumeration, which together account for the ~13-second span between the System: and VMD hardware present: log lines. The v23 harness returned Passed 16, failed 0, skipped 0 (of 16) on the same machine.The v48 intervening-anchor path was field-verified on:
C: | D: | Recovery layout that motivated it. The anchor shrank by 200 MiB, the recovery partition was recreated at the planned offset, and the whole-layout assertion passed against the shrunk anchor. Operating mode: DEDICATED.The v47 and v48 field gaps. The v47 non-destructive paths are field-verified on the ASUS run above. The v47-specific code paths that have not been exercised on any storage, physical or virtual: the strip stage with a non-zero third-party driver set, the strip-failure abort path, the source-selection LKG and GitHub cold-start branches, the pre-/disable race-detector abort path, the metadata-triggered rebuild branch, the WIM_READY checkpoint save/resume, and the destructive partition paths under v47 (the existing recovery partition was reusable on the ASUS run, so Ensure-AdequateRecoveryPartition was never called). The v48 intervening-anchor happy path is field-verified, but the v48 multi-intervening rejection, the surplus rejection, the transactional WIM replacement’s rollback branch, the architecture gate on ARM64, and the intervening-anchor post-deletion failure behaviour have not been exercised.
The v49 field gap. The v49 release adds four pipeline refinements plus the backup / restore actions, the temporary resume task, and the rewritten wrapper. The current field-verification status, per CHANGELOG.md:
Foreign-No-Drivers branch (repeatedly, across the v49 development cycle) and in its Foreign-With-Drivers preserve branch on a real machine carrying a third-party driver (ASUS Zenbook 14 UX3405MA, 2026-10-09 — the machine preserved the source, recorded ForeignSourceAcceptedHash, and took the fast path on the subsequent run). The four-class test plan is documented in testing.md.The backup action was exercised end-to-end on 2026-10-11 on the ASUS PRIME H510M-D test machine (two consecutive runs, byte-for-byte WIM copy, SHA256 verification, sidecar written, exit 0). The restore action has not been field-verified: the two mid-transformation failure paths, the rollback-restore failure branch, and the wrapper’s backup and restore menu options with paths containing spaces are all pending exercise in the field. See the v49 Field verification section in CHANGELOG.md. The temporary resume task has been exercised on the clean-completion path (task registered and deleted), and its Ctrl+C preservation path has been verified on physical hardware (ASUS PRIME H510M-D, 2026-10-09); the other interruption classes - the outer catch, Invoke-RestoreAction’s three mid-transformation failure paths, hard kill, and reboot - have not fired in the field. The wrapper’s stable install location has been exercised on the install path, but not the copy-hash mismatch refusal branch.
The BitLocker failure is instructive because it was invisible to each function in isolation. Test-BitLockerProtected was correctly implementing the tri-state contract for the state it observed (ProtectionStatus=Off). Suspend-BitLockerForWinRE was correctly taking the “already off, no suspension needed” branch. New-Partition was correctly creating a partition. Set-RecoveryPartitionAttributes was correctly applying the recovery type GUID. Each function did exactly what it was written to do. The bug was in the composition: the two BitLocker functions queried a subset of the protection state that was insufficient evidence for the decision the downstream code made with the answer.
The shared shape. All of the documented failures have one property in common: each function or check was individually correct, and each was answering a question that was not the question the downstream code needed answered.
Test-BitLockerProtected asked “is C: protected?” when reagentc was asking “is the target volume unencrypted?”.DesiredStateId asked “has the hardware identity changed?” when the driver set could change without the identity changing.The corrective pattern is the same in every case: move the check from the state that is easy to query to the state that actually matters, and record enough about the deployment’s inputs that a divergence from the last known good state will be detected rather than assumed absent. That pattern is what the invariants in this document exist to enforce.
The v49 patch 2 fail-closed corrections are a related but distinct pattern. The shared shape above is about asking the right question; the fail-open class is about a query that failed being read as an answer. The corrective pattern there is the same principle stated as a rule rather than as an example: every safety check either positively confirms the safe state or refuses. A query that could not complete is not a query that returned a safe answer, and the guards must be written so that the two cannot be confused. See “The fail-closed principle (v49 patch 2)” above for the four corrected sites.
LocalInputsId field that closes the v44-v47 hardware-drift residual. v49 adds two optional state-file fields (ForeignSourceAcceptedHash, LineageId); v50 adds a separate machine-wide config file (C:\ProgramData\OEM\WinRE-Manager\manager.json) for durable settings that are not deployment identity. The backup sidecar lives in the operator’s backup directory and is not part of the deployment identity.