Skip to content

The agent that grows with you

fix(update): SSH remote gates keep a dead marker while the checkout lock is held

Teknium7417f3786e52
diff --git a/apps/desktop/electron/remote-lifecycle.ts b/apps/desktop/electron/remote-lifecycle.ts
index 9ba534210ea..a043888c95e 100644
--- a/apps/desktop/electron/remote-lifecycle.ts
+++ b/apps/desktop/electron/remote-lifecycle.ts
@@ -326,17 +326,20 @@ async function probeRemoteHermesHome(ssh) {
* The probe uses only the host's system Python and the shared marker judge
* (remote-update-marker-programs.ts); it never imports the changing checkout.
* Absence or a confirmed-dead claim (owner and delegate) is clear, and a dead
- * claim is unlinked under `<marker>.lock`. Every parse, read, lock, or
+ * claim is unlinked under `<marker>.lock` unless the checkout lock is still
+ * held (HELD: a killed updater's child is still running). `hermesPath`, once
+ * located, adds its checkout to the probed ones. Every parse, read, lock, or
* transport uncertainty fails closed so a Desktop relaunch cannot start
* `serve` beside an updater that survived the old app process.
*/
-async function assertRemoteInstallUpdateClear(ssh, hermesHome) {
+async function assertRemoteInstallUpdateClear(ssh, hermesHome, hermesPath = '') {
const marker = expandRemotePath(`${remoteInstallRoot(hermesHome)}/.hermes-update-in-progress`)
+ const hermes = hermesPath ? ` '' ${expandRemotePath(hermesPath)}` : ''
let observation = ''
try {
observation =
- String(await ssh.exec(`python3 -c ${shq(REMOTE_MARKER_GATE_PY)} ${marker}`))
+ String(await ssh.exec(`python3 -c ${shq(REMOTE_MARKER_GATE_PY)} ${marker}${hermes}`))
.trim()
.split(/\r?\n/)
.pop() || ''
@@ -356,7 +359,9 @@ async function assertRemoteInstallUpdateClear(ssh, hermesHome) {
const error: any = new Error(
live
? `Remote Hermes update process ${live[1]} is still running; SSH startup is paused.`
- : 'The remote Hermes update marker is unreadable, malformed, or locked; refusing SSH startup.'
+ : observation === 'HELD'
+ ? 'A process the remote Hermes update started still holds the install; SSH startup is paused.'
+ : 'The remote Hermes update marker is unreadable, malformed, or locked; refusing SSH startup.'
)
error.kind = 'update-in-progress'
@@ -960,14 +965,16 @@ finally:
// Run `command` under the updaters' marker lock: REMOTE_MARKER_GATE_PY holds
// `<marker>.lock` (the sidecar Python update_lock and marker.sh flock), clears a
-// dead claim, and refuses (exit 75) a live or unreadable one, then keeps the
+// dead claim while `hermes`'s checkout lock is free, and refuses (exit 75) a
+// live, unreadable, or checkout-held one, then keeps the
// lock across the spawn and the initial lockfile publication. The descriptor
// is close-on-exec and passed only to the outer shell; each detached child
// closes it before execing Hermes. markerPath is expandRemotePath() output — a
// complete shell word ("$HOME"'/…' or '/abs/…') embedded raw so $HOME expands
-// remotely; a second shq() would hand python the quote characters.
-function withRemoteUpdateMutex(command, markerPath) {
- return `python3 -c ${shq(REMOTE_MARKER_GATE_PY)} ${markerPath} ${shq(command)}`
+// remotely; a second shq() would hand python the quote characters. `hermes`
+// is the same kind of word (expandRemotePath of the located executable).
+function withRemoteUpdateMutex(command, markerPath, hermes) {
+ return `python3 -c ${shq(REMOTE_MARKER_GATE_PY)} ${markerPath} ${shq(command)} ${hermes}`
}
/**
@@ -1135,7 +1142,8 @@ function buildSpawnCommand(hermesPath, profile, opts: any = {}) {
`mkdir -p "$(dirname ${logPath})" && ` +
`${detachedSpawn}; ` +
`${markerAbsent} || { kill "$child" 2>/dev/null || true; wait "$child" 2>/dev/null || true; exit 75; }; echo "$child"`,
- marker
+ marker,
+ hermes
)
}
@@ -1176,7 +1184,8 @@ function buildSpawnCommand(hermesPath, profile, opts: any = {}) {
`temporary_lock="\${lock}.${reservationNonce}.tmp"; ` +
`printf '%s' "$lock_json" > "$temporary_lock" && mv -f "$temporary_lock" "$lock" || { kill "$child" 2>/dev/null || true; wait "$child" 2>/dev/null || true; exit 76; }; ` +
`echo "$child"`,
- marker
+ marker,
+ hermes
)
}
@@ -1545,7 +1554,7 @@ async function connect(deps) {
}
assertBootstrapNotSuperseded(signal)
- await assertRemoteInstallUpdateClear(ssh, hermesHome)
+ await assertRemoteInstallUpdateClear(ssh, hermesHome, hermesPath)
const localPort = await openForward(deps, lock.port)
try {
@@ -1564,7 +1573,7 @@ async function connect(deps) {
if (reuseClassification === 'authenticated-stale') {
assertBootstrapNotSuperseded(signal)
await cancelForwardSafe(deps, localPort, lock.port)
- await assertRemoteInstallUpdateClear(ssh, hermesHome)
+ await assertRemoteInstallUpdateClear(ssh, hermesHome, hermesPath)
await cleanupStale(ssh, ownershipId, lock)
} else if (reuseClassification === 'authenticated-ok') {
const token = await adoptOwnedServedToken(
@@ -1608,13 +1617,13 @@ async function connect(deps) {
}
} else {
assertBootstrapNotSuperseded(signal)
- await assertRemoteInstallUpdateClear(ssh, hermesHome)
+ await assertRemoteInstallUpdateClear(ssh, hermesHome, hermesPath)
await cleanupStale(ssh, ownershipId, lock, pidAlive)
}
}
assertBootstrapNotSuperseded(signal)
- await assertRemoteInstallUpdateClear(ssh, hermesHome)
+ await assertRemoteInstallUpdateClear(ssh, hermesHome, hermesPath)
const spawnToken = mintToken()
const spawned = await spawnRemoteDashboard(ssh, {
@@ -1624,7 +1633,7 @@ async function connect(deps) {
ownershipId,
hermesHome,
guestOnboarding,
- assertInstallClear: () => assertRemoteInstallUpdateClear(ssh, hermesHome)
+ assertInstallClear: () => assertRemoteInstallUpdateClear(ssh, hermesHome, hermesPath)
})
if (spawned.existing) {
diff --git a/apps/desktop/electron/remote-update-marker-programs.test.ts b/apps/desktop/electron/remote-update-marker-programs.test.ts
index 6aea230311d..8c9dec32049 100644
--- a/apps/desktop/electron/remote-update-marker-programs.test.ts
+++ b/apps/desktop/electron/remote-update-marker-programs.test.ts
@@ -1,12 +1,13 @@
import assert from 'node:assert/strict'
-import { execFile as execFileCallback } from 'node:child_process'
-import { readFileSync } from 'node:fs'
+import { execFile as execFileCallback, spawn, spawnSync } from 'node:child_process'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import os from 'node:os'
import path from 'node:path'
import { promisify } from 'node:util'
import { test } from 'vitest'
-import { REMOTE_MARKER_JUDGE_PY } from './remote-update-marker-programs'
+import { REMOTE_MARKER_GATE_PY, REMOTE_MARKER_JUDGE_PY } from './remote-update-marker-programs'
const execFile = promisify(execFileCallback)
const corpusPath = path.resolve(__dirname, '../../../tests/fixtures/update_marker_corpus.json')
@@ -37,3 +38,97 @@ test.skipIf(process.platform === 'win32')('the remote marker judge agrees with e
assert.ok(corpus.judge.length >= 40)
assert.deepEqual(JSON.parse(stdout), expected)
})
+
+// A dead claim whose checkout lock is still flocked (a killed updater's completion
+// child) must be kept: the gate answers HELD instead of unlinking it (review G1).
+const HOLD_PY = String.raw`
+import fcntl,os,sys,time
+fd=os.open(sys.argv[1],os.O_RDWR|os.O_CREAT)
+fcntl.flock(fd,fcntl.LOCK_EX)
+print('held',flush=True)
+time.sleep(60)
+`
+
+async function withCheckoutLockHeld(lockPath: string, body: () => Promise<void>) {
+ const holder = spawn('python3', ['-c', HOLD_PY, lockPath], { stdio: ['ignore', 'pipe', 'inherit'] })
+
+ try {
+ await new Promise(resolve => holder.stdout.once('data', resolve))
+ await body()
+ } finally {
+ holder.kill('SIGKILL')
+ await new Promise(resolve => holder.once('exit', resolve))
+ }
+}
+
+function deadMarker(marker: string) {
+ const exited = spawnSync('true')
+ writeFileSync(marker, `${exited.pid}\n${Math.floor(Date.now() / 1000)}\n`)
+}
+
+async function gate(args: string[]) {
+ try {
+ const { stdout, stderr } = await execFile('python3', ['-c', REMOTE_MARKER_GATE_PY, ...args])
+
+ return { code: 0, stdout: stdout.trim(), stderr: stderr.trim() }
+ } catch (error: any) {
+ return { code: error.code, stdout: String(error.stdout).trim(), stderr: String(error.stderr).trim() }
+ }
+}
+
+test.skipIf(process.platform === 'win32')(
+ 'the remote gate keeps a dead marker while the default checkout lock is held',
+ async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'hermes-remote-gate-'))
+ const marker = path.join(root, '.hermes-update-in-progress')
+
+ try {
+ mkdirSync(path.join(root, 'hermes-agent', '.git'), { recursive: true })
+ deadMarker(marker)
+
+ await withCheckoutLockHeld(path.join(root, 'hermes-agent', '.git', 'hermes-update.lock'), async () => {
+ assert.deepEqual(await gate([marker]), { code: 0, stdout: 'HELD', stderr: '' })
+ assert.ok(existsSync(marker), 'a dead marker beside a held checkout lock must be kept')
+ const refused = await gate([marker, 'echo PAYLOAD-RAN'])
+ assert.deepEqual(refused, { code: 75, stdout: '', stderr: 'HELD' })
+ })
+
+ assert.deepEqual(await gate([marker]), { code: 0, stdout: 'CLEAR', stderr: '' })
+ assert.ok(!existsSync(marker), 'a dead marker beside a free checkout lock is reclaimed')
+ } finally {
+ rmSync(root, { recursive: true, force: true })
+ }
+ }
+)
+
+test.skipIf(process.platform === 'win32')(
+ 'the remote gate probes the checkout of the hermes executable it is given (linked worktree)',
+ async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), 'hermes-remote-gate-'))
+ const home = path.join(root, 'home')
+ const marker = path.join(home, '.hermes-update-in-progress')
+ const checkout = path.join(root, 'src', 'hermes-agent')
+ const common = path.join(root, 'repo.git')
+
+ try {
+ mkdirSync(home, { recursive: true })
+ mkdirSync(path.join(checkout, 'venv', 'bin'), { recursive: true })
+ mkdirSync(path.join(common, 'worktrees', 'co'), { recursive: true })
+ writeFileSync(path.join(checkout, '.git'), `gitdir: ${path.join(common, 'worktrees', 'co')}\n`)
+ writeFileSync(path.join(common, 'worktrees', 'co', 'commondir'), '../..\n')
+ writeFileSync(path.join(checkout, 'venv', 'bin', 'hermes'), '')
+ mkdirSync(path.join(root, 'bin'))
+ symlinkSync(path.join(checkout, 'venv', 'bin', 'hermes'), path.join(root, 'bin', 'hermes'))
+ deadMarker(marker)
+
+ await withCheckoutLockHeld(path.join(common, 'hermes-update.lock'), async () => {
+ const hermes = path.join(root, 'bin', 'hermes')
+ assert.deepEqual(await gate([marker, '', hermes]), { code: 0, stdout: 'HELD', stderr: '' })
+ assert.deepEqual((await gate([marker, 'echo PAYLOAD-RAN', hermes])).code, 75)
+ assert.ok(existsSync(marker))
+ })
+ } finally {
+ rmSync(root, { recursive: true, force: true })
+ }
+ }
+)
diff --git a/apps/desktop/electron/remote-update-marker-programs.ts b/apps/desktop/electron/remote-update-marker-programs.ts
index 2eab8818cf8..42559357b4e 100644
--- a/apps/desktop/electron/remote-update-marker-programs.ts
+++ b/apps/desktop/electron/remote-update-marker-programs.ts
@@ -104,18 +104,23 @@ def marker_verdict(raw):
`
/**
- * POSIX gate: `python3 -c GATE <marker> [payload]`. Holds the updaters' kernel
- * lock `<marker>.lock` (A7 rule 1: Python update_lock flock, marker.sh flock)
- * for a bounded 10 s, judges the marker, unlinks a dead claim inside that hold,
- * then either prints the verdict (no payload: the relaunch probe) or runs the
- * payload as `sh -c payload hermes-update-mutex <fd>` still holding the lock.
- * A refused payload exits 75 with the verdict on stderr. The probe skips the
- * lock when there is no marker, so it never creates files on a clean host.
+ * POSIX gate: `python3 -c GATE <marker> [payload] [hermes...]` (an empty payload
+ * is the probe). Holds the updaters' kernel lock `<marker>.lock` (A7 rule 1:
+ * Python update_lock flock, marker.sh flock) for a bounded 10 s, judges the
+ * marker, and unlinks a dead claim inside that hold only while the install's
+ * CHECKOUT lock is free (update_lock._reclaim_dead): a killed updater's
+ * completion/build child still holding it answers HELD and keeps the marker.
+ * The checkouts probed are `<marker dir>/hermes-agent` plus the checkout of
+ * each `hermes` executable argument (`<root>/venv/bin/hermes`, symlinks
+ * resolved). Then it either prints the verdict (no payload: the relaunch probe)
+ * or runs the payload as `sh -c payload hermes-update-mutex <fd>` still holding
+ * the lock. A refused payload exits 75 with the verdict on stderr. The probe
+ * skips the lock when there is no marker, so it never creates files on a clean host.
*/
export const REMOTE_MARKER_GATE_PY = `${REMOTE_MARKER_JUDGE_PY}
import fcntl,subprocess
marker=sys.argv[1]
-payload=sys.argv[2] if len(sys.argv)>2 else None
+payload=sys.argv[2] if len(sys.argv)>2 and sys.argv[2] else None
if payload is None and not os.path.lexists(marker):
print('CLEAR');sys.exit(0)
@@ -133,6 +138,36 @@ def read_marker():
with open(marker,'rb') as stream:return stream.read(4097)
except FileNotFoundError:return None
+def checkout_lock(root):
+ # hermes_cli/update_lock.py::checkout_lock_path: <git common dir>/hermes-update.lock, else <root>/.hermes-update.lock.
+ plain=os.path.join(root,'.hermes-update.lock');dot=os.path.join(root,'.git')
+ try:
+ if os.path.isdir(dot):gitdir=dot
+ elif os.path.isfile(dot):
+ with open(dot,encoding='utf-8-sig') as stream:text=stream.read().strip()
+ if not text.startswith('gitdir:'):return plain
+ gitdir=os.path.join(root,text[len('gitdir:'):].strip())
+ else:return plain
+ common=os.path.join(gitdir,'commondir')
+ if os.path.isfile(common):
+ with open(common,encoding='utf-8-sig') as stream:gitdir=os.path.join(gitdir,stream.read().strip())
+ except (OSError,ValueError):return plain
+ return os.path.join(os.path.normpath(gitdir),'hermes-update.lock')
+
+def checkout_held():
+ # update_lock.checkout_lock_held: take the flock for one try and drop it. A lock file that
+ # exists but cannot be opened or probed counts as held: reclaim needs a provably free checkout.
+ roots=[os.path.join(os.path.dirname(marker),'hermes-agent')]
+ roots+=[os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(os.path.expanduser(exe))))) for exe in sys.argv[3:] if exe]
+ for root in roots:
+ try:lock=os.open(checkout_lock(root),os.O_RDONLY|os.O_CLOEXEC)
+ except (FileNotFoundError,NotADirectoryError):continue
+ except OSError:return True
+ try:fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
+ except OSError:return True
+ finally:os.close(lock)
+ return False
+
os.makedirs(os.path.dirname(marker),exist_ok=True)
try:fd=os.open(marker+'.lock',os.O_RDWR|os.O_CREAT|os.O_CLOEXEC,0o644)
except PermissionError:fd=os.open(marker+'.lock',os.O_RDONLY|os.O_CLOEXEC)
@@ -140,8 +175,10 @@ verdict='UNCERTAIN'
if hold(fd):
raw=read_marker();verdict=marker_verdict(raw)
if verdict=='CLEAR' and raw is not None:
- try:os.unlink(marker)
- except FileNotFoundError:pass
+ if checkout_held():verdict='HELD'
+ else:
+ try:os.unlink(marker)
+ except FileNotFoundError:pass
if payload is None or verdict!='CLEAR':
print(verdict,file=sys.stderr if payload else sys.stdout);sys.exit(75 if payload else 0)
sys.exit(subprocess.run(['sh','-c',payload,'hermes-update-mutex',str(fd)],pass_fds=(fd,)).returncode)
@@ -176,3 +213,32 @@ export const WINDOWS_MARKER_JUDGE_PS = [
'return "CLEAR"',
'}'
].join('\n')
+
+/**
+ * PowerShell `Test-CheckoutLockHeld $roots` -> $true while any checkout in
+ * `$roots` has its update kernel lock held: the Python update_lock byte range on
+ * `checkout_lock_path` (offset 1048576, the owner byte plus the 16 R5b lease
+ * bytes a refused completion child keeps while it outlives its owner), taken for
+ * one try and dropped. A lock file that exists but cannot be opened or locked
+ * counts as held. Gates delete a dead marker only when this is $false.
+ */
+export const WINDOWS_CHECKOUT_LOCK_PS = [
+ 'function Get-CheckoutLockPath([string]$root){',
+ '$plain=[IO.Path]::Combine($root,".hermes-update.lock");$dot=[IO.Path]::Combine($root,".git");$gitdir=$null',
+ 'try{',
+ 'if([IO.Directory]::Exists($dot)){$gitdir=$dot}elseif([IO.File]::Exists($dot)){$text=[IO.File]::ReadAllText($dot).Trim();if($text.StartsWith("gitdir:")){$gitdir=[IO.Path]::Combine($root,$text.Substring(7).Trim())}}',
+ 'if($gitdir){$common=[IO.Path]::Combine($gitdir,"commondir");if([IO.File]::Exists($common)){$gitdir=[IO.Path]::Combine($gitdir,[IO.File]::ReadAllText($common).Trim())}}',
+ '}catch{return $plain}',
+ 'if(-not $gitdir){return $plain}',
+ 'return [IO.Path]::GetFullPath([IO.Path]::Combine($gitdir,"hermes-update.lock"))',
+ '}',
+ 'function Test-CheckoutLockHeld([object[]]$roots){',
+ 'foreach($root in $roots){',
+ 'if([string]::IsNullOrWhiteSpace([string]$root)){continue}',
+ '$lockFile=$null',
+ 'try{$lockFile=[IO.File]::Open((Get-CheckoutLockPath ([string]$root)),[IO.FileMode]::Open,[IO.FileAccess]::Read,[IO.FileShare]::ReadWrite)}catch [IO.FileNotFoundException],[IO.DirectoryNotFoundException]{continue}catch{return $true}',
+ 'try{$lockFile.Lock(1048576,17);$lockFile.Unlock(1048576,17)}catch{return $true}finally{$lockFile.Dispose()}',
+ '}',
+ 'return $false',
+ '}'
+].join('\n')
diff --git a/apps/desktop/electron/windows-remote-lifecycle.test.ts b/apps/desktop/electron/windows-remote-lifecycle.test.ts
index 88858713047..3089fc322ed 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.test.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.test.ts
@@ -225,6 +225,41 @@ test('Windows relaunch gate refuses live and uncertain markers before executing
}
})
+test('Windows gates keep a dead marker while the checkout lock or a lease byte is held', async () => {
+ // Review G1: a dead claim is deleted (spawn) or reported CLEAR (probe) only
+ // after the update_lock byte range -- owner byte + 16 R5b lease bytes at
+ // 1048576 -- of the installer checkout and the runtime python's checkout is free.
+ const decode = (command: string) => Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')
+ const runtime = { hermesHome: 'C:\\Users\\alice\\.hermes', python: 'C:\\src\\hermes\\venv\\Scripts\\python.exe' }
+ const spawnScript = decode(atomicWindowsSpawnCommand(runtime))
+ let probeScript = ''
+
+ const observed = await assertWindowsRemoteInstallUpdateClear(
+ sshWith(async command => {
+ probeScript = decode(command)
+
+ return 'HELD'
+ }),
+ runtime.hermesHome,
+ runtime.python
+ ).catch(error => error)
+
+ assert.equal(observed.kind, 'update-in-progress')
+ assert.match(observed.message, /still holds the install/)
+
+ for (const script of [spawnScript, probeScript]) {
+ assert.match(script, /\$lockFile\.Lock\(1048576,17\)/)
+ assert.match(script, /Combine\(\$gitdir,"hermes-update\.lock"\)/)
+ assert.match(script, /\$checkoutRoots=@\(\[IO\.Path\]::Combine\(\$installRoot,"hermes-agent"\),/)
+ assert.ok(script.includes("GetDirectoryName('C:\\src\\hermes\\venv\\Scripts\\python.exe')"))
+ }
+
+ const deleteAt = spawnScript.indexOf('[IO.File]::Delete($marker)')
+ const guardAt = spawnScript.indexOf('if($verdict -eq "CLEAR" -and (Test-CheckoutLockHeld $checkoutRoots)){$verdict="HELD"}')
+ assert.ok(guardAt > 0 && guardAt < deleteAt, 'the checkout probe must precede the dead-marker delete')
+ assert.match(probeScript, /if\(\$result -eq "CLEAR" -and \(Test-CheckoutLockHeld \$checkoutRoots\)\)\{\$result="HELD"\}/)
+})
+
test('Windows relaunch gate uses strict install-wide marker parsing and fail-closed PID probing', async () => {
let script = ''
diff --git a/apps/desktop/electron/windows-remote-lifecycle.ts b/apps/desktop/electron/windows-remote-lifecycle.ts
index f78300f21ff..8bb96b9d07b 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.ts
@@ -1,7 +1,7 @@
import crypto from 'node:crypto'
import { resolveReadyTimeoutMs } from './remote-lifecycle'
-import { WINDOWS_MARKER_JUDGE_PS } from './remote-update-marker-programs'
+import { WINDOWS_CHECKOUT_LOCK_PS, WINDOWS_MARKER_JUDGE_PS } from './remote-update-marker-programs'
import { assertBootstrapNotSuperseded, redactSecrets, SSH_ERROR } from './ssh-connection'
const LOCKFILE_SCHEMA_VERSION = 2
@@ -106,7 +106,18 @@ async function probeWindowsRemote(ssh, explicitHermesPath = '') {
return parsed
}
-function windowsUpdateMarkerProbeCommand(hermesHome) {
+// The checkouts whose update lock guards a dead marker (update_lock._reclaim_dead):
+// the installer's `<install root>\hermes-agent` and the checkout of the runtime
+// python (`<root>\venv\Scripts\python.exe`). Defines $checkoutRoots; needs $installRoot.
+function windowsCheckoutRootsScript(python = '') {
+ const runtimeRoot = python
+ ? `[IO.Path]::GetDirectoryName([IO.Path]::GetDirectoryName([IO.Path]::GetDirectoryName(${psLiteral(python)})))`
+ : '$null'
+
+ return `$checkoutRoots=@([IO.Path]::Combine($installRoot,"hermes-agent"),${runtimeRoot})`
+}
+
+function windowsUpdateMarkerProbeCommand(hermesHome, python = '') {
const script = [
'$ProgressPreference="SilentlyContinue"',
'$ErrorActionPreference="Stop"',
@@ -127,6 +138,7 @@ public static class HermesMarkerNoFollow {
'@
`,
WINDOWS_MARKER_JUDGE_PS,
+ WINDOWS_CHECKOUT_LOCK_PS,
'function Assert-NoReparse([string]$candidate,[bool]$allowMissing=$false){',
'if([string]::IsNullOrWhiteSpace($candidate)){return}',
'$current=[IO.Path]::GetFullPath($candidate);$first=$true',
@@ -141,6 +153,7 @@ public static class HermesMarkerNoFollow {
'$parent=Split-Path -Parent $hermesHome',
'if((Split-Path -Leaf $parent) -ieq "profiles"){$installRoot=Split-Path -Parent $parent}',
'$marker=Join-Path $installRoot ".hermes-update-in-progress"',
+ windowsCheckoutRootsScript(python),
'$result="UNCERTAIN"',
'$stream=$null;$memory=$null',
'try{',
@@ -152,6 +165,7 @@ public static class HermesMarkerNoFollow {
'$utf8=[Text.UTF8Encoding]::new($false,$true)',
'$text=$utf8.GetString($bytes)',
'$result=Get-MarkerVerdict $text',
+ 'if($result -eq "CLEAR" -and (Test-CheckoutLockHeld $checkoutRoots)){$result="HELD"}',
'}',
'}}catch [IO.FileNotFoundException]{$result="CLEAR"}catch{$result="UNCERTAIN"}finally{if($memory){$memory.Dispose()};if($stream){$stream.Dispose()}}',
'Write-Output $result'
@@ -165,14 +179,14 @@ public static class HermesMarkerNoFollow {
* This uses only PowerShell/.NET and therefore never imports the remote
* checkout while an updater may be replacing it.
*/
-async function assertWindowsRemoteInstallUpdateClear(ssh, hermesHome) {
+async function assertWindowsRemoteInstallUpdateClear(ssh, hermesHome, python = '') {
let observation = ''
try {
// Same stdout channel as the probe: a CLIXML progress block after the
// final `Write-Output $result` would otherwise win the .pop() and turn a
// CLEAR gate into a fail-closed 'update-in-progress' verdict.
- observation = stripPowerShellNoise(await ssh.exec(windowsUpdateMarkerProbeCommand(hermesHome))).pop() || ''
+ observation = stripPowerShellNoise(await ssh.exec(windowsUpdateMarkerProbeCommand(hermesHome, python))).pop() || ''
} catch (cause) {
const error: any = new Error('Could not prove that the remote Hermes install is clear for SSH startup.')
error.kind = 'update-in-progress'
@@ -189,7 +203,9 @@ async function assertWindowsRemoteInstallUpdateClear(ssh, hermesHome) {
const error: any = new Error(
live
? `Remote Hermes update process ${live[1]} is still running; SSH startup is paused.`
- : 'The remote Hermes update marker is unreadable or malformed; refusing SSH startup.'
+ : observation === 'HELD'
+ ? 'A process the remote Hermes update started still holds the install; SSH startup is paused.'
+ : 'The remote Hermes update marker is unreadable or malformed; refusing SSH startup.'
)
error.kind = 'update-in-progress'
@@ -279,18 +295,22 @@ function atomicWindowsSpawnCommand(runtime, reservation: any = {}) {
'$ProgressPreference="SilentlyContinue"',
'$ErrorActionPreference="Stop"',
WINDOWS_MARKER_JUDGE_PS,
+ WINDOWS_CHECKOUT_LOCK_PS,
`$hermesHome=${psLiteral(runtime.hermesHome)}`,
'$installRoot=$hermesHome',
'$parent=Split-Path -Parent $hermesHome',
'if((Split-Path -Leaf $parent) -ieq "profiles"){$installRoot=Split-Path -Parent $parent}',
'$marker=Join-Path $installRoot ".hermes-update-in-progress"',
+ windowsCheckoutRootsScript(runtime.python),
// The updaters' kernel lock (A7 rule 1): `<marker>.lock` opened sharing
// nothing, like marker.ps1 Open-MarkerLock / update_lock.py, bounded 10 s.
- // A dead claim is deleted inside the hold; a live/malformed one refuses.
+ // A dead claim is deleted inside the hold, but only while the checkout lock
+ // is free (a killed updater's child still holding it answers HELD); a
+ // live/malformed one refuses.
'$clock=[Diagnostics.Stopwatch]::StartNew();$mutex=$null',
'while(-not $mutex){try{$mutex=[IO.File]::Open($marker+".lock",[IO.FileMode]::OpenOrCreate,[IO.FileAccess]::ReadWrite,[IO.FileShare]::None)}catch{if($clock.ElapsedMilliseconds -ge 10000){throw "remote update marker lock is busy"};Start-Sleep -Milliseconds 25}}',
'try{',
- ' if([IO.File]::Exists($marker)){$verdict=Get-MarkerVerdict ([IO.File]::ReadAllText($marker));if($verdict -ne "CLEAR"){throw "remote update marker is $verdict"};[IO.File]::Delete($marker)}',
+ ' if([IO.File]::Exists($marker)){$verdict=Get-MarkerVerdict ([IO.File]::ReadAllText($marker));if($verdict -eq "CLEAR" -and (Test-CheckoutLockHeld $checkoutRoots)){$verdict="HELD"};if($verdict -ne "CLEAR"){throw "remote update marker is $verdict"};[IO.File]::Delete($marker)}',
reservation.ownershipId
? ` $existingLines=@(& ${helper('read-lock').map(psLiteral).join(' ')} ${psLiteral(reservation.ownershipId)}); $existingExit=$LASTEXITCODE; ` +
' if($existingExit -eq 0 -and $existingLines.Count -gt 0){try{$existing=$existingLines[-1]|ConvertFrom-Json}catch{$existing=$null}; ' +
@@ -589,7 +609,7 @@ async function connectWindowsRemote(deps) {
assertBootstrapNotSuperseded(signal)
const runtime = await probeWindowsRemote(ssh, remoteHermesPath)
- await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
const inspection = await helper(ssh, runtime, 'inspect', [runtime.hermesPath])
if (!inspection.supported) {
@@ -603,7 +623,7 @@ async function connectWindowsRemote(deps) {
rememberLog(`[ssh-lifecycle] remote platform Windows/${runtime.arch}`)
rememberLog(`[ssh-lifecycle] located hermes at ${runtime.hermesPath}`)
- await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
const lock = await helper(ssh, runtime, 'read-lock', [ownershipId])
if (validLock(lock, ownershipId)) {
@@ -618,7 +638,7 @@ async function connectWindowsRemote(deps) {
const reusable = reusableWindowsLock(lock, state, profile, reuseToken, runtime)
if (reusable) {
- await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
const localPort = await pickLocalPort()
await forward(localPort, lock.port)
@@ -650,23 +670,23 @@ async function connectWindowsRemote(deps) {
}
await cancelForward(localPort, lock.port)
- await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
await cleanupOwned(ssh, runtime, ownershipId, lock)
} catch (error) {
await cancelForward(localPort, lock.port)
throw error
}
} else {
- await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
await cleanupOwned(ssh, runtime, ownershipId, lock)
}
} else if (lock) {
- await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
await helper(ssh, runtime, 'remove-lock', [ownershipId])
}
assertBootstrapNotSuperseded(signal)
- await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
const token = crypto.randomBytes(32).toString('hex')
const spawnNonce = crypto.randomBytes(8).toString('hex')
await helper(ssh, runtime, 'upload-token', [ownershipId, spawnNonce], token)
@@ -675,7 +695,7 @@ async function connectWindowsRemote(deps) {
let spawned
try {
- await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome, runtime.python)
spawned = await atomicWindowsSpawn(
ssh,
runtime,