The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop-update): A7 marker lock and hand-off protocol 2 on Windows
Teknium8fb5c3b5360a
diff --git a/scripts/desktop-update/marker-claim.ps1 b/scripts/desktop-update/marker-claim.ps1new file mode 100644index 00000000000..053bad878d1--- /dev/null+++ b/scripts/desktop-update/marker-claim.ps1@@ -0,0 +1,283 @@+# marker-claim.ps1 -- claim / delegate / release / heartbeat / helper ops of+# the update marker, dot-sourced by marker.ps1 (still before any Add-Type).+# Every function here mutates the marker only inside one Open-MarkerLock hold+# (A7 rule 1) and judges it inside that same hold.+#+# Claim modes (hand-off protocol 2, see windows.ps1):+# -HandoffRun R new Desktop: ADOPT ONLY its bridge (line 1 = the Desktop's+# live incarnation, run:R, no live delegate), else refuse.+# -DesktopPid P old packaged Desktop (no run): it spawned a cmd.exe+# wrapper (our parent) and then OVERWROTE the marker with a+# v1 "<wrapper pid>\n<startedAt>\n". Accepted by LINEAGE,+# never by dropping the check -- see Invoke-MarkerAdoptLegacy.+# neither plain claim: reclaim a dead/malformed marker, refuse a live one.++function Write-MarkerOwnClaim([bool]$Exists, [int64]$Started, $Run, [string]$Verb) {+ # Caller holds the lock. Our canonical claim, published or rewritten.+ $runs = @()+ if ($Run) { $runs = @("run:$Run") }+ $body = Format-MarkerBody $PID $Started $script:MarkerOwnCtText $null $runs+ $ok = if ($Exists) { Set-MarkerBodyLocked $body } else { (Publish-MarkerNew $body) -eq 'published' }+ if (-not $ok) {+ Write-HandoffLog "could not write the update marker; refusing"+ return 'refused'+ }+ $script:StartedAt = $Started+ $script:MarkerLastHeartbeat = Get-Date+ return $Verb+}++function Get-MarkerKeptStartedAt($Info) {+ # One acquisition time for the whole chain: keep a sane line 2.+ if ($Info -and $Info.StartedAt -gt 0 -and $Info.StartedAt -le (Get-UnixNow)) { return [int64]$Info.StartedAt }+ return [int64]$script:StartedAt+}++function Invoke-MarkerAdoptRun($Read, [int]$Desktop, [string]$Run) {+ # Protocol 2 (SPEC 4a step 4): adopt-only of the Desktop bridge for run R.+ $info = $Read.Info+ $reason = $null+ if ($Desktop -le 0) { $reason = "-HandoffRun needs -DesktopPid" }+ elseif ($Run -cnotmatch $script:MarkerRunPattern) { $reason = "invalid run id" }+ elseif ($Read.State -eq 'absent') { $reason = "no bridge marker" }+ elseif ($null -eq $info) { $reason = "the marker is not a bridge claim" }+ elseif ($info.Pid -ne $Desktop) { $reason = "the marker names pid $($info.Pid)" }+ elseif ($info.Run -cne $Run) { $reason = "the marker carries run '$($info.Run)'" }+ elseif (-not (Test-ProcessIdentityExact $Desktop $info.Ct)) { $reason = "the bridge is not the desktop's live incarnation" }+ elseif ($Read.Judgement.DelegateState -in @('live', 'ours')) { $reason = "a delegate (pid $($info.DelegatePid)) is running" }+ if ($reason) {+ if ($Read.Judgement -and $Read.Judgement.Owner) { $script:MarkerBlocker = $Read.Judgement.Owner }+ Write-HandoffLog "update marker is not the bridge of desktop pid $Desktop for run ${Run}: $reason. The Desktop gave up on this hand-off; exiting without claiming"+ return 'refused'+ }+ $verdict = Write-MarkerOwnClaim $true (Get-MarkerKeptStartedAt $info) $Run 'adopted'+ if ($verdict -eq 'adopted') { Write-HandoffLog "adopted update marker from desktop pid $Desktop run $Run (pid $PID)" }+ return $verdict+}++function Get-MarkerLineage([int]$Desktop, $Info) {+ # X = our recorded parent: the old Desktop's cmd.exe wrapper.+ $x = Get-ParentProcessId $PID+ $xAlive = $false+ $xParent = 0+ if ($x -gt 0) {+ $xAlive = (Get-LiveProcessCt $x).Alive+ if ($xAlive) { $xParent = Get-ParentProcessId $x }+ }+ $envStarted = 0L+ $hasEnvStarted = [int64]::TryParse("$env:HERMES_UPDATE_STARTED_AT".Trim(), [ref]$envStarted)+ $namesX = $x -gt 0 -and $Info -and $Info.Pid -eq $x+ $xLineage = $false+ if ($namesX) {+ # Alive: it must still be the Desktop's child. Dead (start /b exits at+ # once): the marker must carry the startedAt the Desktop gave us.+ $xLineage = if ($xAlive) { $xParent -eq $Desktop } else { $hasEnvStarted -and $Info.StartedAt -eq $envStarted }+ }+ return @{+ Parent = $x; ParentAlive = $xAlive; Grandparent = $xParent; LauncherClaim = $xLineage+ Ancestor = ($x -gt 0 -and ($x -eq $Desktop -or ($xAlive -and $xParent -eq $Desktop)))+ }+}++function Invoke-MarkerAdoptLegacy($Read, [int]$Desktop) {+ # SPEC 4c: an OLD packaged Desktop (no run id) + this script.+ $info = $Read.Info+ $j = $Read.Judgement+ $lineage = Get-MarkerLineage $Desktop $info+ if ($lineage.LauncherClaim) {+ $verdict = Write-MarkerOwnClaim $true (Get-MarkerKeptStartedAt $info) $null 'adopted'+ if ($verdict -eq 'adopted') { Write-HandoffLog "adopted update marker from desktop pid $Desktop's launcher pid $($lineage.Parent) (pid $PID)" }+ return $verdict+ }+ if ($info -and $info.Pid -eq $Desktop -and $j.OwnerState -eq 'live' -and $j.DelegateState -notin @('live', 'ours')) {+ $verdict = Write-MarkerOwnClaim $true (Get-MarkerKeptStartedAt $info) $null 'adopted'+ if ($verdict -eq 'adopted') { Write-HandoffLog "adopted update marker from desktop pid $Desktop (pid $PID)" }+ return $verdict+ }+ if ($j.Verdict -in @('absent', 'dead', 'malformed') -and $lineage.Ancestor) {+ if ($Read.State -ne 'absent') { Write-HandoffLog "reclaiming stale update marker (owner pid $(if ($info) { $info.Pid } else { '?' }) is not running)" }+ $verdict = Write-MarkerOwnClaim ($Read.State -ne 'absent') $script:StartedAt $null 'claimed'+ if ($verdict -eq 'claimed') { Write-HandoffLog "claimed update marker (pid $PID) for desktop pid $Desktop" }+ return $verdict+ }+ if ($j.Owner) { $script:MarkerBlocker = $j.Owner }+ $named = if ($info) { "pid $($info.Pid)" } else { $j.Verdict }+ Write-HandoffLog "update marker ($named) is neither the live bridge of desktop pid $Desktop nor its launcher's (parent pid $($lineage.Parent)): it gave up on this hand-off; exiting without claiming"+ return 'refused'+}++function Invoke-MarkerClaim {+ # The FIRST act of windows.ps1. Returns claimed | adopted | refused.+ $epoch = Get-UnixNow+ $startedAt = 0L+ $hasStartedAt = [int64]::TryParse($env:HERMES_UPDATE_STARTED_AT, [ref]$startedAt)+ if (-not $hasStartedAt -or $startedAt -gt $epoch -or ($epoch - $startedAt) -gt $script:MarkerCeilingSeconds) {+ $startedAt = $epoch+ }+ $script:StartedAt = $startedAt+ $ctx = New-MarkerContext+ if ($null -ne $ctx.OwnCt) { $script:MarkerOwnCtText = Format-Ct $ctx.OwnCt }+ $lock = Open-MarkerLock+ if ($null -eq $lock) {+ Write-HandoffLog "update marker lock ($MarkerPath.lock) stayed busy; refusing"+ return 'refused'+ }+ try {+ $read = Read-MarkerLocked $ctx+ if ($read.State -eq 'busy') {+ Write-HandoffLog "update marker is being written by another process; refusing"+ return 'refused'+ }+ if ($HandoffRun) { return Invoke-MarkerAdoptRun $read $DesktopPid $HandoffRun }+ if ($DesktopPid -gt 0) { return Invoke-MarkerAdoptLegacy $read $DesktopPid }+ $j = $read.Judgement+ if ($j.Verdict -eq 'live') {+ $script:MarkerBlocker = $j.Owner+ Write-HandoffLog "update marker is held by live pid $($j.Owner); refusing"+ return 'refused'+ }+ if ($read.State -ne 'absent') {+ $stalePid = if ($read.Info) { $read.Info.Pid } else { "?" }+ Write-HandoffLog "reclaiming stale update marker (owner pid $stalePid is not running)"+ }+ $verdict = Write-MarkerOwnClaim ($read.State -ne 'absent') $script:StartedAt $null 'claimed'+ if ($verdict -eq 'claimed') { Write-HandoffLog "claimed update marker (pid $PID)" }+ return $verdict+ } finally {+ $lock.Dispose()+ }+}++function Add-MarkerDelegate([int[]]$Candidates) {+ # Name a running updater process (the `hermes update` child BEFORE it is+ # resumed, or a member of a tree that could not be quiesced) as the+ # delegate so every reader keeps the marker LIVE exactly as long as that+ # process lives. Only while line 1 is still our exact incarnation.+ # Returns published | kept (another live delegate stays) | skipped | lost.+ if ($script:MarkerClaim -notin @('claimed', 'adopted')) { return 'lost' }+ $lock = Open-MarkerLock+ if ($null -eq $lock) { Write-HandoffLog "update marker lock stayed busy; could not name a delegate"; return 'lost' }+ try {+ $ctx = New-MarkerContext+ $read = Read-MarkerLocked $ctx+ $info = $read.Info+ if ($null -eq $info -or $read.Judgement.OwnerState -ne 'ours') {+ Write-HandoffLog "update marker no longer names this hand-off (pid $PID); not naming a delegate"+ return 'lost'+ }+ if ($read.Judgement.DelegateState -eq 'live' -and $info.DelegatePid -notin @($Candidates)) {+ Write-HandoffLog "update marker keeps its running delegate pid $($info.DelegatePid)"+ return 'kept'+ }+ foreach ($candidate in @($Candidates)) {+ if ($candidate -le 0 -or $candidate -eq $PID) { continue }+ $probe = Get-LiveProcessCt $candidate+ if (-not $probe.Alive -or $null -eq $probe.Ct) { continue }+ $line = "delegate:$candidate ct:$(Format-Ct $probe.Ct)"+ if (-not (Set-MarkerBodyLocked (Format-MarkerBody $info.Pid $info.StartedAt $info.CtText $line $info.Runs))) { return 'lost' }+ Write-HandoffLog "update marker now names updater pid $candidate as its delegate"+ return 'published'+ }+ return 'skipped'+ } finally {+ $lock.Dispose()+ }+}++function Invoke-MarkerRelease {+ # Corpus 'release' under the lock: owner deletes, or hands the claim over+ # to a live delegate; anything that is not ours is kept.+ if ($NoMarkerCleanup -or $script:MarkerClaim -notin @('claimed', 'adopted')) { return }+ $lock = Open-MarkerLock+ if ($null -eq $lock) { Write-HandoffLog "update marker lock stayed busy; leaving the marker to identity-checking readers"; return }+ try {+ if (-not [System.IO.File]::Exists($MarkerPath)) { return }+ $info = ConvertFrom-MarkerText (Read-MarkerText)+ $release = Get-MarkerReleaseAction $info (New-MarkerContext)+ switch ($release.Action) {+ 'delete' { if (Remove-MarkerLocked) { Write-HandoffLog "removed update marker (owned)" } }+ 'rewrite' {+ if (Set-MarkerBodyLocked $release.Text) {+ Write-HandoffLog "handed update marker over to running pid $((ConvertFrom-MarkerText $release.Text).Pid)"+ }+ }+ default {+ $owner = if ($info) { $info.Pid } else { '?' }+ Write-HandoffLog "leaving update marker: owned by pid '$owner', not us ($PID)"+ }+ }+ } catch {+ Write-HandoffLog "could not release the update marker: $($_.Exception.Message)"+ } finally {+ $lock.Dispose()+ }+}++function Update-MarkerHeartbeat {+ # Old packaged Electron readers age a marker on line 2 (20-minute+ # ceiling, then delete it). While a step runs, refresh line 2 every 5+ # minutes -- only while line 1 is still our exact incarnation.+ if ($script:MarkerClaim -notin @('claimed', 'adopted')) { return }+ $now = Get-Date+ if ($script:MarkerLastHeartbeat -and ($now - $script:MarkerLastHeartbeat).TotalSeconds -lt $script:MarkerHeartbeatSeconds) { return }+ $script:MarkerLastHeartbeat = $now+ $lock = Open-MarkerLock 500+ if ($null -eq $lock) { return }+ try {+ $ctx = New-MarkerContext+ $read = Read-MarkerLocked $ctx+ if ($null -eq $read.Info -or $read.Judgement.OwnerState -ne 'ours') { return }+ $info = $read.Info+ [void](Set-MarkerBodyLocked (Format-MarkerBody $info.Pid $ctx.Now $info.CtText (Get-MarkerDelegateLine $info) $info.Runs))+ } catch {} finally {+ $lock.Dispose()+ }+}++function Invoke-MarkerOp([string]$Op, [int]$Desktop, [string]$Run) {+ # SPEC 6 helper ops (Electron's only way to mutate). Returns the verdict+ # line: absent | reclaimed | live <pid> | busy | withdrawn | taken <pid> | foreign.+ $lock = Open-MarkerLock+ if ($null -eq $lock) { return 'busy' }+ try {+ $ctx = New-MarkerContext+ $read = Read-MarkerLocked $ctx+ if ($read.State -eq 'absent') { return 'absent' }+ if ($read.State -eq 'busy') { return 'busy' }+ $info = $read.Info+ $j = $read.Judgement+ if ($Op -eq 'reclaim') {+ if ($j.Verdict -in @('live', 'ours')) { return "live $($j.Owner)" }+ if (-not (Remove-MarkerLocked)) { return 'busy' }+ Write-HandoffLog "marker-op reclaim: removed a $($j.Verdict) update marker"+ return 'reclaimed'+ }+ # withdraw+ if ($null -eq $info -or $info.Run -cne $Run) { return 'foreign' }+ if ($info.Pid -eq $Desktop -and (Test-ProcessIdentityExact $Desktop $info.Ct)) {+ if (-not (Remove-MarkerLocked)) { return 'busy' }+ Write-HandoffLog "marker-op withdraw: removed the bridge of desktop pid $Desktop run $Run"+ return 'withdrawn'+ }+ if ($info.Pid -ne $Desktop -and $info.Pid -ne $PID -and (Test-ProcessIdentityExact $info.Pid $info.Ct)) {+ return "taken $($info.Pid)"+ }+ return 'foreign'+ } finally {+ $lock.Dispose()+ }+}++function Invoke-MarkerOpCli([string]$Op, [int]$Desktop, [string]$Run) {+ # Exactly one verdict line on stdout; 0 when one was printed, 64 on bad usage.+ if ($Op -cnotin @('reclaim', 'withdraw')) {+ [Console]::Error.WriteLine("unknown -MarkerOp '$Op' (reclaim|withdraw)")+ return 64+ }+ if ($Op -eq 'withdraw' -and ($Desktop -le 0 -or $Run -cnotmatch $script:MarkerRunPattern)) {+ [Console]::Error.WriteLine("-MarkerOp withdraw needs -DesktopPid and a valid -HandoffRun")+ return 64+ }+ [Console]::Out.WriteLine((Invoke-MarkerOp $Op $Desktop $Run))+ return 0+}diff --git a/scripts/desktop-update/marker.ps1 b/scripts/desktop-update/marker.ps1index b9fe21990fe..9640aadc43c 100644--- a/scripts/desktop-update/marker.ps1+++ b/scripts/desktop-update/marker.ps1@@ -1,24 +1,41 @@-# marker.ps1 -- the update marker (contract C1 v2) for windows.ps1, which-# dot-sources it as its first act. Pure PowerShell + CIM on purpose: the claim-# runs before the first Add-Type.+# marker.ps1 -- the update marker (contract C1 v2, hand-off protocol 2 / A7)+# for windows.ps1, which dot-sources it as its first act. Pure PowerShell ++# CIM on purpose: the claim runs before the first Add-Type (CLM, #66753).#-# Body: "<pid>\n<started_at>\nct:<creation>\n" plus an optional line 4-# "delegate:<pid> ct:<creation>". Every reader (Python, Rust, Electron, bash,-# this file) parses it the same way (amendment A2): a leading BOM and CRLF are-# accepted; line 1 is the owner pid and line 2 an integer started_at, else the-# marker is malformed (dead); line 3 must be `ct:<n>` else the marker is v1;-# line 4 must be `delegate:<pid> ct:<n>` else it is ignored.+# Body (tests/fixtures/update_marker_corpus.json is authoritative):+# line 1 owner pid, ASCII digits, fits u32 (else MALFORMED); pid 0 = dead+# line 2 started_at unix seconds, ASCII digits (else MALFORMED)+# line 3 ct:<digits[.digits]> owner creation time; anything else = v1+# line 4+ 'delegate:<pid> ct:<ct>' (first well-formed wins) and+# 'run:<[A-Za-z0-9._-]{1,128}>' (first wins); others are ignored+# Per line: one leading BOM (line 1), one trailing CR, then surrounding+# spaces/tabs are dropped; whitespace inside a value makes that line malformed.+# Writers are canonical: "<pid>\n<started>\nct:<ct>\n[delegate:..\n][run:..\n]".#-# Liveness (A1): a live pid whose creation time matches is live at any age; a-# live pid whose creation time cannot be read, or a v1 marker, is live for 20-# minutes from started_at only (a reused pid must never park every reader).+# Identity (A7 rule 4): a claim naming OUR pid is ours only at our exact+# creation time (5 ms); without a ct it is a previous incarnation (dead).+# Any other pid: live iff its creation time is within 2 s of the recorded+# one; no recorded ct (v1) or an unreadable one: live for 20 minutes from+# line 2 only (a reused pid must never park every reader).+#+# Mutation (A7 rule 1): every read -> judge -> mutate of the marker happens+# inside ONE hold of an exclusive kernel lock on the sidecar "<marker>.lock"+# ([IO.File]::Open with FileShare.None; the kernel drops it with the process,+# so there is no stale mutex). The wait is bounded (10 s); a busy lock fails+# closed (no claim). The sidecar is never deleted.$script:MarkerCeilingSeconds = 1200+$script:MarkerCtTolerance = 2.0+$script:MarkerOwnCtEpsilon = 0.005+$script:MarkerLockTimeoutMs = 10000+$script:MarkerHeartbeatSeconds = 300$script:ProcessCtCache = @{}-$script:MarkerBody = $null # what we published; release compares lines 1-3-$script:MarkerClaim = "none" # claimed | adopted | refused | unwritable+$script:MarkerClaim = "none" # claimed | adopted | refused$script:MarkerBlocker = 0+$script:MarkerOwnCtText = $null+$script:MarkerLastHeartbeat = $null$script:StartedAt = $null+$script:MarkerRunPattern = '\A[A-Za-z0-9._-]{1,128}\z'function ConvertTo-UnixCt([datetime]$Time) {return [DateTimeOffset]::new($Time.ToUniversalTime()).ToUnixTimeMilliseconds() / 1000.0@@ -26,6 +43,8 @@ function ConvertTo-UnixCt([datetime]$Time) {function Format-Ct([double]$Ct) { return $Ct.ToString('F3', [Globalization.CultureInfo]::InvariantCulture) }+function Get-UnixNow { return [DateTimeOffset]::UtcNow.ToUnixTimeSeconds() }+function Get-ProcessCreationCt([int]$ProcessId) {# Win32_Process needs only limited query rights, so it reads SYSTEM,# elevated and other-user processes; Get-Process .StartTime is access@@ -38,85 +57,198 @@ function Get-ProcessCreationCt([int]$ProcessId) {return $null}-function Get-LiveProcessCt([int]$ProcessId) {+function Get-ParentProcessId([int]$ProcessId) {+ # The RECORDED parent: Windows keeps no tree, so the pid may be gone or reused.+ try {+ $row = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId=$ProcessId" -ErrorAction Stop+ if ($row) { return [int]$row.ParentProcessId }+ } catch {}+ return 0+}++function Get-LiveProcessCt([int64]$ProcessId) {# Alive + creation time (unix seconds, $null when unreadable). The time is# read once per pid and kept while that pid stays alive: a waiter polls# liveness, never one CIM query per poll.- if ($ProcessId -le 0) { return @{ Alive = $false; Ct = $null } }- $p = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue+ if ($ProcessId -le 0 -or $ProcessId -gt [int]::MaxValue) { return @{ Alive = $false; Ct = $null } }+ $id = [int]$ProcessId+ $p = Get-Process -Id $id -ErrorAction SilentlyContinue$alive = [bool]$pif ($alive) { try { $alive = -not $p.HasExited } catch {} }if (-not $alive) {- $script:ProcessCtCache.Remove($ProcessId)+ $script:ProcessCtCache.Remove($id)return @{ Alive = $false; Ct = $null }}- if (-not $script:ProcessCtCache.ContainsKey($ProcessId)) {- $script:ProcessCtCache[$ProcessId] = Get-ProcessCreationCt $ProcessId+ if (-not $script:ProcessCtCache.ContainsKey($id)) {+ $script:ProcessCtCache[$id] = Get-ProcessCreationCt $id}- return @{ Alive = $true; Ct = $script:ProcessCtCache[$ProcessId] }+ return @{ Alive = $true; Ct = $script:ProcessCtCache[$id] }}-function Get-ProcessIdentity([int]$ProcessId, $RecordedCt) {+function Get-ProcessIdentity([int64]$ProcessId, $RecordedCt) {# live | dead | unknown (alive, but a creation time is missing on a side).$probe = Get-LiveProcessCt $ProcessIdif (-not $probe.Alive) { return 'dead' }if ($null -eq $RecordedCt -or $null -eq $probe.Ct) { return 'unknown' }- if ([Math]::Abs($probe.Ct - [double]$RecordedCt) -le 2.0) { return 'live' }+ if ([Math]::Abs($probe.Ct - [double]$RecordedCt) -le $script:MarkerCtTolerance) { return 'live' }return 'dead'}-function Test-ProcessIdentityLive([int]$ProcessId, $RecordedCt) {+function Test-ProcessIdentityLive([int64]$ProcessId, $RecordedCt) {return (Get-ProcessIdentity $ProcessId $RecordedCt) -ne 'dead'}+function Test-ProcessIdentityExact([int64]$ProcessId, $RecordedCt) {+ # 'match', never 'unknown': both creation times known and within 2 s.+ return (Get-ProcessIdentity $ProcessId $RecordedCt) -eq 'live'+}++# -- parsing ----------------------------------------------------------------+function Read-MarkerText {try { return [System.IO.File]::ReadAllText($MarkerPath, [System.Text.Encoding]::UTF8) } catch { return $null }}-function Get-MarkerHead([string]$Text) {- # Lines 1-3 (owner identity); line 4 is the delegate and may change.- return (@($Text -split "`n") | Select-Object -First 3) -join "`n"+function Get-MarkerLineValue([string]$Line) {+ if ($Line.EndsWith("`r")) { $Line = $Line.Substring(0, $Line.Length - 1) }+ return $Line.Trim([char[]]@([char]32, [char]9))+}++function ConvertTo-MarkerPid([string]$Text) {+ # ASCII digits that fit u32, else $null (a malformed pid).+ if ($Text -cnotmatch '\A[0-9]{1,10}\z') { return $null }+ $value = [uint64]$Text+ if ($value -gt 4294967295) { return $null }+ return [int64]$value}function ConvertFrom-MarkerText([string]$Text) {- # Positional (A2). $null = malformed, which every reader treats as dead.- $lines = @($Text.TrimStart([char]0xFEFF) -split "`n" | ForEach-Object { $_.TrimEnd("`r") })- if ($lines.Count -lt 2 -or $lines[0].Trim() -cnotmatch '^[0-9]+$' -or $lines[1].Trim() -cnotmatch '^[0-9]+$') { return $null }- $ownerPid = 0- $started = 0L- if (-not [int]::TryParse($lines[0].Trim(), [ref]$ownerPid) -or $ownerPid -le 0) { return $null }- if (-not [int64]::TryParse($lines[1].Trim(), [ref]$started)) { return $null }- $info = @{ Pid = $ownerPid; StartedAt = $started; Ct = $null; DelegatePid = 0; DelegateCt = $null }+ # $null = malformed, which every reader treats as dead.+ if ($null -eq $Text) { return $null }+ if ($Text.Length -gt 0 -and $Text[0] -eq [char]0xFEFF) { $Text = $Text.Substring(1) }+ $lines = @($Text -split "`n" | ForEach-Object { Get-MarkerLineValue $_ })+ if ($lines.Count -lt 2) { return $null }+ $ownerPid = ConvertTo-MarkerPid $lines[0]+ if ($null -eq $ownerPid -or $lines[1] -cnotmatch '\A[0-9]{1,18}\z') { return $null }$invariant = [Globalization.CultureInfo]::InvariantCulture- if ($lines.Count -ge 3 -and $lines[2] -cmatch '^ct:([0-9]+(\.[0-9]+)?)$') {+ $info = @{+ Pid = $ownerPid; StartedAt = [int64]$lines[1]; Ct = $null; CtText = $null+ DelegatePid = 0; DelegateCt = $null; DelegateCtText = $null; Run = $null; Runs = @()+ }+ if ($lines.Count -ge 3 -and $lines[2] -cmatch '\Act:([0-9]+(\.[0-9]+)?)\z') {+ $info.CtText = $Matches[1]$info.Ct = [double]::Parse($Matches[1], $invariant)}- if ($lines.Count -ge 4 -and $lines[3] -cmatch '^delegate:([0-9]+) ct:([0-9]+(\.[0-9]+)?)$') {- $delegatePid = 0- if ([int]::TryParse($Matches[1], [ref]$delegatePid)) {- $info.DelegatePid = $delegatePid- $info.DelegateCt = [double]::Parse($Matches[2], $invariant)+ $runs = New-Object System.Collections.Generic.List[string]+ for ($i = 3; $i -lt $lines.Count; $i++) {+ $line = $lines[$i]+ if ($info.DelegatePid -eq 0 -and $line -cmatch '\Adelegate:([0-9]+) ct:([0-9]+(\.[0-9]+)?)\z') {+ $delegatePid = ConvertTo-MarkerPid $Matches[1]+ if ($null -ne $delegatePid -and $delegatePid -gt 0) {+ $info.DelegatePid = $delegatePid+ $info.DelegateCtText = $Matches[2]+ $info.DelegateCt = [double]::Parse($Matches[2], $invariant)+ }+ } elseif ($line -cmatch '\Arun:([A-Za-z0-9._-]{1,128})\z') {+ if ($null -eq $info.Run) { $info.Run = $Matches[1] }+ $runs.Add($line)}}+ $info.Runs = @($runs)return $info}-function Test-MarkerIdentityLive([int]$ProcessId, $RecordedCt, $Info) {- switch (Get-ProcessIdentity $ProcessId $RecordedCt) {- 'live' { return $true }- 'unknown' { return ([DateTimeOffset]::UtcNow.ToUnixTimeSeconds() - $Info.StartedAt) -le $script:MarkerCeilingSeconds }+function Format-MarkerBody([int64]$OwnerPid, [int64]$StartedAt, $CtText, $DelegateLine, $Runs) {+ # Canonical, LF framing on purpose: the Rust/TS/Python readers split on "\n".+ $body = "$OwnerPid`n$StartedAt`n"+ if ($CtText) { $body += "ct:$CtText`n" }+ if ($DelegateLine) { $body += "$DelegateLine`n" }+ foreach ($run in @($Runs)) { if ($run) { $body += "$run`n" } }+ return $body+}++function Get-MarkerDelegateLine($Info) {+ if ($null -eq $Info -or $Info.DelegatePid -le 0) { return $null }+ return "delegate:$($Info.DelegatePid) ct:$($Info.DelegateCtText)"+}++# -- judging ----------------------------------------------------------------++function New-MarkerContext {+ # Who "we" are and how a pid is probed; the corpus test injects its own.+ $own = Get-LiveProcessCt $PID+ return @{ OwnPid = [int64]$PID; OwnCt = $own.Ct; Now = (Get-UnixNow); Probe = { param($p) Get-LiveProcessCt $p } }+}++function Get-MarkerIdentityState([int64]$ProcessId, $RecordedCt, [int64]$StartedAt, $Ctx) {+ # ours | live | dead for one (pid, ct) identity of a parsed marker.+ if ($ProcessId -le 0) { return 'dead' }+ if ($ProcessId -eq $Ctx.OwnPid) {+ if ($null -ne $RecordedCt -and $null -ne $Ctx.OwnCt -and+ [Math]::Abs([double]$RecordedCt - [double]$Ctx.OwnCt) -le $script:MarkerOwnCtEpsilon) { return 'ours' }+ return 'dead' # a previous incarnation of our pid, never live}- return $false+ $probe = & $Ctx.Probe $ProcessId+ if (-not $probe.Alive) { return 'dead' }+ if ($null -eq $RecordedCt -or $null -eq $probe.Ct) {+ if (($Ctx.Now - $StartedAt) -le $script:MarkerCeilingSeconds) { return 'live' }+ return 'dead'+ }+ if ([Math]::Abs([double]$RecordedCt - [double]$probe.Ct) -le $script:MarkerCtTolerance) { return 'live' }+ return 'dead'}-function Test-MarkerDelegateLive($Info) {- if ($null -eq $Info -or $Info.DelegatePid -le 0 -or $Info.DelegatePid -eq $PID) { return $false }- return Test-MarkerIdentityLive $Info.DelegatePid $Info.DelegateCt $Info+function Get-MarkerJudgement($Info, $Ctx) {+ # verdict: malformed | dead | ours | live; owner: the owner identity if+ # live, else the delegate if live, else $null.+ if ($null -eq $Info) { return @{ Verdict = 'malformed'; Owner = $null; OwnerState = 'dead'; DelegateState = 'none'; Run = $null } }+ $ownerState = Get-MarkerIdentityState $Info.Pid $Info.Ct $Info.StartedAt $Ctx+ $delegateState = 'none'+ if ($Info.DelegatePid -gt 0) { $delegateState = Get-MarkerIdentityState $Info.DelegatePid $Info.DelegateCt $Info.StartedAt $Ctx }+ $owner = $null+ if ($ownerState -ne 'dead') { $owner = $Info.Pid } elseif ($delegateState -in @('ours', 'live')) { $owner = $Info.DelegatePid }+ $verdict = 'dead'+ if ($ownerState -eq 'ours' -or $delegateState -eq 'ours') { $verdict = 'ours' } elseif ($null -ne $owner) { $verdict = 'live' }+ return @{ Verdict = $verdict; Owner = $owner; OwnerState = $ownerState; DelegateState = $delegateState; Run = $Info.Run }+}++function Get-MarkerReleaseAction($Info, $Ctx) {+ # Corpus 'release': delete | rewrite (Text) | keep.+ if ($null -eq $Info) { return @{ Action = 'keep'; Text = $null } }+ $ownerState = Get-MarkerIdentityState $Info.Pid $Info.Ct $Info.StartedAt $Ctx+ $delegateState = 'none'+ if ($Info.DelegatePid -gt 0) { $delegateState = Get-MarkerIdentityState $Info.DelegatePid $Info.DelegateCt $Info.StartedAt $Ctx }+ if ($Info.Pid -eq $Ctx.OwnPid -and $ownerState -eq 'ours') {+ if ($Info.DelegatePid -gt 0 -and $Info.DelegatePid -ne $Ctx.OwnPid -and $delegateState -eq 'live') {+ # A7 rule 5: hand over to the live delegate, keeping started_at and runs.+ return @{ Action = 'rewrite'; Text = (Format-MarkerBody $Info.DelegatePid $Info.StartedAt $Info.DelegateCtText $null $Info.Runs) }+ }+ return @{ Action = 'delete'; Text = $null }+ }+ if ($Info.DelegatePid -gt 0 -and $Info.DelegatePid -eq $Ctx.OwnPid -and $delegateState -eq 'ours') {+ if ($ownerState -ne 'dead') {+ return @{ Action = 'rewrite'; Text = (Format-MarkerBody $Info.Pid $Info.StartedAt $Info.CtText $null $Info.Runs) }+ }+ return @{ Action = 'delete'; Text = $null }+ }+ return @{ Action = 'keep'; Text = $null }}-function Test-MarkerOwnerLive($Info) {- if ($null -eq $Info -or $Info.Pid -eq $PID) { return $false } # our own pid = a reused, stale claim- return Test-MarkerIdentityLive $Info.Pid $Info.Ct $Info+# -- the A7 lock and in-lock writes -------------------------------------------++function Open-MarkerLock([int]$TimeoutMs = $script:MarkerLockTimeoutMs) {+ # The exclusive kernel lock (A7 rule 1): an open of the sidecar that+ # shares nothing. Returns the open stream (Dispose = release) or $null+ # when it stayed busy past $TimeoutMs. Never deletes the sidecar.+ $clock = [Diagnostics.Stopwatch]::StartNew()+ while ($true) {+ try {+ return [System.IO.File]::Open("$MarkerPath.lock", [System.IO.FileMode]::OpenOrCreate,+ [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)+ } catch {}+ if ($clock.ElapsedMilliseconds -ge $TimeoutMs) { return $null }+ Start-Sleep -Milliseconds 25+ }}function Write-MarkerTemp([string]$Body) {@@ -127,8 +259,8 @@ function Write-MarkerTemp([string]$Body) {function Publish-MarkerNew([string]$Body) {# A3: the complete body goes to a tmp sibling, then an exclusive hard link- # publishes it. Never create-then-write: a reader saw the empty file as a- # dead claim and deleted it. Returns published | exists | unwritable.+ # publishes it (a lockless reader never sees a half-written claim).+ # Returns published | exists | unwritable.try { $tmp = Write-MarkerTemp $Body } catch {Write-HandoffLog "WARNING: could not write update marker: $($_.Exception.Message)"return "unwritable"@@ -151,24 +283,35 @@ function Publish-MarkerNew([string]$Body) {}}-function Set-MarkerIfUnchanged([string]$Expected, [string]$Body) {- # Compare-and-swap: replace only the exact bytes we judged.- if ((Read-MarkerText) -cne $Expected) { return $false }- $tmp = $null- try {- $tmp = Write-MarkerTemp $Body- [System.IO.File]::Replace($tmp, $MarkerPath, [NullString]::Value)- return $true- } catch {- if ($tmp) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue }- return $false+function Set-MarkerBodyLocked([string]$Body) {+ # Caller holds the A7 lock. Atomic replace of the whole body; a lockless+ # reader holding the file open (no FILE_SHARE_DELETE) can make one attempt+ # fail, so retry briefly. A marker that vanished is re-published.+ for ($attempt = 0; $attempt -lt 20; $attempt++) {+ if (-not [System.IO.File]::Exists($MarkerPath)) {+ if ((Publish-MarkerNew $Body) -eq 'published') { return $true }+ } else {+ $tmp = $null+ try {+ $tmp = Write-MarkerTemp $Body+ [System.IO.File]::Replace($tmp, $MarkerPath, [NullString]::Value)+ return $true+ } catch {+ if ($tmp) { Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue }+ }+ }+ Start-Sleep -Milliseconds 50}+ return $false}-function Remove-MarkerIfUnchanged([string]$Expected) {- # Compare-and-delete: never unlink by path on an older verdict.- if ((Read-MarkerText) -cne $Expected) { return $false }- try { [System.IO.File]::Delete($MarkerPath); return $true } catch { return $false }+function Remove-MarkerLocked {+ # Caller holds the A7 lock and judged the marker inside that hold.+ for ($attempt = 0; $attempt -lt 20; $attempt++) {+ try { [System.IO.File]::Delete($MarkerPath); return $true } catch {}+ Start-Sleep -Milliseconds 50+ }+ return $false}function Test-MarkerFileYoung {@@ -177,111 +320,13 @@ function Test-MarkerFileYoung {try { return ([DateTime]::UtcNow - [System.IO.File]::GetLastWriteTimeUtc($MarkerPath)).TotalSeconds -lt 5 } catch { return $false }}-function Invoke-MarkerClaim {- # A hand-off started by the Desktop (-DesktopPid) only ADOPTS the- # Desktop's bridge claim (A4): no bridge, or a bridge that is not that- # Desktop's live claim, means the Desktop already gave up on this run.- $epoch = [DateTimeOffset]::UtcNow.ToUnixTimeSeconds()- $startedAt = 0L- $hasStartedAt = [int64]::TryParse($env:HERMES_UPDATE_STARTED_AT, [ref]$startedAt)- if (-not $hasStartedAt -or $startedAt -gt $epoch -or ($epoch - $startedAt) -gt $script:MarkerCeilingSeconds) {- $startedAt = $epoch- }- $script:StartedAt = $startedAt- $own = Get-LiveProcessCt $PID- $ctLine = if ($null -ne $own.Ct) { "ct:$(Format-Ct $own.Ct)`n" } else { "" }- for ($attempt = 0; $attempt -lt 3; $attempt++) {- # LF framing on purpose: the Rust/TS/Python readers split on "\n".- $body = "$PID`n$($script:StartedAt)`n$ctLine"- if ($DesktopPid -le 0) {- switch (Publish-MarkerNew $body) {- "published" {- $script:MarkerBody = $body- Write-HandoffLog "claimed update marker (pid $PID)"- return "claimed"- }- "unwritable" { return "unwritable" }- }- }- $seen = Read-MarkerText- if ($null -eq $seen) {- if ($DesktopPid -gt 0) {- Write-HandoffLog "no update marker from the Desktop (pid $DesktopPid): it gave up on this hand-off; exiting without claiming"- return "refused"- }- continue- }- $info = ConvertFrom-MarkerText $seen- $ownerLive = Test-MarkerOwnerLive $info- $delegateLive = Test-MarkerDelegateLive $info- if ($seen -eq "" -and (Test-MarkerFileYoung)) { $ownerLive = $true }- if ($DesktopPid -gt 0) {- if ($ownerLive -and -not $delegateLive -and $info.Pid -eq $DesktopPid) {- # One acquisition time for the whole chain: keep its started_at.- if ($info.StartedAt -gt 0 -and $info.StartedAt -le $epoch) { $script:StartedAt = $info.StartedAt }- $body = "$PID`n$($script:StartedAt)`n$ctLine"- if (Set-MarkerIfUnchanged $seen $body) {- $script:MarkerBody = $body- Write-HandoffLog "adopted update marker from desktop pid $DesktopPid (pid $PID)"- return "adopted"- }- continue- }- Write-HandoffLog "update marker is not the live bridge claim of desktop pid ${DesktopPid}: it gave up on this hand-off; exiting without claiming"- return "refused"- }- if ($ownerLive -or $delegateLive) {- $script:MarkerBlocker = if ($delegateLive) { $info.DelegatePid } elseif ($info) { $info.Pid } else { 0 }- Write-HandoffLog "update marker is held by live pid $($script:MarkerBlocker); refusing"- return "refused"- }- $stalePid = if ($info) { $info.Pid } else { "?" }- Write-HandoffLog "reclaiming stale update marker (owner pid $stalePid is not running)"- [void](Remove-MarkerIfUnchanged $seen)- }- return "refused"-}--function Remove-MarkerIfOwned {- # Compare-and-delete (C1 rule 5): only our own lines 1-3, and never while- # a line-4 delegate (an update process running under our claim) lives.- if ($NoMarkerCleanup -or $null -eq $script:MarkerBody) { return }- try {- $seen = Read-MarkerText- if ($null -eq $seen) { return }- if ((Get-MarkerHead $seen) -cne (Get-MarkerHead $script:MarkerBody)) {- $firstLine = (@($seen -split "`n"))[0]- Write-HandoffLog "leaving update marker: owned by pid '$firstLine', not us ($PID)"- return- }- $info = ConvertFrom-MarkerText $seen- if (Test-MarkerDelegateLive $info) {- Write-HandoffLog "keeping update marker: delegate pid $($info.DelegatePid) is still running"- return- }- if (Remove-MarkerIfUnchanged $seen) { Write-HandoffLog "removed update marker (owned)" }- } catch {}+function Read-MarkerLocked($Ctx) {+ # absent | busy (unreadable, or an empty claim in flight) | judged.+ if (-not [System.IO.File]::Exists($MarkerPath)) { return @{ State = 'absent'; Info = $null; Judgement = @{ Verdict = 'absent'; Owner = $null; OwnerState = 'dead'; DelegateState = 'none'; Run = $null } } }+ $text = Read-MarkerText+ if ($null -eq $text -or ($text.Length -eq 0 -and (Test-MarkerFileYoung))) { return @{ State = 'busy'; Info = $null; Judgement = $null } }+ $info = ConvertFrom-MarkerText $text+ return @{ State = 'judged'; Info = $info; Judgement = (Get-MarkerJudgement $info $Ctx) }}-function Add-MarkerDelegate([int[]]$Candidates) {- # Name a running updater process (the `hermes update` child as soon as it- # starts, or a member of a tree that could not be quiesced) as the- # marker's delegate so every reader keeps it LIVE exactly as long as that- # process lives, instead of judging it dead with this script. A2 readers- # ignore a delegate line without a creation time, so a member whose time- # cannot be read is skipped.- if ($null -eq $script:MarkerBody) { return }- $seen = Read-MarkerText- if ($null -eq $seen -or (Get-MarkerHead $seen) -cne (Get-MarkerHead $script:MarkerBody)) { return }- if (Test-MarkerDelegateLive (ConvertFrom-MarkerText $seen)) { return }- foreach ($candidate in @($Candidates)) {- if ($candidate -le 0 -or $candidate -eq $PID) { continue }- $probe = Get-LiveProcessCt $candidate- if (-not $probe.Alive -or $null -eq $probe.Ct) { continue }- $line = "delegate:$candidate ct:$(Format-Ct $probe.Ct)"- if (Set-MarkerIfUnchanged $seen ((Get-MarkerHead $script:MarkerBody) + "`n" + $line + "`n")) {- Write-HandoffLog "update marker now names updater pid $candidate as its delegate"- }- return- }-}+. (Join-Path $PSScriptRoot 'marker-claim.ps1')diff --git a/scripts/desktop-update/update-job.ps1 b/scripts/desktop-update/update-job.ps1new file mode 100644index 00000000000..897b8873d81--- /dev/null+++ b/scripts/desktop-update/update-job.ps1@@ -0,0 +1,302 @@+# update-job.ps1 -- the Win32 job/process helper windows.ps1 runs every+# hermes step through (dot-sourced after the marker claim, never before it:+# Add-Type is not allowed in the claim path). StartAssigned creates the step+# SUSPENDED inside a private job (kill-on-close until Resume), so windows.ps1+# can publish the update marker's delegate before the first instruction runs.++if (-not ("HermesUpdateJob" -as [type])) {+ Add-Type -TypeDefinition @'+using System;+using System.Diagnostics;+using System.IO;+using System.Runtime.InteropServices;+using System.Text;+using System.Threading;+using Microsoft.Win32.SafeHandles;++public static class HermesUpdateJob {+ public sealed class StartedProcess {+ public Process Process;+ public StreamReader StandardOutput;+ public StreamReader StandardError;+ public IntPtr Job;+ public IntPtr Thread;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct BasicLimitInformation {+ public long PerProcessUserTimeLimit;+ public long PerJobUserTimeLimit;+ public uint LimitFlags;+ public UIntPtr MinimumWorkingSetSize;+ public UIntPtr MaximumWorkingSetSize;+ public uint ActiveProcessLimit;+ public UIntPtr Affinity;+ public uint PriorityClass;+ public uint SchedulingClass;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct ExtendedLimitInformation {+ public BasicLimitInformation Basic;+ public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount;+ public ulong ReadTransferCount, WriteTransferCount, OtherTransferCount;+ public UIntPtr ProcessMemoryLimit;+ public UIntPtr JobMemoryLimit;+ public UIntPtr PeakProcessMemoryUsed;+ public UIntPtr PeakJobMemoryUsed;+ }++ [DllImport("kernel32.dll", SetLastError = true)]+ private static extern bool SetInformationJobObject(IntPtr job, int informationClass, ref ExtendedLimitInformation information, uint length);++ // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE (0x2000) on, or every limit off.+ private static bool SetKillOnClose(IntPtr job, bool on) {+ ExtendedLimitInformation information = new ExtendedLimitInformation();+ information.Basic.LimitFlags = on ? 0x2000u : 0u;+ return SetInformationJobObject(job, 9, ref information, (uint)Marshal.SizeOf(typeof(ExtendedLimitInformation)));+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct SecurityAttributes {+ public int Length;+ public IntPtr SecurityDescriptor;+ public bool InheritHandle;+ }++ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]+ private struct StartupInfo {+ public int Size;+ public string Reserved;+ public string Desktop;+ public string Title;+ public int X;+ public int Y;+ public int XSize;+ public int YSize;+ public int XCountChars;+ public int YCountChars;+ public int FillAttribute;+ public int Flags;+ public short ShowWindow;+ public short Reserved2;+ public IntPtr Reserved2Ptr;+ public IntPtr StdInput;+ public IntPtr StdOutput;+ public IntPtr StdError;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct ProcessInformation {+ public IntPtr Process;+ public IntPtr Thread;+ public int ProcessId;+ public int ThreadId;+ }++ [StructLayout(LayoutKind.Sequential)]+ private struct BasicAccountingInformation {+ public long TotalUserTime;+ public long TotalKernelTime;+ public long ThisPeriodTotalUserTime;+ public long ThisPeriodTotalKernelTime;+ public uint TotalPageFaultCount;+ public uint TotalProcesses;+ public uint ActiveProcesses;+ public uint TotalTerminatedProcesses;+ }++ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ private static extern IntPtr CreateJobObject(IntPtr attributes, string name);++ [DllImport("kernel32.dll", SetLastError = true)]+ private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);++ [DllImport("kernel32.dll", SetLastError = true)]+ private static extern bool CreatePipe(out IntPtr read, out IntPtr write, ref SecurityAttributes attributes, int size);++ [DllImport("kernel32.dll", SetLastError = true)]+ private static extern bool SetHandleInformation(IntPtr handle, int mask, int flags);++ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ private static extern IntPtr CreateFile(+ string fileName, uint desiredAccess, uint shareMode, ref SecurityAttributes attributes,+ uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile+ );++ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]+ private static extern bool CreateProcess(+ string applicationName, StringBuilder commandLine,+ IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandles,+ int creationFlags, IntPtr environment, string currentDirectory,+ ref StartupInfo startupInfo, out ProcessInformation processInformation+ );++ [DllImport("kernel32.dll", SetLastError = true)]+ private static extern uint ResumeThread(IntPtr thread);++ [DllImport("kernel32.dll", SetLastError = true)]+ private static extern bool TerminateProcess(IntPtr process, uint exitCode);++ [DllImport("kernel32.dll", SetLastError = true)]+ private static extern bool TerminateJobObject(IntPtr job, uint exitCode);++ [DllImport("kernel32.dll", SetLastError = true)]+ private static extern bool QueryInformationJobObject(+ IntPtr job,+ int informationClass,+ out BasicAccountingInformation information,+ uint informationLength,+ IntPtr returnLength+ );++ [DllImport("kernel32.dll", EntryPoint = "QueryInformationJobObject", SetLastError = true)]+ private static extern bool QueryInformationJobObjectRaw(+ IntPtr job, int informationClass, IntPtr information, uint informationLength, IntPtr returnLength);++ [DllImport("kernel32.dll")]+ private static extern bool CloseHandle(IntPtr handle);++ // Pids still assigned to the job (JobObjectBasicProcessIdList).+ public static int[] ProcessIds(IntPtr job) {+ if (job == IntPtr.Zero) return new int[0];+ const int capacity = 1024;+ int size = 8 + IntPtr.Size * capacity;+ IntPtr buffer = Marshal.AllocHGlobal(size);+ try {+ Marshal.WriteInt64(buffer, 0, 0);+ if (!QueryInformationJobObjectRaw(job, 3, buffer, (uint)size, IntPtr.Zero)) return new int[0];+ int count = Marshal.ReadInt32(buffer, 4);+ int[] ids = new int[count];+ for (int i = 0; i < count; i++) ids[i] = (int)Marshal.ReadIntPtr(buffer, 8 + i * IntPtr.Size).ToInt64();+ return ids;+ } finally { Marshal.FreeHGlobal(buffer); }+ }++ // CPU time plus I/O bytes the job's processes have spent so far+ // (JobObjectBasicAndIoAccountingInformation: 48-byte basic accounting,+ // then IO_COUNTERS). Any change is progress; -1 when unavailable.+ public static long Activity(IntPtr job) {+ if (job == IntPtr.Zero) return -1;+ const int size = 96;+ IntPtr buffer = Marshal.AllocHGlobal(size);+ try {+ if (!QueryInformationJobObjectRaw(job, 8, buffer, size, IntPtr.Zero)) return -1;+ return Marshal.ReadInt64(buffer, 0) + Marshal.ReadInt64(buffer, 8)+ + Marshal.ReadInt64(buffer, 72) + Marshal.ReadInt64(buffer, 80) + Marshal.ReadInt64(buffer, 88);+ } finally { Marshal.FreeHGlobal(buffer); }+ }++ public static StartedProcess StartAssigned(string executable, string arguments) {+ IntPtr job = IntPtr.Zero;+ IntPtr outRead = IntPtr.Zero, outWrite = IntPtr.Zero;+ IntPtr errRead = IntPtr.Zero, errWrite = IntPtr.Zero;+ IntPtr nullInput = new IntPtr(-1);+ ProcessInformation pi = new ProcessInformation();+ try {+ job = CreateJobObject(IntPtr.Zero, null);+ if (job == IntPtr.Zero) throw new InvalidOperationException("CreateJobObject failed");+ // Until Resume: should this script die while the child is still+ // suspended, closing the job kills it before it ran anything.+ if (!SetKillOnClose(job, true)) throw new InvalidOperationException("SetInformationJobObject failed");+ SecurityAttributes sa = new SecurityAttributes();+ sa.Length = Marshal.SizeOf(typeof(SecurityAttributes));+ sa.InheritHandle = true;+ if (!CreatePipe(out outRead, out outWrite, ref sa, 0) ||+ !CreatePipe(out errRead, out errWrite, ref sa, 0))+ throw new InvalidOperationException("CreatePipe failed");+ if (!SetHandleInformation(outRead, 1, 0) || !SetHandleInformation(errRead, 1, 0))+ throw new InvalidOperationException("SetHandleInformation failed");+ // Steps read NUL, never the hand-off console. A step that sees a+ // console asks its question into the captured stdout, where the+ // user cannot see it, and waits for an answer that never comes.+ nullInput = CreateFile("NUL", 0x80000000, 0x00000003, ref sa, 3, 0, IntPtr.Zero);+ if (nullInput == new IntPtr(-1))+ throw new InvalidOperationException("CreateFile(NUL) failed");++ StartupInfo si = new StartupInfo();+ si.Size = Marshal.SizeOf(typeof(StartupInfo));+ si.Flags = 0x00000100; // STARTF_USESTDHANDLES+ si.StdInput = nullInput;+ si.StdOutput = outWrite;+ si.StdError = errWrite;+ StringBuilder commandLine = new StringBuilder("\"" + executable + "\" " + arguments);+ if (!CreateProcess(executable, commandLine, IntPtr.Zero, IntPtr.Zero, true,+ 0x00000004 | 0x08000000, IntPtr.Zero, null, ref si, out pi))+ throw new InvalidOperationException("CreateProcess failed");+ if (!AssignProcessToJobObject(job, pi.Process)) {+ TerminateProcess(pi.Process, 1);+ throw new InvalidOperationException("AssignProcessToJobObject failed");+ }++ Process process = Process.GetProcessById(pi.ProcessId);+ // Force Process to open its own stable query handle before the raw+ // CreateProcess handle is closed; PS 5.1 otherwise reports a null+ // ExitCode after fast children have already disappeared.+ IntPtr stableProcessHandle = process.Handle;+ StreamReader stdout = new StreamReader(new FileStream(+ new SafeFileHandle(outRead, true), FileAccess.Read, 4096, false), Encoding.UTF8);+ StreamReader stderr = new StreamReader(new FileStream(+ new SafeFileHandle(errRead, true), FileAccess.Read, 4096, false), Encoding.UTF8);+ outRead = IntPtr.Zero;+ errRead = IntPtr.Zero;+ CloseHandle(outWrite); outWrite = IntPtr.Zero;+ CloseHandle(errWrite); errWrite = IntPtr.Zero;+ // Still suspended: the caller publishes the marker delegate, then Resume().+ StartedProcess started = new StartedProcess { Process = process, StandardOutput = stdout, StandardError = stderr, Job = job, Thread = pi.Thread };+ pi.Thread = IntPtr.Zero;+ return started;+ } catch {+ if (pi.Process != IntPtr.Zero) TerminateProcess(pi.Process, 1);+ if (job != IntPtr.Zero) CloseHandle(job);+ throw;+ } finally {+ if (pi.Thread != IntPtr.Zero) CloseHandle(pi.Thread);+ if (pi.Process != IntPtr.Zero) CloseHandle(pi.Process);+ if (outRead != IntPtr.Zero) CloseHandle(outRead);+ if (outWrite != IntPtr.Zero) CloseHandle(outWrite);+ if (errRead != IntPtr.Zero) CloseHandle(errRead);+ if (errWrite != IntPtr.Zero) CloseHandle(errWrite);+ if (nullInput != new IntPtr(-1)) CloseHandle(nullInput);+ }+ }++ public static void Resume(StartedProcess started) {+ // Detached services a successful step starts must outlive the job+ // handle: drop kill-on-close before the first instruction runs.+ try {+ if (!SetKillOnClose(started.Job, false)) {+ TerminateJobObject(started.Job, 1);+ throw new InvalidOperationException("SetInformationJobObject failed");+ }+ if (ResumeThread(started.Thread) == 0xffffffff) {+ TerminateJobObject(started.Job, 1);+ throw new InvalidOperationException("ResumeThread failed");+ }+ } finally {+ if (started.Thread != IntPtr.Zero) CloseHandle(started.Thread);+ started.Thread = IntPtr.Zero;+ }+ }++ public static bool TerminateAndWait(IntPtr job, uint exitCode, int timeoutMs) {+ if (job == IntPtr.Zero || !TerminateJobObject(job, exitCode)) return false;+ Stopwatch clock = Stopwatch.StartNew();+ BasicAccountingInformation information;+ do {+ if (!QueryInformationJobObject(+ job, 1, out information,+ (uint)Marshal.SizeOf(typeof(BasicAccountingInformation)),+ IntPtr.Zero)) return false;+ if (information.ActiveProcesses == 0) return true;+ Thread.Sleep(50);+ } while (clock.ElapsedMilliseconds < timeoutMs);+ return false;+ }++ public static void Close(IntPtr job) {+ if (job != IntPtr.Zero) CloseHandle(job);+ }+}+'@+}diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1index c666e2a37aa..53a33c89381 100644--- a/scripts/desktop-update/windows.ps1+++ b/scripts/desktop-update/windows.ps1@@ -26,6 +26,18 @@# [-NoUi] headless (tests); default shows a progress window# [-NoMarkerCleanup] leave .hermes-update-in-progress in place (tests)# [-ProbeTimeoutSeconds <n>] launcher probe bound, default 60 (tests)+# [-HandoffRun <id>] protocol 2: the run id of the Desktop's bridge claim+#+# hermes-handoff-protocol: 2+# (exact line above: the Desktop reads it to learn this script speaks hand-off+# protocol 2 -- it accepts -HandoffRun and the -MarkerOp helper below.)+#+# HELPER OPS (Electron's only way to mutate the marker; runs right after+# marker.ps1 loads -- no UI, log rotation, result or relaunch):+# powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File windows.ps1+# -MarkerOp reclaim|withdraw -InstallRoot <root> [-DesktopPid P] [-HandoffRun R]+# prints ONE line (absent | reclaimed | live <pid> | busy | withdrawn |+# taken <pid> | foreign) and exits 0; 64 on bad usage.## SAFETY POSTURE: both preflight gates FAIL CLOSED. A Desktop that never# exits, or a venv shim that never unlocks, aborts the hand-off without@@ -35,16 +47,16 @@# relaunches the Desktop so the user is never left stranded. The one# exception is a refused run (exit 2): it changed nothing and writes no result.#-# Marker (contract C1 v2, marker.ps1): claiming HERMES_HOME\.hermes-update-+# Marker (contract C1 v2 + A7, marker.ps1): claiming HERMES_HOME\.hermes-update-# in-progress is the FIRST thing the script does -- before any Add-Type, UI-# or probe. Started with -DesktopPid it only adopts that Desktop's live-# bridge claim (compare-and-swap); otherwise it publishes a fresh claim with-# an exclusive hard link. Any other live owner refuses the run (exit 2,-# nothing changed, no result file); a dead owner is compare-and-deleted and-# the claim retried. hermes_cli/update_lock.py's ancestry rule lets our-# `hermes update` child run under the claim (it may add a line-4 delegate).-# Release is compare-and-delete and never drops a marker whose delegate is-# still running.+# or probe -- and every read/judge/mutate of it happens inside one hold of+# the kernel lock on "<marker>.lock". With -HandoffRun it only adopts the+# Desktop's bridge for that run; with only -DesktopPid (an old packaged+# Desktop) it accepts that Desktop's cmd.exe launcher claim by lineage;+# otherwise it claims fresh, reclaiming a dead marker. Any other live owner+# refuses the run (exit 2, nothing changed, no result file). The `hermes+# update` child is named as the line-4 delegate BEFORE it is resumed.+# Release deletes our claim, or hands it to a still-running delegate.param([string]$InstallRoot,@@ -60,9 +72,16 @@ param([switch]$SelfTestUi,[switch]$SelfTestPipeDrain,[switch]$SelfTestMarker,- [switch]$SelfTestWorkingDirectory+ [switch]$SelfTestWorkingDirectory,+ [string]$HandoffRun = "",+ [string]$MarkerOp = "")+if ($MarkerOp -and -not $InstallRoot) {+ [Console]::Error.WriteLine("-MarkerOp needs -InstallRoot")+ exit 64+}+if ($PSBoundParameters.ContainsKey("Branch") -and $PSBoundParameters.ContainsKey("Channel")) {throw "-Branch and -Channel are mutually exclusive"}@@ -86,6 +105,7 @@ $ResultPath = Join-Path $HermesHome ".hermes-update-result.json"function Write-HandoffLog([string]$Message) {$line = "{0:yyyy-MM-ddTHH:mm:ssK} {1}" -f (Get-Date), $Messagetry { Add-Content -LiteralPath $LogPath -Value $line -Encoding UTF8 } catch {}+ if ($MarkerOp) { return } # a helper op's stdout is its one verdict lineif ($script:ConsoleInput -and [HermesHandoff.ConsoleInput]::Selecting()) { return }Write-Host $line}@@ -99,6 +119,9 @@ try { . (Join-Path $PSScriptRoot 'marker.ps1') } catch {exit 3}+# Helper op (SPEC 6): one verdict line, before any UI, result or relaunch.+if ($MarkerOp) { exit (Invoke-MarkerOpCli $MarkerOp $DesktopPid $HandoffRun) }+# The Desktop's identity is pinned now: a reused pid later is not "still open".$script:DesktopCt = $null$script:DesktopSeenAlive = $false@@ -918,245 +941,7 @@ function Get-StepProgressLogStamp {}}-if (-not ("HermesUpdateJob" -as [type])) {- Add-Type -TypeDefinition @'-using System;-using System.Diagnostics;-using System.IO;-using System.Runtime.InteropServices;-using System.Text;-using System.Threading;-using Microsoft.Win32.SafeHandles;--public static class HermesUpdateJob {- public sealed class StartedProcess {- public Process Process;- public StreamReader StandardOutput;- public StreamReader StandardError;- public IntPtr Job;- }-- [StructLayout(LayoutKind.Sequential)]- private struct SecurityAttributes {- public int Length;- public IntPtr SecurityDescriptor;- public bool InheritHandle;- }-- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]- private struct StartupInfo {- public int Size;- public string Reserved;- public string Desktop;- public string Title;- public int X;- public int Y;- public int XSize;- public int YSize;- public int XCountChars;- public int YCountChars;- public int FillAttribute;- public int Flags;- public short ShowWindow;- public short Reserved2;- public IntPtr Reserved2Ptr;- public IntPtr StdInput;- public IntPtr StdOutput;- public IntPtr StdError;- }-- [StructLayout(LayoutKind.Sequential)]- private struct ProcessInformation {- public IntPtr Process;- public IntPtr Thread;- public int ProcessId;- public int ThreadId;- }-- [StructLayout(LayoutKind.Sequential)]- private struct BasicAccountingInformation {- public long TotalUserTime;- public long TotalKernelTime;- public long ThisPeriodTotalUserTime;- public long ThisPeriodTotalKernelTime;- public uint TotalPageFaultCount;- public uint TotalProcesses;- public uint ActiveProcesses;- public uint TotalTerminatedProcesses;- }-- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]- private static extern IntPtr CreateJobObject(IntPtr attributes, string name);-- [DllImport("kernel32.dll", SetLastError = true)]- private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);-- [DllImport("kernel32.dll", SetLastError = true)]- private static extern bool CreatePipe(out IntPtr read, out IntPtr write, ref SecurityAttributes attributes, int size);-- [DllImport("kernel32.dll", SetLastError = true)]- private static extern bool SetHandleInformation(IntPtr handle, int mask, int flags);-- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]- private static extern IntPtr CreateFile(- string fileName, uint desiredAccess, uint shareMode, ref SecurityAttributes attributes,- uint creationDisposition, uint flagsAndAttributes, IntPtr templateFile- );-- [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]- private static extern bool CreateProcess(- string applicationName, StringBuilder commandLine,- IntPtr processAttributes, IntPtr threadAttributes, bool inheritHandles,- int creationFlags, IntPtr environment, string currentDirectory,- ref StartupInfo startupInfo, out ProcessInformation processInformation- );-- [DllImport("kernel32.dll", SetLastError = true)]- private static extern uint ResumeThread(IntPtr thread);-- [DllImport("kernel32.dll", SetLastError = true)]- private static extern bool TerminateProcess(IntPtr process, uint exitCode);-- [DllImport("kernel32.dll", SetLastError = true)]- private static extern bool TerminateJobObject(IntPtr job, uint exitCode);-- [DllImport("kernel32.dll", SetLastError = true)]- private static extern bool QueryInformationJobObject(- IntPtr job,- int informationClass,- out BasicAccountingInformation information,- uint informationLength,- IntPtr returnLength- );-- [DllImport("kernel32.dll", EntryPoint = "QueryInformationJobObject", SetLastError = true)]- private static extern bool QueryInformationJobObjectRaw(- IntPtr job, int informationClass, IntPtr information, uint informationLength, IntPtr returnLength);-- [DllImport("kernel32.dll")]- private static extern bool CloseHandle(IntPtr handle);-- // Pids still assigned to the job (JobObjectBasicProcessIdList).- public static int[] ProcessIds(IntPtr job) {- if (job == IntPtr.Zero) return new int[0];- const int capacity = 1024;- int size = 8 + IntPtr.Size * capacity;- IntPtr buffer = Marshal.AllocHGlobal(size);- try {- Marshal.WriteInt64(buffer, 0, 0);- if (!QueryInformationJobObjectRaw(job, 3, buffer, (uint)size, IntPtr.Zero)) return new int[0];- int count = Marshal.ReadInt32(buffer, 4);- int[] ids = new int[count];- for (int i = 0; i < count; i++) ids[i] = (int)Marshal.ReadIntPtr(buffer, 8 + i * IntPtr.Size).ToInt64();- return ids;- } finally { Marshal.FreeHGlobal(buffer); }- }-- // CPU time plus I/O bytes the job's processes have spent so far- // (JobObjectBasicAndIoAccountingInformation: 48-byte basic accounting,- // then IO_COUNTERS). Any change is progress; -1 when unavailable.- public static long Activity(IntPtr job) {- if (job == IntPtr.Zero) return -1;- const int size = 96;- IntPtr buffer = Marshal.AllocHGlobal(size);- try {- if (!QueryInformationJobObjectRaw(job, 8, buffer, size, IntPtr.Zero)) return -1;- return Marshal.ReadInt64(buffer, 0) + Marshal.ReadInt64(buffer, 8)- + Marshal.ReadInt64(buffer, 72) + Marshal.ReadInt64(buffer, 80) + Marshal.ReadInt64(buffer, 88);- } finally { Marshal.FreeHGlobal(buffer); }- }-- public static StartedProcess StartAssigned(string executable, string arguments) {- IntPtr job = IntPtr.Zero;- IntPtr outRead = IntPtr.Zero, outWrite = IntPtr.Zero;- IntPtr errRead = IntPtr.Zero, errWrite = IntPtr.Zero;- IntPtr nullInput = new IntPtr(-1);- ProcessInformation pi = new ProcessInformation();- try {- job = CreateJobObject(IntPtr.Zero, null);- if (job == IntPtr.Zero) throw new InvalidOperationException("CreateJobObject failed");- SecurityAttributes sa = new SecurityAttributes();- sa.Length = Marshal.SizeOf(typeof(SecurityAttributes));- sa.InheritHandle = true;- if (!CreatePipe(out outRead, out outWrite, ref sa, 0) ||- !CreatePipe(out errRead, out errWrite, ref sa, 0))- throw new InvalidOperationException("CreatePipe failed");- if (!SetHandleInformation(outRead, 1, 0) || !SetHandleInformation(errRead, 1, 0))- throw new InvalidOperationException("SetHandleInformation failed");- // Steps read NUL, never the hand-off console. A step that sees a- // console asks its question into the captured stdout, where the- // user cannot see it, and waits for an answer that never comes.- nullInput = CreateFile("NUL", 0x80000000, 0x00000003, ref sa, 3, 0, IntPtr.Zero);- if (nullInput == new IntPtr(-1))- throw new InvalidOperationException("CreateFile(NUL) failed");-- StartupInfo si = new StartupInfo();- si.Size = Marshal.SizeOf(typeof(StartupInfo));- si.Flags = 0x00000100; // STARTF_USESTDHANDLES- si.StdInput = nullInput;- si.StdOutput = outWrite;- si.StdError = errWrite;- StringBuilder commandLine = new StringBuilder("\"" + executable + "\" " + arguments);- if (!CreateProcess(executable, commandLine, IntPtr.Zero, IntPtr.Zero, true,- 0x00000004 | 0x08000000, IntPtr.Zero, null, ref si, out pi))- throw new InvalidOperationException("CreateProcess failed");- if (!AssignProcessToJobObject(job, pi.Process)) {- TerminateProcess(pi.Process, 1);- throw new InvalidOperationException("AssignProcessToJobObject failed");- }-- Process process = Process.GetProcessById(pi.ProcessId);- // Force Process to open its own stable query handle before the raw- // CreateProcess handle is closed; PS 5.1 otherwise reports a null- // ExitCode after fast children have already disappeared.- IntPtr stableProcessHandle = process.Handle;- StreamReader stdout = new StreamReader(new FileStream(- new SafeFileHandle(outRead, true), FileAccess.Read, 4096, false), Encoding.UTF8);- StreamReader stderr = new StreamReader(new FileStream(- new SafeFileHandle(errRead, true), FileAccess.Read, 4096, false), Encoding.UTF8);- outRead = IntPtr.Zero;- errRead = IntPtr.Zero;- CloseHandle(outWrite); outWrite = IntPtr.Zero;- CloseHandle(errWrite); errWrite = IntPtr.Zero;- if (ResumeThread(pi.Thread) == 0xffffffff)- throw new InvalidOperationException("ResumeThread failed");- return new StartedProcess { Process = process, StandardOutput = stdout, StandardError = stderr, Job = job };- } catch {- if (pi.Process != IntPtr.Zero) TerminateProcess(pi.Process, 1);- if (job != IntPtr.Zero) CloseHandle(job);- throw;- } finally {- if (pi.Thread != IntPtr.Zero) CloseHandle(pi.Thread);- if (pi.Process != IntPtr.Zero) CloseHandle(pi.Process);- if (outRead != IntPtr.Zero) CloseHandle(outRead);- if (outWrite != IntPtr.Zero) CloseHandle(outWrite);- if (errRead != IntPtr.Zero) CloseHandle(errRead);- if (errWrite != IntPtr.Zero) CloseHandle(errWrite);- if (nullInput != new IntPtr(-1)) CloseHandle(nullInput);- }- }-- public static bool TerminateAndWait(IntPtr job, uint exitCode, int timeoutMs) {- if (job == IntPtr.Zero || !TerminateJobObject(job, exitCode)) return false;- Stopwatch clock = Stopwatch.StartNew();- BasicAccountingInformation information;- do {- if (!QueryInformationJobObject(- job, 1, out information,- (uint)Marshal.SizeOf(typeof(BasicAccountingInformation)),- IntPtr.Zero)) return false;- if (information.ActiveProcesses == 0) return true;- Thread.Sleep(50);- } while (clock.ElapsedMilliseconds < timeoutMs);- return false;- }-- public static void Close(IntPtr job) {- if (job != IntPtr.Zero) CloseHandle(job);- }-}-'@-}+. (Join-Path $PSScriptRoot 'update-job.ps1')function Step-PipeDrain($Reader, [ref]$Task, $Buffer, $Sink, [ref]$Moved) {# Advance one redirected pipe by whatever has already arrived, without@@ -1232,11 +1017,19 @@ function Invoke-HermesStep([string]$Exe, [string[]]$HermesArgs, [string]$Tag) {if ($null -eq $savedPythonUnbuffered) { Remove-Item Env:PYTHONUNBUFFERED -ErrorAction SilentlyContinue } else { $env:PYTHONUNBUFFERED = $savedPythonUnbuffered }}$proc = $started.Process- # C1 rule 6: the update child is the marker's delegate from its first- # instant. Killed before that child takes the update lock (about a second- # of Python start-up), this script would otherwise leave a marker that- # reads DEAD while the update goes on.- if ($Tag -eq 'update') { Add-MarkerDelegate @($proc.Id) }+ # C1 rule 6 + SPEC 5: the update child is the marker's delegate from its+ # first instruction. It is still SUSPENDED here (and its job kills it if+ # this script dies first), so no update work can run before the delegate+ # line is published under the marker lock -- and none runs when it can't be.+ if ($Tag -eq 'update') {+ $delegate = Add-MarkerDelegate @($proc.Id)+ if ($delegate -notin @('published', 'kept')) {+ [void][HermesUpdateJob]::TerminateAndWait($started.Job, 1, 5000)+ [HermesUpdateJob]::Close($started.Job)+ throw "could not name the update process as the update marker's delegate ($delegate); nothing was run"+ }+ }+ [HermesUpdateJob]::Resume($started)$stdoutReader = $started.StandardOutput$stderrReader = $started.StandardError$job = $started.Job@@ -1338,6 +1131,7 @@ function Invoke-HermesStep([string]$Exe, [string[]]$HermesArgs, [string]$Tag) {}}if ($script:Ui) { [System.Windows.Forms.Application]::DoEvents() }+ Update-MarkerHeartbeat}# Bounded overload deliberately: the argument-less overload also waits on# redirected streams, which is the very wait we just bounded. HasExited is@@ -1882,7 +1676,7 @@ try {# A failed job termination means a mutating descendant may still own# checkout/install files. Keep the marker LIVE for as long as a# surviving member does and do not relaunch into that state.- Add-MarkerDelegate $script:UnquiescedPids+ [void](Add-MarkerDelegate $script:UnquiescedPids)if ($script:Committed) {# C3: the update landed; only a follow-up step outlived its cancellation.$finalCode = 0@@ -1905,7 +1699,7 @@ try {}$manualAction = $finalCode -eq 0 -and $script:ManualFollowupWrite-Result ($finalCode -eq 0) $finalCode $finalMsg $manualAction- Remove-MarkerIfOwned+ Invoke-MarkerReleaseif ($finalCode -ne 0) {Show-ErrorFinale $finalMsgClose-ProgressWindow