The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: windows hand-off reads other users' creation times and never fails a committed update
Teknium4729c737e538
diff --git a/scripts/desktop-update/marker.ps1 b/scripts/desktop-update/marker.ps1new file mode 100644index 00000000000..eacd8ab6d77--- /dev/null+++ b/scripts/desktop-update/marker.ps1@@ -0,0 +1,286 @@+# 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.+#+# 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.+#+# 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).++$script:MarkerCeilingSeconds = 1200+$script:ProcessCtCache = @{}+$script:MarkerBody = $null # what we published; release compares lines 1-3+$script:MarkerClaim = "none" # claimed | adopted | refused | unwritable+$script:MarkerBlocker = 0+$script:StartedAt = $null++function ConvertTo-UnixCt([datetime]$Time) {+ return [DateTimeOffset]::new($Time.ToUniversalTime()).ToUnixTimeMilliseconds() / 1000.0+}++function Format-Ct([double]$Ct) { return $Ct.ToString('F3', [Globalization.CultureInfo]::InvariantCulture) }++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+ # denied for those under Windows PowerShell 5.1.+ if ($ProcessId -eq $PID) { return ConvertTo-UnixCt ([Diagnostics.Process]::GetCurrentProcess().StartTime) }+ try {+ $row = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId=$ProcessId" -ErrorAction Stop+ if ($row -and $row.CreationDate) { return ConvertTo-UnixCt $row.CreationDate }+ } catch {}+ return $null+}++function Get-LiveProcessCt([int]$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+ $alive = [bool]$p+ if ($alive) { try { $alive = -not $p.HasExited } catch {} }+ if (-not $alive) {+ $script:ProcessCtCache.Remove($ProcessId)+ return @{ Alive = $false; Ct = $null }+ }+ if (-not $script:ProcessCtCache.ContainsKey($ProcessId)) {+ $script:ProcessCtCache[$ProcessId] = Get-ProcessCreationCt $ProcessId+ }+ return @{ Alive = $true; Ct = $script:ProcessCtCache[$ProcessId] }+}++function Get-ProcessIdentity([int]$ProcessId, $RecordedCt) {+ # live | dead | unknown (alive, but a creation time is missing on a side).+ $probe = Get-LiveProcessCt $ProcessId+ if (-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' }+ return 'dead'+}++function Test-ProcessIdentityLive([int]$ProcessId, $RecordedCt) {+ return (Get-ProcessIdentity $ProcessId $RecordedCt) -ne 'dead'+}++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 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 }+ $invariant = [Globalization.CultureInfo]::InvariantCulture+ if ($lines.Count -ge 3 -and $lines[2] -cmatch '^ct:([0-9]+(\.[0-9]+)?)$') {+ $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)+ }+ }+ 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 }+ }+ return $false+}++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 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+}++function Write-MarkerTemp([string]$Body) {+ $tmp = "$MarkerPath.$PID.tmp"+ [System.IO.File]::WriteAllText($tmp, $Body, (New-Object System.Text.UTF8Encoding $false))+ return $tmp+}++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.+ try { $tmp = Write-MarkerTemp $Body } catch {+ Write-HandoffLog "WARNING: could not write update marker: $($_.Exception.Message)"+ return "unwritable"+ }+ try {+ try {+ New-Item -ItemType HardLink -Path $MarkerPath -Value $tmp -ErrorAction Stop | Out-Null+ return "published"+ } catch {+ if ([System.IO.File]::Exists($MarkerPath)) { return "exists" }+ }+ # No hard links on this volume: a no-replace rename of the full body.+ try { [System.IO.File]::Move($tmp, $MarkerPath); return "published" } catch {+ if ([System.IO.File]::Exists($MarkerPath)) { return "exists" }+ Write-HandoffLog "WARNING: could not publish update marker: $($_.Exception.Message)"+ return "unwritable"+ }+ } finally {+ Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue+ }+}++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 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 Test-MarkerFileYoung {+ # A3 fallback writers create then write: an empty marker younger than 5 s+ # is a claim in flight, not a dead one.+ 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 Add-MarkerDelegate([int[]]$Candidates) {+ # The tree could not be quiesced: name a still-running member 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 surviving updater pid $candidate as its delegate"+ }+ return+ }+}diff --git a/scripts/desktop-update/runtime.ps1 b/scripts/desktop-update/runtime.ps1index af936576364..69f236a6021 100644--- a/scripts/desktop-update/runtime.ps1+++ b/scripts/desktop-update/runtime.ps1@@ -3,11 +3,8 @@ function Invoke-HermesProbe {# Every launcher probe is bounded (60 s): a launcher that hangs (a stuck# import, an AV scan) fails the probe instead of parking the hand-off# forever after the Desktop already closed. Timeout kills the probe tree.- $timeout = 60- $parsed = 0- if ($env:HERMES_UPDATE_PROBE_TIMEOUT_SECONDS -and [int]::TryParse($env:HERMES_UPDATE_PROBE_TIMEOUT_SECONDS, [ref]$parsed) -and $parsed -gt 0) {- $timeout = $parsed- }+ # windows.ps1 -ProbeTimeoutSeconds sets the bound for tests.+ $timeout = if ($HermesProbeTimeoutSeconds -gt 0) { $HermesProbeTimeoutSeconds } else { 60 }$psi = New-Object System.Diagnostics.ProcessStartInfo$psi.FileName = $Exe$psi.Arguments = (@($Arguments) | ForEach-Object { '"{0}"' -f ($_ -replace '"', '\"') }) -join ' 'diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1index 519bc9c82cd..ea91d28454b 100644--- a/scripts/desktop-update/windows.ps1+++ b/scripts/desktop-update/windows.ps1@@ -25,25 +25,26 @@# [-RelaunchExe <path>] Hermes.exe to start when done (omit = no relaunch)# [-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)## SAFETY POSTURE: both preflight gates FAIL CLOSED. A Desktop that never# exits, or a venv shim that never unlocks, aborts the hand-off without# mutating the install -- a skipped update is recoverable, a half-updated# venv is not. Every exit path (success, abort, crash) writes# .hermes-update-result.json for the relaunched Desktop to surface, and-# relaunches the Desktop so the user is never left stranded.+# 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): claiming HERMES_HOME\.hermes-update-in-progress-# is the FIRST thing the script does -- before any Add-Type, UI or probe -- so-# the Desktop sees the hand-off take over within seconds and no second update-# can start in the gap. The claim is an exclusive create (tmp + File.Move,-# which never overwrites); a live marker owned by exactly -DesktopPid (the-# Desktop's bridge claim) is adopted by compare-and-swap, any other live owner-# refuses the run (exit 2, nothing changed), a dead owner is compare-and--# deleted and the claim retried once. 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.+# Marker (contract C1 v2, 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.param([string]$InstallRoot,@@ -55,6 +56,7 @@ param([switch]$NoUi,[switch]$NoMarkerCleanup,[switch]$NoGateway,+ [int]$ProbeTimeoutSeconds = 60,[switch]$SelfTestUi,[switch]$SelfTestPipeDrain,[switch]$SelfTestMarker,@@ -88,169 +90,13 @@ function Write-HandoffLog([string]$Message) {Write-Host $line}-# -- Update marker, contract C1 v2: "<pid>\n<started_at>\nct:<creation>\n"-# plus an optional line 4 "delegate:<pid> ct:<creation>". Pure PowerShell on-# purpose: this runs before the first Add-Type.-function ConvertTo-UnixCt([datetime]$StartTime) {- return [DateTimeOffset]::new($StartTime.ToUniversalTime()).ToUnixTimeMilliseconds() / 1000.0-}--function Format-Ct([double]$Ct) { return $Ct.ToString('F3', [Globalization.CultureInfo]::InvariantCulture) }--function Get-LiveProcessCt([int]$ProcessId) {- # Alive + creation time (unix seconds, $null when it cannot be read).- if ($ProcessId -le 0) { return @{ Alive = $false; Ct = $null } }- $p = Get-Process -Id $ProcessId -ErrorAction SilentlyContinue- if (-not $p) { return @{ Alive = $false; Ct = $null } }- try { if ($p.HasExited) { return @{ Alive = $false; Ct = $null } } } catch {}- $ct = $null- try { $ct = ConvertTo-UnixCt $p.StartTime } catch {}- return @{ Alive = $true; Ct = $ct }-}--function Test-ProcessIdentityLive([int]$ProcessId, $RecordedCt) {- # Same process = pid alive AND creation time within 2 s of the recorded- # one; an unknown time on either side counts as the same process.- $probe = Get-LiveProcessCt $ProcessId- if (-not $probe.Alive) { return $false }- if ($null -eq $RecordedCt -or $null -eq $probe.Ct) { return $true }- return [Math]::Abs($probe.Ct - [double]$RecordedCt) -le 2.0-}--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 ConvertFrom-MarkerText([string]$Text) {- $lines = @($Text -split "`n" | ForEach-Object { $_.TrimEnd("`r") })- $ownerPid = 0- if ($lines.Count -lt 1 -or -not [int]::TryParse($lines[0].Trim(), [ref]$ownerPid) -or $ownerPid -le 0) { return $null }- $info = @{ Pid = $ownerPid; StartedAt = $null; Ct = $null; DelegatePid = 0; DelegateCt = $null }- $started = 0L- if ($lines.Count -ge 2 -and [int64]::TryParse($lines[1].Trim(), [ref]$started)) { $info.StartedAt = $started }- if ($lines.Count -ge 3 -and $lines[2] -match '^ct:([0-9]+(?:\.[0-9]+)?)\s*$') {- $info.Ct = [double]::Parse($Matches[1], [Globalization.CultureInfo]::InvariantCulture)- }- if ($lines.Count -ge 4 -and $lines[3] -match '^delegate:([0-9]+)(?:\s+ct:([0-9]+(?:\.[0-9]+)?))?\s*$') {- $delegateCt = $Matches[2]- $delegatePid = 0- if ([int]::TryParse($Matches[1], [ref]$delegatePid)) { $info.DelegatePid = $delegatePid }- if ($delegateCt) { $info.DelegateCt = [double]::Parse($delegateCt, [Globalization.CultureInfo]::InvariantCulture) }- }- return $info-}--function Test-MarkerDelegateLive($Info) {- return $null -ne $Info -and $Info.DelegatePid -gt 0 -and $Info.DelegatePid -ne $PID -and (Test-ProcessIdentityLive $Info.DelegatePid $Info.DelegateCt)-}--function Test-MarkerOwnerLive($Info) {- if ($null -eq $Info -or $Info.Pid -eq $PID) { return $false } # our own pid = a reused, stale claim- if (-not (Test-ProcessIdentityLive $Info.Pid $Info.Ct)) { return $false }- if ($null -eq $Info.Ct -and $null -ne $Info.StartedAt) {- # v1 marker (no creation time): keep the legacy 20-minute ceiling so- # pid reuse still self-heals. A v2 owner is live regardless of age.- return ([DateTimeOffset]::UtcNow.ToUnixTimeSeconds() - $Info.StartedAt) -le 1200- }- return $true-}--function Write-MarkerTemp([string]$Body) {- $tmp = "$MarkerPath.$PID.tmp"- [System.IO.File]::WriteAllText($tmp, $Body, (New-Object System.Text.UTF8Encoding $false))- return $tmp-}--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 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 }-}--$script:MarkerBody = $null # what we published; release compares lines 1-3-$script:MarkerClaim = "none" # claimed | adopted | refused | unwritable-$script:MarkerBlocker = 0-$script:StartedAt = $null--function Invoke-MarkerClaim {- $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 1200) {- $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"- try { $tmp = Write-MarkerTemp $body } catch {- Write-HandoffLog "WARNING: could not write update marker: $($_.Exception.Message)"- return "unwritable"- }- try {- [System.IO.File]::Move($tmp, $MarkerPath) # never overwrites- $script:MarkerBody = $body- Write-HandoffLog "claimed update marker (pid $PID)"- return "claimed"- } catch {- Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue- }- $seen = Read-MarkerText- if ($null -eq $seen) { continue }- if ($seen.Trim() -eq "") {- # A legacy writer may be between create and write.- Start-Sleep -Milliseconds 500- $seen = Read-MarkerText- if ($null -eq $seen) { continue }- }- $info = ConvertFrom-MarkerText $seen- $ownerLive = Test-MarkerOwnerLive $info- $delegateLive = Test-MarkerDelegateLive $info- if ($ownerLive -and -not $delegateLive -and $DesktopPid -gt 0 -and $info.Pid -eq $DesktopPid) {- # The Desktop's bridge claim: take it over, keeping its started_at- # so the whole chain reports one acquisition time.- if ($null -ne $info.StartedAt -and $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- }- if ($ownerLive -or $delegateLive) {- $script:MarkerBlocker = if ($delegateLive) { $info.DelegatePid } else { $info.Pid }- 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"+# Update marker (contract C1 v2 + amendments A1-A4) lives in marker.ps1 next+# to this script. It is pure PowerShell + CIM: the claim runs before the+# first Add-Type. A hand-off that cannot load it changes nothing.+New-Item -ItemType Directory -Path $LogDir -Force -ErrorAction SilentlyContinue | Out-Null+try { . (Join-Path $PSScriptRoot 'marker.ps1') } catch {+ Write-HandoffLog "Update aborted: $PSScriptRoot\marker.ps1 could not be loaded ($($_.Exception.Message)). Nothing was changed. Repair the installation and try again."+ exit 3}# The Desktop's identity is pinned now: a reused pid later is not "still open".@@ -262,7 +108,6 @@ if ($DesktopPid -gt 0) {$script:DesktopCt = $desktopProbe.Ct}if (-not $SelfTestUi -and -not $SelfTestPipeDrain) {- New-Item -ItemType Directory -Path $LogDir -Force -ErrorAction SilentlyContinue | Out-Null$script:MarkerClaim = Invoke-MarkerClaim}@@ -848,48 +693,6 @@ function Add-Followup([string]$Warning, [string]$Sentence, [switch]$Manual) {Write-HandoffLog "WARNING: $Warning"}-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 Add-MarkerDelegate([int[]]$Candidates) {- # The tree could not be quiesced: name a still-running member 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.- 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) { continue }- $line = "delegate:$candidate"- if ($null -ne $probe.Ct) { $line += " ct:$(Format-Ct $probe.Ct)" }- if (Set-MarkerIfUnchanged $seen ((Get-MarkerHead $script:MarkerBody) + "`n" + $line + "`n")) {- Write-HandoffLog "update marker now names surviving updater pid $candidate as its delegate"- }- return- }-}-function Test-DesktopAlive {if ($DesktopPid -le 0 -or -not $script:DesktopSeenAlive) { return $false }return Test-ProcessIdentityLive $DesktopPid $script:DesktopCt@@ -1832,12 +1635,12 @@ $savedConsoleInputMode = if ($script:ConsoleInput) { [HermesHandoff.ConsoleInputtry {# -- 0. The marker was claimed before anything else (top of script) -----if ($script:MarkerClaim -eq "refused") {+ # A4: this run changed nothing and owns no result -- the other update+ # (or the Desktop that gave up on this hand-off) reports its own.$finalCode = 2$blocker = if ($script:MarkerBlocker -gt 0) { " (process $($script:MarkerBlocker))" } else { "" }- $finalMsg = "Another Hermes update is already running$blocker. Nothing was changed."+ $finalMsg = "Another Hermes update is already running$blocker, or the Desktop gave up on this hand-off. Nothing was changed."Write-HandoffLog $finalMsg- # The Desktop is quitting for this hand-off; bring it back once it is gone.- [void](Wait-DesktopExit 30)exit $finalCode}# The previous result is replaced atomically at finish, never deleted here.@@ -1887,6 +1690,7 @@ try {exit 0}+ $HermesProbeTimeoutSeconds = $ProbeTimeoutSeconds. (Join-Path $PSScriptRoot 'runtime.ps1')$legacyInstall = -not (Test-Path -LiteralPath (Join-Path $InstallRoot 'pm') -PathType Container)try {@@ -1981,7 +1785,7 @@ try {$finalCode = 0$finalMsg = "Update complete."if ($script:UpdateInterrupted) {- Add-Followup "post-update steps (gateway resume) were interrupted; run hermes update again" "its post-update steps (gateway resume) were interrupted. Run 'hermes update' again to finish them." -Manual:$NoGateway+ Add-Followup "post-update steps (gateway resume) were interrupted; run hermes update again" "its post-update steps (gateway resume) were interrupted. Run 'hermes update' again to finish them." -Manual}# Pre-PM updates reported a successful exit with a failed build warning.@@ -2050,9 +1854,10 @@ try {} catch {# An unexpected throw. Before the commit point the update did not land# (exit 1 below). After it, the install IS updated: report the broken- # follow-up as a warning on an ok result (contract C3).+ # follow-up as a warning on an ok result (contract C3); an unquiesced+ # tree gets its own warning in the finally block.Write-HandoffLog "hand-off error: $($_.Exception.Message)"- if ($script:Committed) {+ if ($script:Committed -and $script:TreeSafeToFinalize) {Add-Followup "hand-off: $($_.Exception.Message)" "a post-update step failed unexpectedly. Run 'hermes update' again to finish it." -Manual$finalCode = 0}@@ -2064,19 +1869,30 @@ try {# 3. only then the terminal UI state — done means "Hermes is back",# manual means "it is not, reopen it", error is error (and still# tries to bring the app back after showing itself).- if (-not $script:TreeSafeToFinalize) {+ if ($script:MarkerClaim -eq "refused") {+ # No result (A4). An older Desktop quits right after spawning us: bring+ # it back when it is gone; one that gave up on this run is still open.+ if (-not (Test-DesktopAlive)) { [void](Start-DesktopRelaunch) }+ } elseif (-not $script:TreeSafeToFinalize) {# A failed job termination means a mutating descendant may still own- # checkout/install files. Preserve the marker and do not relaunch into- # that unknown state. This is intentionally fail-closed; the marker's- # dead-owner recovery remains the next-start escape hatch.- $finalCode = 7- $finalMsg = "Update recovery could not stop every updater process. Hermes was not restarted to avoid overlapping the active install. Wait for it to finish or restart Windows, then reopen Hermes."- # This script is about to exit while that tree runs: keep the marker- # LIVE for as long as a surviving member does.+ # 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- Write-Result $false $finalCode $finalMsg- Write-HandoffLog $finalMsg- Show-ErrorFinale $finalMsg+ if ($script:Committed) {+ # C3: the update landed; only a follow-up step outlived its cancellation.+ $finalCode = 0+ Add-Followup "follow-up processes could not be stopped" "a follow-up step's processes could not be stopped, so Hermes was not reopened. Reopen Hermes once they finish, or restart Windows first." -Manual+ $finalMsg = "Hermes was updated, but " + ($script:FollowupText -join " Also, ")+ Write-Result $true $finalCode $finalMsg $true+ Write-HandoffLog $finalMsg+ Show-ManualFinale $finalMsg+ } else {+ $finalCode = 7+ $finalMsg = "Update recovery could not stop every updater process. Hermes was not restarted to avoid overlapping the active install. Wait for it to finish or restart Windows, then reopen Hermes."+ Write-Result $false $finalCode $finalMsg+ Write-HandoffLog $finalMsg+ Show-ErrorFinale $finalMsg+ }Close-ProgressWindow} else {if ($finalCode -eq 0 -and $script:FollowupText.Count -gt 0) {diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.py b/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.pyindex 80bbb995e7b..89b4340b8c2 100644--- a/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.py+++ b/tests/scripts/desktop_update/test_desktop_update_windows_commit_outcome.py@@ -21,7 +21,7 @@ from tests.installation_launcher_fixture import publish_fixture_launcherROOT = Path(__file__).resolve().parent.parent.parent.parentSCRIPT = ROOT / 'scripts/desktop-update/windows.ps1'CLI = """-import json, os, subprocess, sys, time+import ctypes, json, os, subprocess, sys, timefrom pathlib import Pathdef main():if '--version' in sys.argv:@@ -43,9 +43,17 @@ def main():child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(600)'],stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)Path(os.environ['HANDOFF_DELEGATE']).write_text(str(child.pid))+ # update_lock's delegate line: pid + creation time (GetProcessTimes, limited rights).+ k32 = ctypes.windll.kernel32+ k32.OpenProcess.restype = ctypes.c_void_p+ handle = ctypes.c_void_p(k32.OpenProcess(0x1000, False, child.pid))+ times = [ctypes.c_ulonglong() for _ in range(4)]+ k32.GetProcessTimes(handle, *[ctypes.byref(t) for t in times])+ k32.CloseHandle(handle)+ ct = times[0].value / 1e7 - 11644473600marker = Path(os.environ['HERMES_HOME']) / '.hermes-update-in-progress'head = marker.read_bytes().decode().split('\\n')[:3]- marker.write_bytes(('\\n'.join(head) + '\\ndelegate:%d\\n' % child.pid).encode())+ marker.write_bytes(('\\n'.join(head) + '\\ndelegate:%d ct:%.3f\\n' % (child.pid, ct)).encode())if os.environ.get('HANDOFF_HANG'):print(os.environ['HANDOFF_HANG'], flush=True)time.sleep(300)@@ -59,7 +67,7 @@ if __name__ == '__main__':def _handoff(tmp_path: Path, *args: str, verify: str = 'pass\n', timeout: int = 150, **env: str):install = tmp_path / 'checkout'publish_fixture_launcher(install, CLI)- (install / 'hermes_cli/desktop_update_verify.py').write_text(verify)+ (install / 'hermes_cli/desktop_update_verify.py').write_text(verify, encoding='utf-8')home = tmp_path / 'home'; home.mkdir()calls = tmp_path / 'calls.jsonl'proc = subprocess.Popen(@@ -75,7 +83,7 @@ def _handoff(tmp_path: Path, *args: str, verify: str = 'pass\n', timeout: int =subprocess.run(['taskkill', '/T', '/F', '/PID', str(proc.pid)], capture_output=True)out, _ = proc.communicate()pytest.fail(f'hand-off did not finish within {timeout}s: {out}')- argv = [json.loads(line) for line in calls.read_text().splitlines()] if calls.exists() else []+ argv = [json.loads(line) for line in calls.read_text(encoding='utf-8-sig').splitlines()] if calls.exists() else []result = json.loads((home / '.hermes-update-result.json').read_text(encoding='utf-8-sig'))return proc.returncode, out, argv, result, home@@ -108,10 +116,10 @@ def test_marker_with_a_live_delegate_is_kept_at_finish(tmp_path: Path) -> None:code, out, _, result, home = _handoff(tmp_path, HANDOFF_DELEGATE=str(pid_file))assert code == 0, outmarker = (home / '.hermes-update-in-progress').read_bytes().decode().split('\n')- assert marker[3] == f'delegate:{pid_file.read_text()}', marker+ assert marker[3].startswith(f"delegate:{pid_file.read_text(encoding='utf-8-sig')} ct:"), markerfinally:if pid_file.exists():- subprocess.run(['taskkill', '/F', '/PID', pid_file.read_text()], capture_output=True)+ subprocess.run(['taskkill', '/F', '/PID', pid_file.read_text(encoding='utf-8-sig')], capture_output=True)@pytest.mark.platforms('windows')@@ -137,7 +145,7 @@ def test_cpu_busy_pipe_silent_update_is_not_killed_by_the_idle_watchdog(tmp_path@pytest.mark.platforms('windows')def test_hanging_update_help_probe_is_bounded(tmp_path: Path) -> None:code, out, argv, result, _ = _handoff(- tmp_path, '-NoGateway', timeout=120, HANDOFF_HELP_HANG='1', HERMES_UPDATE_PROBE_TIMEOUT_SECONDS='10',+ tmp_path, '-NoGateway', '-ProbeTimeoutSeconds', '10', timeout=120, HANDOFF_HELP_HANG='1',)assert code == 0, outassert argv[0][:2] == ['update', '--yes'] and '--keep-stash' not in argv[0], argvdiff --git a/tests/scripts/desktop_update/test_desktop_update_windows_marker.py b/tests/scripts/desktop_update/test_desktop_update_windows_marker.pyindex e30dd922102..047aef7719c 100644--- a/tests/scripts/desktop_update/test_desktop_update_windows_marker.py+++ b/tests/scripts/desktop_update/test_desktop_update_windows_marker.py@@ -43,15 +43,28 @@ def sleeper():def _creation_time(pid: int) -> str:+ # Limited query rights (what Python/Rust readers use): works for every process.out = subprocess.run(['powershell', '-NoProfile', '-Command',- f"[DateTimeOffset]::new((Get-Process -Id {pid}).StartTime.ToUniversalTime())"- ".ToUnixTimeMilliseconds().ToString()"],+ f"$c = (Get-CimInstance Win32_Process -Filter 'ProcessId={pid}').CreationDate; "+ "[DateTimeOffset]::new($c.ToUniversalTime()).ToUnixTimeMilliseconds().ToString()"],capture_output=True, text=True, timeout=60, check=True,).stdout.strip()return f'{int(out) / 1000:.3f}'+def _protected_pid() -> int:+ """A live pid whose StartTime Windows PowerShell cannot read (SYSTEM / protected)."""+ out = subprocess.run(+ ['powershell', '-NoProfile', '-Command',+ "foreach ($n in 'csrss','wininit','services','smss','lsass') { foreach ($p in @(Get-Process -Name $n "+ "-ErrorAction SilentlyContinue)) { try { $null = $p.StartTime } catch { $p.Id; exit 0 } } }"],+ capture_output=True, text=True, timeout=60,+ ).stdout.split()+ assert out, 'no process with an unreadable StartTime on this host'+ return int(out[0])++def _dead_pid() -> int:proc = subprocess.Popen([sys.executable, '-c', 'pass'])proc.wait()@@ -101,15 +114,83 @@ def test_live_foreign_owner_refuses_and_reused_pid_is_reclaimed(if ct_matches:assert code == 2, outassert (tmp_path / MARKER).read_bytes() == body- result = _result(tmp_path)- assert (result['ok'], result['exit_code']) == (False, 2)- assert 'Nothing was changed' in result['message']+ # A refused run changed nothing and owns no result (A4): the other update reports.+ assert not (tmp_path / '.hermes-update-result.json').exists()else:assert code == 0, outlines = (tmp_path / MARKER).read_bytes().decode().split('\n')assert lines[0] == str(pid) and lines[2].startswith('ct:'), lines[email protected]('windows')[email protected]('ct_matches', [True, False])+def test_owner_creation_time_is_read_for_system_processes(tmp_path: Path, ct_matches: bool) -> None:+ """A1: a marker naming a SYSTEM/protected pid (a reused pid after a reboot) is judged by its+ real creation time, not treated as live forever because StartTime is access-denied."""+ owner = _protected_pid()+ ct = _creation_time(owner) if ct_matches else '1000.000'+ body = f'{owner}\n{int(time.time())}\nct:{ct}\n'.encode()+ (tmp_path / MARKER).write_bytes(body)+ pid, code, out = _run(tmp_path, '-SelfTestMarker', '-NoMarkerCleanup')+ if ct_matches:+ assert code == 2, out+ assert (tmp_path / MARKER).read_bytes() == body+ else:+ assert code == 0, out+ assert (tmp_path / MARKER).read_bytes().decode().split('\n')[0] == str(pid)+++_BODIES = { # contract A2: identical verdicts in every reader+ 'crlf-bom-v2': ('\ufeff{pid}\r\n{now}\r\nct:{ct}\r\n', 'live'),+ 'missing-line-2': ('{pid}\n', 'dead'),+ 'garbled-line-2': ('{pid}\nsoon\nct:{ct}\n', 'dead'),+ 'fractional-started-at': ('{pid}\n{now}.5\nct:{ct}\n', 'dead'),+ 'garbled-ct-is-v1-fresh': ('{pid}\n{now}\nct:garbage\n', 'live'),+ 'garbled-ct-is-v1-past-20min': ('{pid}\n{old}\nct:garbage\n', 'dead'),+ 'delegate-without-ct-is-ignored': ('999999\n{now}\nct:1.000\ndelegate:{pid}\n', 'dead'),+}++[email protected]('windows')[email protected]('case', sorted(_BODIES))+def test_marker_bodies_are_parsed_positionally_like_every_other_reader(+ tmp_path: Path, sleeper: subprocess.Popen, case: str,+) -> None:+ template, verdict = _BODIES[case]+ now = int(time.time())+ body = template.format(pid=sleeper.pid, now=now, old=now - 1300, ct=_creation_time(sleeper.pid)).encode()+ (tmp_path / MARKER).write_bytes(body)+ pid, code, out = _run(tmp_path, '-SelfTestMarker', '-NoMarkerCleanup')+ if verdict == 'live':+ assert code == 2, out+ assert (tmp_path / MARKER).read_bytes() == body+ else:+ assert code == 0, out+ assert (tmp_path / MARKER).read_bytes().decode().split('\n')[0] == str(pid)++[email protected]('windows')[email protected]('bridge', ['absent', 'someone-else'])+def test_desktop_started_handoff_only_adopts_its_bridge(+ tmp_path: Path, sleeper: subprocess.Popen, bridge: str,+) -> None:+ """A4: the Desktop gave up on a late script: it must not claim fresh, run, or leave a result."""+ other = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(600)'])+ try:+ body = f'{other.pid}\n{int(time.time())}\nct:{_creation_time(other.pid)}\n'.encode()+ if bridge == 'someone-else':+ (tmp_path / MARKER).write_bytes(body)+ _, code, out = _run(tmp_path, '-DesktopPid', str(sleeper.pid))+ finally:+ other.kill(); other.wait()+ assert code == 2, out+ assert not (tmp_path / '.hermes-update-result.json').exists()+ if bridge == 'absent':+ assert not (tmp_path / MARKER).exists()+ else:+ assert (tmp_path / MARKER).read_bytes() == body++@pytest.mark.platforms('windows')def test_live_desktop_bridge_marker_is_adopted_keeping_its_started_at(tmp_path: Path, sleeper: subprocess.Popen,@@ -142,6 +223,8 @@ def test_desktop_that_never_exits_is_not_relaunched_over(install = tmp_path / 'checkout'publish_fixture_launcher(install, CLI)home = tmp_path / 'home'; home.mkdir()+ # The Desktop's bridge claim, which a -DesktopPid hand-off adopts (A4).+ (home / MARKER).write_bytes(f'{sleeper.pid}\n{int(time.time())}\nct:{_creation_time(sleeper.pid)}\n'.encode())relaunch = Path(os.environ.get('SystemRoot', r'C:\Windows')) / 'System32' / 'hostname.exe'_, code, out = _run(home, '-DesktopPid', str(sleeper.pid), '-RelaunchExe', str(relaunch),install=install, timeout=180)