Files
rust-discovery/deploy/windows/Install-ClosedControlSuccessor.ps1
2026-11-16 22:46:30 +01:00

244 lines
24 KiB
PowerShell

#requires -Version 5.1
#requires -RunAsAdministrator
# One fixed S2 development-maintenance transition, not an updater/job/recovery API.
# No SQLite connection, row rewrite, clock relaxation, qualification or job grant.
# No manifest is supplied by this source. Actual frozen build/render/control
# evidence must be reviewed, hash-bound and staged before any action can run.
[CmdletBinding()]
param(
[Parameter(Mandatory)][ValidateSet('Read','PrepareStopped','InstallStoppedPassive','PrepareProfile','PublishProfile','RestoreActiveStopped','StartActive')][string]$Action,
[Parameter(Mandatory)][ValidatePattern('^[0-9a-f]{64}$')][string]$ManifestSha256
)
$ErrorActionPreference='Stop'
$utf8=[Text.UTF8Encoding]::new($false,$true)
$requestedAction=$Action;$requestedManifest=$ManifestSha256
$root='C:\ProgramData\RustDiscoveryBootstrap'
$legacySha='2de0f7733c377ee1a4534fb00e5aa4cfb0652bd037afe07316f03ef4d51abfef'
$legacy=Join-Path (Join-Path $root $legacySha) 'Install-SystemScriptPairSuccessor.ps1'
if((Get-FileHash -LiteralPath $legacy).Hash.ToLowerInvariant()-cne$legacySha){throw 'Exact qualified Pair8 primitive source required.'}
# Read imports only the hash-sealed primitive definitions. It never enters an
# old Prepare/Install/Profile/Restore phase; its output is not a new authority.
$legacyRead=@(. $legacy -Action Read -ManifestSha256 'dac4e984a301e1c9b8ff6b732e43d54a73302d5ebaec34ebfb9547bd209db33a')
$inputFolder=Join-Path $root $requestedManifest
$manifestPath=Join-Path $inputFolder 'closed-control-successor.json'
CheckControl $inputFolder $true;CheckControl $manifestPath $false
if((Hash $manifestPath)-cne$requestedManifest){throw 'Exact reviewed successor manifest required.'}
$t=Get-Content -LiteralPath $manifestPath -Raw|ConvertFrom-Json
$fields='build_receipt_sha256,candidate_input_sha256,candidate_render_sha256,case_id,control_export_sha256,linux_proof_sha256,new_agent_sha256,new_helper_sha256,previous_publication_sha256,qualification_archive_sha256,renderer_sha256,schema_version,server_preflight_sha256,source_commit,windows_proof_sha256'
if((($t.PSObject.Properties.Name|Sort-Object)-join',')-cne$fields-or$t.schema_version-ne1-or$t.case_id-cne'29264503-e47b-4d0c-8dbc-a7f353446ba7'-or$t.source_commit-cnotmatch'^[0-9a-f]{40}$'){throw 'Fixed one-case successor manifest schema required.'}
foreach($p in $t.PSObject.Properties){if($p.Name-notin@('case_id','schema_version','source_commit')-and$p.Value-cnotmatch'^[0-9a-f]{64}$'){throw 'Unfilled or invalid manifest digest.'}}
$Action=$requestedAction;$ManifestSha256=$requestedManifest;$id=$t.case_id
$work=Join-Path $root ('job-stopped-pair-'+$id)
$previousCase=Join-Path $root 'job-stopped-pair-5c091437-12e0-4b23-8ee0-5f274ba92c4a'
$previousRevision=8
$profileHash='17b50660d6a659a90696967d8b05b9ddaeffa5f2ed0f7abda42c71c507f3c31d'
$activeConfigHash='5cd4cb9802d0dd20b961de7e3cd4e5874a1e9a72fc57b577e075e2d2918baac6'
$passiveConfigHash='d3ed4840c0f87971f752319a9e8bc5d6752edd864d11330d47faca16d1bac537'
$oldHashes=[ordered]@{agent='bfbca0cd81d0ac7da99c2b5276afa4ea09405f3ebe6208ef29cffeb2b4da9590';helper='5616ca956fa3328eae96a82dd44779eb298dadfa386e80768e12e1c7d058d082';settings='9b6b7489b98b90de222e5041b5484c1b261fb4ffd301b3481325cd4a4545caf9';pin='cb0b618d5e5fa3349c0f04585f0769ca2e0154905276b807d45759ca22696a14';config=$activeConfigHash}
$locations=[ordered]@{agent=$agentBinary;helper=$helperBinary;settings=$settings;pin=$pin;config=$config}
function InputFile($name,$digest){$p=Join-Path $inputFolder $name;CheckControl $p $false;if((Hash $p)-cne$digest){throw ('Reviewed input changed: '+$name)};return $p}
$buildPath=InputFile 'pair-build.json' $t.build_receipt_sha256
$build=Get-Content -LiteralPath $buildPath -Raw|ConvertFrom-Json
if($build.git_commit-cne$t.source_commit-or$build.artifacts.'rmm-agent-windows.exe'-cne$t.new_agent_sha256-or$build.artifacts.'rmm-helper-windows.exe'-cne$t.new_helper_sha256-or$build.artifacts.'windows_script_pair_prepare.exe'-cne$t.renderer_sha256-or$t.new_agent_sha256-ceq$oldHashes.agent-or$t.new_helper_sha256-ceq$oldHashes.helper){throw 'Both successor images and typed codec must belong to one actual frozen build.'}
# These are retained ORIGINAL raw operator evidence files, not booleans invented
# by this bootstrap. Their signature/control-edge review belongs to the actual
# readonly SDK and integrator; hashing here grants no RMM permission or repair.
foreach($e in @(@('control-export.json',$t.control_export_sha256),@('server-preflight.json',$t.server_preflight_sha256),@('linux-proof.json',$t.linux_proof_sha256),@('windows-proof.json',$t.windows_proof_sha256))){$null=InputFile $e[0] $e[1]}
$previousPublication=Join-Path $previousCase 'profile-published.json';CheckControl $previousPublication $false
if((Hash $previousPublication)-cne$t.previous_publication_sha256){throw 'Actual predecessor publication changed.'}
$previous=Get-Content -LiteralPath $previousPublication -Raw|ConvertFrom-Json
if($previous.id-cne'5c091437-12e0-4b23-8ee0-5f274ba92c4a'-or$previous.successor_revision-ne8-or$previous.configuration.sha256-cne$profileHash-or$previous.agent.image_file.sha256-cne$oldHashes.agent-or$previous.helper.image_file.sha256-cne$oldHashes.helper){throw 'Exact actually published Pair8 predecessor required.'}
function RequireNoQualification {
foreach($name in @('system-qualification.json','system-native-result.json')){if(Test-Path -LiteralPath (Join-Path $helperRoot $name)){throw 'SYSTEM qualification must remain absent throughout this maintenance.'}}
$archive=Join-Path $previousCase 'qualification-archived.json';CheckControl $archive $false
if((Hash $archive)-cne$t.qualification_archive_sha256){throw 'Exact actual archive receipt changed.'}
$original=Get-Content -LiteralPath $archive -Raw|ConvertFrom-Json
if($original.id-cne'5c091437-12e0-4b23-8ee0-5f274ba92c4a'){throw 'Original archive case differs.'}
foreach($e in @(@('qualification','archived-system-qualification.json','a42fb76b198f1e4ec2f1de322070ee61f728c87e6cf96c430c643db02ae4e497'),@('native_result','archived-system-native-result.json','0b3f48088116644b149b44a8b41f5b08bed8d9f294d89f4b5ab9cb7d51d29d77'))){
$p=Join-Path $previousCase $e[1]
# These archived ORIGINAL descriptors intentionally retain service-SID
# read ACEs. Never narrow them to satisfy a private-input ACL checker.
$actual=FileIdentity $p;$label=$e[0]
if($actual.sha256-cne$e[2]-or!(JsonEqual $original.files.$label $actual)){throw 'Original archive bytes, native identity or ACL changed.'}
}
}
RequireNoQualification
# Reuse the actual typed active->passive renderer without weakening its input
# contract: original cfd seed -> proven current 9b6 output -> candidate output.
$priorInput=InputFile 'prior-typed-input.json' '99d91247852e3c9f442c3b605d959441984394e9d10ba724741cd02f7411ca3e'
$priorRender=InputFile 'prior-typed-render.json' 'cc39919194217593900228fb9226713e5df53e738b71e44e5acea6c08eaac264'
$ri=Get-Content -LiteralPath (InputFile 'candidate-input.json' $t.candidate_input_sha256) -Raw|ConvertFrom-Json
$ro=Get-Content -LiteralPath (InputFile 'candidate-render.json' $t.candidate_render_sha256) -Raw|ConvertFrom-Json
$pi=Get-Content -LiteralPath $priorInput -Raw|ConvertFrom-Json;$po=Get-Content -LiteralPath $priorRender -Raw|ConvertFrom-Json
$seed=Join-Path $previousCase 'old-settings';CheckControl $seed $false
if((Hash $seed)-cne'cfd126d383ec0a948a73270a8362bd835d79341a079be05ce50088f0dbc5791c'-or$ri.schema_version-ne1-or$pi.schema_version-ne1-or$ri.current_settings_sha256-cne$pi.current_settings_sha256-or(BytesHash ([byte[]]$ri.current_settings))-cne(Hash $seed)-or!(JsonEqual $ri.current_settings $pi.current_settings)-or$ri.new_agent_sha256-cne$t.new_agent_sha256-or$ri.new_helper_sha256-cne$t.new_helper_sha256-or$pi.new_agent_sha256-cne$oldHashes.agent-or$pi.new_helper_sha256-cne$oldHashes.helper){throw 'Exact original typed seed and proven current pair chain required.'}
foreach($r in @($po,$ro)){
if($r.schema_version-ne1-or$r.source-cne'actual_rust_settings_codec'-or$r.prepared_only-ne$true-or$r.target_mutations-ne$false-or$r.target_job_executed-ne$false-or$r.effects_enabled-ne$false-or(BytesHash ([byte[]]$r.settings_bytes))-cne$r.settings_sha256-or(BytesHash ([byte[]]$r.pin_bytes))-cne$r.pin_sha256){throw 'Actual deny-only typed renderer bytes required.'}
}
if($po.settings_sha256-cne$oldHashes.settings-or$po.pin_sha256-cne$oldHashes.pin-or$ro.helper_settings_source_sha256-cne$build.role_source_sha256.'helper_system.rs'-or$ro.peer_codec_source_sha256-cne$build.role_source_sha256.'helper_ipc.rs'){throw 'Typed current/candidate settings provenance changed.'}
$oldTyped=$utf8.GetString([byte[]]$po.settings_bytes)|ConvertFrom-Json
$newTyped=$utf8.GetString([byte[]]$ro.settings_bytes)|ConvertFrom-Json
$normalized=$utf8.GetString([byte[]]$ro.settings_bytes)|ConvertFrom-Json
$normalized.agent.binary_sha256=$oldHashes.agent;$normalized.helper.binary_sha256=$oldHashes.helper
$newPin=$utf8.GetString([byte[]]$ro.pin_bytes)|ConvertFrom-Json
if(!(JsonEqual $normalized $oldTyped)-or$newTyped.enable_effects-ne$false-or$newTyped.allow_reboot-ne$false-or$newTyped.max_runtime_seconds-ne30-or@($newTyped.allowed_services).Count-ne0-or$null-ne$newTyped.PSObject.Properties['allowed_script_profiles']-or$null-ne$newTyped.PSObject.Properties['allowed_msi_recipe_sha256']-or$newTyped.agent.binary_sha256-cne$t.new_agent_sha256-or$newTyped.helper.binary_sha256-cne$t.new_helper_sha256-or$newPin.policy_sha256-cne$ro.settings_sha256-or!(JsonEqual $newPin.binding $newTyped.binding)){throw 'Only both image pins may change in the current deny-only typed policy.'}
$renderer=Join-Path (Join-Path $root $t.renderer_sha256) 'windows_script_pair_prepare.exe';CheckControl $renderer $false
if((Hash $renderer)-cne$t.renderer_sha256){throw 'Actual typed metadata codec artifact missing.'}
$passiveConfig=Join-Path $previousCase 'new-config';CheckControl $passiveConfig $false
if((Hash $passiveConfig)-cne$passiveConfigHash){throw 'Exact retained passive d3ed configuration required.'}
$newHashes=[ordered]@{agent=$t.new_agent_sha256;helper=$t.new_helper_sha256;settings=$ro.settings_sha256;pin=$ro.pin_sha256;config=$passiveConfigHash}
$helperHash=$newHashes.helper;$configHash=$passiveConfigHash
function VerifySuccessorFiles {VerifyFiles (CurrentFiles) $newHashes;RequireNoQualification}
# Physical equality of all four DBs AND present WAL/SHM sidecars proves no row
# rewrite during each quiescent replacement. No SQLite library is invoked.
# Read-only handles deny concurrent writes/deletes while they are held.
function OpenFrozenState {
StopCheck
$held=New-Object 'System.Collections.Generic.List[object]';$proof=[ordered]@{}
$paths=@((Join-Path $agentState 'telemetry.sqlite'),(Join-Path $agentState 'consumption.sqlite'),(Join-Path $helperState 'ledger.sqlite'),'C:\ProgramData\RustDiscoverySystem\agent-intents\system-intents.sqlite')
$all=@();foreach($p in $paths){$all+=@($p,($p+'-wal'),($p+'-shm'))};$all+=@((Join-Path $agentState 'agent.lock'),(Join-Path $helperState 'executor.lock'))
try {
foreach($p in $all){
if(!(Test-Path -LiteralPath $p)){if($p-cnotmatch '-(wal|shm)$'){throw 'Original database/lock absent.'};$proof[$p]=$null;continue}
$item=Get-Item -LiteralPath $p -Force;if($item.PSIsContainer-or($item.Attributes-band[IO.FileAttributes]::ReparsePoint)){throw 'Regular original state file required.'}
for($ancestor=$item.Directory;$null-ne$ancestor;$ancestor=$ancestor.Parent){if($ancestor.Attributes-band[IO.FileAttributes]::ReparsePoint){throw 'Original state reparse ancestry.'}}
if($p-ceq(Join-Path $agentState 'agent.lock')-or$p-ceq(Join-Path $helperState 'executor.lock')){
# Actual first Prepare failed with ERROR_LOCK_VIOLATION only
# when hashing these already exclusively held lifetime locks
# through a second data handle. All four database reads passed;
# the case remained empty and no product replacement occurred.
# The original RmmStoppedPairLocks handles remain held here.
$meta=FileIdentityMetadata $p
if($meta.bytes-ne0){throw 'Original lifetime lock must remain empty.'}
$proof[$p]=[ordered]@{metadata=$meta;sha256=(BytesHash ([byte[]]@()));bytes=0};continue
}
$f=[IO.File]::Open($p,'Open','Read','Read');$held.Add([pscustomobject]@{path=$p;stream=$f})
$meta=FileIdentityMetadata $p;$h=[Security.Cryptography.SHA256]::Create();try{$hash=[BitConverter]::ToString($h.ComputeHash($f)).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}
$proof[$p]=[ordered]@{metadata=$meta;sha256=$hash;bytes=$f.Length}
}
return [pscustomobject]@{held=$held;proof=$proof}
} catch {foreach($x in $held){$x.stream.Dispose()};throw}
}
function CheckFrozenState($frozen) {
StopCheck
foreach($p in $frozen.proof.Keys){
$before=$frozen.proof[$p]
if($null-eq$before){if(Test-Path -LiteralPath $p){throw 'Original sidecar namespace changed.'};continue}
if($p-ceq(Join-Path $agentState 'agent.lock')-or$p-ceq(Join-Path $helperState 'executor.lock')){
$current=FileIdentityMetadata $p
if($current.bytes-ne0-or$before.bytes-ne0-or$before.sha256-cne(BytesHash ([byte[]]@()))-or!(JsonEqual $before.metadata $current)){throw 'Original held empty lock identity, length or ACL changed.'};continue
}
$entry=@($frozen.held|Where-Object{$_.path-ceq$p});if($entry.Count-ne1){throw 'Original held file missing.'};$f=$entry[0].stream;$f.Position=0
$h=[Security.Cryptography.SHA256]::Create();try{$hash=[BitConverter]::ToString($h.ComputeHash($f)).Replace('-','').ToLowerInvariant()}finally{$h.Dispose()}
if($hash-cne$before.sha256-or$f.Length-ne$before.bytes-or!(JsonEqual $before.metadata (FileIdentityMetadata $p))){throw 'Original database/lock bytes, file identity or ACL changed.'}
}
}
function CloseFrozenState($frozen){foreach($x in $frozen.held){$x.stream.Dispose()}}
function WithStoppedState([scriptblock]$body){
StopCheck;$locks=[RmmStoppedPairLocks]::new();$frozen=$null
try{StopCheck;$frozen=OpenFrozenState;& $body $frozen;CheckFrozenState $frozen}finally{if($null-ne$frozen){CloseFrozenState $frozen};$locks.Dispose()}
}
if($Action-ceq'Read'){
[ordered]@{id=$id;manifest_sha256=$ManifestSha256;read_only=$true;files=(CurrentFiles);device=(PreservedNativeState);agent=(Service 'agent');helper=(Service 'helper');profile=(FileIdentity $target);marks=@(Get-ChildItem -LiteralPath $work -Filter '*.json' -File -ErrorAction SilentlyContinue|Select-Object -ExpandProperty Name)}|ConvertTo-Json -Depth 18 -Compress;return
}
if($Action-ceq'PrepareStopped'){
VerifyFiles (CurrentFiles) $oldHashes;if((Hash $target)-cne$profileHash){throw 'Current Profile8 changed.'}
if(Test-Path -LiteralPath $work){
CheckControl $work $true
if(@(Get-ChildItem -LiteralPath $work -Force -ErrorAction Stop).Count-ne0){throw 'Any existing case entry means readback only; no retry.'}
}else{[IO.Directory]::CreateDirectory($work)|Out-Null;CheckControl $work $true}
# Only the independently observed empty no-effect preparation case may be
# reused. Any intent, backup, marker, hidden file or child blocks this path.
WithStoppedState {
param($frozen)
$before=CurrentFiles;$retained=PreservedNativeState
foreach($n in $locations.Keys){$copy=Join-Path $work ('old-'+$n);[IO.File]::Copy($locations[$n],$copy,$false);$acl=[Security.AccessControl.FileSecurity]::new();$acl.SetSecurityDescriptorSddlForm('O:BAG:BAD:P(A;;FA;;;SY)(A;;FA;;;BA)');Set-Acl -LiteralPath $copy -AclObject $acl;FlushFile $copy;if((Hash $copy)-cne$oldHashes[$n]){throw 'Original public backup mismatch.'}}
WriteBytes (Join-Path $work 'new-settings') ([byte[]]$ro.settings_bytes);WriteBytes (Join-Path $work 'new-pin') ([byte[]]$ro.pin_bytes)
foreach($role in @('agent','helper')){$p=Join-Path (Join-Path $root $newHashes[$role]) ('rmm-'+$role+'-windows.exe');CheckControl $p $false;if((Hash $p)-cne$newHashes[$role]){throw 'Actual frozen image missing.'}}
if(!(JsonEqual $before (CurrentFiles))-or!(JsonEqual $retained (PreservedNativeState))){throw 'Original context changed before preparation.'}
CheckFrozenState $frozen
Record 'prepared' @{id=$id;manifest_sha256=$ManifestSha256;files=$before;device=$retained;frozen_state=$frozen.proof;new_hashes=$newHashes;successor_revision=9}
}
Write-Output 'Prepared fixed stopped successor, no original target changed.';return
}
$preparedPair=LoadRecord 'prepared'
if($preparedPair.id-cne$id-or$preparedPair.manifest_sha256-cne$ManifestSha256-or!(JsonEqual $preparedPair.new_hashes $newHashes)){throw 'Exact one-case preparation required.'}
if($Action-ceq'InstallStoppedPassive'){
if(Test-Path -LiteralPath (Marker 'install-intent')){throw 'Existing install intent means readback only.'}
WithStoppedState {
param($frozen)
if(!(JsonEqual $preparedPair.files (CurrentFiles))-or!(JsonEqual $preparedPair.device (PreservedNativeState))-or!(JsonEqual $preparedPair.frozen_state $frozen.proof)-or(Hash $target)-cne$profileHash){throw 'Original quiescent predecessor changed.'}
Record 'install-intent' @{id=$id;manifest_sha256=$ManifestSha256;frozen_state=$frozen.proof}
foreach($n in $locations.Keys){$rmmSwapInput=Join-Path $work ('new-'+$n);if($n-in@('agent','helper')){$rmmSwapInput=Join-Path (Join-Path $root $newHashes[$n]) ('rmm-'+$n+'-windows.exe')};if($n-ceq'config'){$rmmSwapInput=$passiveConfig};SwapFile $n $rmmSwapInput $preparedPair.files.$n $newHashes[$n] 'install'}
CheckFrozenState $frozen;RequireNoQualification
if(!(JsonEqual $preparedPair.device (PreservedNativeState))){throw 'Original identity/journal metadata changed.'}
Record 'files-installed' @{id=$id;files=(CurrentFiles);device=(PreservedNativeState);frozen_state=$frozen.proof;job_mode=$false;privileged_effects=$false}
}
StartKnownRole 'helper' $helperName $newHashes.helper 'install';StartKnownRole 'agent' $agentName $newHashes.agent 'install'
Record 'installed' @{id=$id;files=(CurrentFiles);device=(PreservedNativeState);agent=(LiveRole 'agent' $newHashes.agent);helper=(LiveRole 'helper' $newHashes.helper);job_mode=$false;clock_qualified=$false;privileged_effects=$false}
Write-Output 'Installed both fixed images passively; original rows preserved.';return
}
$installed=LoadRecord 'installed'
if($installed.id-cne$id){throw 'Actual successor installation required.'}
if($Action-ceq'RestoreActiveStopped'){
if(Test-Path -LiteralPath (Marker 'active-config-restore-intent')){throw 'Existing restore intent means readback only.'}
$publication=LoadRecord 'profile-published';if($publication.id-cne$id-or$publication.successor_revision-ne9-or(Hash $target)-cne$publication.configuration.sha256){throw 'Actual profile9 publication required.'}
VerifySuccessorFiles
WithStoppedState {
param($frozen)
$before=FileIdentity $config;$retained=PreservedNativeState;$active=Join-Path $work 'old-config'
if((Hash $active)-cne$activeConfigHash){throw 'Exact original active configuration required.'}
Record 'active-config-restore-intent' @{id=$id;before=$before;frozen_state=$frozen.proof}
SwapFile 'config' $active $before $activeConfigHash 'active-config';CheckFrozenState $frozen
if(!(JsonEqual $retained (PreservedNativeState))){throw 'Original identity/journal metadata changed.'}
Record 'active-config-restored' @{id=$id;configuration=(FileIdentity $config);frozen_state=$frozen.proof;services_started=$false;scope_activated=$false}
}
Write-Output 'Original5cd active config restored; both roles remain stopped.';return
}
if($Action-ceq'StartActive'){
$restore=LoadRecord 'active-config-restored';$publication=LoadRecord 'profile-published'
if($restore.id-cne$id-or(Hash $config)-cne$activeConfigHash-or(Hash $target)-cne$publication.configuration.sha256){throw 'Exact actual active restoration required.'}
foreach($n in @('agent','helper','settings','pin')){if((Hash $locations[$n])-cne$newHashes[$n]){throw 'Candidate pair changed.'}}
RequireNoQualification;StopCheck
if(Test-Path -LiteralPath (Marker 'active-start-intent')){throw 'Existing start intent means readback only.'}
Record 'active-start-intent' @{id=$id;manifest_sha256=$ManifestSha256}
StartKnownRole 'helper' $helperName $newHashes.helper 'active';StartKnownRole 'agent' $agentName $newHashes.agent 'active'
Record 'active-started' @{id=$id;agent=(LiveRole 'agent' $newHashes.agent);helper=(LiveRole 'helper' $newHashes.helper);configuration=(FileIdentity $config);normal_sync_result_not_claimed=$true;system_scope_activated=$false}
Write-Output 'Actual active roles started; fresh normal signed reconciliation still required.';return
}
# Reuse the unchanged hash-qualified publisher declarations, excluding all old
# actions. Pair8's already reviewed RoleDigests and exact two-image extension
# bind both current candidate images to the same actual frozen build receipt.
$publisher=Join-Path $root 'mvp-successor-prerequisites\Publish-JobPairTimeProfile.ps1';CheckControl $publisher $false
if((Hash $publisher)-cne'6b6f64192d82f98c449ea3c36c5da0f8b179ecd5d6f944f36151969d645b9fb5'){throw 'Qualified publisher primitives changed.'}
$pub=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($publisher));$i=$pub.IndexOf('function RequireNewPassivePair {',[StringComparison]::Ordinal);$j=$pub.IndexOf("`nif (`$Action -ceq 'Read') {",[StringComparison]::Ordinal)
if($i-lt0-or$j-le$i){throw 'Exact publisher declaration boundary required.'};. ([scriptblock]::Create($pub.Substring($i,$j-$i)))
$src=[Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($legacy));$i=$src.IndexOf('function RoleDigests(',[StringComparison]::Ordinal);$j=$src.IndexOf('# Exact, reviewed changes to the hash-sealed one-image renderer:',[StringComparison]::Ordinal)
if($i-lt0-or$j-le$i){throw 'Exact qualified Pair8 role proof boundary required.'};. ([scriptblock]::Create($src.Substring($i,$j-$i)))
$m=[pscustomobject]@{pair_build_sha256=$t.build_receipt_sha256}
$platformArchive=Join-Path $previousCase 'profile-platform.json';$roleArchive=Join-Path $previousCase 'profile-role-{0}.json'
$previousPublicationHash=$t.previous_publication_sha256;$agentBuildHash=$t.build_receipt_sha256;$linuxProofHash=$t.linux_proof_sha256;$unitHash=$t.windows_proof_sha256;$unitProof=Join-Path $inputFolder 'windows-proof.json'
$activation=Marker 'profile-publish-intent';$ready=Marker 'profile-prepared';$success=Marker 'profile-published'
function PreservedDevice {return (PreservedNativeState)}
$builder=(Get-Item Function:\BuildSuccessor).ScriptBlock.ToString();$needle='$changes[$oldHashes.agent]=$newHashes.agent'
if($builder.IndexOf($needle,[StringComparison]::Ordinal)-lt0-or$builder.IndexOf($needle,[StringComparison]::Ordinal)-ne$builder.LastIndexOf($needle,[StringComparison]::Ordinal)-or!$builder.Contains('$changes.Count -ne 4')){throw 'Exact original publisher renderer required.'}
Set-Item Function:\BuildSuccessor ([scriptblock]::Create($builder.Replace($needle,$needle+"`n "+'$changes[$oldHashes.helper]=$newHashes.helper').Replace('$changes.Count -ne 4','$changes.Count -ne 5')))
VerifySuccessorFiles;RequireNewPassivePair
if($Action-ceq'PrepareProfile'){
if(Test-Path -LiteralPath $ready){throw 'Existing profile preparation means readback only.'}
BuildSuccessor;Write-Output 'Prepared actual candidate profile9 provenance; no profile target changed.';return
}
if($Action-cne'PublishProfile'){throw 'Unsupported phase.'}
$prepared=LoadRecord 'profile-prepared';CheckPrepared;$held=LoadRecord 'profile-independent-native-read'
if(!(JsonEqual $held.agent (LiveRole 'agent' $newHashes.agent))-or!(JsonEqual $held.helper (LiveRole 'helper' $newHashes.helper))-or!(JsonEqual $held.device (PreservedNativeState))){throw 'Current candidate roles changed.'}
if(Test-Path -LiteralPath $activation){throw 'Existing profile intent means readback only.'}
Record 'profile-publish-intent' @{id=$id;utc=[DateTime]::UtcNow.ToString('o');prepared_sha256=(Hash $ready)}
StopKnownRole 'agent' $agentName $held.agent 'time';StopKnownRole 'helper' $helperName $held.helper 'time'
WithStoppedState {
param($frozen)
$locations.Add('time',$target)
try{SwapFile 'time' (Join-Path $work 'new-time-profile') $prepared.predecessor $prepared.successor_sha256 'time'}finally{$locations.Remove('time')}
CheckFrozenState $frozen;Record 'profile-quiescent-state-preserved' @{id=$id;frozen_state=$frozen.proof}
}
FinishPublication