The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: an old Desktop stays parked when the Windows hand-off dies mid-update
Tekniumd899d5a74b3c
diff --git a/scripts/desktop-update/marker-claim.ps1 b/scripts/desktop-update/marker-claim.ps1index e25f9a99330..c6949526327 100644--- a/scripts/desktop-update/marker-claim.ps1+++ b/scripts/desktop-update/marker-claim.ps1@@ -217,7 +217,7 @@ function Add-MarkerDelegate([int[]]$Candidates) {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 }+ if ($NoMarkerCleanup -or $script:MarkerClaim -notin @('claimed', 'adopted')) { Stop-MarkerCustodian; return }# R6: never while a survivor of the update still holds the checkout lock --# the marker would read free while that process still mutates the checkout.# Line 2 keeps its heartbeat through that wait: an old packaged Desktop would@@ -228,12 +228,14 @@ function Invoke-MarkerRelease {$script:MarkerReleaseWaited = $trueif ($waited -ge $script:MarkerReleaseWaitSeconds) {Write-HandoffLog "checkout update lock still held after $($waited)s; leaving the update marker"+ Stop-MarkerCustodianreturn}Update-MarkerHeartbeatStart-Sleep -Seconds 1$waited++}+ Stop-MarkerCustodian$lock = Open-MarkerLockif ($null -eq $lock) { Write-HandoffLog "update marker lock stayed busy; leaving the marker to identity-checking readers"; return }try {@@ -280,6 +282,66 @@ function Update-MarkerHeartbeat {}}+function Start-MarkerCustodian {+ # An old packaged Desktop judges the marker by lines 1 and 2 alone, and the+ # heartbeat above runs in this process: killed outright (taskkill /F runs+ # no finally) it would leave line 1 naming a dead pid while the resumed+ # `hermes update` or a completion survivor still mutates the checkout. A+ # hidden watcher process takes the claim over then (Invoke-MarkerCustody);+ # Invoke-MarkerRelease stops it once our own release is decided.+ if ($script:MarkerClaim -notin @('claimed', 'adopted')) { return }+ $exe = [Diagnostics.Process]::GetCurrentProcess().MainModule.FileName+ # A trailing backslash would escape the closing quote (CommandLineToArgvW).+ $arguments = "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File `"$(Join-Path $PSScriptRoot 'windows.ps1')`" " ++ "-MarkerOp custody -InstallRoot `"$($InstallRoot.TrimEnd('\'))`" -CustodyOf $PID"+ try {+ $script:MarkerCustodian = Start-Process -FilePath $exe -ArgumentList $arguments -WindowStyle Hidden -PassThru -ErrorAction Stop+ } catch {+ Write-HandoffLog "could not start the update marker custodian: $($_.Exception.Message)"+ }+}++function Stop-MarkerCustodian {+ if ($null -eq $script:MarkerCustodian) { return }+ try { $script:MarkerCustodian.Kill() } catch {} # it already exited+ $script:MarkerCustodian = $null+}++function Invoke-MarkerCustody([int]$Of) {+ # -MarkerOp custody: once hand-off pid $Of is gone, if its claim is still+ # published while its delegate runs or the checkout lock is held, name this+ # process on line 1 and keep line 2 young until both end (bounded like the+ # R6 wait), then release. A claim the hand-off released or handed over is+ # no longer its own: nothing to keep. Only the hand-off ever wrote a+ # delegate, so an unlocked look finding neither one nor a held checkout+ # lock is final -- no need to wait out a busy marker lock.+ $watched = Get-Process -Id $Of -ErrorAction SilentlyContinue+ if ($watched) { $watched.WaitForExit() }+ $peek = ConvertFrom-MarkerText (Read-MarkerText)+ if ($null -eq $peek -or $peek.Pid -ne $Of -or ($peek.DelegatePid -le 0 -and -not (Test-CheckoutLockHeld))) { return }+ $lock = Open-MarkerLock+ if ($null -eq $lock) { return }+ try {+ $ctx = New-MarkerContext+ $read = Read-MarkerLocked $ctx+ $info = $read.Info+ if ($null -eq $info -or $info.Pid -ne $Of -or (Test-ProcessIdentityLive $Of $info.Ct)) { return }+ $delegate = if ($read.Judgement.DelegateState -eq 'live') { Get-MarkerDelegateLine $info } else { $null }+ if (-not $delegate -and -not (Test-CheckoutLockHeld)) { return }+ if (-not (Set-MarkerBodyLocked (Format-MarkerBody $PID $ctx.Now (Format-Ct $ctx.OwnCt) $delegate $info.Runs))) { return }+ } finally {+ $lock.Dispose()+ }+ $script:MarkerClaim = 'claimed'+ Write-HandoffLog "update hand-off pid $Of died while its update still holds the checkout; pid $PID keeps the update marker"+ for ($waited = 0; ($delegate -and (Test-ProcessIdentityLive $info.DelegatePid $info.DelegateCt)) -or (Test-CheckoutLockHeld); $waited++) {+ if ($waited -ge $script:MarkerReleaseWaitSeconds) { return }+ Update-MarkerHeartbeat+ Start-Sleep -Seconds 1+ }+ Invoke-MarkerRelease+}+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 | held | live <pid> | busy | withdrawn | taken <pid> | foreign.diff --git a/scripts/desktop-update/marker.ps1 b/scripts/desktop-update/marker.ps1index f7bdd86924c..6c8e67b8765 100644--- a/scripts/desktop-update/marker.ps1+++ b/scripts/desktop-update/marker.ps1@@ -35,6 +35,7 @@ $script:MarkerClaim = "none" # claimed | adopted | refused$script:MarkerBlocker = 0$script:MarkerOwnCtText = $null$script:MarkerLastHeartbeat = $null+$script:MarkerCustodian = $null # the watcher process Start-MarkerCustodian started$script:MarkerReleaseWaited = $false # the R6 wait ran (windows.ps1 re-stamps the result after it)$script:StartedAt = $null$script:MarkerRunPattern = '\A[A-Za-z0-9._-]{1,128}\z'diff --git a/scripts/desktop-update/windows.ps1 b/scripts/desktop-update/windows.ps1index 2e010d32117..0f2a1844469 100644--- a/scripts/desktop-update/windows.ps1+++ b/scripts/desktop-update/windows.ps1@@ -38,6 +38,7 @@# -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.+# (-MarkerOp custody -CustodyOf <pid> is internal: Start-MarkerCustodian.)## SAFETY POSTURE: both preflight gates FAIL CLOSED. A Desktop that never# exits, or a venv shim that never unlocks, aborts the hand-off without@@ -74,7 +75,8 @@ param([switch]$SelfTestMarker,[switch]$SelfTestWorkingDirectory,[string]$HandoffRun = "",- [string]$MarkerOp = ""+ [string]$MarkerOp = "",+ [int]$CustodyOf = 0)if ($MarkerOp -and -not $InstallRoot) {@@ -120,6 +122,7 @@ try { . (Join-Path $PSScriptRoot 'marker.ps1') } catch {}# Helper op (SPEC 6): one verdict line, before any UI, result or relaunch.+if ($MarkerOp -ceq 'custody') { Invoke-MarkerCustody $CustodyOf; exit 0 } # Start-MarkerCustodian's watcherif ($MarkerOp) { exit (Invoke-MarkerOpCli $MarkerOp $DesktopPid $HandoffRun) }# The Desktop's identity is pinned now: a reused pid later is not "still open".@@ -1490,6 +1493,7 @@ try {$finalMsg = "marker self-test complete"exit 0}+ Start-MarkerCustodian# StartAssigned passes a null CreateProcess currentDirectory, so children# inherit the hand-off process directory rather than PowerShell's $PWD.diff --git a/tests/scripts/desktop_update/legacy_desktop_reader.py b/tests/scripts/desktop_update/legacy_desktop_reader.pynew file mode 100644index 00000000000..49cf52c7314--- /dev/null+++ b/tests/scripts/desktop_update/legacy_desktop_reader.py@@ -0,0 +1,27 @@+"""Run the update-marker reader an old packaged Desktop shipped (not collected)."""+from __future__ import annotations++import json+from pathlib import Path+import shutil+import subprocess++import pytest++LEGACY_READER = Path(__file__).resolve().parents[2] / "fixtures" / "legacy_desktop" / "update-marker-be3fd671.mts"+++def legacy_read(home: Path) -> dict:+ """The exact reader an old packaged Desktop runs at boot: line 1 dead or line 2 past 20+ minutes => it unlinks the marker and starts its backend. {'live': {pid, ageMs} | None,+ 'kept': marker still exists afterwards}."""+ node = shutil.which("node")+ if node is None:+ pytest.skip("node is needed to run the shipped Desktop reader")+ code = (f"import fs from 'fs'; import {{ readLiveUpdateMarker }} from {json.dumps(LEGACY_READER.as_uri())}; "+ "const live = readLiveUpdateMarker(process.argv[1]); "+ "console.log(JSON.stringify({ live, kept: fs.existsSync(process.argv[1] + '/.hermes-update-in-progress') }))")+ out = subprocess.run([node, "--input-type=module", "-e", code, str(home)], capture_output=True, text=True,+ encoding="utf-8", timeout=60)+ assert out.returncode == 0, out.stderr+ return json.loads(out.stdout.strip().splitlines()[-1])diff --git a/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py b/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.pyindex de02720eba4..c44c8f227d8 100644--- a/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py+++ b/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py@@ -30,6 +30,7 @@ import pytest# failing collection on Windowsfcntl = pytest.importorskip("fcntl") # windows-footgun: ok+from tests.scripts.desktop_update.legacy_desktop_reader import legacy_readfrom tests.scripts.desktop_update.lineage_rule_cases import ENV_CASES, RULE_CASESfrom tests.scripts.desktop_update.lineage_rule_cases import FACTS as LINEAGE_FACTSfrom tests.scripts.desktop_update.test_desktop_update_posix_marker import POSIX, _calls, _ct, _install@@ -534,23 +535,6 @@ def test_line_two_is_refreshed_only_while_the_claim_is_still_ours(tmp_path, proc# ── old packaged Desktop after the orchestrator dies ────────────────────────-LEGACY_READER = Path(__file__).resolve().parents[2] / "fixtures" / "legacy_desktop" / "update-marker-be3fd671.mts"---def _legacy_read(home: Path) -> dict:- """The exact reader an old packaged Desktop runs at boot: line 1 dead or line 2 past 20- minutes => it unlinks the marker and starts its backend."""- node = shutil.which("node")- if node is None:- pytest.skip("node is needed to run the shipped Desktop reader")- code = (f"import fs from 'fs'; import {{ readLiveUpdateMarker }} from {json.dumps(LEGACY_READER.as_uri())}; "- f"const live = readLiveUpdateMarker(process.argv[1]); "- f"console.log(JSON.stringify({{ live, kept: fs.existsSync(process.argv[1] + '/.hermes-update-in-progress') }}))")- out = subprocess.run([node, "--input-type=module", "-e", code, str(home)], capture_output=True, text=True,- encoding="utf-8", timeout=60)- assert out.returncode == 0, out.stderr- return json.loads(out.stdout.strip().splitlines()[-1])-def test_old_desktop_stays_parked_after_the_orchestrator_is_killed_while_the_update_holds_the_lock(tmp_path):"""SIGKILL the hand-off once its delegate (`hermes update`) runs and a completion survivor holds@@ -576,7 +560,7 @@ def test_old_desktop_stays_parked_after_the_orchestrator_is_killed_while_the_updfor phase in ("delegate", "survivor"):for _ in range(3):time.sleep(1.5)- seen = _legacy_read(home)+ seen = legacy_read(home)assert seen["live"] is not None and seen["kept"], (phase, seen)if phase == "delegate":hold.touch()@@ -593,4 +577,4 @@ def test_old_desktop_stays_parked_after_the_orchestrator_is_killed_while_the_updwhile marker.exists():assert time.monotonic() < deadline, marker.read_text(encoding="utf-8-sig")time.sleep(0.1)- assert _legacy_read(home)["live"] is None+ assert legacy_read(home)["live"] is Nonediff --git a/tests/scripts/desktop_update/test_desktop_update_windows_marker.py b/tests/scripts/desktop_update/test_desktop_update_windows_marker.pyindex 430af7c8b56..f123129f7e4 100644--- a/tests/scripts/desktop_update/test_desktop_update_windows_marker.py+++ b/tests/scripts/desktop_update/test_desktop_update_windows_marker.py@@ -16,6 +16,7 @@ import timeimport pytestfrom tests.installation_launcher_fixture import publish_fixture_launcher+from tests.scripts.desktop_update.legacy_desktop_reader import legacy_readROOT = Path(__file__).resolve().parent.parent.parent.parentSCRIPT = ROOT / 'scripts/desktop-update/windows.ps1'@@ -303,7 +304,9 @@ def _parent_pid(pid: int) -> int:def test_script_killed_right_after_spawning_the_update_leaves_a_live_marker(tmp_path: Path) -> None:"""C1 rule 6, written by the script itself: windows.ps1 is killed (taskkill /F, no /T) whileits `hermes update` child is only starting up and has not taken the update lock. The marker- must still read LIVE through the child named on line 4, and turn dead once that child is gone."""+ must still read LIVE through the child named on line 4 -- also to an old packaged Desktop,+ which judges line 1 alone, so the hand-off's custodian takes line 1 -- and be released once+ that child is gone."""install = tmp_path / 'checkout'publish_fixture_launcher(install, HOLD_CLI)home = tmp_path / 'home'; home.mkdir()@@ -329,8 +332,10 @@ def test_script_killed_right_after_spawning_the_update_leaves_a_live_marker(tmp_subprocess.run(['taskkill', '/F', '/PID', str(script.pid)], capture_output=True, check=True)script.wait(timeout=30)child = int(child_pid_file.read_text(encoding='utf-8-sig'))- lines = marker.read_bytes().decode().splitlines()- assert lines[0] == str(script.pid)+ deadline = time.monotonic() + 60+ while (lines := _marker_lines(marker))[:1] in ([], [str(script.pid)]): # the custodian takes over+ assert time.monotonic() < deadline, lines+ time.sleep(0.1)assert lines[3].startswith('delegate:'), linesdelegate = int(lines[3].split()[0].split(':')[1])assert delegate in (child, _parent_pid(child), _parent_pid(_parent_pid(child))) # update or its launcher@@ -339,6 +344,8 @@ def test_script_killed_right_after_spawning_the_update_leaves_a_live_marker(tmp_# A real reader (the script itself) sees an update in progress and refuses._, code, out = _run(home, '-SelfTestMarker', '-NoMarkerCleanup', install=install)assert code == 2, out+ seen = legacy_read(home)+ assert seen['live'] == {'pid': int(lines[0]), 'ageMs': seen['live']['ageMs']} and seen['kept'], seenhold.touch()deadline = time.monotonic() + 60@@ -346,6 +353,10 @@ def test_script_killed_right_after_spawning_the_update_leaves_a_live_marker(tmp_['tasklist', '/FI', f'PID eq {delegate}', '/NH'], capture_output=True, text=True,).stdout.find(str(delegate)) >= 0:time.sleep(0.2)+ while marker.exists(): # the custodian releases once the delegate is gone+ assert time.monotonic() < deadline, _marker_lines(marker)+ time.sleep(0.2)+ assert legacy_read(home)['live'] is None_, code, out = _run(home, '-SelfTestMarker', '-NoMarkerCleanup', install=install)assert code == 0, outfinally: