Skip to content

The agent that grows with you

fix(desktop): read-only marker, corpus judge, live+correlated hand-off ack

Teknium9d0b685538d0
diff --git a/apps/desktop/electron/update-handoff-ack.test.ts b/apps/desktop/electron/update-handoff-ack.test.ts
new file mode 100644
index 00000000000..5051b4b0f61
--- /dev/null
+++ b/apps/desktop/electron/update-handoff-ack.test.ts
@@ -0,0 +1,157 @@
+/**
+ * Hand-off acknowledgment (R5, A7 rule 6, SPEC 4a.5 / 4b) against REAL
+ * processes: the Desktop counts a hand-off as taken only when the marker's
+ * line-1 owner is a LIVE incarnation that is not the Desktop and that is
+ * correlated with THIS hand-off — protocol 2 by the `run:` id it passed (and a
+ * verified creation time), legacy scripts by the started_at they echo.
+ * A claimant that died before the confirmation is never a running update.
+ */
+
+import fs from 'fs'
+import assert from 'node:assert/strict'
+
+import { afterEach, describe, test } from 'vitest'
+
+import { claimBridgeMarker, markerPath, processCreateTime, waitForHandoffClaim } from './update-marker'
+import {
+ claimantChild,
+ cleanupMarkerFixtures,
+ deadPid,
+ killAndReap,
+ nowSeconds,
+ tmpHome
+} from './update-marker.test-helpers'
+
+const HAS_CT_PROBE = process.platform === 'linux' || process.platform === 'darwin' || process.platform === 'win32'
+const RUN = 'desk-4242-mabc123-0f0f'
+
+afterEach(cleanupMarkerFixtures)
+
+describe.skipIf(!HAS_CT_PROBE)('protocol 2 acknowledgment (R5)', () => {
+ test('a claimant that published our run and was SIGKILLed before the ack is NOT a hand-off', async () => {
+ const home = tmpHome('ack-dead')
+ const startedAt = nowSeconds()
+ await claimBridgeMarker(home, { startedAt, runId: RUN })
+ const { child, body } = await claimantChild(markerPath(home), { startedAt, run: RUN })
+
+ await killAndReap(child)
+
+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), body, 'the dead claim is still on disk')
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { runId: RUN, timeoutMs: 300, pollMs: 50 }), {
+ taken: false
+ })
+ })
+
+ test('a live claimant carrying a DIFFERENT run is an unrelated update, not our hand-off', async () => {
+ const home = tmpHome('ack-other-run')
+ await claimantChild(markerPath(home), { startedAt: nowSeconds(), run: 'desk-1-zzz-ffff' })
+
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { runId: RUN, timeoutMs: 300, pollMs: 50 }), {
+ taken: false
+ })
+ })
+
+ test('a live claimant with our run but NO verifiable creation time is not acknowledged', async () => {
+ const home = tmpHome('ack-no-ct')
+ await claimantChild(markerPath(home), { startedAt: nowSeconds(), run: RUN, withCt: false })
+
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { runId: RUN, timeoutMs: 300, pollMs: 50 }), {
+ taken: false
+ })
+ })
+
+ test('a live claimant with our run but a reused-pid creation time is not acknowledged', async () => {
+ const home = tmpHome('ack-reused')
+ await claimantChild(markerPath(home), { startedAt: nowSeconds(), run: RUN, ctOffset: -3600 })
+
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { runId: RUN, timeoutMs: 300, pollMs: 50 }), {
+ taken: false
+ })
+ })
+
+ test('the Desktop own bridge carrying the run is never its own acknowledgment', async () => {
+ const home = tmpHome('ack-self')
+ assert.ok((await claimBridgeMarker(home, { startedAt: nowSeconds(), runId: RUN })).ok)
+
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { runId: RUN, timeoutMs: 300, pollMs: 50 }), {
+ taken: false
+ })
+ })
+
+ test('a live claimant with our run and its verified creation time IS the hand-off', async () => {
+ const home = tmpHome('ack-taken')
+ const startedAt = nowSeconds()
+ await claimBridgeMarker(home, { startedAt, runId: RUN })
+ const { child } = await claimantChild(markerPath(home), { startedAt, run: RUN })
+
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { runId: RUN, timeoutMs: 5_000, pollMs: 50 }), {
+ taken: true,
+ pid: child.pid
+ })
+ })
+
+ test('the claimant is waited for while it starts, then acknowledged', async () => {
+ const home = tmpHome('ack-late')
+ const startedAt = nowSeconds()
+ await claimBridgeMarker(home, { startedAt, runId: RUN })
+ const waiting = waitForHandoffClaim(home, process.pid, { runId: RUN, timeoutMs: 10_000, pollMs: 50 })
+ await new Promise(resolve => setTimeout(resolve, 200))
+ const { child } = await claimantChild(markerPath(home), { startedAt, run: RUN })
+
+ assert.deepEqual(await waiting, { taken: true, pid: child.pid })
+ })
+})
+
+describe('legacy acknowledgment: new Desktop + script without protocol 2 (R4, SPEC 4b)', () => {
+ test('a DEAD pid that echoed our started_at is not taken (the dead-PID hole stays closed)', async () => {
+ const home = tmpHome('legacy-dead')
+ const startedAt = nowSeconds()
+ fs.writeFileSync(markerPath(home), `${await deadPid()}\n${startedAt}\n`)
+
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { startedAt, timeoutMs: 300, pollMs: 50 }), {
+ taken: false
+ })
+ })
+
+ test('a live pid that echoed our started_at IS taken (old scripts write `$$\\n$HERMES_UPDATE_STARTED_AT`)', async () => {
+ const home = tmpHome('legacy-live')
+ const startedAt = nowSeconds()
+ const { child } = await claimantChild(markerPath(home), { startedAt, withCt: false })
+
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { startedAt, timeoutMs: 5_000, pollMs: 50 }), {
+ taken: true,
+ pid: child.pid
+ })
+ })
+
+ test('a live pid carrying ANOTHER started_at is someone else, not our hand-off', async () => {
+ const home = tmpHome('legacy-other')
+ const startedAt = nowSeconds()
+ await claimantChild(markerPath(home), { startedAt: startedAt - 30, withCt: false })
+
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { startedAt, timeoutMs: 300, pollMs: 50 }), {
+ taken: false
+ })
+ })
+
+ test.skipIf(!HAS_CT_PROBE)('a legacy v2 claim is ct-verified: a reused pid is not taken', async () => {
+ const home = tmpHome('legacy-reused')
+ const startedAt = nowSeconds()
+ const { child } = await claimantChild(markerPath(home), { startedAt, ctOffset: -3600 })
+
+ assert.ok(await processCreateTime(child.pid))
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { startedAt, timeoutMs: 300, pollMs: 50 }), {
+ taken: false
+ })
+ })
+
+ test('the Desktop own pid is never the successor', async () => {
+ const home = tmpHome('legacy-self')
+ const startedAt = nowSeconds()
+ fs.writeFileSync(markerPath(home), `${process.pid}\n${startedAt}\n`)
+
+ assert.deepEqual(await waitForHandoffClaim(home, process.pid, { startedAt, timeoutMs: 300, pollMs: 50 }), {
+ taken: false
+ })
+ })
+})
diff --git a/apps/desktop/electron/update-marker-corpus.test.ts b/apps/desktop/electron/update-marker-corpus.test.ts
new file mode 100644
index 00000000000..1b3a8386061
--- /dev/null
+++ b/apps/desktop/electron/update-marker-corpus.test.ts
@@ -0,0 +1,140 @@
+/**
+ * Shared update-marker corpus consumer (A7 rule 7):
+ * `tests/fixtures/update_marker_corpus.json` is authoritative for parsing and
+ * judging in every language. Every `judge` case runs through the Desktop's
+ * judge with the case's live table, our pid/ct and the corpus clock.
+ *
+ * The corpus `release` cases do not apply here: Electron never releases,
+ * reclaims or rewrites a marker (A7 rule 3) — the checkout script helper does,
+ * under the sidecar lock. The second half of this file proves that every
+ * marker export leaves the bytes of every corpus marker untouched.
+ */
+
+import fs from 'fs'
+import assert from 'node:assert/strict'
+import path from 'path'
+
+import { afterEach, describe, test } from 'vitest'
+
+import {
+ claimBridgeMarker,
+ inspectUpdateMarker,
+ markerPath,
+ readLiveUpdateMarker,
+ updateHandoffConflict,
+ waitForHandoffClaim,
+ writeUpdateMarker
+} from './update-marker'
+import { type JudgeEnv, judgeMarkerText } from './update-marker-judge'
+import { cleanupMarkerFixtures, tmpHome } from './update-marker.test-helpers'
+
+interface JudgeCase {
+ name: string
+ text: string
+ live: Record<string, number | null>
+ our_pid?: number
+ our_ct?: number
+ expect: { verdict: string; owner: number | null; run: string | null }
+}
+
+interface Corpus {
+ schema: number
+ now: number
+ own_ct_epsilon: number
+ ct_tolerance: number
+ v1_max_age: number
+ our_pid: number
+ our_ct: number
+ judge: JudgeCase[]
+ release: unknown[]
+}
+
+const CORPUS_PATH = path.resolve(__dirname, '..', '..', '..', 'tests', 'fixtures', 'update_marker_corpus.json')
+const corpus: Corpus = JSON.parse(fs.readFileSync(CORPUS_PATH, 'utf8'))
+
+afterEach(cleanupMarkerFixtures)
+
+function caseEnv(c: JudgeCase): JudgeEnv {
+ const ourPid = c.our_pid ?? corpus.our_pid
+ const ourCt = c.our_ct ?? corpus.our_ct
+
+ return {
+ ourPid,
+ ourCt: () => ourCt,
+ isAlive: pid => Object.prototype.hasOwnProperty.call(c.live, String(pid)),
+ createTime: pid => c.live[String(pid)] ?? null,
+ nowS: corpus.now
+ }
+}
+
+describe('update marker corpus (A7 rule 7)', () => {
+ test('the corpus constants are the Desktop constants', async () => {
+ const judge = await import('./update-marker-judge')
+
+ assert.equal(corpus.schema, 1)
+ assert.equal(judge.OWN_CT_EPSILON_S, corpus.own_ct_epsilon)
+ assert.equal(judge.CREATE_TIME_TOLERANCE_S, corpus.ct_tolerance)
+ assert.equal(judge.V1_MAX_AGE_S, corpus.v1_max_age)
+ assert.ok(corpus.judge.length >= 40, `corpus has ${corpus.judge.length} judge cases`)
+ })
+
+ test.each(corpus.judge.map(c => [c.name, c] as const))('judge: %s', async (_name, c) => {
+ const got = await judgeMarkerText(c.text, caseEnv(c))
+
+ assert.deepEqual({ verdict: got.verdict, owner: got.owner, run: got.run }, c.expect)
+ })
+})
+
+/**
+ * A process table for the HOST probes: nothing named in a corpus marker is
+ * alive (kill(0) => ESRCH) except via this injected table, so the real
+ * readers judge corpus bytes without touching live host pids.
+ */
+function hostDeps(c: JudgeCase) {
+ const ownPid = c.our_pid ?? corpus.our_pid
+
+ return {
+ ownPid,
+ now: () => corpus.now * 1000,
+ kill: ((pid: number) => {
+ if (pid === ownPid || Object.prototype.hasOwnProperty.call(c.live, String(pid))) {
+ return true
+ }
+
+ throw Object.assign(new Error('no such process'), { code: 'ESRCH' })
+ }) as typeof process.kill,
+ processState: () => null,
+ createTime: (pid: number) => (pid === ownPid ? (c.our_ct ?? corpus.our_ct) : (c.live[String(pid)] ?? null))
+ }
+}
+
+describe('Electron never mutates a marker (A7 rule 3)', () => {
+ test.each(corpus.judge.map(c => [c.name, c] as const))('every export leaves the bytes: %s', async (_name, c) => {
+ const home = tmpHome('corpus-ro')
+ const file = markerPath(home)
+ fs.writeFileSync(file, c.text)
+ const before = fs.readFileSync(file)
+ const deps = hostDeps(c)
+
+ await inspectUpdateMarker(home, deps)
+ await readLiveUpdateMarker(home, deps)
+ await updateHandoffConflict(home, deps)
+ await claimBridgeMarker(home, { ...deps, pid: deps.ownPid, startedAt: corpus.now, runId: 'desk-1-a-0000' })
+ await writeUpdateMarker(home, 4343, { ...deps, startedAt: corpus.now })
+ await waitForHandoffClaim(home, deps.ownPid, { ...deps, timeoutMs: 0, runId: 'desk-1-a-0000' })
+ await waitForHandoffClaim(home, deps.ownPid, { ...deps, timeoutMs: 0, startedAt: corpus.now })
+
+ assert.ok(fs.readFileSync(file).equals(before), 'marker bytes unchanged')
+ assert.deepEqual(fs.readdirSync(home), ['.hermes-update-in-progress'], 'no tmp litter, no sidecar')
+ })
+
+ test('no marker module unlinks, renames, truncates or overwrites a path', () => {
+ for (const name of ['update-marker.ts', 'update-marker-judge.ts', 'update-marker-gate.ts']) {
+ const source = fs.readFileSync(path.join(__dirname, name), 'utf8')
+
+ for (const mutator of ['unlinkSync', 'unlink(', 'renameSync', 'rename(', 'truncate', 'writeFileSync', "'w'", "'w+'", "'a'"]) {
+ assert.ok(!source.includes(mutator), `${name} must not call ${mutator}`)
+ }
+ }
+ })
+})
diff --git a/apps/desktop/electron/update-marker-gate.test.ts b/apps/desktop/electron/update-marker-gate.test.ts
new file mode 100644
index 00000000000..b9c151fb264
--- /dev/null
+++ b/apps/desktop/electron/update-marker-gate.test.ts
@@ -0,0 +1,112 @@
+/**
+ * The update gate's marker probe (R6): a dead/malformed marker is routed
+ * through the checkout script's `reclaim` helper — never deleted by Electron —
+ * and `held` (a completion still holds the checkout lock) keeps the boot
+ * parked. The helper runs as a REAL fake script process.
+ */
+
+import fs from 'fs'
+import assert from 'node:assert/strict'
+import path from 'path'
+
+import { afterEach, describe, test } from 'vitest'
+
+import { markerPath } from './update-marker'
+import { liveMarkerProbe } from './update-marker-gate'
+import { cleanupMarkerFixtures, deadPid, liveOwner, minutesAgo, tmpHome } from './update-marker.test-helpers'
+import { runMarkerHelper } from './updater/marker-helper'
+import { cleanupFakeCheckouts, fakeHelperCheckout } from './updater/marker-helper.test-helpers'
+
+afterEach(() => {
+ cleanupMarkerFixtures()
+ cleanupFakeCheckouts()
+})
+
+function helperCalls(home: string): string[] {
+ try {
+ return fs.readFileSync(path.join(home, 'helper-calls.log'), 'utf8').trim().split('\n').filter(Boolean)
+ } catch {
+ return []
+ }
+}
+
+describe.skipIf(process.platform === 'win32')('gate over a dead marker (R6)', () => {
+ function gate(root: string, home: string, now?: () => number) {
+ return liveMarkerProbe({
+ hermesHome: home,
+ reclaim: () => runMarkerHelper('reclaim', { updateRoot: root, hermesHome: home, isWindows: false }),
+ now
+ })
+ }
+
+ test('`held` keeps the gate closed and is re-asked every 5 s; the marker is never touched', async () => {
+ const { root, home } = fakeHelperCheckout()
+ const body = `${await deadPid()}\n${minutesAgo(1)}\nct:1.000\n`
+ fs.writeFileSync(markerPath(home), body)
+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'held')
+ let clock = Date.now()
+ const hasLiveMarker = gate(root, home, () => clock)
+
+ assert.equal(await hasLiveMarker(), true, 'a completion still holds the checkout: keep waiting')
+ assert.equal(await hasLiveMarker(), true)
+ assert.equal(helperCalls(home).length, 1, 'not one helper spawn per poll')
+
+ clock += 5_000
+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'busy')
+ assert.equal(await hasLiveMarker(), true)
+ assert.equal(helperCalls(home).length, 2, 'held is re-probed after 5 s')
+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), body)
+
+ clock += 5_000
+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'reclaimed')
+ assert.equal(await hasLiveMarker(), false, 'once the script reclaims, the gate opens')
+ assert.equal(fs.existsSync(markerPath(home)), false, 'the SCRIPT removed it, under its lock')
+ })
+
+ test('`live <pid>` from the helper keeps the gate closed', async () => {
+ const { root, home } = fakeHelperCheckout()
+ fs.writeFileSync(markerPath(home), 'garbage\n')
+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'live 4242')
+
+ assert.equal(await gate(root, home)(), true)
+ })
+
+ test('`unsupported` (old checkout) opens the gate WITHOUT deleting; asked once per distinct body', async () => {
+ const { root, home } = fakeHelperCheckout()
+ const body = `${await deadPid()}\n${minutesAgo(1)}\n`
+ fs.writeFileSync(markerPath(home), body)
+ fs.writeFileSync(path.join(home, 'helper-verdict'), 'usage: unknown option --marker-op')
+ fs.writeFileSync(path.join(home, 'helper-exit'), '64')
+ const hasLiveMarker = gate(root, home)
+
+ assert.equal(await hasLiveMarker(), false)
+ assert.equal(await hasLiveMarker(), false)
+ assert.equal(helperCalls(home).length, 1)
+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), body, 'dead = not running, and left in place')
+
+ const next = `${await deadPid()}\n${minutesAgo(1)}\n`
+ fs.writeFileSync(markerPath(home), next)
+ assert.equal(await hasLiveMarker(), false)
+ assert.equal(helperCalls(home).length, 2, 'a different dead body is asked about again')
+ })
+
+ test('a live owner never reaches the helper; an absent marker neither', async () => {
+ const { root, home } = fakeHelperCheckout()
+ const hasLiveMarker = gate(root, home)
+
+ assert.equal(await hasLiveMarker(), false)
+ const owner = await liveOwner()
+ fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(1)}\n`)
+ assert.equal(await hasLiveMarker(), true)
+ assert.deepEqual(helperCalls(home), [])
+ })
+})
+
+test('without a protocol-2 script the gate judges dead = not running and deletes nothing', async () => {
+ const home = tmpHome('gate-legacy')
+ const body = `${await deadPid()}\n${minutesAgo(1)}\n`
+ fs.writeFileSync(markerPath(home), body)
+
+ assert.equal(await liveMarkerProbe({ hermesHome: home, reclaim: null })(), false)
+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), body)
+})
diff --git a/apps/desktop/electron/update-marker-gate.ts b/apps/desktop/electron/update-marker-gate.ts
new file mode 100644
index 00000000000..021b1808e36
--- /dev/null
+++ b/apps/desktop/electron/update-marker-gate.ts
@@ -0,0 +1,86 @@
+/**
+ * The update gate's marker probe (R6, SPEC section 6 "Electron gate").
+ *
+ * A marker whose owner and delegate are dead is not necessarily a finished
+ * update: an inheriting completion process can still hold the checkout's
+ * kernel lock after the script's immediate child died. The Desktop cannot see
+ * that lock portably and must never delete the marker (A7 rule 3), so a
+ * dead/malformed marker is routed through the checkout script's `reclaim`
+ * helper, which decides under the `<marker>.lock` sidecar:
+ *
+ * - `held` / `busy` / `live <pid>` => an update still owns the checkout: keep waiting;
+ * - `reclaimed` / `absent` => nothing runs: proceed;
+ * - `unsupported` (older checkout, no helper) => proceed without deleting
+ * (dead = not running, as before minus the deletion).
+ *
+ * The helper is asked once per distinct dead marker body per wait; a `held` /
+ * `busy` / `live` answer is re-asked every `reprobeMs` (5 s) because only the
+ * script can see the lock being released.
+ */
+
+import { type CreateTimeProbe, inspectUpdateMarker } from './update-marker'
+import type { MarkerHelperVerdict } from './updater/marker-helper'
+
+export const HELD_REPROBE_MS = 5_000
+
+export interface LiveMarkerProbeOptions {
+ hermesHome: string
+ /** The script helper `reclaim`, or null when the checkout's script predates protocol 2. */
+ reclaim: (() => Promise<MarkerHelperVerdict>) | null
+ createTime?: CreateTimeProbe
+ onLiveMarker?: (marker: { startedAt: number | null }) => void
+ log?: (line: string) => void
+ now?: () => number
+ reprobeMs?: number
+}
+
+const STILL_RUNNING = new Set(['held', 'busy', 'live'])
+
+/** `hasLiveMarker` for one gate wait (create it per wait, never module-wide). */
+export function liveMarkerProbe({
+ hermesHome,
+ reclaim,
+ createTime,
+ onLiveMarker,
+ log,
+ now = Date.now,
+ reprobeMs = HELD_REPROBE_MS
+}: LiveMarkerProbeOptions): () => Promise<boolean> {
+ const asked = new Map<string, { running: boolean; at: number }>()
+
+ return async () => {
+ const inspection = await inspectUpdateMarker(hermesHome, { createTime, now })
+
+ if (inspection.state === 'live') {
+ onLiveMarker?.({ startedAt: inspection.marker?.startedAt ?? null })
+
+ return true
+ }
+
+ if (inspection.state !== 'dead' || !reclaim) {
+ return false
+ }
+
+ const key = inspection.raw.toString('hex')
+ const previous = asked.get(key)
+
+ if (previous && (!previous.running || now() - previous.at < reprobeMs)) {
+ return previous.running
+ }
+
+ const verdict = await reclaim()
+ const running = STILL_RUNNING.has(verdict.kind)
+
+ if (!previous || previous.running !== running) {
+ log?.(`[updates] dead update marker: script helper says ${verdict.kind}${'pid' in verdict ? ` ${verdict.pid}` : ''}`)
+ }
+
+ asked.set(key, { running, at: now() })
+
+ if (running) {
+ onLiveMarker?.({ startedAt: inspection.marker?.startedAt ?? null })
+ }
+
+ return running
+ }
+}
diff --git a/apps/desktop/electron/update-marker-judge.ts b/apps/desktop/electron/update-marker-judge.ts
new file mode 100644
index 00000000000..f8637633ad6
--- /dev/null
+++ b/apps/desktop/electron/update-marker-judge.ts
@@ -0,0 +1,205 @@
+/**
+ * Pure parse + judge of the update marker `HERMES_HOME/.hermes-update-in-progress`
+ * (A7 rule 4, contract in `tests/fixtures/update_marker_corpus.json`).
+ *
+ * The corpus is authoritative: every reader (Python, Rust, bash, PowerShell,
+ * this Desktop) runs its `judge` cases. Process facts are injected
+ * (`JudgeEnv`), so the same code serves the corpus table and the real host.
+ *
+ * Format:
+ *
+ * line 1 owner pid, ASCII digits, fits u32 (else MALFORMED). pid 0 is never a process.
+ * line 2 started_at unix seconds, ASCII digits (else MALFORMED)
+ * line 3 ct:<digits[.digits]> owner creation time; anything else => v1
+ * lines 4+ 'delegate:<pid> ct:<ct>' (exactly one space; first well-formed wins)
+ * 'run:<[A-Za-z0-9._-]{1,128}>' (first wins); other lines ignored
+ *
+ * Per line: one leading BOM (line 1), one trailing CR, then surrounding
+ * spaces/tabs are dropped. Interior whitespace in a pid makes the line bad.
+ */
+
+/** A claim naming OUR pid is ours only within this creation-time slack (rounding to 3 dp). */
+export const OWN_CT_EPSILON_S = 0.005
+
+/** |recorded - actual| creation-time slack for any other pid, in seconds. */
+export const CREATE_TIME_TOLERANCE_S = 2.0
+
+/** Ceiling for an identity whose creation time is unknown (v1 marker, or unreadable). */
+export const V1_MAX_AGE_S = 1200
+
+const U32_MAX = 0xffff_ffff
+const INT_RE = /^[0-9]+$/
+const CT_RE = /^ct:([0-9]+(?:\.[0-9]+)?)$/
+const DELEGATE_RE = /^delegate:([0-9]+) ct:([0-9]+(?:\.[0-9]+)?)$/
+const RUN_RE = /^run:([A-Za-z0-9._-]{1,128})$/
+
+/** The run-id grammar of a `run:` line. */
+export const RUN_ID_RE = /^[A-Za-z0-9._-]{1,128}$/
+
+export interface UpdateMarker {
+ pid: number
+ /** Unix seconds (line 2). */
+ startedAt: number
+ /** Recorded owner creation time; null for a v1 marker. */
+ ct: number | null
+ delegate: { pid: number; ct: number } | null
+ /** The hand-off run id this claim carries (protocol 2), or null. */
+ run: string | null
+}
+
+function cleanLine(line: string): string {
+ return line.replace(/\r$/, '').replace(/^[ \t]+|[ \t]+$/g, '')
+}
+
+function u32(text: string): number | null {
+ const value = Number(text)
+
+ return Number.isSafeInteger(value) && value <= U32_MAX ? value : null
+}
+
+/** Positional parse, identical in every reader. Null = MALFORMED. */
+export function parseUpdateMarker(raw: string): UpdateMarker | null {
+ const lines = String(raw).replace(/^\uFEFF/, '').split('\n').map(cleanLine)
+
+ if (lines.length < 2 || !INT_RE.test(lines[0]) || !INT_RE.test(lines[1])) {
+ return null
+ }
+
+ const pid = u32(lines[0])
+
+ if (pid === null) {
+ return null
+ }
+
+ const ct = lines.length > 2 ? CT_RE.exec(lines[2]) : null
+ let delegate: UpdateMarker['delegate'] = null
+ let run: string | null = null
+
+ for (const line of lines.slice(3)) {
+ const d = delegate === null ? DELEGATE_RE.exec(line) : null
+ const delegatePid = d ? u32(d[1]) : null
+
+ if (d && delegatePid !== null) {
+ delegate = { pid: delegatePid, ct: Number(d[2]) }
+
+ continue
+ }
+
+ const r = run === null ? RUN_RE.exec(line) : null
+
+ if (r) {
+ run = r[1]
+ }
+ }
+
+ return { pid, startedAt: Number(lines[1]), ct: ct ? Number(ct[1]) : null, delegate, run }
+}
+
+/**
+ * State of one (pid, recorded ct) identity:
+ * - `ours`: our own pid at our exact incarnation (5 ms);
+ * - `match`: another live pid whose creation time matches within 2 s;
+ * - `unknown`: another live pid with no ct to compare (v1 or unreadable), inside the v1 ceiling;
+ * - `dead`: gone, zombie, pid 0, reused pid, past the ceiling, or a previous incarnation of us.
+ */
+export type IdentityState = 'ours' | 'match' | 'unknown' | 'dead'
+
+export type MarkerVerdict = 'malformed' | 'dead' | 'ours' | 'live'
+
+export interface MarkerJudgement {
+ verdict: MarkerVerdict
+ /** Owner identity if live, else the delegate if live, else null. */
+ owner: number | null
+ run: string | null
+ marker: UpdateMarker | null
+ ownerState: IdentityState
+ /** `null` when the marker has no delegate line. */
+ delegateState: IdentityState | null
+}
+
+export interface JudgeEnv {
+ ourPid: number
+ /** Our own creation time (unix seconds); null when unreadable. */
+ ourCt: () => number | null | Promise<number | null>
+ /** Alive and not a zombie. Never called for our own pid. */
+ isAlive: (pid: number) => boolean
+ /** Creation time of a live pid; null when unreadable. Only called when the marker recorded one. */
+ createTime: (pid: number) => number | null | Promise<number | null>
+ /** Unix seconds. */
+ nowS: number
+}
+
+async function identityState(
+ pid: number,
+ recordedCt: number | null,
+ startedAt: number,
+ env: JudgeEnv
+): Promise<IdentityState> {
+ if (pid === 0) {
+ return 'dead'
+ }
+
+ if (pid === env.ourPid) {
+ // A7 rule 4: our pid is ours only at our exact incarnation; a no-ct claim
+ // naming our pid is a previous incarnation, never live.
+ const ourCt = await env.ourCt()
+
+ return recordedCt !== null && ourCt !== null && Math.abs(recordedCt - ourCt) <= OWN_CT_EPSILON_S ? 'ours' : 'dead'
+ }
+
+ if (!env.isAlive(pid)) {
+ return 'dead'
+ }
+
+ const actual = recordedCt === null ? null : await env.createTime(pid)
+
+ if (recordedCt === null || actual === null) {
+ return env.nowS - startedAt <= V1_MAX_AGE_S ? 'unknown' : 'dead'
+ }
+
+ return Math.abs(recordedCt - actual) <= CREATE_TIME_TOLERANCE_S ? 'match' : 'dead'
+}
+
+export function isLiveIdentity(state: IdentityState | null): boolean {
+ return state === 'ours' || state === 'match' || state === 'unknown'
+}
+
+/** Judge marker text (corpus `contract.liveness`). */
+export async function judgeMarkerText(text: string, env: JudgeEnv): Promise<MarkerJudgement> {
+ const marker = parseUpdateMarker(text)
+
+ if (!marker) {
+ return { verdict: 'malformed', owner: null, run: null, marker: null, ownerState: 'dead', delegateState: null }
+ }
+
+ const ownerState = await identityState(marker.pid, marker.ct, marker.startedAt, env)
+
+ const delegateState = marker.delegate
+ ? await identityState(marker.delegate.pid, marker.delegate.ct, marker.startedAt, env)
+ : null
+
+ const ownerLive = isLiveIdentity(ownerState)
+ const delegateLive = isLiveIdentity(delegateState)
+ const owner = ownerLive ? marker.pid : delegateLive ? marker.delegate!.pid : null
+ const ours = ownerState === 'ours' || delegateState === 'ours'
+
+ return {
+ verdict: ours ? 'ours' : owner !== null ? 'live' : 'dead',
+ owner,
+ run: marker.run,
+ marker,
+ ownerState,
+ delegateState
+ }
+}
+
+/**
+ * Whether some LIVE identity in the marker is not this process — an update
+ * someone else is running. `ours` alone (a stale bridge of this very process)
+ * is not an update in progress.
+ */
+export function hasForeignLiveIdentity(judgement: Pick<MarkerJudgement, 'ownerState' | 'delegateState'>): boolean {
+ const foreign = (state: IdentityState | null) => state === 'match' || state === 'unknown'
+
+ return foreign(judgement.ownerState) || foreign(judgement.delegateState)
+}
diff --git a/apps/desktop/electron/update-marker-readonly.test.ts b/apps/desktop/electron/update-marker-readonly.test.ts
new file mode 100644
index 00000000000..06e7958bcc5
--- /dev/null
+++ b/apps/desktop/electron/update-marker-readonly.test.ts
@@ -0,0 +1,94 @@
+/**
+ * A7 rule 3: Electron NEVER deletes or rewrites the update marker. Reading
+ * and judging a dead marker — at boot, before a hand-off, before a bridge or
+ * staged-updater pre-write — leaves its bytes exactly as they were; reclaiming
+ * belongs to the checkout script helper under the sidecar lock. (The previous
+ * head compare-and-deleted a dead marker from all of these paths.)
+ */
+
+import fs from 'fs'
+import assert from 'node:assert/strict'
+
+import { afterEach, test } from 'vitest'
+
+import {
+ claimBridgeMarker,
+ EMPTY_MARKER_GRACE_MS,
+ markerPath,
+ readLiveUpdateMarker,
+ updateHandoffConflict,
+ writeUpdateMarker
+} from './update-marker'
+import { cleanupMarkerFixtures, deadPid, minutesAgo, tmpHome } from './update-marker.test-helpers'
+
+afterEach(cleanupMarkerFixtures)
+
+async function deadMarkerBodies(): Promise<[string, string][]> {
+ const gone = await deadPid()
+
+ return [
+ ['dead v2 owner', `${gone}\n${minutesAgo(1)}\nct:1700000000.000\n`],
+ ['dead v1 owner', `${gone}\n${minutesAgo(1)}\n`],
+ ['dead owner + dead delegate (crash-12db shape)', `${gone}\n${minutesAgo(1)}\nct:1.000\ndelegate:${gone} ct:2.000\n`],
+ ['malformed', 'not-a-pid\nnonsense\n'],
+ ['previous incarnation of our own pid', `${process.pid}\n${minutesAgo(1)}\n`]
+ ]
+}
+
+test('readLiveUpdateMarker on a dead marker reports "not running" and leaves the bytes', async () => {
+ for (const [label, body] of await deadMarkerBodies()) {
+ const home = tmpHome('ro-read')
+ fs.writeFileSync(markerPath(home), body)
+
+ assert.equal(await readLiveUpdateMarker(home), null, label)
+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), body, `${label}: bytes unchanged`)
+ }
+})
+
+test('updateHandoffConflict on a dead marker reports no conflict and leaves the bytes', async () => {
+ for (const [label, body] of await deadMarkerBodies()) {
+ const home = tmpHome('ro-conflict')
+ fs.writeFileSync(markerPath(home), body)
+
+ assert.equal(await updateHandoffConflict(home), null, label)
+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), body, `${label}: bytes unchanged`)
+ }
+})
+
+test('claimBridgeMarker over a dead marker does not reclaim it: no claim, bytes unchanged', async () => {
+ for (const [label, body] of await deadMarkerBodies()) {
+ const home = tmpHome('ro-bridge')
+ fs.writeFileSync(markerPath(home), body)
+
+ const claim = await claimBridgeMarker(home, { startedAt: 1 })
+
+ assert.equal(claim.ok, false, `${label}: the exclusive create loses to any existing marker`)
+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), body, `${label}: bytes unchanged`)
+ }
+})
+
+test('writeUpdateMarker (staged pre-write) over a dead marker skips: bytes unchanged', async () => {
+ for (const [label, body] of await deadMarkerBodies()) {
+ const home = tmpHome('ro-prewrite')
+ fs.writeFileSync(markerPath(home), body)
+
+ const prewrite = await writeUpdateMarker(home, process.pid, { startedAt: 1 })
+
+ assert.equal(prewrite.ok, false, label)
+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), body, `${label}: bytes unchanged`)
+ }
+})
+
+test('a stale 0-byte marker is judged dead and left in place', async () => {
+ const home = tmpHome('ro-empty')
+ const file = markerPath(home)
+ fs.writeFileSync(file, '')
+ const old = (Date.now() - EMPTY_MARKER_GRACE_MS - 5000) / 1000
+ fs.utimesSync(file, old, old)
+
+ assert.equal(await readLiveUpdateMarker(home), null)
+ assert.equal(await updateHandoffConflict(home), null)
+ assert.equal((await claimBridgeMarker(home, { startedAt: 1 })).ok, false)
+ assert.ok(fs.existsSync(file))
+ assert.equal(fs.statSync(file).size, 0)
+})
diff --git a/apps/desktop/electron/update-marker.test-helpers.ts b/apps/desktop/electron/update-marker.test-helpers.ts
new file mode 100644
index 00000000000..0a5ad1986ce
--- /dev/null
+++ b/apps/desktop/electron/update-marker.test-helpers.ts
@@ -0,0 +1,109 @@
+/**
+ * Real-process fixtures for the update-marker suites: sleeping owners, reaped
+ * pids, and a claimant child that publishes a marker naming ITSELF (its own
+ * pid and kernel creation time), the way a hand-off script does.
+ */
+
+import fs from 'fs'
+import { type ChildProcess, spawn } from 'node:child_process'
+import { once } from 'node:events'
+import os from 'os'
+import path from 'path'
+
+import { formatCreateTime, processCreateTime } from './update-marker'
+
+const homes: string[] = []
+const children: ChildProcess[] = []
+
+/** Call from afterEach. */
+export function cleanupMarkerFixtures(): void {
+ for (const child of children.splice(0)) {
+ child.kill('SIGKILL')
+ }
+
+ for (const home of homes.splice(0)) {
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+}
+
+export function tmpHome(tag: string): string {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), `hermes-marker-${tag}-`))
+ homes.push(dir)
+
+ return dir
+}
+
+/** A real, live owner process (sleeps until killed). */
+export async function liveOwner(): Promise<ChildProcess & { pid: number }> {
+ const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })
+ children.push(child)
+ await once(child, 'spawn')
+
+ return child as ChildProcess & { pid: number }
+}
+
+/** A pid that existed and is now gone (reaped). */
+export async function deadPid(): Promise<number> {
+ const child = spawn(process.execPath, ['-e', ''], { stdio: 'ignore' })
+ await once(child, 'exit')
+
+ return child.pid as number
+}
+
+export function nowSeconds(): number {
+ return Math.floor(Date.now() / 1000)
+}
+
+export function minutesAgo(minutes: number): number {
+ return nowSeconds() - minutes * 60
+}
+
+export interface ClaimantOptions {
+ startedAt: number
+ run?: string | null
+ /** Record the claimant's creation time (v2). Default true. */
+ withCt?: boolean
+ /** Shift the recorded ct (simulate a reused pid). */
+ ctOffset?: number
+}
+
+/**
+ * A real claimant process that publishes `<its pid>\n<startedAt>\nct:<its ct>\n
+ * [run:<run>\n]` into `file` itself, then stays alive until killed.
+ */
+export async function claimantChild(
+ file: string,
+ { startedAt, run = null, withCt = true, ctOffset = 0 }: ClaimantOptions
+): Promise<{ child: ChildProcess & { pid: number }; body: string }> {
+ const child = spawn(
+ process.execPath,
+ [
+ '-e',
+ `process.stdin.once('data', d => { require('fs').writeFileSync(${JSON.stringify(file)}, d.toString()); process.stdout.write('published\\n') }); setInterval(() => {}, 1000)`
+ ],
+ { stdio: ['pipe', 'pipe', 'ignore'] }
+ )
+
+ children.push(child)
+ await once(child, 'spawn')
+ const pid = child.pid as number
+ const ct = withCt ? await processCreateTime(pid) : null
+
+ if (withCt && ct === null) {
+ throw new Error(`no creation time for claimant ${pid}`)
+ }
+
+ const body = `${pid}\n${startedAt}\n${ct === null ? '' : `ct:${formatCreateTime(ct + ctOffset)}\n`}${run ? `run:${run}\n` : ''}`
+ const published = once(child.stdout!, 'data')
+ child.stdin!.write(body)
+ await published
+
+ return { child: child as ChildProcess & { pid: number }, body }
+}
+
+/** SIGKILL a child and wait until it is reaped. */
+export async function killAndReap(child: ChildProcess): Promise<void> {
+ const exited = child.exitCode === null && child.signalCode === null ? once(child, 'exit') : Promise.resolve()
+ child.kill('SIGKILL')
+ await exited
+}
diff --git a/apps/desktop/electron/update-marker.test.ts b/apps/desktop/electron/update-marker.test.ts
index 433312562d7..d1b6ed7d43c 100644
--- a/apps/desktop/electron/update-marker.test.ts
+++ b/apps/desktop/electron/update-marker.test.ts
@@ -19,9 +19,9 @@ import { afterEach, test } from 'vitest'
import {
cachedCreateTimeProbe,
claimBridgeMarker,
- compareAndDeleteMarker,
EMPTY_MARKER_GRACE_MS,
formatCreateTime,
+ inspectUpdateMarker,
isPidAlive,
markerPath,
parseUpdateMarker,
@@ -83,30 +83,31 @@ const HAS_CT_PROBE = process.platform === 'linux' || process.platform === 'darwi
// ---------------------------------------------------------------------------
test('parses v1, v2 and the delegate line; garbage is null', () => {
- assert.deepEqual(parseUpdateMarker('42\n100\n'), { pid: 42, startedAt: 100, ct: null, delegate: null })
+ assert.deepEqual(parseUpdateMarker('42\n100\n'), { pid: 42, startedAt: 100, ct: null, delegate: null, run: null })
assert.deepEqual(parseUpdateMarker('42\n100\nct:1700000000.125\ndelegate:77 ct:1700000001.500\n'), {
pid: 42,
startedAt: 100,
ct: 1700000000.125,
- delegate: { pid: 77, ct: 1700000001.5 }
+ delegate: { pid: 77, ct: 1700000001.5 },
+ run: null
})
assert.equal(parseUpdateMarker('not-a-pid\nnonsense'), null)
})
// A2: one positional parse in every language (Python, Rust, PowerShell, bash, TS).
test.each([
- ['BOM + CRLF v2', '\uFEFF42\r\n100\r\nct:5.250\r\n', { pid: 42, startedAt: 100, ct: 5.25, delegate: null }],
+ ['BOM + CRLF v2', '\uFEFF42\r\n100\r\nct:5.250\r\n', { pid: 42, startedAt: 100, ct: 5.25, delegate: null, run: null }],
['fractional started_at is MALFORMED', '42\n100.5\nct:5.000\n', null],
['missing started_at is MALFORMED', '42\n', null],
['garbled started_at is MALFORMED', '42\nsoon\n', null],
- ['garbage ct => v1', '42\n100\nct:abc\n', { pid: 42, startedAt: 100, ct: null, delegate: null }],
- ['delegate on line 3 is ignored', '42\n100\ndelegate:77 ct:1.000\n', { pid: 42, startedAt: 100, ct: null, delegate: null }],
- ['space after delegate: is ignored', '42\n100\nct:1.000\ndelegate: 77 ct:1.000\n', { pid: 42, startedAt: 100, ct: 1, delegate: null }],
- ['delegate without ct is ignored', '42\n100\nct:1.000\ndelegate:77\n', { pid: 42, startedAt: 100, ct: 1, delegate: null }],
+ ['garbage ct => v1', '42\n100\nct:abc\n', { pid: 42, startedAt: 100, ct: null, delegate: null, run: null }],
+ ['delegate on line 3 is ignored', '42\n100\ndelegate:77 ct:1.000\n', { pid: 42, startedAt: 100, ct: null, delegate: null, run: null }],
+ ['space after delegate: is ignored', '42\n100\nct:1.000\ndelegate: 77 ct:1.000\n', { pid: 42, startedAt: 100, ct: 1, delegate: null, run: null }],
+ ['delegate without ct is ignored', '42\n100\nct:1.000\ndelegate:77\n', { pid: 42, startedAt: 100, ct: 1, delegate: null, run: null }],
[
'empty ct line (Python probe failure) + delegate on line 4',
'42\n100\n\ndelegate:77 ct:2.500\n',
- { pid: 42, startedAt: 100, ct: null, delegate: { pid: 77, ct: 2.5 } }
+ { pid: 42, startedAt: 100, ct: null, delegate: { pid: 77, ct: 2.5 }, run: null }
]
])('A2 parse: %s', (_name, body, expected) => {
assert.deepEqual(parseUpdateMarker(body), expected)
@@ -130,7 +131,7 @@ test.skipIf(!HAS_CT_PROBE)('a LIVE v2 owner past 20 minutes stays live and is NO
assert.ok(fs.existsSync(markerPath(home)), 'a live owner is never aged out')
})
-test.skipIf(!HAS_CT_PROBE)('a reused pid (creation time mismatch) is dead and compare-deleted (V22)', async () => {
+test.skipIf(!HAS_CT_PROBE)('a reused pid (creation time mismatch) is dead and left for the script (V22, A7 rule 3)', async () => {
const home = tmpHome('v2-reused')
const owner = await liveOwner()
const ct = await processCreateTime(owner.pid)
@@ -138,8 +139,9 @@ test.skipIf(!HAS_CT_PROBE)('a reused pid (creation time mismatch) is dead and co
// an hour earlier: the original owner died and the OS recycled its pid.
fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(2)}\nct:${formatCreateTime(ct! - 3600)}\n`)
+ const body = fs.readFileSync(markerPath(home), 'utf8')
assert.equal(await readLiveUpdateMarker(home), null)
- assert.ok(!fs.existsSync(markerPath(home)), 'a reused-pid marker self-heals')
+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), body, 'Electron never deletes; the script helper reclaims')
})
test('a v1 marker (no creation time) keeps the legacy 20-minute ceiling', async () => {
@@ -147,8 +149,8 @@ test('a v1 marker (no creation time) keeps the legacy 20-minute ceiling', async
const owner = await liveOwner()
fs.writeFileSync(markerPath(home), `${owner.pid}\n${Math.floor((Date.now() - UPDATE_MARKER_MAX_AGE_MS) / 1000) - 60}\n`)
- assert.equal(await readLiveUpdateMarker(home), null, 'v1 pid reuse must still self-heal')
- assert.ok(!fs.existsSync(markerPath(home)))
+ assert.equal(await readLiveUpdateMarker(home), null, 'v1 pid reuse reads as not running')
+ assert.ok(fs.existsSync(markerPath(home)), 'and is left for the script helper (A7 rule 3)')
})
// A1: Windows refuses creation-time queries for SYSTEM/elevated/other-user
@@ -164,7 +166,7 @@ test('a v2 owner whose creation time is UNREADABLE is live only inside the 20-mi
fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(25)}\nct:1700000000.000\n`)
assert.equal(await readLiveUpdateMarker(home, { createTime: accessDenied }), null, 'past the ceiling it is dead')
- assert.ok(!fs.existsSync(markerPath(home)), 'and compare-deleted, so boot is never parked forever')
+ assert.ok(fs.existsSync(markerPath(home)), 'not running, so boot is never parked forever — and left in place (A7 rule 3)')
})
// A1 on a real Windows host: csrss.exe is a SYSTEM (protected) process whose
@@ -188,7 +190,7 @@ test.runIf(process.platform === 'win32')('Windows reads a SYSTEM process creatio
fs.writeFileSync(markerPath(home), `${pid}\n${minutesAgo(1)}\nct:${formatCreateTime(ct! - 3600)}\n`)
assert.equal(await readLiveUpdateMarker(home), null)
- assert.ok(!fs.existsSync(markerPath(home)))
+ assert.ok(fs.existsSync(markerPath(home)), 'left in place (A7 rule 3)')
})
test('a gate wait probes each pid creation time ONCE (A1: no powershell spawn per poll)', async () => {
@@ -257,7 +259,7 @@ test('dead pid / zombie => no live update; unknown state fails open', async () =
const home = tmpHome('dead')
fs.writeFileSync(markerPath(home), `${await deadPid()}\n${minutesAgo(0)}\n`)
assert.equal(await readLiveUpdateMarker(home), null)
- assert.ok(!fs.existsSync(markerPath(home)))
+ assert.ok(fs.existsSync(markerPath(home)), 'left in place (A7 rule 3)')
fs.writeFileSync(markerPath(home), `4242\n${minutesAgo(0)}\n`)
assert.equal(await readLiveUpdateMarker(home, { kill: () => true, processState: () => 'Z' }), null)
@@ -266,16 +268,6 @@ test('dead pid / zombie => no live update; unknown state fails open', async () =
assert.ok(await readLiveUpdateMarker(home, { kill: () => true, processState: () => null }))
})
-test('compare-and-delete never removes a claim written after the dead verdict (C1 rule 5)', () => {
- const home = tmpHome('cas')
- fs.writeFileSync(markerPath(home), '999999\n1\n')
- const judgedDead = fs.readFileSync(markerPath(home))
- fs.writeFileSync(markerPath(home), `${process.pid}\n2\nct:3.000\n`)
-
- assert.equal(compareAndDeleteMarker(home, judgedDead), false)
- assert.ok(fs.existsSync(markerPath(home)), 'the newer claim survives')
-})
-
test('isPidAlive / posixProcessState basics', () => {
assert.equal(isPidAlive(process.pid), true)
assert.equal(isPidAlive(-1), false)
@@ -309,10 +301,14 @@ test('the bridge marker names THIS process with its creation time (V4)', async (
assert.ok(marker.ct !== null && Math.abs(marker.ct - (await processCreateTime(process.pid))!) <= 2)
}
- assert.ok(await readLiveUpdateMarker(home), 'our own bridge claim reads live')
+ // A bridge of this very process is not someone else's update: the gate's
+ // in-process flags cover the hand-off window, and a stale bridge left by a
+ // failed withdraw must not park this Desktop's own backend restart.
+ assert.equal((await inspectUpdateMarker(home)).state, 'ours')
+ assert.equal(await readLiveUpdateMarker(home), null)
})
-test('the bridge claim refuses a LIVE foreign owner and reclaims a dead one', async () => {
+test('the bridge claim refuses a LIVE foreign owner and reports (never reclaims) a dead one', async () => {
const home = tmpHome('bridge-conflict')
const owner = await liveOwner()
fs.writeFileSync(markerPath(home), `${owner.pid}\n${minutesAgo(30)}\nct:${formatCreateTime((await processCreateTime(owner.pid)) ?? 0)}\n`)
@@ -323,8 +319,13 @@ test('the bridge claim refuses a LIVE foreign owner and reclaims a dead one', as
assert.match(String(!refused.ok && refused.conflict?.message), /already running/)
assert.equal(parseUpdateMarker(fs.readFileSync(markerPath(home), 'utf8'))!.pid, owner.pid, 'never overwritten')
- fs.writeFileSync(markerPath(home), `${await deadPid()}\n${minutesAgo(1)}\n`)
- assert.ok((await claimBridgeMarker(home, { startedAt: 2 })).ok, 'a dead claim is reclaimed')
+ const dead = `${await deadPid()}\n${minutesAgo(1)}\nct:1.000\nrun:desk-1-a-0000\n`
+ fs.writeFileSync(markerPath(home), dead)
+ const blocked = await claimBridgeMarker(home, { startedAt: 2 })
+ assert.equal(blocked.ok, false, 'exclusive create only (A7 rule 3)')
+ assert.equal(blocked.existing?.state, 'dead', 'reported for the script helper to reclaim')
+ assert.equal(blocked.existing?.run, 'desk-1-a-0000')
+ assert.equal(fs.readFileSync(markerPath(home), 'utf8'), dead)
})
// r1 M1: the staged Tauri updater path pre-writes the marker for the spawned
@@ -345,7 +346,7 @@ test.skipIf(!HAS_CT_PROBE)('writeUpdateMarker names the spawned updater with its
// A3: a claim is never visible half-written, and a 0-byte claim being written
// by an O_EXCL-only writer is not mistaken for garbage and deleted.
-test('a fresh 0-byte marker reads LIVE and survives; a stale one is reclaimed (A3)', async () => {
+test('a fresh 0-byte marker reads LIVE and survives; a stale one reads dead and is left (A3, A7 rule 3)', async () => {
const home = tmpHome('empty')
const file = markerPath(home)
fs.writeFileSync(file, '')
@@ -357,7 +358,7 @@ test('a fresh 0-byte marker reads LIVE and survives; a stale one is reclaimed (A
const old = (Date.now() - EMPTY_MARKER_GRACE_MS - 5000) / 1000
fs.utimesSync(file, old, old)
assert.equal(await readLiveUpdateMarker(home), null)
- assert.ok(!fs.existsSync(file))
+ assert.ok(fs.existsSync(file))
})
test('claims publish by hard link and leave no tmp litter; a dead writer tmp is reclaimed (A3)', async () => {
@@ -391,30 +392,37 @@ test('writeUpdateMarker (staged updater) never overwrites a live claim', async (
// Hand-off confirmation (C2, desktop V7)
// ---------------------------------------------------------------------------
-test('the hand-off counts as started only when a real script process takes the marker', async () => {
+test('the hand-off counts as started only when a real legacy script process takes the marker', async () => {
const home = tmpHome('handoff-taken')
- await claimBridgeMarker(home, { startedAt: 5 })
const file = markerPath(home)
+ const startedAt = Math.floor(Date.now() / 1000)
- // A real "script": waits, then claims the marker in its own name.
+ // A real old-style "script": waits, then claims the marker in its own name,
+ // echoing HERMES_UPDATE_STARTED_AT on line 2.
const script = spawn(
process.execPath,
- ['-e', `setTimeout(() => { require('fs').writeFileSync(${JSON.stringify(file)}, process.pid + '\\n5\\n'); setInterval(() => {}, 1000) }, 300)`],
+ [
+ '-e',
+ `setTimeout(() => { require('fs').writeFileSync(${JSON.stringify(file)}, process.pid + '\\n${startedAt}\\n'); setInterval(() => {}, 1000) }, 300)`
+ ],
{ stdio: 'ignore' }
)
children.push(script)
- const taken = await waitForHandoffClaim(home, process.pid, { timeoutMs: 10_000, pollMs: 50 })
+ const taken = await waitForHandoffClaim(home, process.pid, { startedAt, timeoutMs: 10_000, pollMs: 50 })
assert.deepEqual(taken, { taken: true, pid: script.pid })
})
test('a wrapper that exits 0 without the script ever claiming is NOT a hand-off', async () => {
const home = tmpHome('handoff-never')
- await claimBridgeMarker(home, { startedAt: 5 })
+ await claimBridgeMarker(home, { startedAt: 5, runId: 'desk-1-a-0000' })
const wrapper = spawn(process.execPath, ['-e', 'process.exit(0)'], { stdio: 'ignore' })
await new Promise(resolve => wrapper.once('exit', resolve))
- assert.deepEqual(await waitForHandoffClaim(home, process.pid, { timeoutMs: 400, pollMs: 50 }), { taken: false })
+ assert.deepEqual(
+ await waitForHandoffClaim(home, process.pid, { runId: 'desk-1-a-0000', timeoutMs: 400, pollMs: 50 }),
+ { taken: false }
+ )
})
diff --git a/apps/desktop/electron/update-marker.ts b/apps/desktop/electron/update-marker.ts
index cf7103ff288..9b84cb04549 100644
--- a/apps/desktop/electron/update-marker.ts
+++ b/apps/desktop/electron/update-marker.ts
@@ -6,46 +6,52 @@
* Desktop. While it names a LIVE owner, a Desktop reopened mid-update must not
* spawn a backend on the runtime being replaced, and no second update may start.
*
- * Body (UTF-8, `\n` line ends):
+ * Parsing and judging live in `update-marker-judge.ts` and follow the shared
+ * corpus `tests/fixtures/update_marker_corpus.json` (A7 rules 4 and 7).
*
- * <pid>
- * <started_at unix seconds>
- * ct:<owner creation time, unix seconds, 3 decimals> (absent in v1 writers)
- * delegate:<pid> ct:<creation time> (optional, see below)
- *
- * Parsing is positional and identical in every language (contract A2): a
- * leading BOM and `\r\n` are accepted; line 2 must be an integer or the marker
- * is malformed (dead); a line 3 that is not `ct:<n>` makes it v1; a line 4
- * that is not `delegate:<pid> ct:<n>` is ignored.
- *
- * Liveness: a pid that is alive (not a zombie) with a creation time MATCHING
- * the recorded one within 2 s is live regardless of age — a Windows update is
- * routinely 25-40 minutes. A live pid whose creation time is unknown (v1
- * marker, or the probe was refused) is live only inside the legacy 20-minute
- * ceiling (A1): without a creation time nothing else tells a reused pid from
- * the original owner. The marker is LIVE when the owner OR the delegate
- * (`hermes update` running under a hand-off script's claim) is live, so a
- * killed script cannot hide a still-mutating update.
+ * A7 rule 3: this Desktop NEVER deletes or rewrites the marker. Node has no
+ * portable kernel lock, so every read-judge-mutate (reclaim a dead claim,
+ * withdraw a bridge) belongs to the checkout's script helper, which holds the
+ * `<marker>.lock` sidecar for the whole decision (see
+ * `updater/marker-helper.ts`). Electron reads, decides "running / not
+ * running", and may exclusive-create its own bridge or the staged updater's
+ * pre-write — an exclusive create can only succeed where no marker exists.
*
* Claims publish a complete body with an exclusive hard link (A3), so a
* reader never sees a half-written claim; where links are unsupported the
* O_EXCL fallback can expose an empty file for an instant, and readers treat
* a 0-byte marker younger than 5 s as live.
- *
- * Deletes are compare-and-delete: re-read the bytes and unlink only when they
- * still equal the bytes judged dead (or the bytes we wrote). A verdict from an
- * earlier read never unlinks a newer claim.
*/
import fs from 'fs'
import { execFile, execFileSync } from 'node:child_process'
+import { randomBytes } from 'node:crypto'
import path from 'path'
-/** Legacy ceiling, applied ONLY to v1 markers (no creation time recorded). */
-export const UPDATE_MARKER_MAX_AGE_MS = 20 * 60 * 1000
-
-/** |recorded - actual| creation-time slack, in seconds (C1 rule 3). */
-export const CREATE_TIME_TOLERANCE_S = 2.0
+import {
+ CREATE_TIME_TOLERANCE_S,
+ hasForeignLiveIdentity,
+ type JudgeEnv,
+ judgeMarkerText,
+ type MarkerJudgement,
+ RUN_ID_RE,
+ type UpdateMarker,
+ V1_MAX_AGE_S
+} from './update-marker-judge'
+
+export {
+ CREATE_TIME_TOLERANCE_S,
+ type IdentityState,
+ judgeMarkerText,
+ type MarkerJudgement,
+ OWN_CT_EPSILON_S,
+ parseUpdateMarker,
+ type UpdateMarker,
+ V1_MAX_AGE_S
+} from './update-marker-judge'
+
+/** Legacy ceiling, applied ONLY to identities without a comparable creation time. */
+export const UPDATE_MARKER_MAX_AGE_MS = V1_MAX_AGE_S * 1000
/** How long a hand-off script has to take the bridge marker (C2). */
export const HANDOFF_CLAIM_TIMEOUT_MS = 20_000
@@ -305,89 +311,43 @@ export function formatCreateTime(seconds: number): string {
return seconds.toFixed(3)
}
-export interface UpdateMarker {
- pid: number
- /** Unix seconds (line 2; an integer, or the marker is malformed). */
- startedAt: number
- /** Recorded owner creation time; null for a v1 marker. */
- ct: number | null
- delegate: { pid: number; ct: number } | null
-}
-
-const INT_LINE_RE = /^\d+$/
-const CT_LINE_RE = /^ct:(\d+(?:\.\d+)?)$/
-const DELEGATE_LINE_RE = /^delegate:(\d+) ct:(\d+(?:\.\d+)?)$/
-
-/**
- * Positional parse, identical in every reader (A2). Null = MALFORMED (dead):
- * line 1 not a pid or line 2 not an integer. A bad line 3 means v1; a bad
- * line 4 is ignored.
- */
-export function parseUpdateMarker(raw: string): UpdateMarker | null {
- const lines = String(raw)
- .replace(/^\uFEFF/, '')
- .split('\n')
- .map(line => line.trim())
-
- const [pidLine = '', startedLine = '', ctLine = '', delegateLine = ''] = lines
-
- if (!INT_LINE_RE.test(pidLine) || !INT_LINE_RE.test(startedLine)) {
- return null
- }
-
- const ct = CT_LINE_RE.exec(ctLine)
- const delegate = DELEGATE_LINE_RE.exec(delegateLine)
-
- return {
- pid: Number(pidLine),
- startedAt: Number(startedLine),
- ct: ct ? Number(ct[1]) : null,
- delegate: delegate ? { pid: Number(delegate[1]), ct: Number(delegate[2]) } : null
- }
-}
-
export interface MarkerProbeDeps {
kill?: typeof process.kill
+ /** Milliseconds since the epoch. */
now?: () => number
- maxAgeMs?: number
processState?: (pid: number) => string | null
createTime?: CreateTimeProbe
+ /** The pid judged as "us" (A7 rule 4); default this process. */
+ ownPid?: number
}
-/**
- * C1 rule 3 identity of one (pid, recorded ct) pair: `match` = alive with the
- * recorded creation time; `unknown` = alive but no creation time to compare
- * (v1, or the probe was refused); `dead` = gone, a zombie, or a reused pid.
- */
-async function processIdentity(
- pid: number,
- recordedCt: number | null,
- deps: MarkerProbeDeps
-): Promise<'match' | 'unknown' | 'dead'> {
- if (!isPidAlive(pid, deps.kill) || isZombieState((deps.processState || posixProcessState)(pid))) {
- return 'dead'
- }
+/** The host's process facts as a judge environment (A7 rule 4). */
+export function hostJudgeEnv(deps: MarkerProbeDeps = {}): JudgeEnv {
+ const createTime = deps.createTime || processCreateTime
+ const ourPid = deps.ownPid ?? process.pid
- if (recordedCt === null) {
- return 'unknown'
- }
-
- const actual = await (deps.createTime || processCreateTime)(pid)
-
- if (actual === null) {
- return 'unknown'
+ return {
+ ourPid,
+ ourCt: () => createTime(ourPid),
+ isAlive: pid => isPidAlive(pid, deps.kill) && !isZombieState((deps.processState || posixProcessState)(pid)),
+ createTime,
+ nowS: (deps.now || Date.now)() / 1000
}
-
- return Math.abs(actual - recordedCt) <= CREATE_TIME_TOLERANCE_S ? 'match' : 'dead'
}
export type MarkerInspection =
| { state: 'absent' }
- /** `marker` is null for a 0-byte claim still being written (A3). */
- | { state: 'live'; raw: Buffer; marker: UpdateMarker | null; ageMs: number; livePid: number }
- | { state: 'dead'; raw: Buffer; marker: UpdateMarker | null }
-
-/** Read and judge the marker without touching it. */
+ /**
+ * Someone else's update is running (a live identity that is not this
+ * process), or a 0-byte claim is being written (`judgement` null, A3).
+ */
+ | { state: 'live'; raw: Buffer; marker: UpdateMarker | null; ageMs: number; livePid: number; judgement: MarkerJudgement | null }
+ /** A bridge of THIS process incarnation and nothing foreign alive in it. */
+ | { state: 'ours'; raw: Buffer; marker: UpdateMarker; judgement: MarkerJudgement }
+ /** Dead or malformed (`judgement` null for a stale 0-byte file). */
+ | { state: 'dead'; raw: Buffer; marker: UpdateMarker | null; judgement: MarkerJudgement | null }
+
+/** Read and judge the marker. Never touches it. */
export async function inspectUpdateMarker(hermesHome: string, deps: MarkerProbeDeps = {}): Promise<MarkerInspection> {
const file = markerPath(hermesHome)
const now = deps.now || Date.now
@@ -409,76 +369,70 @@ export async function inspectUpdateMarker(hermesHome: string, deps: MarkerProbeD
}
return ageMs < EMPTY_MARKER_GRACE_MS
- ? { state: 'live', raw, marker: null, ageMs: Math.max(0, ageMs), livePid: 0 }
- : { state: 'dead', raw, marker: null }
+ ? { state: 'live', raw, marker: null, ageMs: Math.max(0, ageMs), livePid: 0, judgement: null }
+ : { state: 'dead', raw, marker: null, judgement: null }
}
- const marker = parseUpdateMarker(raw.toString('utf8'))
+ const judgement = await judgeMarkerText(raw.toString('utf8'), hostJudgeEnv(deps))
+ const { marker } = judgement
- if (!marker) {
- return { state: 'dead', raw, marker: null }
+ if (!marker || judgement.verdict === 'malformed' || judgement.verdict === 'dead') {
+ return { state: 'dead', raw, marker, judgement }
}
- const ageMs = now() - marker.startedAt * 1000
- const withinCeiling = ageMs <= (deps.maxAgeMs ?? UPDATE_MARKER_MAX_AGE_MS)
-
- // A1: only a MATCHING creation time is live regardless of age.
- const isLive = (identity: 'match' | 'unknown' | 'dead') =>
- identity === 'match' || (identity === 'unknown' && withinCeiling)
-
- if (isLive(await processIdentity(marker.pid, marker.ct, deps))) {
- return { state: 'live', raw, marker, ageMs, livePid: marker.pid }
- }
+ if (hasForeignLiveIdentity(judgement)) {
+ const ownerForeign = judgement.ownerState === 'match' || judgement.ownerState === 'unknown'
+ const livePid = ownerForeign ? marker.pid : (marker.delegate?.pid ?? marker.pid)
- if (marker.delegate && isLive(await processIdentity(marker.delegate.pid, marker.delegate.ct, deps))) {
- return { state: 'live', raw, marker, ageMs, livePid: marker.delegate.pid }
+ return { state: 'live', raw, marker, ageMs: now() - marker.startedAt * 1000, livePid, judgement }
}
- return { state: 'dead', raw, marker }
-}
-
-/** C1 rule 5: unlink only while the file still holds exactly `expected`. */
-export function compareAndDeleteMarker(hermesHome: string, expected: Buffer | string): boolean {
- const file = markerPath(hermesHome)
-
- try {
- if (!fs.readFileSync(file).equals(Buffer.isBuffer(expected) ? expected : Buffer.from(expected, 'utf8'))) {
- return false
- }
-
- fs.unlinkSync(file)
-
- return true
- } catch {
- return false
- }
+ return { state: 'ours', raw, marker, judgement }
}
/**
- * `{ pid, ageMs }` while an update is genuinely running, else null. A dead
- * marker is compare-and-deleted so it cannot strand future launches.
+ * `{ pid, ageMs }` while someone else's update is genuinely running, else
+ * null. Read-only (A7 rule 3): a dead marker is left for the script helper /
+ * the next claimant to reclaim under the lock.
*/
export async function readLiveUpdateMarker(hermesHome: string, deps: MarkerProbeDeps = {}) {
const inspection = await inspectUpdateMarker(hermesHome, deps)
- if (inspection.state === 'live') {
- return {
- pid: inspection.livePid,
- ownerPid: inspection.marker?.pid ?? 0,
- ageMs: inspection.ageMs,
- startedAt: inspection.marker?.startedAt ?? null
- }
+ if (inspection.state !== 'live') {
+ return null
}
- if (inspection.state === 'dead') {
- compareAndDeleteMarker(hermesHome, inspection.raw)
+ return {
+ pid: inspection.livePid,
+ ownerPid: inspection.marker?.pid ?? 0,
+ ageMs: inspection.ageMs,
+ startedAt: inspection.marker?.startedAt ?? null
}
+}
- return null
+function markerBody(pid: number, startedAt: number, ct: number | null, runId?: string | null): string {
+ const ctLine = ct === null ? '' : `ct:${formatCreateTime(ct)}\n`
+ const runLine = runId ? `run:${runId}\n` : ''
+
+ return `${pid}\n${startedAt}\n${ctLine}${runLine}`
}
-function markerBody(pid: number, startedAt: number, ct: number | null): string {
- return `${pid}\n${startedAt}\n${ct === null ? '' : `ct:${formatCreateTime(ct)}\n`}`
+/** What an exclusive create found instead of publishing. */
+export interface ExistingMarker {
+ state: 'dead' | 'ours'
+ raw: Buffer
+ /** The run id the existing claim carries (to withdraw a stale bridge of ours). */
+ run: string | null
+}
+
+export interface ClaimResult {
+ ok: boolean
+ body?: string
+ /** Set when a LIVE claim blocks ours. */
+ owner?: { pid: number; ageMs: number } | null
+ /** Set when a dead/malformed claim, or a stale bridge of this process, blocks ours. */
+ existing?: ExistingMarker
+ error?: string
}
/**
@@ -486,9 +440,9 @@ function markerBody(pid: number, startedAt: number, ct: number | null): string {
* child IS the updater there, so the marker names its pid AND its creation
* time. A v2 body takes this path off the v1 20-minute ceiling, lets the
* updater adopt it as its own claim, and lets the `hermes update` it runs add
- * its delegate line (frozen updaters read only lines 1-2). An unreadable ct
- * falls back to a v1 body. Exclusive publish — a live claim is never
- * overwritten; a dead one is compare-and-deleted first.
+ * its delegate line. Exclusive create ONLY (A7 rule 3): over any existing
+ * marker — live or dead — the pre-write is skipped and the staged updater
+ * claims (and reclaims) for itself.
*/
export async function writeUpdateMarker(
hermesHome: string,
@@ -505,18 +459,26 @@ export async function writeUpdateMarker(
return createMarkerExclusive(hermesHome, markerBody(pid, acquiredAt, ct), deps)
}
-interface ClaimResult {
- ok: boolean
- body?: string
- /** Set when a LIVE claim blocks ours. */
- owner?: { pid: number; ageMs: number } | null
- error?: string
+/** Log line for a staged-updater pre-write that was skipped (exclusive create lost). */
+export function describeSkippedPrewrite(result: ClaimResult): string {
+ if (result.owner) {
+ return `an update owned by pid ${result.owner.pid || '(claim being written)'} holds the marker`
+ }
+
+ if (result.existing) {
+ return `a ${result.existing.state} marker exists; the staged updater reclaims it under its own lock`
+ }
+
+ return result.error || 'unknown error'
}
const TMP_SIBLING_RE = /^\.hermes-update-in-progress\.(\d+)(?:\.\d+)?\.tmp$/
let tmpSequence = 0
-/** Drop publish/CAS tmp siblings whose writer died between write and link/rename. */
+/**
+ * Drop OUR publish tmp siblings (`<marker>.<pid>.<seq>.tmp`) whose writer died
+ * between write and link. Never the marker itself.
+ */
function reclaimDeadTmpSiblings(hermesHome: string) {
try {
for (const name of fs.readdirSync(hermesHome)) {
@@ -591,36 +553,40 @@ function publishExclusive(file: string, body: string): 'published' | 'exists' {
return 'published'
}
+/**
+ * One exclusive create (A7 rule 2). On EEXIST the existing marker is judged
+ * read-only and reported: a live owner blocks, a dead one / our own stale
+ * bridge is handed back for the caller to route through the script helper.
+ */
async function createMarkerExclusive(hermesHome: string, body: string, deps: MarkerProbeDeps): Promise<ClaimResult> {
const file = markerPath(hermesHome)
reclaimDeadTmpSiblings(hermesHome)
- for (let attempt = 0; attempt < 2; attempt++) {
- try {
- if (publishExclusive(file, body) === 'published') {
- return { ok: true, body }
- }
- } catch (error: any) {
- return { ok: false, owner: null, error: error?.message || String(error) }
+ try {
+ if (publishExclusive(file, body) === 'published') {
+ return { ok: true, body }
}
+ } catch (error: any) {
+ return { ok: false, owner: null, error: error?.message || String(error) }
+ }
- const inspection = await inspectUpdateMarker(hermesHome, deps)
-
- if (inspection.state === 'live') {
- return { ok: false, owner: { pid: inspection.livePid, ageMs: inspection.ageMs } }
- }
+ const inspection = await inspectUpdateMarker(hermesHome, deps)
- if (inspection.state === 'dead') {
- compareAndDeleteMarker(hermesHome, inspection.raw)
- }
+ if (inspection.state === 'live') {
+ return { ok: false, owner: { pid: inspection.livePid, ageMs: inspection.ageMs } }
}
- const inspection = await inspectUpdateMarker(hermesHome, deps)
+ if (inspection.state === 'absent') {
+ // Withdrawn between our create and our read: the caller may retry once.
+ return { ok: false, owner: null, error: 'the marker changed while it was being claimed' }
+ }
- return inspection.state === 'live'
- ? { ok: false, owner: { pid: inspection.livePid, ageMs: inspection.ageMs } }
- : { ok: false, owner: null, error: 'lost the marker claim race twice' }
+ return {
+ ok: false,
+ owner: null,
+ existing: { state: inspection.state, raw: inspection.raw, run: inspection.judgement?.run ?? null }
+ }
}
function conflictMessage(owner: { pid: number; ageMs: number }): string {
@@ -636,11 +602,33 @@ function conflictMessage(owner: { pid: number; ageMs: number }): string {
return `An update is already running (PID ${owner.pid}, started ${elapsed} ago). Wait for it to finish, then try again.`
}
+/** A protocol-2 hand-off run id: `desk-<pid>-<base36 ms>-<hex4>` (run-line grammar). */
+export function makeHandoffRunId(pid: number = process.pid, nowMs: number = Date.now()): string {
+ const id = `desk-${pid}-${nowMs.toString(36)}-${randomBytes(2).toString('hex')}`
+
+ if (!RUN_ID_RE.test(id)) {
+ throw new Error(`invalid hand-off run id ${id}`)
+ }
+
+ return id
+}
+
+export interface BridgeClaimResult {
+ ok: boolean
+ body?: string
+ /** A live foreign owner (or a claim being written) refuses the hand-off. */
+ conflict?: { pid: number; ageMs: number; message: string } | null
+ /** A dead/malformed marker or a stale bridge of ours blocks the create (protocol 2: script helper). */
+ existing?: ExistingMarker
+ error?: string
+}
+
/**
- * C2 bridge claim: the Desktop claims the marker in ITS OWN name (pid +
- * creation time) before spawning the hand-off script. Electron is alive until
- * it quits, so the claim never names a short-lived `cmd.exe`/launcher wrapper.
- * A live foreign owner refuses the hand-off (#75778).
+ * C2 bridge claim, protocol 2 (SPEC 4a): the Desktop exclusive-creates the
+ * marker in ITS OWN name (pid + creation time) with the hand-off `run:` line
+ * before spawning the script. Never reclaims or overwrites anything (A7
+ * rule 3): an existing marker is reported for the caller to route through
+ * the checkout's script helper.
*/
export async function claimBridgeMarker(
hermesHome: string,
@@ -648,14 +636,10 @@ export async function claimBridgeMarker(
pid = process.pid,
createTime,
startedAt,
+ runId,
...deps
- }: MarkerProbeDeps & { pid?: number; startedAt?: number } = {}
-): Promise<{
- ok: boolean
- body?: string
- conflict?: { pid: number; ageMs: number; message: string } | null
- error?: string
-}> {
+ }: MarkerProbeDeps & { pid?: number; startedAt?: number; runId?: string } = {}
+): Promise<BridgeClaimResult> {
const ct = await (createTime || processCreateTime)(pid)
const acquiredAt =
@@ -663,47 +647,92 @@ export async function claimBridgeMarker(
? startedAt
: Math.floor((deps.now || Date.now)() / 1000)
- const body = markerBody(pid, acquiredAt, ct)
+ const body = markerBody(pid, acquiredAt, ct, runId)
fs.mkdirSync(hermesHome, { recursive: true })
- const result = await createMarkerExclusive(hermesHome, body, { ...deps, createTime })
+ const result = await createMarkerExclusive(hermesHome, body, { ...deps, createTime, ownPid: deps.ownPid ?? pid })
if (result.ok || !result.owner) {
- return result
+ return { ok: result.ok, body: result.body, existing: result.existing, error: result.error }
}
return { ok: false, conflict: { ...result.owner, message: conflictMessage(result.owner) } }
}
+export interface HandoffClaimOptions extends MarkerProbeDeps {
+ /** Protocol 2: the run id passed to the script; the claim must carry it. */
+ runId?: string
+ /** Legacy scripts: the HERMES_UPDATE_STARTED_AT they echo on line 2. */
+ startedAt?: number
+ timeoutMs?: number
+ pollMs?: number
+ sleep?: (ms: number) => Promise<void>
+}
+
+/**
+ * Whether the marker body proves a LIVE successor took the hand-off (R5,
+ * A7 rule 6). Never the Desktop's own incarnation, never a dead or reused pid.
+ * - protocol 2 (`runId`): line-1 owner verified by pid AND creation time
+ * (`match`, not `unknown`) and the claim's run == runId;
+ * - legacy (`startedAt`): line-1 owner live (ct verified when recorded, else
+ * alive inside the v1 ceiling) and line 2 == the startedAt we passed.
+ */
+export async function handoffTakenBy(
+ text: string,
+ desktopPid: number,
+ { runId, startedAt, ...deps }: HandoffClaimOptions
+): Promise<number | null> {
+ const judgement = await judgeMarkerText(text, hostJudgeEnv({ ...deps, ownPid: desktopPid }))
+ const marker = judgement.marker
+
+ if (!marker || marker.pid === desktopPid) {
+ return null
+ }
+
+ if (runId !== undefined) {
+ return judgement.ownerState === 'match' && marker.run === runId ? marker.pid : null
+ }
+
+ const live = judgement.ownerState === 'match' || judgement.ownerState === 'unknown'
+
+ return live && (startedAt === undefined || marker.startedAt === startedAt) ? marker.pid : null
+}
+
/**
- * C2: the hand-off has started only once the script took the marker — its
- * owner pid is no longer ours. A wrapper's exit code says nothing about
- * whether the script ever ran (#66753: CLM-blocked Add-Type, a missing
- * /usr/bin/python3 for the posix daemonizer).
+ * C2 + R5: the hand-off has started only once a LIVE, correlated script
+ * process holds the marker. A wrapper's exit code says nothing about whether
+ * the script ever ran (#66753), and a pid that claimed then died is not a
+ * running update.
*/
export async function waitForHandoffClaim(
hermesHome: string,
- ownPid: number,
+ desktopPid: number,
{
timeoutMs = HANDOFF_CLAIM_TIMEOUT_MS,
pollMs = 200,
now = Date.now,
- sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
- }: { timeoutMs?: number; pollMs?: number; now?: () => number; sleep?: (ms: number) => Promise<void> } = {}
+ sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)),
+ createTime,
+ ...rest
+ }: HandoffClaimOptions = {}
): Promise<{ taken: true; pid: number } | { taken: false }> {
const deadline = now() + timeoutMs
+ // One creation-time probe per pid for this wait (a powershell spawn on Windows).
+ const probe = cachedCreateTimeProbe(createTime)
for (;;) {
- let marker: UpdateMarker | null = null
+ let text: string | null = null
try {
- marker = parseUpdateMarker(fs.readFileSync(markerPath(hermesHome), 'utf8'))
+ text = fs.readFileSync(markerPath(hermesHome), 'utf8')
} catch {
- marker = null
+ text = null
}
- if (marker && marker.pid !== ownPid) {
- return { taken: true, pid: marker.pid }
+ const pid = text ? await handoffTakenBy(text, desktopPid, { ...rest, now, createTime: probe }) : null
+
+ if (pid !== null) {
+ return { taken: true, pid }
}
if (now() >= deadline) {
@@ -716,7 +745,7 @@ export async function waitForHandoffClaim(
/**
* Whether a NEW updater hand-off must be refused because a different, live
- * updater owns the marker (#75778). Null when it is safe to spawn.
+ * updater owns the marker (#75778). Null when it is safe to spawn. Read-only.
*/
export async function updateHandoffConflict(hermesHome: string, deps: MarkerProbeDeps = {}) {
const owner = await readLiveUpdateMarker(hermesHome, deps)
diff --git a/apps/desktop/electron/updater/checkout-handoff.test.ts b/apps/desktop/electron/updater/checkout-handoff.test.ts
index 7f1c19bacc3..92a31236b34 100644
--- a/apps/desktop/electron/updater/checkout-handoff.test.ts
+++ b/apps/desktop/electron/updater/checkout-handoff.test.ts
@@ -4,29 +4,32 @@ import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
-import { afterEach, expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
-import { markerPath } from '../update-marker'
+import { markerPath, parseUpdateMarker } from '../update-marker'
+import { claimantChild, cleanupMarkerFixtures, deadPid, killAndReap } from '../update-marker.test-helpers'
import * as updaterProcess from '../updater-process'
import { type CheckoutStrategyDeps, createCheckoutStrategy } from './checkout'
import type { SourceUpdate } from './checkout-source'
+import { fakeHelperScript } from './marker-helper.test-helpers'
const IS_WINDOWS: boolean = process.platform === 'win32'
const NO_GATEWAY_FLAG: string = IS_WINDOWS ? '-NoGateway' : '--no-gateway'
afterEach((): void => {
vi.restoreAllMocks()
+ cleanupMarkerFixtures()
})
/** A checkout root with the repo hand-off script staged, plus a strategy over it. */
-function handoffFixture(remote: boolean): { root: string; deps: CheckoutStrategyDeps } {
+function handoffFixture(remote: boolean, scriptText: string = ''): { root: string; deps: CheckoutStrategyDeps } {
const root: string = fs.mkdtempSync(path.join(os.tmpdir(), 'checkout-handoff-'))
const home: string = path.join(root, 'profile')
const scriptDirectory: string = path.join(root, 'scripts', 'desktop-update')
fs.mkdirSync(home)
fs.mkdirSync(scriptDirectory, { recursive: true })
- fs.writeFileSync(path.join(scriptDirectory, IS_WINDOWS ? 'windows.ps1' : 'posix.sh'), '')
+ fs.writeFileSync(path.join(scriptDirectory, IS_WINDOWS ? 'windows.ps1' : 'posix.sh'), scriptText)
fs.writeFileSync(path.join(scriptDirectory, 'runtime.ps1'), '')
fs.mkdirSync(path.join(root, '.hermes', 'bin'), { recursive: true })
fs.writeFileSync(path.join(root, '.hermes', 'bin', 'hermes.exe'), '')
@@ -58,9 +61,13 @@ function handoffFixture(remote: boolean): { root: string; deps: CheckoutStrategy
return { root, deps }
}
-/** The hand-off script's first act (C2): it takes the Desktop's bridge marker. */
-function scriptTakesMarker(home: string): void {
- fs.writeFileSync(markerPath(home), `${process.ppid}\n${Math.floor(Date.now() / 1000)}\n`)
+/**
+ * A legacy (pre-protocol-2) script's first act: it claims the marker in its
+ * own name, echoing HERMES_UPDATE_STARTED_AT on line 2 (origin/main shape).
+ * The vitest parent stands in for the live script process.
+ */
+function scriptTakesMarker(home: string, options: Parameters<typeof updaterProcess.spawnUpdaterProcess>[2]): void {
+ fs.writeFileSync(markerPath(home), `${process.ppid}\n${options.env?.HERMES_UPDATE_STARTED_AT}\n`)
}
// One gateway per host (#117529): a Desktop served by a remote gateway must
@@ -80,7 +87,7 @@ it.each([true, false])(
): updaterProcess.UpdaterChild => {
spawned.push(args)
spawnOptions.push(options)
- scriptTakesMarker(deps.hermesHome)
+ scriptTakesMarker(deps.hermesHome, options)
return { unref: (): void => {} }
}
@@ -118,9 +125,13 @@ it('the Windows hand-off wrapper is spawned non-detached so the script shares it
)
const spawned: { command: string; args: string[]; detached: unknown }[] = []
vi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation(
- (command: string, args: string[], options: { detached?: boolean }): updaterProcess.UpdaterChild => {
+ (
+ command: string,
+ args: string[],
+ options: Parameters<typeof updaterProcess.spawnUpdaterProcess>[2]
+ ): updaterProcess.UpdaterChild => {
spawned.push({ command, args, detached: options.detached })
- scriptTakesMarker(deps.hermesHome)
+ scriptTakesMarker(deps.hermesHome, options)
return { unref: (): void => {} }
}
@@ -169,9 +180,9 @@ it('a failed hand-off spawn keeps the app alive and reports the failure in plain
})
// V7: the wrapper's exit 0 is not a hand-off. Without the script taking the
-// bridge marker the Desktop stays up, restarts its backend, reports the
-// failure, and compare-deletes its own bridge marker.
-it('a hand-off whose script never takes the marker keeps the app alive and clears the bridge', async (): Promise<void> => {
+// marker the Desktop stays up, restarts its backend and reports the failure.
+// A legacy script (no protocol line) gets no bridge at all (SPEC 4b).
+it('a hand-off whose legacy script never takes the marker keeps the app alive and wrote no bridge', async (): Promise<void> => {
const { root, deps } = handoffFixture(false)
vi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation(
(): updaterProcess.UpdaterChild => ({ unref: (): void => {} })
@@ -253,3 +264,251 @@ it.skipIf(IS_WINDOWS)('a timed-out hand-off kills the real script tree it spawne
fs.rmSync(root, { recursive: true, force: true })
}
})
+
+// ---------------------------------------------------------------------------
+// Hand-off protocol 2 (SPEC 4a, A7 rules 3 and 6) — POSIX: the marker helper
+// runs as the checkout's REAL (fake) script process.
+// ---------------------------------------------------------------------------
+
+type SpawnOptions = Parameters<typeof updaterProcess.spawnUpdaterProcess>[2]
+
+function argAfter(args: string[], flag: string): string | undefined {
+ const at = args.indexOf(flag)
+
+ return at >= 0 ? args[at + 1] : undefined
+}
+
+function helperCalls(home: string): string[] {
+ try {
+ return fs.readFileSync(path.join(home, 'helper-calls.log'), 'utf8').trim().split('\n').filter(Boolean)
+ } catch {
+ return []
+ }
+}
+
+interface Protocol2Run {
+ args: string[]
+ bridgeAtSpawn: string | null
+}
+
+/**
+ * Spawn double for the protocol-2 hand-off: records the argv and the bridge
+ * the Desktop published BEFORE spawning, then (per `script`) lets a REAL
+ * claimant process adopt the run, adopt-and-die, or never show up.
+ */
+function mockProtocol2Spawn(home: string, script: 'adopts' | 'adopts-then-dies' | 'never'): Protocol2Run[] {
+ const runs: Protocol2Run[] = []
+
+ vi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation(
+ (_command: string, args: string[], options: SpawnOptions): updaterProcess.UpdaterChild => {
+ let bridgeAtSpawn: string | null = null
+
+ try {
+ bridgeAtSpawn = fs.readFileSync(markerPath(home), 'utf8')
+ } catch {
+ bridgeAtSpawn = null
+ }
+
+ runs.push({ args, bridgeAtSpawn })
+ const run = argAfter(args, '--handoff-run')
+ const startedAt = Number(options.env?.HERMES_UPDATE_STARTED_AT)
+
+ if (script !== 'never') {
+ void claimantChild(markerPath(home), { startedAt, run }).then(async ({ child }) => {
+ if (script === 'adopts-then-dies') {
+ await killAndReap(child)
+ }
+ })
+ }
+
+ return { unref: (): void => {} }
+ }
+ )
+
+ return runs
+}
+
+
+
+describe.skipIf(IS_WINDOWS)('protocol 2 hand-off', () => {
+ it('bridges with a run id, passes --handoff-run, and acknowledges the live adopting script', async (): Promise<void> => {
+ const { root, deps } = handoffFixture(false, fakeHelperScript())
+ const runs = mockProtocol2Spawn(deps.hermesHome, 'adopts')
+
+ try {
+ expect(await createCheckoutStrategy({ ...deps, handoffClaimTimeoutMs: 10_000 }).apply()).toMatchObject({
+ ok: true,
+ handedOff: true
+ })
+ expect(runs).toHaveLength(1)
+ const runId = argAfter(runs[0]!.args, '--handoff-run')!
+ expect(runId).toMatch(new RegExp(`^desk-${process.pid}-[0-9a-z]+-[0-9a-f]{4}$`))
+ const bridge = parseUpdateMarker(runs[0]!.bridgeAtSpawn ?? '')
+ expect(bridge).toMatchObject({ pid: process.pid, run: runId })
+ expect(bridge?.ct).not.toBeNull()
+ expect(argAfter(runs[0]!.args, '--desktop-pid')).toBe(String(process.pid))
+ expect(helperCalls(deps.hermesHome)).toEqual([])
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ })
+
+ it('R5: a script that adopted the run and died before the ack is a failed hand-off', async (): Promise<void> => {
+ const { root, deps } = handoffFixture(false, fakeHelperScript())
+ fs.writeFileSync(path.join(deps.hermesHome, 'helper-verdict'), 'withdrawn')
+ const runs = mockProtocol2Spawn(deps.hermesHome, 'adopts-then-dies')
+
+ try {
+ const result = await createCheckoutStrategy({ ...deps, handoffClaimTimeoutMs: 1_500 }).apply()
+
+ expect(result).toMatchObject({ ok: false, error: 'updater-spawn-failed' })
+ expect(deps.quit).not.toHaveBeenCalled()
+ const runId = argAfter(runs[0]!.args, '--handoff-run')!
+ expect(helperCalls(deps.hermesHome)).toEqual([
+ `--marker-op withdraw --install-root ${root} --desktop-pid ${process.pid} --handoff-run ${runId}`
+ ])
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ })
+
+ it('a timeout withdraws the bridge through the script helper (never by unlinking it)', async (): Promise<void> => {
+ const { root, deps } = handoffFixture(false, fakeHelperScript())
+ fs.writeFileSync(path.join(deps.hermesHome, 'helper-verdict'), 'busy')
+ const runs = mockProtocol2Spawn(deps.hermesHome, 'never')
+
+ try {
+ const result = await createCheckoutStrategy({ ...deps, handoffClaimTimeoutMs: 400 }).apply()
+
+ expect(result).toMatchObject({ ok: false, error: 'updater-spawn-failed' })
+ expect(helperCalls(deps.hermesHome)).toHaveLength(1)
+ // The helper answered `busy` and kept it: Electron left the bytes alone.
+ expect(fs.readFileSync(markerPath(deps.hermesHome), 'utf8')).toBe(runs[0]!.bridgeAtSpawn)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ })
+
+ it('`taken <pid>` from the withdraw helper is a late success', async (): Promise<void> => {
+ const { root, deps } = handoffFixture(false, fakeHelperScript())
+ fs.writeFileSync(path.join(deps.hermesHome, 'helper-verdict'), 'taken 31337')
+ mockProtocol2Spawn(deps.hermesHome, 'never')
+
+ try {
+ expect(await createCheckoutStrategy({ ...deps, handoffClaimTimeoutMs: 300 }).apply()).toMatchObject({
+ ok: true,
+ handedOff: true
+ })
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ })
+
+ it('a dead marker is reclaimed by the script helper, then the bridge is created once', async (): Promise<void> => {
+ const { root, deps } = handoffFixture(false, fakeHelperScript())
+ fs.writeFileSync(markerPath(deps.hermesHome), `${await deadPid()}\n${Math.floor(Date.now() / 1000)}\nct:1.000\n`)
+ fs.writeFileSync(path.join(deps.hermesHome, 'helper-verdict'), 'reclaimed')
+ const runs = mockProtocol2Spawn(deps.hermesHome, 'adopts')
+
+ try {
+ expect(await createCheckoutStrategy({ ...deps, handoffClaimTimeoutMs: 10_000 }).apply()).toMatchObject({
+ ok: true
+ })
+ expect(helperCalls(deps.hermesHome)).toEqual([
+ `--marker-op reclaim --install-root ${root} --desktop-pid ${process.pid}`
+ ])
+ expect(parseUpdateMarker(runs[0]!.bridgeAtSpawn ?? '')?.pid).toBe(process.pid)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ })
+
+ it('R6: a dead marker whose checkout lock is still `held` refuses the hand-off and is left in place', async (): Promise<void> => {
+ const { root, deps } = handoffFixture(false, fakeHelperScript())
+ const body = `${await deadPid()}\n${Math.floor(Date.now() / 1000)}\nct:1.000\n`
+ fs.writeFileSync(markerPath(deps.hermesHome), body)
+ fs.writeFileSync(path.join(deps.hermesHome, 'helper-verdict'), 'held')
+ const runs = mockProtocol2Spawn(deps.hermesHome, 'adopts')
+
+ try {
+ expect(await createCheckoutStrategy(deps).apply()).toMatchObject({ ok: false, error: 'update-already-running' })
+ expect(runs).toHaveLength(0)
+ expect(fs.readFileSync(markerPath(deps.hermesHome), 'utf8')).toBe(body)
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ })
+
+ it('a stale bridge of THIS process is withdrawn with its own run before the new bridge', async (): Promise<void> => {
+ const { root, deps } = handoffFixture(false, fakeHelperScript())
+ const ct = (await import('../update-marker')).processCreateTime
+ const own = await ct(process.pid)
+ fs.writeFileSync(
+ markerPath(deps.hermesHome),
+ `${process.pid}\n${Math.floor(Date.now() / 1000)}\nct:${own!.toFixed(3)}\nrun:desk-old-run\n`
+ )
+ fs.writeFileSync(path.join(deps.hermesHome, 'helper-verdict'), 'withdrawn')
+ const runs = mockProtocol2Spawn(deps.hermesHome, 'adopts')
+
+ try {
+ expect(await createCheckoutStrategy({ ...deps, handoffClaimTimeoutMs: 10_000 }).apply()).toMatchObject({
+ ok: true
+ })
+ expect(helperCalls(deps.hermesHome)).toEqual([
+ `--marker-op withdraw --install-root ${root} --desktop-pid ${process.pid} --handoff-run desk-old-run`
+ ])
+ expect(parseUpdateMarker(runs[0]!.bridgeAtSpawn ?? '')?.run).toBe(argAfter(runs[0]!.args, '--handoff-run'))
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+ })
+})
+
+// SPEC 4b: an old script (no protocol line) writes its own claim
+// unconditionally and knows no run id: the Desktop writes no bridge and
+// passes no run argument.
+it.skipIf(IS_WINDOWS)('a legacy script gets no bridge and no --handoff-run', async (): Promise<void> => {
+ const { root, deps } = handoffFixture(false, '#!/usr/bin/env bash\necho legacy\n')
+ const runs = mockProtocol2Spawn(deps.hermesHome, 'never')
+
+ try {
+ await createCheckoutStrategy({ ...deps, handoffClaimTimeoutMs: 200 }).apply()
+ expect(runs).toHaveLength(1)
+ expect(runs[0]!.bridgeAtSpawn).toBeNull()
+ expect(runs[0]!.args).not.toContain('--handoff-run')
+ expect(helperCalls(deps.hermesHome)).toEqual([])
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
+
+// Windows protocol 2: the run id rides the wrapped PowerShell argv.
+it('the Windows protocol-2 hand-off passes -HandoffRun with the bridged run id', async (): Promise<void> => {
+ const { root, deps } = handoffFixture(false)
+ fs.writeFileSync(path.join(root, 'scripts', 'desktop-update', 'windows.ps1'), '# hermes-handoff-protocol: 2\r\n')
+ const resolveHandoff: typeof updaterProcess.resolveUpdateScriptHandoff = updaterProcess.resolveUpdateScriptHandoff
+ vi.spyOn(updaterProcess, 'resolveUpdateScriptHandoff').mockImplementation(
+ (updateRoot: string): updaterProcess.UpdateScriptHandoff | null => resolveHandoff(updateRoot, { isWindows: true })
+ )
+ const helper = vi.fn(async () => ({ kind: 'withdrawn' as const }))
+ const runs: string[][] = []
+ let bridge: string | null = null
+ vi.spyOn(updaterProcess, 'spawnUpdaterProcess').mockImplementation((_command: string, args: string[]) => {
+ runs.push(args)
+ bridge = fs.readFileSync(markerPath(deps.hermesHome), 'utf8')
+
+ return { unref: (): void => {} }
+ })
+
+ try {
+ await createCheckoutStrategy({ ...deps, isWindows: true, markerHelper: helper, handoffClaimTimeoutMs: 200 }).apply()
+ const runId = argAfter(runs[0]!, '-HandoffRun')
+ expect(runId).toMatch(/^desk-\d+-[0-9a-z]+-[0-9a-f]{4}$/)
+ expect(parseUpdateMarker(bridge ?? '')?.run).toBe(runId)
+ expect(argAfter(runs[0]!, '-DesktopPid')).toBe(String(process.pid))
+ // Nothing adopted it: the bridge is withdrawn through the helper, with the run.
+ expect(helper).toHaveBeenCalledWith('withdraw', expect.objectContaining({ runId, desktopPid: process.pid, isWindows: true }))
+ } finally {
+ fs.rmSync(root, { recursive: true, force: true })
+ }
+})
diff --git a/apps/desktop/electron/updater/checkout.ts b/apps/desktop/electron/updater/checkout.ts
index 14cd8014644..6e01ef7a5aa 100644
--- a/apps/desktop/electron/updater/checkout.ts
+++ b/apps/desktop/electron/updater/checkout.ts
@@ -5,8 +5,9 @@ import * as path from 'node:path'
import {
claimBridgeMarker,
- compareAndDeleteMarker,
+ describeSkippedPrewrite,
HANDOFF_CLAIM_TIMEOUT_MS,
+ makeHandoffRunId,
updateHandoffConflict,
waitForHandoffClaim,
writeUpdateMarker
@@ -27,6 +28,7 @@ import {
} from '../updater-process'
import { type SourceUpdate, sourceUpdateEnvironment } from './checkout-source'
+import { type MarkerHelperOp, type MarkerHelperVerdict, readHandoffProtocol, runMarkerHelper } from './marker-helper'
import type { UpdaterApplyResultWire, UpdaterMechanism, UpdaterStatusWire, UpdaterStrategy } from './index'
@@ -62,8 +64,23 @@ export interface CheckoutStrategyDeps {
runningAppBundle: () => string | null
markQuittingForHandoff: () => void
quit: () => void
+ /** The checkout script's marker helper (A7 rule 3); injectable for tests. */
+ markerHelper?: typeof runMarkerHelper
}
+/**
+ * How one script hand-off is correlated (SPEC 4a/4b). Protocol 2 scripts adopt
+ * the Desktop's bridge carrying `runId`; legacy scripts (no protocol line)
+ * claim for themselves and echo `startedAt` on marker line 2.
+ */
+export interface HandoffPlan {
+ protocol: number
+ runId: string | null
+ startedAt: number
+}
+
+const STILL_RUNNING_VERDICTS = new Set(['held', 'busy', 'live'])
+
/**
* The manual command card for a checkout with no staged updater: the exact
* `hermes update` line to run, branch-pinned to the checkout's current branch
@@ -98,47 +115,96 @@ export function readStampedCommit(root: string): string | null {
* every result the way the wire contract expects.
*/
export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrategy {
+ function markerHelper(op: MarkerHelperOp, runId: string | null): Promise<MarkerHelperVerdict> {
+ return (deps.markerHelper ?? runMarkerHelper)(op, {
+ updateRoot: deps.resolveUpdateRoot(),
+ hermesHome: deps.hermesHome,
+ desktopPid: process.pid,
+ runId,
+ isWindows: deps.isWindows
+ })
+ }
+
+ function refuse(message: string, error: string): { refusal: UpdaterApplyResultWire } {
+ deps.rememberLog(`[updates] refusing hand-off: ${message}`)
+ deps.emitUpdateProgress({ stage: 'error', message, percent: null })
+
+ return { refusal: { ok: false, error, message } }
+ }
+
/**
- * C2 bridge: claim the marker in this Desktop's own name before spawning the
- * hand-off script, so it never names the short-lived cmd.exe/launcher
- * wrapper (V4). Returns the refusal result on a live foreign owner.
+ * Plan the hand-off for this script (SPEC 4). Protocol 2: exclusive-create
+ * the bridge in this Desktop's own name with a fresh run id, routing an
+ * existing dead marker (or a stale bridge of ours) through the script
+ * helper, then retrying the create ONCE. Legacy scripts get no bridge at all
+ * (they overwrite unconditionally and know no run id). Never deletes or
+ * rewrites the marker itself (A7 rule 3).
*/
- async function claimBridge(updateStartedAt: number): Promise<{ body: string | null; refusal?: UpdaterApplyResultWire }> {
- const bridge = await claimBridgeMarker(deps.hermesHome, { startedAt: updateStartedAt })
+ async function planHandoff(
+ scriptPath: string,
+ updateStartedAt: number
+ ): Promise<{ plan: HandoffPlan } | { refusal: UpdaterApplyResultWire }> {
+ const protocol = readHandoffProtocol(scriptPath)
+
+ if (protocol < 2) {
+ deps.rememberLog('[updates] hand-off script predates protocol 2; legacy acknowledgment (live owner + started_at)')
- if (bridge.ok) {
- return { body: bridge.body ?? null }
+ return { plan: { protocol, runId: null, startedAt: updateStartedAt } }
}
- if (bridge.conflict) {
- deps.rememberLog(`[updates] refusing hand-off: ${bridge.conflict.message}`)
- deps.emitUpdateProgress({ stage: 'error', message: bridge.conflict.message, percent: null })
+ const runId = makeHandoffRunId()
- return {
- body: null,
- refusal: { ok: false, error: 'update-already-running', message: bridge.conflict.message }
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const bridge = await claimBridgeMarker(deps.hermesHome, { startedAt: updateStartedAt, runId })
+
+ if (bridge.ok) {
+ return { plan: { protocol, runId, startedAt: updateStartedAt } }
}
- }
- // The script claims with a fresh exclusive create in that case; the
- // owner-change check below still proves it started.
- deps.rememberLog(`[updates] could not write the bridge marker (${bridge.error}); continuing without it`)
+ if (bridge.conflict) {
+ return refuse(bridge.conflict.message, 'update-already-running')
+ }
- return { body: null }
+ if (attempt > 0) {
+ break
+ }
+
+ if (bridge.existing) {
+ const op: MarkerHelperOp = bridge.existing.state === 'ours' ? 'withdraw' : 'reclaim'
+ const verdict = await markerHelper(op, op === 'withdraw' ? bridge.existing.run : null)
+ deps.rememberLog(`[updates] ${bridge.existing.state} update marker: script helper ${op} => ${verdict.kind}`)
+
+ if (STILL_RUNNING_VERDICTS.has(verdict.kind)) {
+ return refuse(
+ 'Another update still holds this installation. Wait for it to finish, then try again.',
+ 'update-already-running'
+ )
+ }
+ } else {
+ deps.rememberLog(`[updates] could not write the bridge marker (${bridge.error}); retrying once`)
+ }
+ }
+
+ return refuse(
+ 'The updater could not take the update lock, so nothing was changed. Hermes keeps running on the previous version — try the update again.',
+ 'updater-spawn-failed'
+ )
}
/**
- * C2: the hand-off started only when the script took the marker (its owner
- * is no longer this pid) — not when a wrapper exited 0 (V7). Returns an
- * error message when it did not; the caller stays up.
+ * C2 + R5: the hand-off started only when a LIVE, correlated script process
+ * holds the marker — not when a wrapper exited 0 (V7), and not when a pid
+ * claimed and died. Returns an error message when it did not; the caller
+ * stays up.
*/
- async function confirmScriptHandoff(child, bridgeBody: string | null, startedAtMs: number): Promise<string | null> {
+ async function confirmScriptHandoff(child, plan: HandoffPlan, startedAtMs: number): Promise<string | null> {
const outcome = await observeUpdaterHandoff(child, deps.updateHandoffDwellMs)
let failure: string | null = outcome.ok ? null : describeUpdaterHandoffFailure(outcome)
if (!failure) {
const claim = await waitForHandoffClaim(deps.hermesHome, process.pid, {
- timeoutMs: Math.max(0, (deps.handoffClaimTimeoutMs ?? HANDOFF_CLAIM_TIMEOUT_MS) - (Date.now() - startedAtMs))
+ timeoutMs: Math.max(0, (deps.handoffClaimTimeoutMs ?? HANDOFF_CLAIM_TIMEOUT_MS) - (Date.now() - startedAtMs)),
+ ...(plan.runId ? { runId: plan.runId } : { startedAt: plan.startedAt })
})
if (claim.taken) {
@@ -154,17 +220,20 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
deps.rememberLog(`[updates] hand-off not viable, aborting quit: ${failure}`)
- // Withdraw the bridge first: an adopt-only script that starts late then
- // finds nothing to adopt (A4). If the compare-and-delete misses because
- // the script took the marker at the deadline, the update IS running.
- if (bridgeBody && !compareAndDeleteMarker(deps.hermesHome, bridgeBody)) {
- const late = await waitForHandoffClaim(deps.hermesHome, process.pid, { timeoutMs: 0 })
+ // Withdraw the bridge through the script helper (under its lock): an
+ // adopt-only script that starts late then finds nothing to adopt (A4).
+ // `taken` means a live script adopted our run at the deadline — the
+ // update IS running.
+ if (plan.runId) {
+ const verdict = await markerHelper('withdraw', plan.runId)
- if (late.taken) {
- deps.rememberLog(`[updates] hand-off script took the update marker at the deadline (pid ${late.pid})`)
+ if (verdict.kind === 'taken') {
+ deps.rememberLog(`[updates] hand-off script took the update marker at the deadline (pid ${verdict.pid})`)
return null
}
+
+ deps.rememberLog(`[updates] bridge withdraw: ${verdict.kind}`)
}
// MINOR-3: and stop the script tree we spawned, so nothing the UI just
@@ -349,19 +418,19 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
const scriptHandoff = resolveUpdateScriptHandoff(updateRoot)
const handoffStartedAt = Date.now()
let child
- let bridgeBody: string | null = null
+ let plan: HandoffPlan | null = null
if (scriptHandoff) {
const updateStartedAt = Math.floor(Date.now() / 1000)
- const bridge = await claimBridge(updateStartedAt)
+ const planned = await planHandoff(scriptHandoff.scriptPath, updateStartedAt)
- if (bridge.refusal) {
+ if ('refusal' in planned) {
deps.startHermes().catch(() => {})
- return bridge.refusal
+ return planned.refusal
}
- bridgeBody = bridge.body
+ plan = planned.plan
// A bare detached+hidden powershell spawn silently dies before -File
// processing (console-subsystem init failure — see
@@ -386,6 +455,10 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
wrappedArgs.push('-NoGateway')
}
+ if (plan.runId) {
+ wrappedArgs.push('-HandoffRun', plan.runId)
+ }
+
const wrapped = wrapHandoffForDetachedConsole(scriptHandoff, wrappedArgs)
child = spawnUpdaterProcess(wrapped.command, wrapped.args, {
@@ -431,8 +504,14 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
// binary is the one being refused. Losing the anti-respawn hardening is
// strictly better than never updating again, and the updater still writes
// its own marker moments later.
+ // Exclusive create only (A7 rule 3): over any existing marker the
+ // pre-write is skipped and the staged updater claims for itself.
if (Number.isInteger(child.pid) && stagedUpdaterSupportsPrewrittenMarker(updater)) {
- await writeUpdateMarker(deps.hermesHome, child.pid)
+ const prewrite = await writeUpdateMarker(deps.hermesHome, child.pid)
+
+ if (!prewrite.ok) {
+ deps.rememberLog(`[updates] skipping marker pre-write: ${describeSkippedPrewrite(prewrite)}`)
+ }
} else if (Number.isInteger(child.pid)) {
deps.rememberLog(
`[updates] skipping marker pre-write: staged updater predates self-adopt (${updater}); it would refuse its own claim`
@@ -460,8 +539,8 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
const dwellStartedAt = Date.now()
let failure: string | null
- if (scriptHandoff) {
- failure = await confirmScriptHandoff(child, bridgeBody, handoffStartedAt)
+ if (plan) {
+ failure = await confirmScriptHandoff(child, plan, handoffStartedAt)
} else {
const handoffOutcome = await observeUpdaterHandoff(child, deps.updateHandoffDwellMs)
failure = handoffOutcome.ok ? null : describeUpdaterHandoffFailure(handoffOutcome)
@@ -536,10 +615,16 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
const handoffStartedAt = Date.now()
const updateStartedAt = Math.floor(handoffStartedAt / 1000)
- const bridge = await claimBridge(updateStartedAt)
+ const planned = await planHandoff(handoff.scriptPath, updateStartedAt)
+
+ if ('refusal' in planned) {
+ return planned.refusal
+ }
+
+ const { plan } = planned
- if (bridge.refusal) {
- return bridge.refusal
+ if (plan.runId) {
+ args.push('--handoff-run', plan.runId)
}
// Relaunch target: the running .app bundle on mac (script swaps the
@@ -594,7 +679,7 @@ export function createCheckoutStrategy(deps: CheckoutStrategyDeps): UpdaterStrat
// The launcher always exits 0 after daemonizing, so only the daemon taking
// the bridge marker proves an update is running (C2, V7).
const dwellStartedAt = Date.now()
- const failure = await confirmScriptHandoff(child, bridge.body, handoffStartedAt)
+ const failure = await confirmScriptHandoff(child, plan, handoffStartedAt)
if (failure) {
deps.emitUpdateProgress({ stage: 'error', message: failure, percent: null })