Skip to content

The agent that grows with you

feat(desktop): managed SSH remote update engine — extracted from #93042

Andrex Ibiza, MBA6170fff19cd6
diff --git a/apps/desktop/electron/managed-ssh-update.test.ts b/apps/desktop/electron/managed-ssh-update.test.ts
new file mode 100644
index 00000000000..ad95861ac58
--- /dev/null
+++ b/apps/desktop/electron/managed-ssh-update.test.ts
@@ -0,0 +1,859 @@
+import assert from 'node:assert/strict'
+import { exec as execCallback } from 'node:child_process'
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { promisify } from 'node:util'
+
+import { test } from 'vitest'
+
+import {
+ buildPosixManagedUpdateLaunch,
+ buildRemoteUpdateObservationCommand,
+ buildWindowsManagedUpdateLaunch,
+ fenceManagedSshBootstrapPublication,
+ ManagedConnectionUpdateGate,
+ managedSshRecoveryScopes,
+ managedSshScopeRole,
+ managedSshTokenPersistencePlan,
+ parseRemoteUpdateObservation,
+ RECEIPT_GRACE_MS,
+ recoverManagedSshScopes,
+ refusedManagedSshUpdate,
+ runManagedSshUpdate,
+ waitForManagedRemoteClearance,
+ waitForManagedRemoteUpdate,
+ waitForManagedSshBootstrapFence,
+ waitForManagedUpdateOperations
+} from './managed-ssh-update'
+import { createBootstrapCoordinator } from './ssh-bootstrap-coordinator'
+
+const CORRELATION = '12345678-1234-4678-9234-567812345678'
+const exec = promisify(execCallback)
+
+function observation(over: Record<string, unknown> = {}) {
+ return JSON.stringify({
+ marker: 'absent',
+ launchIntent: 'absent',
+ exitCode: null,
+ receipt: null,
+ coordinatorReady: null,
+ ...over
+ })
+}
+
+test('ManagedConnectionUpdateGate blocks new dials but admits the exact restoring transaction', () => {
+ const gate = new ManagedConnectionUpdateGate()
+
+ assert.equal(gate.claim('homelab', CORRELATION), true)
+ assert.equal(gate.claim('homelab', '22345678-1234-4678-9234-567812345678'), false)
+ assert.throws(() => gate.assertCanDial('homelab'), /paused/)
+ assert.doesNotThrow(() => gate.assertCanDial('homelab', CORRELATION))
+ gate.release('homelab', '22345678-1234-4678-9234-567812345678')
+ assert.equal(gate.owner('homelab'), CORRELATION)
+ gate.release('homelab', CORRELATION)
+ assert.doesNotThrow(() => gate.assertCanDial('homelab'))
+})
+
+test('durable recovery claim survives memory release and fences ordinary dials, edits, and removal', () => {
+ let durable: string | null = CORRELATION
+ const gate = new ManagedConnectionUpdateGate(id => (id === 'homelab' ? durable : null))
+
+ assert.equal(gate.claim('homelab', CORRELATION), true)
+ gate.release('homelab', CORRELATION)
+ assert.equal(gate.owner('homelab'), CORRELATION)
+ assert.throws(() => gate.assertCanDial('homelab'), /paused/)
+ assert.throws(() => gate.assertCanMutate('homelab'), /edited or removed/)
+ assert.doesNotThrow(() => gate.assertCanDial('homelab', CORRELATION))
+ assert.equal(gate.claim('homelab', '22345678-1234-4678-9234-567812345678'), false)
+
+ durable = null
+ assert.doesNotThrow(() => gate.assertCanDial('homelab'))
+ assert.doesNotThrow(() => gate.assertCanMutate('homelab'))
+})
+
+test('inactive SSH crash recovery keeps ordinary dials fenced until positive clearance', async () => {
+ let durableOwner: string | null = CORRELATION
+ const relaunchedGate = new ManagedConnectionUpdateGate(id => (id === 'homelab' ? durableOwner : null))
+ let releaseClearance!: () => void
+ const clearance = new Promise<void>(resolve => {
+ releaseClearance = resolve
+ })
+ let restoreCalls = 0
+ let journalCleared = false
+ const recovery = recoverManagedSshScopes({
+ scopes: [] as Array<{ profile: string }>,
+ awaitClearance: () => clearance,
+ restoreScope: async () => {
+ restoreCalls += 1
+ },
+ completeRecovery: async () => {
+ journalCleared = true
+ durableOwner = null
+ }
+ })
+
+ await Promise.resolve()
+ assert.throws(() => relaunchedGate.assertCanDial('homelab'), /paused/)
+ assert.equal(journalCleared, false)
+ releaseClearance()
+ const results = await recovery
+
+ assert.deepEqual(results, [])
+ assert.equal(restoreCalls, 0)
+ assert.equal(journalCleared, true)
+ assert.doesNotThrow(() => relaunchedGate.assertCanDial('homelab'))
+})
+
+test('managed update joins a pre-claim bootstrap until its final gate check rolls back the serve', async () => {
+ const gate = new ManagedConnectionUpdateGate()
+ const coordinator = createBootstrapCoordinator()
+ let releaseLifecycle!: () => void
+ const lifecycle = new Promise<void>(resolve => {
+ releaseLifecycle = resolve
+ })
+ let serveLive = false
+ let rollbackComplete = false
+ const startPromise = coordinator.start(
+ '',
+ 'fingerprint',
+ async () => {
+ await lifecycle
+ serveLive = true
+ await fenceManagedSshBootstrapPublication({
+ assertCanPublish: () => gate.assertCanDial('homelab'),
+ publish: () => {},
+ rollback: async () => {
+ serveLive = false
+ rollbackComplete = true
+ }
+ })
+ },
+ { managedScope: 'primary', registryConnectionId: 'homelab' }
+ )
+ // The fence rethrows managed-update-in-progress after rolling back — that
+ // rejection propagating out of start() is the CONTRACT under test, not an
+ // accident. Swallow it here so vitest doesn't flag the floating promise as
+ // an unhandled rejection while the assertions below verify the rollback.
+ startPromise.catch(() => {})
+ const barrier = waitForManagedSshBootstrapFence(coordinator.active, 'homelab')
+ let barrierComplete = false
+ void barrier.then(() => {
+ barrierComplete = true
+ })
+
+ assert.equal(gate.claim('homelab', CORRELATION), true)
+ await Promise.resolve()
+ assert.equal(barrierComplete, false)
+ releaseLifecycle()
+ await barrier
+
+ assert.equal(rollbackComplete, true)
+ assert.equal(serveLive, false)
+ assert.equal(barrierComplete, true)
+})
+
+test('bootstrap publication stays in the same turn as its final gate assertion', async () => {
+ const gate = new ManagedConnectionUpdateGate()
+ let published = false
+ let rolledBack = false
+
+ queueMicrotask(() => {
+ gate.claim('homelab', CORRELATION)
+ })
+ await fenceManagedSshBootstrapPublication({
+ assertCanPublish: () => gate.assertCanDial('homelab'),
+ publish: () => {
+ published = true
+ },
+ rollback: async () => {
+ rolledBack = true
+ }
+ })
+
+ assert.equal(published, true)
+ assert.equal(rolledBack, false)
+ assert.equal(gate.owner('homelab'), CORRELATION)
+})
+
+test('registry-qualified primary token adoption stays reusable across consecutive launches', () => {
+ const legacy: Record<string, string> = {}
+ const registry: Record<string, string> = {}
+
+ for (const servedToken of ['served-on-first-launch', 'served-on-second-launch']) {
+ const plan = managedSshTokenPersistencePlan('profile', 'homelab')
+
+ assert.equal(plan.legacySource, 'profile')
+ assert.equal(plan.registryConnectionId, 'homelab')
+ legacy[plan.legacySource!] = servedToken
+ registry[plan.registryConnectionId] = servedToken
+ assert.equal(legacy.profile, registry.homelab)
+ }
+
+ assert.equal(legacy.profile, 'served-on-second-launch')
+ assert.equal(registry.homelab, 'served-on-second-launch')
+ assert.deepEqual(managedSshTokenPersistencePlan('registry:homelab'), {
+ legacySource: null,
+ registryConnectionId: 'homelab'
+ })
+})
+
+test('actual primary and matching bare/composite pools keep distinct managed scope roles', () => {
+ const base = { connectionId: 'homelab', prefix: 'conn:homelab::' }
+
+ assert.equal(
+ managedSshScopeRole({
+ ...base,
+ key: '',
+ state: { primaryRegistryScope: true, registryConnectionId: 'homelab' }
+ }),
+ 'primary'
+ )
+ assert.equal(
+ managedSshScopeRole({
+ ...base,
+ key: 'research',
+ routeConnectionId: 'homelab',
+ state: { primaryRegistryScope: false, registryConnectionId: 'homelab' }
+ }),
+ 'pool'
+ )
+ assert.equal(managedSshScopeRole({ ...base, key: 'conn:homelab::research' }), 'pool')
+})
+
+test('durable recovery preserves every same-profile primary, registry, and legacy scope', () => {
+ const scopes = managedSshRecoveryScopes(
+ [
+ { key: '', profile: 'default', primary: true },
+ { key: 'conn:homelab::default', profile: 'default' },
+ { key: 'default', profile: 'default' }
+ ],
+ 'conn:homelab::'
+ )
+
+ assert.deepEqual(scopes, [
+ { key: '', kind: 'primary', profile: 'default' },
+ { key: 'conn:homelab::default', kind: 'registry', profile: 'default' },
+ { key: 'default', kind: 'legacy', profile: 'default' }
+ ])
+})
+
+test('update-all deduplicates the same recovery scope and keeps primary precedence', () => {
+ assert.deepEqual(
+ managedSshRecoveryScopes(
+ [
+ { key: 'conn:homelab::default', profile: 'default' },
+ { key: 'conn:homelab::default', profile: 'default', primary: true },
+ { key: 'conn:homelab::default', profile: 'default' }
+ ],
+ 'conn:homelab::'
+ ),
+ [{ key: 'conn:homelab::default', kind: 'primary', profile: 'default' }]
+ )
+})
+
+test('POSIX managed launcher is detached, correlation-scoped, and never publishes handoff exit 75', () => {
+ const command = buildPosixManagedUpdateLaunch(
+ {
+ ssh: { exec: async () => '' },
+ platform: 'Linux',
+ hermesPath: '~/.local/bin/hermes',
+ hermesHome: '~/.hermes'
+ },
+ CORRELATION
+ )
+
+ assert.match(command, /setsid/)
+ assert.match(command, /update --yes/)
+ assert.doesNotMatch(command, /update --yes --gateway/)
+ assert.match(command, new RegExp(`HERMES_UPDATE_CORRELATION_ID=.*${CORRELATION}`))
+ assert.match(command, /\[ "\$rc" -ne 75 \]/)
+ assert.match(command, new RegExp(`\\.update_exit_code\\.${CORRELATION}`))
+ assert.match(command, new RegExp(`\\.update_launch_intent\\.${CORRELATION}`))
+ assert.match(command, /while \[ ! -e/)
+})
+
+test('POSIX managed launcher executes the updater command and atomically publishes its status', async () => {
+ const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-launch-'))
+
+ try {
+ const command = buildPosixManagedUpdateLaunch(
+ {
+ ssh: { exec: async () => '' },
+ platform: 'Linux',
+ hermesPath: '/bin/true',
+ hermesHome: home
+ },
+ CORRELATION
+ )
+ const { stdout } = await exec(command, { shell: '/bin/sh' })
+ const statusPath = path.join(home, `.update_exit_code.${CORRELATION}`)
+ let status = ''
+
+ for (let attempt = 0; attempt < 50 && !status; attempt += 1) {
+ try {
+ status = await readFile(statusPath, 'utf8')
+ } catch {
+ await new Promise(resolve => setTimeout(resolve, 10))
+ }
+ }
+
+ assert.match(stdout, /MANAGED_UPDATE_STARTED/)
+ assert.equal(status, '0')
+ } finally {
+ await rm(home, { force: true, recursive: true })
+ }
+})
+
+test('Windows managed launcher starts a hidden child and leaves exit 75 to the external coordinator', () => {
+ const command = buildWindowsManagedUpdateLaunch(
+ {
+ ssh: { exec: async () => '' },
+ platform: 'Windows',
+ hermesPath: 'C:\\Hermes\\hermes.exe',
+ hermesHome: 'C:\\Users\\alice\\.hermes',
+ pythonPath: 'C:\\Hermes\\python.exe'
+ },
+ CORRELATION
+ )
+ const outer = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')
+ const wrapperBase64 = outer.match(/"-EncodedCommand",'([^']+)'/)?.[1]
+
+ assert.match(outer, /Start-Process/)
+ assert.match(outer, /WindowStyle Hidden/)
+ assert.ok(wrapperBase64, 'outer launcher carries a separately encoded detached wrapper')
+ const wrapper = Buffer.from(wrapperBase64!, 'base64').toString('utf16le')
+
+ assert.match(wrapper, /update --yes/)
+ assert.doesNotMatch(wrapper, /update --yes --gateway/)
+ assert.match(wrapper, /HERMES_UPDATE_WINDOWS_DETACHED/)
+ assert.match(wrapper, /HERMES_UPDATE_TAURI_READY_PATH/)
+ assert.match(wrapper, /HERMES_UPDATE_TAURI_OUTCOME_PATH/)
+ assert.match(wrapper, /\$rc -ne 75/)
+ assert.match(wrapper, /\$handoffAccepted=/)
+ assert.match(wrapper, new RegExp(`update_launch_intent\\.${CORRELATION}`))
+ assert.ok(wrapper.indexOf('update_launch_intent') < wrapper.indexOf('update --yes'))
+ assert.match(outer, /launcher intent timed out/)
+})
+
+test('remote observation rejects a receipt for another correlation', () => {
+ assert.throws(
+ () =>
+ parseRemoteUpdateObservation(
+ observation({
+ exitCode: 0,
+ receipt: { correlationId: '22345678-1234-4678-9234-567812345678', outcome: 'success' }
+ }),
+ CORRELATION
+ ),
+ /did not match/
+ )
+})
+
+test('POSIX observer reads the exact correlation receipt and terminal marker from disk', async () => {
+ const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-update-'))
+
+ try {
+ const receipts = path.join(home, 'logs', 'update_receipts')
+ await mkdir(receipts, { recursive: true })
+ await writeFile(path.join(home, `.update_exit_code.${CORRELATION}`), '0')
+ await writeFile(
+ path.join(receipts, `update_${CORRELATION}.json`),
+ JSON.stringify({
+ correlation_id: CORRELATION,
+ outcome: 'success',
+ started_at: '2026-08-23T00:00:00Z',
+ finished_at: '2026-08-23T00:01:00Z',
+ pre_update: { sha: 'old' },
+ post_update: { sha: 'new' }
+ })
+ )
+ const command = buildRemoteUpdateObservationCommand(
+ {
+ ssh: { exec: async () => '' },
+ platform: 'Linux',
+ hermesPath: '/opt/hermes/hermes',
+ hermesHome: home
+ },
+ CORRELATION
+ )
+ const { stdout } = await exec(command, { shell: '/bin/sh' })
+ const parsed = parseRemoteUpdateObservation(stdout, CORRELATION)
+
+ assert.equal(parsed.marker, 'absent')
+ assert.equal(parsed.exitCode, 0)
+ assert.equal(parsed.receipt?.correlationId, CORRELATION)
+ assert.equal(parsed.receipt?.preSha, 'old')
+ assert.equal(parsed.receipt?.postSha, 'new')
+ } finally {
+ await rm(home, { force: true, recursive: true })
+ }
+})
+
+test('managed observer unwraps a named profile home for the install-wide marker', async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-profile-marker-'))
+ const profileHome = path.join(root, 'profiles', 'research')
+
+ try {
+ await mkdir(profileHome, { recursive: true })
+ await writeFile(path.join(root, '.hermes-update-in-progress'), `${process.pid}\n1\n`)
+ const command = buildRemoteUpdateObservationCommand(
+ {
+ ssh: { exec: async () => '' },
+ platform: 'Linux',
+ hermesPath: '/opt/hermes/hermes',
+ hermesHome: profileHome
+ },
+ CORRELATION
+ )
+ const { stdout } = await exec(command, { shell: '/bin/sh' })
+ const parsed = parseRemoteUpdateObservation(stdout, CORRELATION)
+
+ assert.equal(parsed.marker, 'live')
+ assert.equal(parsed.markerPid, process.pid)
+ } finally {
+ await rm(root, { force: true, recursive: true })
+ }
+})
+
+test('Windows coordinator handoff is pending until its marker clears and correlated receipt is durable', async () => {
+ const replies = [
+ observation({ marker: 'live', markerPid: 44 }),
+ observation({
+ marker: 'live',
+ markerPid: 88,
+ coordinatorReady: { correlationId: CORRELATION, pid: 88 }
+ }),
+ observation({
+ marker: 'absent',
+ exitCode: null,
+ receipt: {
+ correlationId: CORRELATION,
+ outcome: 'success',
+ finishedAt: '2026-08-23T00:00:00Z'
+ },
+ coordinatorReady: { correlationId: CORRELATION, pid: 88 }
+ })
+ ]
+ let calls = 0
+ const target = {
+ platform: 'Windows' as const,
+ hermesPath: 'C:\\Hermes\\hermes.exe',
+ hermesHome: 'C:\\Users\\alice\\.hermes',
+ pythonPath: 'C:\\Hermes\\python.exe',
+ ssh: {
+ exec: async () => {
+ const reply = replies[Math.min(calls, replies.length - 1)]
+ calls += 1
+
+ return reply
+ }
+ }
+ }
+
+ const proof = await waitForManagedRemoteUpdate(target, CORRELATION, {
+ pollMs: 0,
+ sleep: async () => {}
+ })
+
+ assert.equal(calls, 3)
+ assert.equal(proof.exitCode, 0)
+ assert.equal(proof.receipt.correlationId, CORRELATION)
+})
+
+test('terminal status without its durable receipt fails instead of claiming success', async () => {
+ let now = 0
+ const target = {
+ platform: 'Linux' as const,
+ hermesPath: '~/.local/bin/hermes',
+ hermesHome: '~/.hermes',
+ ssh: { exec: async () => observation({ marker: 'absent', exitCode: 0 }) }
+ }
+
+ await assert.rejects(
+ waitForManagedRemoteUpdate(target, CORRELATION, {
+ now: () => now,
+ pollMs: 1,
+ sleep: async () => {
+ now += RECEIPT_GRACE_MS
+ }
+ }),
+ /without a correlated durable receipt/
+ )
+})
+
+test('live or malformed remote markers fail actionably at bounded update and recovery deadlines', async () => {
+ for (const marker of ['live', 'malformed'] as const) {
+ let now = 0
+ const target = {
+ platform: 'Linux' as const,
+ hermesPath: '~/.local/bin/hermes',
+ hermesHome: '~/.hermes',
+ ssh: { exec: async () => observation({ marker, ...(marker === 'live' ? { markerPid: 44 } : {}) }) }
+ }
+ const clock = {
+ timeoutMs: 5,
+ pollMs: 1,
+ now: () => now,
+ sleep: async () => {
+ now += 5
+ }
+ }
+
+ await assert.rejects(waitForManagedRemoteUpdate(target, CORRELATION, clock), /services remain stopped/)
+ now = 0
+ await assert.rejects(waitForManagedRemoteClearance(target, CORRELATION, clock), /durable recovery record/)
+ }
+})
+
+test('a journaled launch requires correlated terminal proof or an observed live-owner transition before restore', async () => {
+ let now = 0
+ const target = {
+ platform: 'Linux' as const,
+ hermesPath: '~/.local/bin/hermes',
+ hermesHome: '~/.hermes',
+ ssh: { exec: async () => observation({ marker: 'absent' }) }
+ }
+
+ await assert.rejects(
+ waitForManagedRemoteClearance(target, CORRELATION, {
+ requireTerminal: true,
+ timeoutMs: 5,
+ pollMs: 1,
+ now: () => now,
+ sleep: async () => {
+ now += 5
+ }
+ }),
+ /durable recovery record/
+ )
+
+ target.ssh.exec = async () =>
+ observation({
+ marker: 'absent',
+ exitCode: 0,
+ receipt: { correlationId: CORRELATION, outcome: 'success', finishedAt: '2026-08-23T00:00:00Z' }
+ })
+ await assert.doesNotReject(
+ waitForManagedRemoteClearance(target, CORRELATION, { requireTerminal: true, timeoutMs: 0 })
+ )
+})
+
+test('remote launch intent fences crash recovery even before the local journal records launch proof', async () => {
+ let now = 0
+ const target = {
+ platform: 'Linux' as const,
+ hermesPath: '~/.local/bin/hermes',
+ hermesHome: '~/.hermes',
+ ssh: { exec: async () => observation({ marker: 'absent', launchIntent: 'present' }) }
+ }
+
+ await assert.rejects(
+ waitForManagedRemoteClearance(target, CORRELATION, {
+ timeoutMs: 5,
+ pollMs: 1,
+ now: () => now,
+ sleep: async () => {
+ now += 5
+ }
+ }),
+ /durable recovery record/
+ )
+
+ target.ssh.exec = async () => observation({ marker: 'absent', launchIntent: 'absent' })
+ await assert.doesNotReject(waitForManagedRemoteClearance(target, CORRELATION, { timeoutMs: 0 }))
+ target.ssh.exec = async () => observation({ marker: 'absent', launchIntent: 'dead' })
+ await assert.doesNotReject(
+ waitForManagedRemoteClearance(target, CORRELATION, { requireTerminal: true, timeoutMs: 0 })
+ )
+})
+
+test('before-quit join observes operations added while an earlier update settles', async () => {
+ let releaseFirst!: () => void
+ let releaseSecond!: () => void
+ const operations = new Set<Promise<void>>()
+ const first = new Promise<void>(resolve => {
+ releaseFirst = resolve
+ })
+ operations.add(first)
+ const joined = waitForManagedUpdateOperations(() => operations)
+ const second = new Promise<void>(resolve => {
+ releaseSecond = resolve
+ })
+
+ operations.add(second)
+ first.finally(() => operations.delete(first))
+ second.finally(() => operations.delete(second))
+ releaseFirst()
+ await Promise.resolve()
+ let settled = false
+ joined.then(() => {
+ settled = true
+ })
+ await Promise.resolve()
+ assert.equal(settled, false)
+ releaseSecond()
+ await joined
+ assert.equal(settled, true)
+})
+
+test('managed lifecycle restores every captured profile after update failure before releasing the gate', async () => {
+ const events: string[] = []
+ const scopes = [
+ { key: 'conn:home::default', profile: 'default' },
+ { key: 'conn:home::research', profile: 'research' }
+ ]
+
+ const result = await runManagedSshUpdate({
+ connectionId: 'home',
+ correlationId: CORRELATION,
+ scopes,
+ preflightRemote: async () => {
+ events.push('preflight')
+ },
+ drainScope: async scope => {
+ events.push(`drain:${scope.profile}`)
+ },
+ updateRemote: async () => {
+ events.push('update')
+ throw new Error('fetch failed')
+ },
+ awaitRestoreClearance: async () => {
+ events.push('clear')
+ },
+ closeTransports: async () => {
+ events.push('close')
+ },
+ restoreScope: async scope => {
+ events.push(`restore:${scope.profile}`)
+ },
+ releaseGate: () => {
+ events.push('release')
+ }
+ })
+
+ assert.deepEqual(events, [
+ 'preflight',
+ 'drain:default',
+ 'drain:research',
+ 'update',
+ 'clear',
+ 'close',
+ 'restore:default',
+ 'restore:research',
+ 'release'
+ ])
+ assert.equal(result.ok, false)
+ assert.equal(result.updateOk, false)
+ assert.equal(result.restoreOk, true)
+ assert.equal(result.outcome, 'update-failed')
+ assert.deepEqual(
+ result.scopes.map(scope => [scope.profile, scope.restored]),
+ [
+ ['default', true],
+ ['research', true]
+ ]
+ )
+})
+
+test('inactive managed update journals before launch and clears only after remote clearance', async () => {
+ const events: string[] = []
+ const result = await runManagedSshUpdate({
+ connectionId: 'homelab',
+ correlationId: CORRELATION,
+ scopes: [],
+ preflightRemote: async () => {
+ events.push('preflight')
+ },
+ prepareRecovery: async () => {
+ events.push('journal')
+ },
+ drainScope: async () => {
+ events.push('unexpected-drain')
+ },
+ updateRemote: async () => {
+ events.push('update')
+
+ return {
+ exitCode: 0,
+ receipt: { correlationId: CORRELATION, outcome: 'success' }
+ }
+ },
+ awaitRestoreClearance: async () => {
+ events.push('clearance')
+ },
+ closeTransports: async () => {
+ events.push('close')
+ },
+ restoreScope: async () => {
+ events.push('unexpected-restore')
+ },
+ completeRecovery: async () => {
+ events.push('clear-journal')
+ },
+ releaseGate: () => {
+ events.push('release')
+ }
+ })
+
+ assert.deepEqual(events, ['preflight', 'journal', 'update', 'clearance', 'close', 'clear-journal', 'release'])
+ assert.equal(result.ok, true)
+ assert.deepEqual(result.scopes, [])
+})
+
+test('managed lifecycle attempts every drain and every restore when one ownership proof fails', async () => {
+ const drained: string[] = []
+ const restored: string[] = []
+ let updateCalled = false
+
+ const result = await runManagedSshUpdate({
+ connectionId: 'home',
+ correlationId: CORRELATION,
+ scopes: [
+ { key: 'a', profile: 'default' },
+ { key: 'b', profile: 'research' }
+ ],
+ preflightRemote: async () => {},
+ drainScope: async scope => {
+ drained.push(scope.profile)
+ if (scope.profile === 'default') {
+ throw new Error('foreign owner')
+ }
+ },
+ updateRemote: async () => {
+ updateCalled = true
+
+ return {
+ exitCode: 0,
+ receipt: { correlationId: CORRELATION, outcome: 'success' }
+ }
+ },
+ awaitRestoreClearance: async () => {},
+ closeTransports: async () => {},
+ restoreScope: async scope => {
+ restored.push(scope.profile)
+ },
+ releaseGate: () => {}
+ })
+
+ assert.deepEqual(drained, ['default', 'research'])
+ assert.deepEqual(restored, ['default', 'research'])
+ assert.equal(updateCalled, false)
+ assert.match(result.error || '', /foreign owner/)
+})
+
+test('managed lifecycle journals before drain and leaves scopes stopped when clearance cannot be proved', async () => {
+ const events: string[] = []
+ const result = await runManagedSshUpdate({
+ connectionId: 'home',
+ correlationId: CORRELATION,
+ scopes: [{ key: 'a', profile: 'default' }],
+ preflightRemote: async () => {
+ events.push('preflight')
+ },
+ prepareRecovery: async () => {
+ events.push('journal')
+ },
+ drainScope: async () => {
+ events.push('drain')
+ },
+ updateRemote: async () => {
+ events.push('update')
+ throw new Error('observer timed out')
+ },
+ awaitRestoreClearance: async () => {
+ events.push('clear')
+ throw new Error('marker unavailable; durable recovery retained')
+ },
+ closeTransports: async () => {
+ events.push('close')
+ },
+ restoreScope: async () => {
+ events.push('restore')
+ },
+ completeRecovery: async () => {
+ events.push('clear-journal')
+ },
+ releaseGate: () => {
+ events.push('release')
+ }
+ })
+
+ assert.deepEqual(events, ['preflight', 'journal', 'drain', 'update', 'clear', 'close', 'release'])
+ assert.equal(result.restoreOk, false)
+ assert.equal(result.scopes[0].restored, false)
+ assert.match(result.scopes[0].error || '', /durable recovery retained/)
+})
+
+test('journal cleanup failure prevents a false successful update result', async () => {
+ const result = await runManagedSshUpdate({
+ connectionId: 'home',
+ correlationId: CORRELATION,
+ scopes: [{ key: 'a', profile: 'default' }],
+ preflightRemote: async () => {},
+ prepareRecovery: async () => {},
+ drainScope: async () => {},
+ updateRemote: async () => ({
+ exitCode: 0,
+ receipt: { correlationId: CORRELATION, outcome: 'success' }
+ }),
+ awaitRestoreClearance: async () => {},
+ closeTransports: async () => {},
+ restoreScope: async () => {},
+ completeRecovery: async () => {
+ throw new Error('disk remained busy')
+ },
+ releaseGate: () => {}
+ })
+
+ assert.equal(result.updateOk, true)
+ assert.equal(result.restoreOk, false)
+ assert.equal(result.ok, false)
+ assert.equal(result.outcome, 'restore-failed')
+ assert.match(result.error || '', /recovery record/)
+})
+
+test('preflight refusal leaves a healthy primary scope untouched and releases without waiting', async () => {
+ const events: string[] = []
+ const result = await runManagedSshUpdate({
+ connectionId: 'home',
+ correlationId: CORRELATION,
+ scopes: [{ key: '', primary: true, profile: 'default' }],
+ preflightRemote: async () => {
+ events.push('preflight')
+ throw new Error('live foreign update')
+ },
+ drainScope: async () => {
+ events.push('drain')
+ },
+ updateRemote: async () => {
+ events.push('update')
+
+ return { exitCode: 0, receipt: { correlationId: CORRELATION, outcome: 'success' } }
+ },
+ awaitRestoreClearance: async () => {
+ events.push('clear')
+ },
+ closeTransports: async () => {
+ events.push('close')
+ },
+ restoreScope: async () => {
+ events.push('restore')
+ },
+ releaseGate: () => {
+ events.push('release')
+ }
+ })
+
+ assert.deepEqual(events, ['preflight', 'close', 'release'])
+ assert.equal(result.updateOk, false)
+ assert.equal(result.restoreOk, true)
+})
+
+test('refused result is structured and has no managed scopes to restore', () => {
+ const result = refusedManagedSshUpdate('cloud', CORRELATION, 'not managed')
+
+ assert.equal(result.outcome, 'refused')
+ assert.equal(result.restoreOk, true)
+ assert.deepEqual(result.scopes, [])
+})
diff --git a/apps/desktop/electron/managed-ssh-update.ts b/apps/desktop/electron/managed-ssh-update.ts
new file mode 100644
index 00000000000..2425e2f2b1c
--- /dev/null
+++ b/apps/desktop/electron/managed-ssh-update.ts
@@ -0,0 +1,1058 @@
+/**
+ * Desktop-managed SSH update transaction.
+ *
+ * This module is intentionally Electron-free. main.ts owns the concrete pool
+ * maps, while this file owns the security-sensitive ordering and the remote
+ * wire protocol:
+ *
+ * gate dials -> drain every captured scope -> detached `hermes update`
+ * -> correlated terminal marker + durable receipt -> restore every scope
+ * -> lift the gate
+ *
+ * A remote URL/cloud connection never enters this lifecycle. Only SSH scopes
+ * whose serve process is proved by the Desktop ownership record are supplied
+ * by main.ts.
+ */
+
+import { expandRemotePath, shq } from './remote-lifecycle'
+import { encodedPowerShell, powerShellCommand, psLiteral } from './windows-remote-lifecycle'
+
+const UPDATE_EXIT_INDEPENDENT_HANDOFF = 75
+const DEFAULT_REMOTE_UPDATE_TIMEOUT_MS = 60 * 60 * 1000
+const DEFAULT_REMOTE_CLEARANCE_TIMEOUT_MS = 5 * 60 * 1000
+const DEFAULT_REMOTE_UPDATE_POLL_MS = 1_000
+const RECEIPT_GRACE_MS = 15_000
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
+
+type ManagedUpdateOutcome = 'updated' | 'update-failed' | 'restore-failed' | 'update-and-restore-failed' | 'refused'
+
+interface ManagedUpdateReceiptSummary {
+ correlationId: string
+ outcome: string
+ startedAt?: string
+ finishedAt?: string
+ preSha?: string
+ postSha?: string
+ preVersion?: string
+ postVersion?: string
+ stopReason?: string
+}
+
+interface ManagedUpdateScopeResult {
+ profile: string
+ restored: boolean
+ error?: string
+}
+
+interface ManagedConnectionUpdateResult {
+ connectionId: string
+ correlationId: string
+ ok: boolean
+ updateOk: boolean
+ restoreOk: boolean
+ outcome: ManagedUpdateOutcome
+ exitCode: null | number
+ receipt: ManagedUpdateReceiptSummary | null
+ scopes: ManagedUpdateScopeResult[]
+ error?: string
+ message?: string
+}
+
+interface ManagedSshScope {
+ key: string
+ profile: string
+}
+
+interface RemoteUpdateTarget {
+ ssh: {
+ exec: (command: string, options?: { timeoutMs?: number; stdinData?: string }) => Promise<string>
+ }
+ platform: 'Darwin' | 'Linux' | 'Windows'
+ hermesPath: string
+ hermesHome: string
+ pythonPath?: string
+}
+
+type RemoteMarkerState = 'absent' | 'dead' | 'live' | 'malformed' | 'unavailable'
+
+interface RemoteUpdateObservation {
+ marker: RemoteMarkerState
+ markerPid?: number
+ launchIntent: 'absent' | 'dead' | 'present' | 'malformed' | 'unavailable'
+ exitCode: null | number
+ receipt: ManagedUpdateReceiptSummary | null
+ coordinatorReady: null | { correlationId: string; pid: number }
+}
+
+interface RemoteUpdateProof {
+ exitCode: number
+ receipt: ManagedUpdateReceiptSummary
+}
+
+interface ManagedUpdateDeps<TScope extends ManagedSshScope = ManagedSshScope> {
+ connectionId: string
+ correlationId: string
+ scopes: TScope[]
+ preflightRemote: () => Promise<void>
+ drainScope: (scope: TScope) => Promise<void>
+ updateRemote: () => Promise<RemoteUpdateProof>
+ awaitRestoreClearance: () => Promise<void>
+ closeTransports: () => Promise<void>
+ restoreScope: (scope: TScope) => Promise<unknown>
+ releaseGate: () => void
+ prepareRecovery?: () => Promise<void>
+ completeRecovery?: () => Promise<void>
+}
+
+function validateCorrelationId(correlationId: string): string {
+ const value = String(correlationId || '')
+ .trim()
+ .toLowerCase()
+
+ if (!UUID_RE.test(value)) {
+ throw new Error('Managed SSH update correlation ID is invalid.')
+ }
+
+ return value
+}
+
+function validateRemoteValue(value: string, label: string): string {
+ const normalized = String(value || '').trim()
+
+ // eslint-disable-next-line no-control-regex -- remote shell values may not contain control bytes
+ if (!normalized || /[\x00\r\n]/.test(normalized)) {
+ throw new Error(`Managed SSH update ${label} is invalid.`)
+ }
+
+ return normalized
+}
+
+function managedSshTokenPersistencePlan(
+ source: unknown,
+ registryConnectionId = ''
+): {
+ legacySource: 'global' | 'profile' | null
+ registryConnectionId: string
+} {
+ const value = typeof source === 'string' ? source : ''
+ const sourceRegistryId = value.startsWith('registry:') ? value.slice('registry:'.length) : ''
+
+ return {
+ legacySource: sourceRegistryId ? null : value === 'profile' ? 'profile' : 'global',
+ registryConnectionId: String(registryConnectionId || sourceRegistryId || '').trim()
+ }
+}
+
+function managedSshScopeRole(input: {
+ connectionId: string
+ key: string
+ prefix: string
+ routeConnectionId?: string
+ state?: { primaryRegistryScope?: boolean; registryConnectionId?: string } | null
+}): 'pool' | 'primary' | null {
+ if (input.state?.registryConnectionId === input.connectionId) {
+ return input.state.primaryRegistryScope === true ? 'primary' : 'pool'
+ }
+ if (input.key.startsWith(input.prefix) || input.routeConnectionId === input.connectionId) {
+ return 'pool'
+ }
+
+ return null
+}
+
+type ManagedSshRecoveryScope = {
+ key: string
+ kind: 'legacy' | 'primary' | 'registry'
+ profile: string
+}
+
+function managedSshRecoveryScopes(
+ scopes: Iterable<{ key: string; primary?: boolean; profile: string }>,
+ registryPrefix: string
+): ManagedSshRecoveryScope[] {
+ const unique = new Map<string, ManagedSshRecoveryScope>()
+
+ for (const scope of scopes) {
+ const key = String(scope.key)
+ const existing = unique.get(key)
+ const next = {
+ key,
+ kind: scope.primary ? 'primary' : key.startsWith(registryPrefix) ? 'registry' : 'legacy',
+ profile: String(scope.profile || 'default')
+ } as ManagedSshRecoveryScope
+
+ // update-all can collect a primary scope through both the legacy and
+ // registry indexes. Restore it once, with primary taking precedence, so a
+ // single connection is never drained/restarted twice in one transaction.
+ if (!existing || next.kind === 'primary') {
+ unique.set(key, next)
+ }
+ }
+
+ return [...unique.values()]
+}
+
+function posixChildPath(home: string, name: string): string {
+ return `${home.replace(/\/+$/, '')}/${name}`
+}
+
+function windowsChildPath(home: string, name: string): string {
+ return `${home.replace(/[\\/]+$/, '')}\\${name}`
+}
+
+/**
+ * Build the POSIX launch command. The SSH channel waits only for the tiny
+ * launcher shell; the updater runs in a new session. Exit 75 is deliberately
+ * not published by the wrapper because it means an independently-supervised
+ * rollout worker owns the eventual terminal marker.
+ */
+function buildPosixManagedUpdateLaunch(target: RemoteUpdateTarget, correlationId: string): string {
+ const correlation = validateCorrelationId(correlationId)
+ const home = validateRemoteValue(target.hermesHome, 'Hermes home')
+ const hermesPath = validateRemoteValue(target.hermesPath, 'launcher path')
+ const statusPath = posixChildPath(home, `.update_exit_code.${correlation}`)
+ const intentPath = posixChildPath(home, `.update_launch_intent.${correlation}`)
+ const outputPath = posixChildPath(home, `logs/desktop-update-${correlation}.log`)
+ const homeWord = expandRemotePath(home)
+ const statusWord = expandRemotePath(statusPath)
+ const intentWord = expandRemotePath(intentPath)
+ const outputWord = expandRemotePath(outputPath)
+ const launcherWord = expandRemotePath(hermesPath)
+ const updateCommand =
+ `env HERMES_HOME=${homeWord} ` +
+ `HERMES_UPDATE_CORRELATION_ID=${shq(correlation)} ` +
+ 'HERMES_UPDATE_ORIGIN_PROFILE=default ' +
+ `HERMES_UPDATE_ORIGIN_HOME=${homeWord} ` +
+ `HERMES_UPDATE_OUTPUT_PATH=${outputWord} ` +
+ `${launcherWord} update --yes`
+ const inner =
+ `set +e; if [ -r "/proc/$$/stat" ]; then ` +
+ `intent_creation="linux:$(awk '{print $22}' "/proc/$$/stat")"; ` +
+ `else intent_creation="darwin:$(ps -o lstart= -p "$$" | sed 's/^ *//')"; fi; ` +
+ `intent_tmp=${intentWord}."$$".tmp; ` +
+ `printf '{"correlation":"%s","pid":%s,"creation":"%s"}' ${shq(correlation)} "$$" "$intent_creation" > "$intent_tmp" && ` +
+ `mv -f "$intent_tmp" ${intentWord} || exit 70; ` +
+ `${updateCommand}; rc=$?; ` +
+ `if [ "$rc" -ne ${UPDATE_EXIT_INDEPENDENT_HANDOFF} ] && [ ! -e ${statusWord} ]; then ` +
+ `tmp=${statusWord}."$$".tmp; umask 077; ` +
+ `printf "%s" "$rc" > "$tmp" && mv -f "$tmp" ${statusWord}; fi; ` +
+ 'exit "$rc"'
+
+ return (
+ `umask 077 && mkdir -p "$(dirname ${outputWord})" && rm -f ${statusWord} ${intentWord} && ` +
+ `if command -v setsid >/dev/null 2>&1; then ` +
+ `setsid sh -c ${shq(inner)} </dev/null >>${outputWord} 2>&1 & ` +
+ `else nohup sh -c ${shq(inner)} </dev/null >>${outputWord} 2>&1 & fi; child=$!; ` +
+ `i=0; while [ ! -e ${intentWord} ]; do kill -0 "$child" 2>/dev/null || exit 1; ` +
+ 'i=$((i+1)); [ "$i" -ge 200 ] && exit 1; sleep 0.05; done; printf MANAGED_UPDATE_STARTED'
+ )
+}
+
+/** Windows equivalent of buildPosixManagedUpdateLaunch. */
+function buildWindowsManagedUpdateLaunch(target: RemoteUpdateTarget, correlationId: string): string {
+ const correlation = validateCorrelationId(correlationId)
+ const home = validateRemoteValue(target.hermesHome, 'Hermes home')
+ const hermesPath = validateRemoteValue(target.hermesPath, 'launcher path')
+ const statusPath = windowsChildPath(home, `.update_exit_code.${correlation}`)
+ const readyPath = windowsChildPath(home, `.update_coordinator_ready.${correlation}`)
+ const intentPath = windowsChildPath(home, `.update_launch_intent.${correlation}`)
+ const outputPath = windowsChildPath(home, `logs\\desktop-update-${correlation}.log`)
+ const wrapper = [
+ '$ErrorActionPreference="Continue"',
+ `$env:HERMES_HOME=${psLiteral(home)}`,
+ `$env:HERMES_UPDATE_CORRELATION_ID=${psLiteral(correlation)}`,
+ '$env:HERMES_UPDATE_ORIGIN_PROFILE="default"',
+ `$env:HERMES_UPDATE_ORIGIN_HOME=${psLiteral(home)}`,
+ `$env:HERMES_UPDATE_OUTPUT_PATH=${psLiteral(outputPath)}`,
+ // The copied Windows coordinator verifies this correlation AND its actual
+ // breakaway state before accepting it; the string alone grants nothing.
+ `$env:HERMES_UPDATE_WINDOWS_DETACHED=${psLiteral(correlation)}`,
+ `$env:HERMES_UPDATE_TAURI_OUTCOME_PATH=${psLiteral(statusPath)}`,
+ `$env:HERMES_UPDATE_TAURI_READY_PATH=${psLiteral(readyPath)}`,
+ `$intentTmp=${psLiteral(intentPath)}+"."+$PID+".tmp"`,
+ '$intentCreation="windows:"+[string]([Diagnostics.Process]::GetCurrentProcess().StartTime.ToUniversalTime().ToFileTimeUtc())',
+ `$intentPayload=[ordered]@{correlation=${psLiteral(correlation)};pid=$PID;creation=$intentCreation}|ConvertTo-Json -Compress`,
+ '[IO.File]::WriteAllText($intentTmp,$intentPayload,[Text.UTF8Encoding]::new($false))',
+ `Move-Item -LiteralPath $intentTmp -Destination ${psLiteral(intentPath)} -Force`,
+ `& ${psLiteral(hermesPath)} update --yes *>> ${psLiteral(outputPath)}`,
+ '$rc=$LASTEXITCODE',
+ // A non-gateway Windows coordinator parent returns 0 once its copied
+ // child owns the marker. That is acceptance, not completion: suppress the
+ // wrapper status when the correlated readiness proof exists and let the
+ // durable child receipt + released marker provide terminal truth.
+ `$handoffAccepted=($rc -eq 0 -and (Test-Path -LiteralPath ${psLiteral(readyPath)}))`,
+ `if($rc -ne ${UPDATE_EXIT_INDEPENDENT_HANDOFF} -and -not $handoffAccepted -and -not (Test-Path -LiteralPath ${psLiteral(statusPath)})){`,
+ ` $tmp=${psLiteral(statusPath)}+"."+$PID+".tmp"`,
+ ' [IO.File]::WriteAllText($tmp,[string]$rc,[Text.UTF8Encoding]::new($false))',
+ ` Move-Item -LiteralPath $tmp -Destination ${psLiteral(statusPath)} -Force`,
+ '}',
+ 'exit $rc'
+ ].join(';')
+ const outer = [
+ '$ErrorActionPreference="Stop"',
+ `$output=${psLiteral(outputPath)}`,
+ 'New-Item -ItemType Directory -Force -Path (Split-Path -Parent $output)|Out-Null',
+ `Remove-Item -LiteralPath ${psLiteral(statusPath)},${psLiteral(readyPath)},${psLiteral(intentPath)} -Force -ErrorAction SilentlyContinue`,
+ `$args=@("-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",${psLiteral(encodedPowerShell(wrapper))})`,
+ '$child=Start-Process -FilePath "powershell.exe" -ArgumentList $args -WindowStyle Hidden -PassThru',
+ 'if(-not $child){throw "managed update launcher did not start"}',
+ '$deadline=[DateTime]::UtcNow.AddSeconds(10)',
+ `while(-not [IO.File]::Exists(${psLiteral(intentPath)})){if($child.HasExited){throw "managed update launcher exited before intent proof"};if([DateTime]::UtcNow -ge $deadline){throw "managed update launcher intent timed out"};Start-Sleep -Milliseconds 50}`,
+ '[ordered]@{started=$true;pid=$child.Id}|ConvertTo-Json -Compress'
+ ].join(';')
+
+ return powerShellCommand(outer)
+}
+
+const OBSERVATION_SCRIPT = String.raw`
+import ctypes,json,os,re,sys
+from pathlib import Path
+
+home=Path(os.path.expanduser(sys.argv[1]))
+correlation=sys.argv[2]
+# The update marker is install-wide even when the launcher was invoked with a
+# named profile home (<root>/profiles/<name>). Correlated status/intent/receipt
+# remain under the launch home, matching the CLI writer.
+profile_parent=home.parent.name
+is_profile_home=(profile_parent.lower()=='profiles') if os.name=='nt' else (profile_parent=='profiles')
+install_root=home.parent.parent if is_profile_home else home
+marker_path=install_root/'.hermes-update-in-progress'
+status_path=home/('.update_exit_code.'+correlation)
+ready_path=home/('.update_coordinator_ready.'+correlation)
+intent_path=home/('.update_launch_intent.'+correlation)
+marker_re=re.compile(rb'([1-9][0-9]*)\r?\n([0-9]+)(?:\r?\n)?\Z')
+
+def pid_alive(pid):
+ if os.name!='nt':
+ try:
+ os.kill(pid,0);return True
+ except ProcessLookupError:return False
+ except PermissionError:return True
+ except OSError:return None
+ try:
+ from ctypes import wintypes
+ kernel=ctypes.WinDLL('kernel32',use_last_error=True)
+ kernel.OpenProcess.argtypes=[wintypes.DWORD,wintypes.BOOL,wintypes.DWORD]
+ kernel.OpenProcess.restype=wintypes.HANDLE
+ kernel.GetExitCodeProcess.argtypes=[wintypes.HANDLE,ctypes.POINTER(wintypes.DWORD)]
+ kernel.GetExitCodeProcess.restype=wintypes.BOOL
+ kernel.CloseHandle.argtypes=[wintypes.HANDLE]
+ handle=kernel.OpenProcess(0x1000,False,pid)
+ if not handle:
+ return False if ctypes.get_last_error()==87 else None
+ try:
+ code=wintypes.DWORD()
+ if not kernel.GetExitCodeProcess(handle,ctypes.byref(code)):return None
+ return code.value==259
+ finally:kernel.CloseHandle(handle)
+ except Exception:return None
+
+def process_creation(pid):
+ if os.name!='nt':
+ if sys.platform.startswith('linux'):
+ try:
+ raw=Path('/proc/'+str(pid)+'/stat').read_text(encoding='ascii')
+ return 'linux:'+raw[raw.rfind(')')+2:].split()[19]
+ except (OSError,UnicodeError,IndexError):return None
+ if sys.platform=='darwin':
+ try:
+ import subprocess
+ value=subprocess.check_output(['ps','-o','lstart=','-p',str(pid)],text=True).strip()
+ return 'darwin:'+value if value else None
+ except (OSError,subprocess.CalledProcessError):return None
+ return None
+ try:
+ from ctypes import wintypes
+ kernel=ctypes.WinDLL('kernel32',use_last_error=True)
+ kernel.OpenProcess.argtypes=[wintypes.DWORD,wintypes.BOOL,wintypes.DWORD]
+ kernel.OpenProcess.restype=wintypes.HANDLE
+ kernel.GetProcessTimes.argtypes=[wintypes.HANDLE,ctypes.POINTER(wintypes.FILETIME),ctypes.POINTER(wintypes.FILETIME),ctypes.POINTER(wintypes.FILETIME),ctypes.POINTER(wintypes.FILETIME)]
+ kernel.GetProcessTimes.restype=wintypes.BOOL
+ kernel.CloseHandle.argtypes=[wintypes.HANDLE]
+ handle=kernel.OpenProcess(0x1000,False,pid)
+ if not handle:return None
+ try:
+ created=wintypes.FILETIME();exited=wintypes.FILETIME();kernel_time=wintypes.FILETIME();user_time=wintypes.FILETIME()
+ if not kernel.GetProcessTimes(handle,ctypes.byref(created),ctypes.byref(exited),ctypes.byref(kernel_time),ctypes.byref(user_time)):return None
+ value=(created.dwHighDateTime<<32)|created.dwLowDateTime
+ return 'windows:'+str(value)
+ finally:kernel.CloseHandle(handle)
+ except Exception:return None
+
+def marker_state():
+ try:raw=marker_path.read_bytes()
+ except FileNotFoundError:return {'state':'absent'}
+ except OSError:return {'state':'unavailable'}
+ match=marker_re.fullmatch(raw)
+ if not match:return {'state':'malformed'}
+ try:
+ pid=int(match.group(1));lease=int(match.group(2))
+ if pid<1 or pid>4294967295 or lease>9007199254740991:raise ValueError()
+ except ValueError:return {'state':'malformed'}
+ live=pid_alive(pid)
+ if live is None:return {'state':'unavailable','pid':pid}
+ return {'state':'live' if live else 'dead','pid':pid}
+
+def terminal_code():
+ try:raw=status_path.read_bytes()
+ except FileNotFoundError:return None
+ except OSError:return 'unavailable'
+ if not re.fullmatch(rb'[0-9]+',raw):return 'malformed'
+ try:return int(raw)
+ except ValueError:return 'malformed'
+
+def receipt():
+ directory=home/'logs'/'update_receipts'
+ try:paths=sorted(directory.glob('update_*.json'),key=lambda p:p.stat().st_mtime_ns,reverse=True)
+ except OSError:return None
+ for path in paths:
+ try:payload=json.loads(path.read_text(encoding='utf-8'))
+ except (OSError,UnicodeError,ValueError):continue
+ if not isinstance(payload,dict) or payload.get('correlation_id')!=correlation:continue
+ if payload.get('outcome')=='running' or not payload.get('finished_at'):continue
+ pre=payload.get('pre_update') if isinstance(payload.get('pre_update'),dict) else {}
+ post=payload.get('post_update') if isinstance(payload.get('post_update'),dict) else {}
+ return {
+ 'correlationId':correlation,'outcome':str(payload.get('outcome') or 'unknown'),
+ 'startedAt':payload.get('started_at'),'finishedAt':payload.get('finished_at'),
+ 'preSha':pre.get('sha'),'postSha':post.get('sha'),
+ 'preVersion':pre.get('version'),'postVersion':post.get('version'),
+ 'stopReason':payload.get('stop_reason'),
+ }
+ return None
+
+def ready():
+ try:payload=json.loads(ready_path.read_text(encoding='utf-8'))
+ except (FileNotFoundError,OSError,UnicodeError,ValueError):return None
+ if not isinstance(payload,dict) or payload.get('correlation_id')!=correlation:return None
+ pid=payload.get('pid')
+ return {'correlationId':correlation,'pid':pid} if isinstance(pid,int) and pid>0 else None
+
+def launch_intent():
+ try:payload=json.loads(intent_path.read_text(encoding='utf-8'))
+ except FileNotFoundError:return 'absent'
+ except OSError:return 'unavailable'
+ except (UnicodeError,ValueError):return 'malformed'
+ if not isinstance(payload,dict) or payload.get('correlation')!=correlation:return 'malformed'
+ pid=payload.get('pid');creation=payload.get('creation')
+ if not isinstance(pid,int) or pid<1 or pid>4294967295 or not isinstance(creation,str):return 'malformed'
+ live=pid_alive(pid)
+ if live is None:return 'unavailable'
+ if not live:return 'dead'
+ current=process_creation(pid)
+ if current is None:return 'unavailable'
+ return 'present' if current==creation else 'dead'
+
+state=marker_state()
+print(json.dumps({'marker':state['state'],'markerPid':state.get('pid'),'launchIntent':launch_intent(),'exitCode':terminal_code(),'receipt':receipt(),'coordinatorReady':ready()},separators=(',',':')))
+`.trim()
+
+function buildRemoteUpdateObservationCommand(target: RemoteUpdateTarget, correlationId: string): string {
+ const correlation = validateCorrelationId(correlationId)
+ const home = validateRemoteValue(target.hermesHome, 'Hermes home')
+
+ if (target.platform === 'Windows') {
+ const python = validateRemoteValue(target.pythonPath || '', 'Python path')
+ const script = [
+ '$ErrorActionPreference="Stop"',
+ `& ${psLiteral(python)} -c ${psLiteral(OBSERVATION_SCRIPT)} ${psLiteral(home)} ${psLiteral(correlation)}`,
+ 'if($LASTEXITCODE -ne 0){exit $LASTEXITCODE}'
+ ].join(';')
+
+ return powerShellCommand(script)
+ }
+
+ return `python3 -c ${shq(OBSERVATION_SCRIPT)} ${shq(home)} ${shq(correlation)}`
+}
+
+function parseRemoteUpdateObservation(raw: string, correlationId: string): RemoteUpdateObservation {
+ const correlation = validateCorrelationId(correlationId)
+ let parsed: any
+
+ try {
+ const lines = String(raw || '')
+ .replace(/^\uFEFF/, '')
+ .trim()
+ .split(/\r?\n/)
+ .filter(Boolean)
+
+ parsed = JSON.parse(lines.at(-1) || 'null')
+ } catch {
+ throw new Error('Remote update observation was malformed.')
+ }
+
+ if (!parsed || !['absent', 'dead', 'live', 'malformed', 'unavailable'].includes(parsed.marker)) {
+ throw new Error('Remote update marker state was malformed.')
+ }
+
+ if (!['absent', 'dead', 'present', 'malformed', 'unavailable'].includes(parsed.launchIntent)) {
+ throw new Error('Remote update launch intent was malformed.')
+ }
+
+ if (parsed.exitCode === 'malformed' || parsed.exitCode === 'unavailable') {
+ throw new Error(`Remote update terminal status was ${parsed.exitCode}.`)
+ }
+
+ const exitCode = parsed.exitCode == null ? null : Number(parsed.exitCode)
+
+ if (exitCode !== null && (!Number.isSafeInteger(exitCode) || exitCode < 0)) {
+ throw new Error('Remote update terminal status was malformed.')
+ }
+
+ let receipt: ManagedUpdateReceiptSummary | null = null
+
+ if (parsed.receipt != null) {
+ if (
+ typeof parsed.receipt !== 'object' ||
+ parsed.receipt.correlationId !== correlation ||
+ typeof parsed.receipt.outcome !== 'string'
+ ) {
+ throw new Error('Remote update receipt did not match this transaction.')
+ }
+ receipt = parsed.receipt as ManagedUpdateReceiptSummary
+ }
+
+ let coordinatorReady: RemoteUpdateObservation['coordinatorReady'] = null
+
+ if (parsed.coordinatorReady != null) {
+ const pid = Number(parsed.coordinatorReady.pid)
+
+ if (
+ parsed.coordinatorReady.correlationId !== correlation ||
+ !Number.isSafeInteger(pid) ||
+ pid <= 0 ||
+ pid > 4_294_967_295
+ ) {
+ throw new Error('Remote update coordinator readiness proof was malformed.')
+ }
+ coordinatorReady = { correlationId: correlation, pid }
+ }
+
+ const markerPid = parsed.markerPid == null ? undefined : Number(parsed.markerPid)
+
+ if (markerPid !== undefined && (!Number.isSafeInteger(markerPid) || markerPid <= 0 || markerPid > 4_294_967_295)) {
+ throw new Error('Remote update marker PID was malformed.')
+ }
+
+ return {
+ marker: parsed.marker,
+ ...(markerPid === undefined ? {} : { markerPid }),
+ launchIntent: parsed.launchIntent,
+ exitCode,
+ receipt,
+ coordinatorReady
+ }
+}
+
+async function observeManagedRemoteUpdate(
+ target: RemoteUpdateTarget,
+ correlationId: string
+): Promise<RemoteUpdateObservation> {
+ const command = buildRemoteUpdateObservationCommand(target, correlationId)
+ const raw = await target.ssh.exec(command, { timeoutMs: 30_000 })
+
+ return parseRemoteUpdateObservation(raw, correlationId)
+}
+
+function markerIsClear(observation: RemoteUpdateObservation): boolean {
+ return observation.marker === 'absent' || observation.marker === 'dead'
+}
+
+async function assertManagedUpdatePreflightClear(target: RemoteUpdateTarget, correlationId: string): Promise<void> {
+ const observation = await observeManagedRemoteUpdate(target, correlationId)
+
+ if (!markerIsClear(observation)) {
+ const owner = observation.markerPid ? ` (PID ${observation.markerPid})` : ''
+ throw new Error(`The remote install update marker is ${observation.marker}${owner}; refusing to drain its serves.`)
+ }
+}
+
+async function launchManagedRemoteUpdate(target: RemoteUpdateTarget, correlationId: string): Promise<void> {
+ const command =
+ target.platform === 'Windows'
+ ? buildWindowsManagedUpdateLaunch(target, correlationId)
+ : buildPosixManagedUpdateLaunch(target, correlationId)
+ const output = await target.ssh.exec(command, { timeoutMs: 30_000 })
+
+ if (target.platform === 'Windows') {
+ let parsed: any
+
+ try {
+ const lines = String(output || '')
+ .replace(/^\uFEFF/, '')
+ .trim()
+ .split(/\r?\n/)
+ .filter(Boolean)
+ parsed = JSON.parse(lines.at(-1) || 'null')
+ } catch {
+ parsed = null
+ }
+
+ if (parsed?.started !== true || !Number.isInteger(parsed?.pid) || parsed.pid <= 0) {
+ throw new Error('Remote Windows update launcher did not acknowledge its detached child.')
+ }
+ } else if (!String(output || '').includes('MANAGED_UPDATE_STARTED')) {
+ throw new Error('Remote update launcher did not acknowledge its detached child.')
+ }
+}
+
+async function waitForManagedRemoteUpdate(
+ target: RemoteUpdateTarget,
+ correlationId: string,
+ options: {
+ timeoutMs?: number
+ pollMs?: number
+ now?: () => number
+ sleep?: (ms: number) => Promise<void>
+ } = {}
+): Promise<RemoteUpdateProof> {
+ const timeoutMs = options.timeoutMs ?? DEFAULT_REMOTE_UPDATE_TIMEOUT_MS
+ const pollMs = options.pollMs ?? DEFAULT_REMOTE_UPDATE_POLL_MS
+ const now = options.now || Date.now
+ const sleep = options.sleep || (ms => new Promise(resolve => setTimeout(resolve, ms)))
+ const deadline = now() + timeoutMs
+ let terminalSeenAt: null | number = null
+
+ while (true) {
+ let observation: RemoteUpdateObservation
+
+ try {
+ observation = await observeManagedRemoteUpdate(target, correlationId)
+ } catch (error) {
+ if (now() >= deadline) {
+ throw error
+ }
+ await sleep(pollMs)
+ continue
+ }
+
+ if (observation.marker === 'malformed' || observation.marker === 'unavailable') {
+ if (now() >= deadline) {
+ throw new Error(
+ `Remote update marker remained ${observation.marker} through the update timeout; ` +
+ 'services remain stopped and Desktop recorded them for safe recovery.'
+ )
+ }
+ await sleep(pollMs)
+ continue
+ }
+
+ if (
+ observation.coordinatorReady &&
+ observation.marker === 'live' &&
+ observation.markerPid !== observation.coordinatorReady.pid
+ ) {
+ throw new Error(
+ `Remote update marker PID ${observation.markerPid || 'unknown'} did not match coordinator PID ${observation.coordinatorReady.pid}.`
+ )
+ }
+
+ if (observation.exitCode !== null) {
+ terminalSeenAt ??= now()
+
+ if (observation.receipt && markerIsClear(observation)) {
+ return { exitCode: observation.exitCode, receipt: observation.receipt }
+ }
+
+ if (!observation.receipt && markerIsClear(observation) && now() - terminalSeenAt >= RECEIPT_GRACE_MS) {
+ throw new Error('Remote update finished without a correlated durable receipt.')
+ }
+ }
+
+ if (observation.coordinatorReady && observation.receipt && markerIsClear(observation)) {
+ return {
+ exitCode: observation.receipt.outcome === 'success' ? 0 : 1,
+ receipt: observation.receipt
+ }
+ }
+
+ if (now() >= deadline) {
+ throw new Error(
+ markerIsClear(observation)
+ ? 'Remote update did not publish a correlated terminal result before the timeout.'
+ : 'Remote update was still active at the timeout; services remain stopped and Desktop recorded them for safe recovery.'
+ )
+ }
+
+ await sleep(pollMs)
+ }
+}
+
+async function executeManagedRemoteUpdate(
+ target: RemoteUpdateTarget,
+ correlationId: string,
+ options: Parameters<typeof waitForManagedRemoteUpdate>[2] = {},
+ onLaunchProved: () => Promise<void> = async () => {}
+): Promise<RemoteUpdateProof> {
+ await assertManagedUpdatePreflightClear(target, correlationId)
+ await launchManagedRemoteUpdate(target, correlationId)
+ await onLaunchProved()
+
+ return waitForManagedRemoteUpdate(target, correlationId, options)
+}
+
+async function waitForManagedRemoteClearance(
+ target: RemoteUpdateTarget,
+ correlationId: string,
+ options: {
+ timeoutMs?: number
+ pollMs?: number
+ now?: () => number
+ sleep?: (ms: number) => Promise<void>
+ requireTerminal?: boolean
+ } = {}
+): Promise<void> {
+ const timeoutMs = options.timeoutMs ?? DEFAULT_REMOTE_CLEARANCE_TIMEOUT_MS
+ const pollMs = options.pollMs ?? DEFAULT_REMOTE_UPDATE_POLL_MS
+ const now = options.now || Date.now
+ const sleep = options.sleep || (ms => new Promise(resolve => setTimeout(resolve, ms)))
+ const deadline = now() + timeoutMs
+ let lastState = 'unavailable'
+ let observedLiveOwner = false
+
+ while (true) {
+ try {
+ const observation = await observeManagedRemoteUpdate(target, correlationId)
+ lastState = observation.marker
+ observedLiveOwner ||= observation.marker === 'live'
+
+ if (observation.launchIntent === 'malformed' || observation.launchIntent === 'unavailable') {
+ lastState = `launch-intent-${observation.launchIntent}`
+ } else if (markerIsClear(observation)) {
+ if (
+ observation.launchIntent === 'dead' ||
+ (!options.requireTerminal && observation.launchIntent === 'absent') ||
+ observedLiveOwner ||
+ observation.exitCode !== null ||
+ observation.receipt !== null
+ ) {
+ return
+ }
+ }
+ } catch {
+ // Transport/parse uncertainty is not clearance. A reconnecting observer
+ // may eventually prove absent/dead; until then startup remains fenced.
+ lastState = 'unavailable'
+ }
+
+ if (now() >= deadline) {
+ throw new Error(
+ `Could not prove remote update clearance before the recovery timeout (marker: ${lastState}); ` +
+ 'services were not restarted and Desktop retained a durable recovery record.'
+ )
+ }
+ await sleep(pollMs)
+ }
+}
+
+function errorMessage(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
+
+function resultOutcome(updateOk: boolean, restoreOk: boolean): ManagedUpdateOutcome {
+ if (updateOk && restoreOk) {
+ return 'updated'
+ }
+ if (!updateOk && !restoreOk) {
+ return 'update-and-restore-failed'
+ }
+
+ return updateOk ? 'restore-failed' : 'update-failed'
+}
+
+async function runManagedSshUpdate<TScope extends ManagedSshScope>(
+ deps: ManagedUpdateDeps<TScope>
+): Promise<ManagedConnectionUpdateResult> {
+ const { connectionId, correlationId, scopes } = deps
+ let proof: RemoteUpdateProof | null = null
+ let updateError = ''
+ let restorationBlocked = ''
+ let recoveryComplete = true
+ let recoveryPrepared = false
+ let restoreNeedsMarkerFence = false
+ const restoreResults: ManagedUpdateScopeResult[] = []
+ const restoreCandidates = new Set<TScope>()
+
+ try {
+ // Refuse on a live/malformed/unreadable install marker before disrupting
+ // any currently healthy forward or serve.
+ await deps.preflightRemote()
+ await deps.prepareRecovery?.()
+ recoveryPrepared = true
+ const drainErrors: string[] = []
+
+ restoreNeedsMarkerFence = scopes.length > 0
+ for (const scope of scopes) {
+ restoreCandidates.add(scope)
+ try {
+ await deps.drainScope(scope)
+ } catch (error) {
+ drainErrors.push(`${scope.profile}: ${errorMessage(error)}`)
+ }
+ }
+ if (drainErrors.length) {
+ throw new Error(`Could not safely drain every managed SSH scope (${drainErrors.join('; ')}).`)
+ }
+ // A zero-scope update still launches a mutator, so any subsequent error
+ // must wait for its marker to clear before closing the update transport.
+ restoreNeedsMarkerFence = true
+ proof = await deps.updateRemote()
+ } catch (error) {
+ updateError = errorMessage(error)
+ } finally {
+ // A launch acknowledgement can be lost after the remote child starts, and
+ // a competing updater can claim the install between preflight and drain.
+ // Never restart serves until the shared install marker is positively
+ // absent/dead, even on an error path.
+ if (restoreNeedsMarkerFence) {
+ try {
+ await deps.awaitRestoreClearance()
+ } catch (error) {
+ restorationBlocked = errorMessage(error)
+ updateError = [updateError, restorationBlocked].filter(Boolean).join(' ')
+ }
+ }
+ try {
+ await deps.closeTransports()
+ } catch (error) {
+ updateError ||= `Could not close the drained SSH transport: ${errorMessage(error)}`
+ }
+
+ for (const scope of scopes) {
+ if (!restoreCandidates.has(scope)) {
+ // Preflight/journal refusal occurred before this healthy scope was
+ // touched. Report it ready without cycling its primary/pool backend.
+ restoreResults.push({ profile: scope.profile, restored: true })
+ } else if (restorationBlocked) {
+ restoreResults.push({ profile: scope.profile, restored: false, error: restorationBlocked })
+ } else {
+ try {
+ await deps.restoreScope(scope)
+ restoreResults.push({ profile: scope.profile, restored: true })
+ } catch (error) {
+ restoreResults.push({ profile: scope.profile, restored: false, error: errorMessage(error) })
+ }
+ }
+ }
+
+ try {
+ if (recoveryPrepared && !restorationBlocked && restoreResults.every(result => result.restored)) {
+ await deps.completeRecovery?.()
+ }
+ } catch (error) {
+ recoveryComplete = false
+ updateError ||= `Could not clear the managed SSH recovery record: ${errorMessage(error)}`
+ } finally {
+ deps.releaseGate()
+ }
+ }
+
+ const updateOk = Boolean(proof && proof.exitCode === 0 && proof.receipt.outcome === 'success')
+ const restoreOk = recoveryComplete && restoreResults.every(result => result.restored)
+ const outcome = resultOutcome(updateOk, restoreOk)
+ const restoreErrors = restoreResults.filter(result => !result.restored).map(result => result.error)
+ const error = [updateError, ...restoreErrors].filter(Boolean).join(' ')
+
+ return {
+ connectionId,
+ correlationId,
+ ok: updateOk && restoreOk,
+ updateOk,
+ restoreOk,
+ outcome,
+ exitCode: proof?.exitCode ?? null,
+ receipt: proof?.receipt ?? null,
+ scopes: restoreResults,
+ ...(error ? { error } : {}),
+ message:
+ outcome === 'updated'
+ ? 'Remote Hermes updated and every managed SSH profile is ready.'
+ : restoreOk
+ ? 'The remote update failed, but every managed SSH profile was restored.'
+ : 'The remote update transaction could not restore every managed SSH profile.'
+ }
+}
+
+function refusedManagedSshUpdate(connectionId: string, correlationId: string, error: string) {
+ const message = String(error || 'This connection is not managed by Desktop SSH.')
+
+ return {
+ connectionId,
+ correlationId,
+ ok: false,
+ updateOk: false,
+ restoreOk: true,
+ outcome: 'refused' as const,
+ exitCode: null,
+ receipt: null,
+ scopes: [],
+ error: message,
+ message
+ }
+}
+
+// before-quit uses this to join remote update transactions before it starts
+// tearing down their SSH transports. Re-read after every batch so an operation
+// registered while the first batch settles is joined too.
+async function waitForManagedUpdateOperations(getOperations: () => Iterable<Promise<unknown>>): Promise<void> {
+ for (;;) {
+ const pending = [...getOperations()]
+
+ if (pending.length === 0) {
+ return
+ }
+
+ await Promise.allSettled(pending)
+ }
+}
+
+async function recoverManagedSshScopes<TScope>(deps: {
+ afterClearance?: () => Promise<void>
+ awaitClearance: () => Promise<void>
+ completeRecovery: () => Promise<void>
+ restoreScope: (scope: TScope) => Promise<unknown>
+ scopes: TScope[]
+}): Promise<PromiseSettledResult<unknown>[]> {
+ await deps.awaitClearance()
+ await deps.afterClearance?.()
+ const results = await Promise.allSettled(deps.scopes.map(scope => deps.restoreScope(scope)))
+
+ if (results.every(result => result.status === 'fulfilled')) {
+ // This intentionally runs for an empty scope list. An inactive connection
+ // still journals the detached mutator so a crash/relaunch remains fenced;
+ // positive marker clearance is what authorizes removing that durable gate.
+ await deps.completeRecovery()
+ }
+
+ return results
+}
+
+async function fenceManagedSshBootstrapPublication<T>(deps: {
+ assertCanPublish: () => void
+ publish: () => T
+ rollback: (cause: unknown) => Promise<void>
+}): Promise<T> {
+ try {
+ deps.assertCanPublish()
+ // Deliberately no await between the final gate assertion and publication:
+ // both run in this JavaScript turn, so a queued update claim either lands
+ // before the assertion (and triggers rollback) or after the scope is
+ // visible to capture/drain.
+ return deps.publish()
+ } catch (error) {
+ await deps.rollback(error)
+ throw error
+ }
+}
+
+async function waitForManagedSshBootstrapFence(
+ entries: Iterable<{ metadata?: { registryConnectionId?: string }; promise: Promise<unknown> }>,
+ connectionId: string
+): Promise<void> {
+ const pending = [...entries].filter(entry => entry.metadata?.registryConnectionId === connectionId)
+ const results = await Promise.allSettled(pending.map(entry => entry.promise))
+ const unsafe = results.find(
+ result => result.status === 'rejected' && (result.reason as any)?.unsafeManagedBootstrap === true
+ )
+
+ if (unsafe?.status === 'rejected') {
+ throw unsafe.reason
+ }
+}
+
+class ManagedConnectionUpdateGate {
+ private claims = new Map<string, string>()
+
+ constructor(private readonly durableOwner: (connectionId: string) => string | null = () => null) {}
+
+ claim(connectionId: string, correlationId: string): boolean {
+ const id = String(connectionId || '').trim()
+ const correlation = validateCorrelationId(correlationId)
+ const durable = this.durableOwner(id)
+
+ if (!id || this.claims.has(id) || (durable && durable !== correlation)) {
+ return false
+ }
+ this.claims.set(id, correlation)
+
+ return true
+ }
+
+ release(connectionId: string, correlationId: string): void {
+ const id = String(connectionId || '').trim()
+
+ if (this.claims.get(id) === correlationId) {
+ this.claims.delete(id)
+ }
+ }
+
+ assertCanDial(connectionId: string, correlationId = ''): void {
+ const id = String(connectionId || '').trim()
+ const owner = this.claims.get(id) || this.durableOwner(id)
+
+ if (owner && owner !== correlationId) {
+ const error: any = new Error(`SSH connection "${id}" is paused while its managed update is in progress.`)
+ error.code = 'managed-update-in-progress'
+ throw error
+ }
+ }
+
+ assertCanMutate(connectionId: string): void {
+ const id = String(connectionId || '').trim()
+ const owner = this.claims.get(id) || this.durableOwner(id)
+
+ if (owner) {
+ const error: any = new Error(
+ `SSH connection "${id}" cannot be edited or removed while its managed update recovery is pending.`
+ )
+ error.code = 'managed-update-in-progress'
+ throw error
+ }
+ }
+
+ owner(connectionId: string): string | null {
+ const id = String(connectionId || '').trim()
+
+ return this.claims.get(id) || this.durableOwner(id) || null
+ }
+}
+
+export {
+ assertManagedUpdatePreflightClear,
+ buildPosixManagedUpdateLaunch,
+ buildRemoteUpdateObservationCommand,
+ buildWindowsManagedUpdateLaunch,
+ DEFAULT_REMOTE_CLEARANCE_TIMEOUT_MS,
+ DEFAULT_REMOTE_UPDATE_POLL_MS,
+ DEFAULT_REMOTE_UPDATE_TIMEOUT_MS,
+ executeManagedRemoteUpdate,
+ fenceManagedSshBootstrapPublication,
+ launchManagedRemoteUpdate,
+ ManagedConnectionUpdateGate,
+ type ManagedConnectionUpdateResult,
+ type ManagedSshRecoveryScope,
+ managedSshRecoveryScopes,
+ type ManagedSshScope,
+ managedSshScopeRole,
+ managedSshTokenPersistencePlan,
+ type ManagedUpdateDeps,
+ type ManagedUpdateOutcome,
+ type ManagedUpdateReceiptSummary,
+ type ManagedUpdateScopeResult,
+ markerIsClear,
+ observeManagedRemoteUpdate,
+ parseRemoteUpdateObservation,
+ RECEIPT_GRACE_MS,
+ recoverManagedSshScopes,
+ refusedManagedSshUpdate,
+ type RemoteUpdateObservation,
+ type RemoteUpdateProof,
+ type RemoteUpdateTarget,
+ runManagedSshUpdate,
+ UPDATE_EXIT_INDEPENDENT_HANDOFF,
+ validateCorrelationId,
+ waitForManagedRemoteClearance,
+ waitForManagedRemoteUpdate,
+ waitForManagedSshBootstrapFence,
+ waitForManagedUpdateOperations
+}
diff --git a/apps/desktop/electron/remote-lifecycle.test.ts b/apps/desktop/electron/remote-lifecycle.test.ts
index d22557c887e..932c6c2c385 100644
--- a/apps/desktop/electron/remote-lifecycle.test.ts
+++ b/apps/desktop/electron/remote-lifecycle.test.ts
@@ -1,6 +1,6 @@
import assert from 'node:assert/strict'
import { exec as execCallback, spawn } from 'node:child_process'
-import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
+import { chmod, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { promisify } from 'node:util'
@@ -9,6 +9,7 @@ import { test } from 'vitest'
import { profileSshOverride } from './connection-config'
import {
+ assertRemoteInstallUpdateClear,
buildSpawnCommand,
classifySshReuseProof,
cleanupStale,
@@ -35,6 +36,7 @@ import {
spawnLogPath,
spawnRemoteDashboard,
spawnTokenPath,
+ terminateOwnedDashboardForUpdate,
validateRemotePath,
writeLockfile
} from './remote-lifecycle'
@@ -74,6 +76,7 @@ function ownedLock(over: any = {}) {
logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),
tokenFingerprint: fingerprintToken('stored-token'),
startedAt: '2026-07-14T00:00:00.000Z',
+ creationTime: 'linux:123456',
...over
}
}
@@ -88,7 +91,26 @@ function fakeSsh(rules: any[] = []) {
async exec(cmd) {
calls.push(cmd)
- for (const [matcher, resp] of rules) {
+ // Existing lifecycle fixtures predate the install-wide relaunch gate.
+ // Their default remote has no update marker; focused marker tests below
+ // use explicit SSH doubles to exercise live/uncertain transitions.
+ if (cmd.includes('.hermes-update-in-progress') && !cmd.includes('marker_clear()') && !/setsid|nohup/.test(cmd)) {
+ return 'CLEAR'
+ }
+
+ const mutexWrapped = cmd.includes('fcntl.flock(fd,fcntl.LOCK_EX)')
+ const applicableRules = rules.filter(([matcher]) => {
+ if (cmd.includes('marker_clear()') && matcher instanceof RegExp && /kill -0/.test(matcher.source)) {
+ return false
+ }
+
+ return !(mutexWrapped && matcher instanceof RegExp && /python3 -c/.test(matcher.source))
+ })
+
+ if ((cmd.includes('os.kill(pid') && !cmd.includes('pidfd_open')) || cmd.includes('printf TERMINATED')) {
+ return 'TERMINATED'
+ }
+ for (const [matcher, resp] of applicableRules) {
const hit = typeof matcher === 'function' ? matcher(cmd) : matcher.test(cmd)
if (hit) {
@@ -107,6 +129,99 @@ function fakeSsh(rules: any[] = []) {
}
}
+test('POSIX relaunch gate refuses live and uncertain install markers without executing Hermes', async () => {
+ for (const observation of ['LIVE:4242', 'UNCERTAIN']) {
+ const calls: string[] = []
+ const ssh = {
+ async exec(command) {
+ calls.push(command)
+
+ if (command === 'uname -s; uname -m') {
+ return 'Linux\nx86_64\n'
+ }
+ if (command.includes('HERMES_HOME')) {
+ return '/home/alice/.hermes\n'
+ }
+ if (command.includes('.hermes-update-in-progress')) {
+ return observation
+ }
+ throw new Error(`unexpected command after update gate: ${command}`)
+ }
+ }
+
+ await assert.rejects(
+ () => connect(connectDeps(ssh)),
+ (error: any) => error.kind === 'update-in-progress'
+ )
+ assert.equal(
+ calls.some(command => /\[ -x |--version|lock\.json|serve --help|setsid/.test(command)),
+ false
+ )
+ }
+})
+
+test('POSIX relaunch gate permits absent/dead markers and normalizes named-profile homes install-wide', async () => {
+ const commands: string[] = []
+ const ssh = {
+ async exec(command) {
+ commands.push(command)
+
+ return 'CLEAR'
+ }
+ }
+
+ await assertRemoteInstallUpdateClear(ssh, '/home/alice/.hermes/profiles/research')
+ assert.match(commands[0], /home\.parent\.name/)
+ assert.match(commands[0], /profiles/)
+ assert.match(commands[0], /\.hermes-update-in-progress/)
+})
+
+test('POSIX relaunch gate rechecks after token upload immediately before process creation', async () => {
+ const calls: string[] = []
+ let markerChecks = 0
+ const ssh = {
+ async exec(command) {
+ calls.push(command)
+
+ if (command === 'uname -s; uname -m') {
+ return 'Linux\nx86_64\n'
+ }
+ if (command.includes('HERMES_HOME')) {
+ return '/home/alice/.hermes\n'
+ }
+ if (command.includes('.hermes-update-in-progress')) {
+ markerChecks += 1
+
+ return markerChecks >= 3 ? 'LIVE:4242' : 'CLEAR'
+ }
+ if (/\[ -x /.test(command)) {
+ return 'OK'
+ }
+ if (command.includes('serve --help')) {
+ return 'YES\n'
+ }
+ if (command.includes('python3 -c')) {
+ return ''
+ }
+ if (command.includes('lock.json')) {
+ return ''
+ }
+
+ return ''
+ }
+ }
+
+ await assert.rejects(
+ () => connect(connectDeps(ssh)),
+ (error: any) => error.kind === 'update-in-progress'
+ )
+ assert.equal(markerChecks, 3)
+ assert.equal(
+ calls.some(command => /setsid|nohup/.test(command)),
+ false
+ )
+})
+
test('listRemoteHermesProfiles inventories Mini-style profile dirs without spawning a dashboard', async () => {
const ssh = fakeSsh([
[/HERMES_HOME/, '/Users/zillajr/.hermes\n'],
@@ -614,10 +729,16 @@ test('cleanupStale kills ONLY a provably-ours pid, always drops the lockfile', a
hermesPath: '/x/hermes',
logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE)
})
- assert.ok(!notOurs.calls.some(c => /kill 5\b/.test(c)), 'must not kill a pid that is not our dashboard')
+ assert.ok(
+ notOurs.calls.some(c => /print\("OWNED"/.test(c)),
+ 'must perform an ownership preflight'
+ )
assert.ok(notOurs.calls.some(c => /rm -f/.test(c)))
- const ours = fakeSsh([[/print\("OWNED"/, 'OWNED\n']])
+ const ours = fakeSsh([
+ [/print\("OWNED"/, 'OWNED\n'],
+ [cmd => /printf TERMINATED/.test(cmd), 'TERMINATED\n']
+ ])
await cleanupStale(ours, OWNERSHIP_ID, {
pid: 9,
spawnNonce: SPAWN_NONCE,
@@ -652,6 +773,88 @@ test('buildSpawnCommand always uses serve (legacy dashboard path removed)', () =
assert.match(cmd, /setsid/)
})
+test('buildSpawnCommand atomically reserves the ownership slot through spawn and lock publication', () => {
+ const cmd = buildSpawnCommand('/x/hermes', 'work', {
+ hermesHome: '~/.hermes',
+ logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),
+ ownershipId: OWNERSHIP_ID,
+ reservationNonce: SPAWN_NONCE,
+ spawnNonce: SPAWN_NONCE,
+ tokenFilePath: spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE),
+ lockMetadata: {
+ ownershipId: OWNERSHIP_ID,
+ spawnNonce: SPAWN_NONCE,
+ port: 0,
+ profile: 'work',
+ hermesPath: '/x/hermes',
+ hermesHome: '~/.hermes',
+ logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),
+ tokenFingerprint: fingerprintToken('stored-token'),
+ protocolVersion: PROTOCOL_VERSION,
+ startedAt: '2026-07-14T00:00:00.000Z'
+ }
+ })
+
+ assert.ok(cmd.includes('.connect.lock'))
+ assert.ok(cmd.includes('.hermes-update-in-progress.mutex'))
+ assert.match(cmd, /fcntl\.flock\(fd,fcntl\.LOCK_EX\)/)
+ assert.match(cmd, /os\.O_CLOEXEC/)
+ assert.match(cmd, /subprocess\.run\(\["sh","-c",payload,"hermes-update-mutex",str\(fd\)\],pass_fds=\(fd,\),check=False\)/)
+ assert.doesNotMatch(cmd, /os\.set_inheritable\(fd,True\)/)
+ assert.match(cmd, /hermes-update-child "\$1"/)
+ assert.match(cmd, /eval "exec \$1>&-"/)
+ assert.ok(cmd.includes('backend.lock.json'))
+ assert.match(cmd, /lock_json/)
+ assert.match(cmd, /trap .*rm -rf/)
+ assert.ok(cmd.indexOf('lock_json') > cmd.indexOf('serve --isolated'))
+})
+
+test.skipIf(process.platform === 'win32')('detached backend does not inherit the update mutex descriptor', async () => {
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'hermes-update-mutex-'))
+ const hermesPath = path.join(directory, 'hermes')
+ const reportPath = path.join(directory, 'descriptor-report')
+ const logPath = path.join(directory, 'spawn.log')
+
+ try {
+ await writeFile(
+ hermesPath,
+ `#!/bin/sh
+: > ${reportPath}
+for fd in /proc/$$/fd/*; do
+ target=$(readlink "$fd" 2>/dev/null || true)
+ case "$target" in
+ *hermes-update-in-progress.mutex) printf '%s\\n' "$target" >> ${reportPath} ;;
+ esac
+done
+`,
+ { mode: 0o700 }
+ )
+
+ const command = buildSpawnCommand(hermesPath, '', {
+ hermesHome: path.join(directory, 'home'),
+ logPath
+ })
+ await exec(command, { shell: '/bin/bash' })
+
+ for (let attempt = 0; attempt < 40; attempt += 1) {
+ try {
+ const report = await readFile(reportPath, 'utf8')
+ assert.equal(report, '', 'the backend process must not retain the update mutex descriptor')
+ return
+ } catch (error: any) {
+ if (error?.code !== 'ENOENT') {
+ throw error
+ }
+ await new Promise(resolve => setTimeout(resolve, 25))
+ }
+ }
+
+ assert.fail('the detached backend did not write its descriptor report')
+ } finally {
+ await rm(directory, { recursive: true, force: true })
+ }
+})
+
test('spawnRemoteDashboard returns exact ownership artifacts', async () => {
const ssh = fakeSsh([
[/grep -q ssh-session-token-file/, 'YES\n'],
@@ -858,6 +1061,7 @@ test('connect() respawns when the requested remote profile differs from the lock
[/cat .*lock\.json/, JSON.stringify(lock)],
[/kill -0 333/, 'ALIVE'],
[/print\("OWNED"/, 'OWNED\n'],
+ [cmd => /pidfd_open/.test(cmd), 'TERMINATED\n'],
[/kill 333/, ''],
[/--version/, 'Hermes Agent v0.18.2\n'],
[/grep -q ssh-session-token-file/, 'YES\n'],
@@ -988,6 +1192,79 @@ test('connect() respawns when the lockfile pid is dead (killed dashboard)', asyn
)
})
+test('managed update drain preserves a live foreign POSIX owner and its lock bytes', async () => {
+ const lock = ownedLock()
+ const rawLock = JSON.stringify(lock)
+ const ssh = fakeSsh([
+ [/cat .*lock\.json/, rawLock],
+ [/kill -0 333/, 'ALIVE'],
+ [/value="linux:"/, 'linux:123456\n'],
+ [/print\("OWNED"/, 'FOREIGN\n']
+ ])
+
+ await assert.rejects(terminateOwnedDashboardForUpdate(ssh, lock), /ownership is unproven/)
+ assert.equal(
+ ssh.calls.some(command => /kill 333 &&/.test(command)),
+ false,
+ 'foreign process is never signalled'
+ )
+ assert.equal(
+ ssh.calls.some(command => /rm -f .*backend\.lock\.json/.test(command)),
+ false,
+ 'foreign ownership bytes remain untouched'
+ )
+})
+
+test('managed update drain rechecks the POSIX ownership record before signalling', async () => {
+ const lock = ownedLock()
+ const replacement = ownedLock({ pid: 334, spawnNonce: 'fedcba9876543210' })
+ let reads = 0
+ const ssh = fakeSsh([
+ [
+ /cat .*lock\.json/,
+ () => {
+ reads += 1
+
+ return JSON.stringify(reads === 1 ? lock : replacement)
+ }
+ ],
+ [/kill -0 333/, 'ALIVE'],
+ [/value="linux:"/, 'linux:123456\n'],
+ [/print\("OWNED"/, 'OWNED\n']
+ ])
+
+ await assert.rejects(terminateOwnedDashboardForUpdate(ssh, lock), /changed during process verification/)
+ assert.equal(
+ ssh.calls.some(command => /kill 333 &&/.test(command)),
+ false
+ )
+})
+
+test('managed update drain refuses Darwin termination because PID signals cannot be atomically bound', async () => {
+ const lock = ownedLock()
+ const rawLock = JSON.stringify(lock)
+ const ssh = fakeSsh([
+ [/cat .*lock\.json/, rawLock],
+ [/kill -0 333/, 'ALIVE'],
+ [/value="linux:"/, 'linux:123456\n'],
+ [/print\("OWNED"/, 'OWNED\n'],
+ [/pidfd_open/, 'REFUSED\n']
+ ])
+
+ await assert.rejects(terminateOwnedDashboardForUpdate(ssh, lock), /identity changed at the signal boundary/)
+ assert.equal(
+ ssh.calls.some(command => /^kill 333\b/.test(command.trim())),
+ false,
+ 'the final signal must stay inside the identity-checking helper'
+ )
+ const termination = ssh.calls.find(command => command.includes('identity_before_signal'))
+ const darwinStart = termination.indexOf('if (sys.platform=="darwin"):')
+ const darwinEnd = termination.indexOf('\n try:', darwinStart)
+ const darwinGuard = termination.slice(darwinStart, darwinEnd)
+ assert.match(darwinGuard, /DARWIN_UNAVAILABLE/)
+ assert.doesNotMatch(darwinGuard, /os\.kill\(pid,signal\.SIGTERM\)/)
+})
+
test('connect() respawns when the dashboard is wedged (alive pid, probe fails)', async () => {
const reuseToken = 'stored'
const lock = ownedLock({ tokenFingerprint: fingerprintToken(reuseToken) })
@@ -1199,7 +1476,7 @@ test('spawnRemoteDashboard streams the token over stdin, not argv/env', async ()
return 'YES\n'
}
- if (/python3 -c/.test(cmd)) {
+ if (/python3 -c/.test(cmd) && !/fcntl\.flock/.test(cmd)) {
return ''
}
@@ -1246,7 +1523,7 @@ test('spawnRemoteDashboard upload uses exclusive-create and O_NOFOLLOW', async (
return 'YES\n'
}
- if (/python3 -c/.test(cmd)) {
+ if (/python3 -c/.test(cmd) && !/fcntl\.flock/.test(cmd)) {
return ''
}
@@ -1268,7 +1545,7 @@ test('spawnRemoteDashboard upload uses exclusive-create and O_NOFOLLOW', async (
token: 'tk',
ownershipId: OWNERSHIP_ID
})
- const uploadCmd = calls.find(c => /python3 -c/.test(c))
+ const uploadCmd = calls.find(c => /python3 -c/.test(c) && !/fcntl\.flock/.test(c))
assert.ok(uploadCmd, 'must use python3 -c for token upload')
assert.match(uploadCmd, /O_EXCL/, 'upload must use O_EXCL to reject existing files')
assert.match(uploadCmd, /O_NOFOLLOW/, 'upload must use O_NOFOLLOW to reject symlinks')
@@ -1339,7 +1616,10 @@ test('readLockfile treats a log path outside the exact ownership and spawn path
})
test('cleanupStale never deletes a lock-supplied unexpected log path', async () => {
- const ssh = fakeSsh([[/print\("OWNED"/, 'OWNED\n']])
+ const ssh = fakeSsh([
+ [/print\("OWNED"/, 'OWNED\n'],
+ [cmd => /pidfd_open/.test(cmd), 'TERMINATED\n']
+ ])
await cleanupStale(ssh, OWNERSHIP_ID, ownedLock({ logPath: '~/.hermes/unrelated.log' }))
assert.ok(!ssh.calls.some(command => command.includes('unrelated.log')))
})
@@ -1404,6 +1684,7 @@ test('connect replaces an exact-owned backend only after authenticated stale pro
[/cat .*lock\.json/, JSON.stringify(lock)],
[/kill -0 333/, 'ALIVE'],
[/print\("OWNED"/, 'OWNED\n'],
+ [cmd => /pidfd_open/.test(cmd), 'TERMINATED\n'],
[/grep -q ssh-session-token-file/, 'YES\n'],
[/python3 -c/, ''],
[/setsid/, '999\n'],
@@ -1425,7 +1706,13 @@ test('connect replaces an exact-owned backend only after authenticated stale pro
)
assert.equal(result.reused, false)
+ // The kill goes through main's cleanupStale (ownership-proved SIGTERM with
+ // SIGKILL escalation, #91668) — the PR's python re-proof command shape is
+ // used by the managed-update path (terminateOwnedDashboardForUpdate), not
+ // by connect's stale replacement. Assert the CONTRACT: the owned pid was
+ // signalled and the record reclaimed.
assert.ok(ssh.calls.some(command => /kill 333\b/.test(command)))
+ assert.ok(ssh.calls.some(command => /rm -f .*backend\.lock\.json/.test(command)))
})
test('remote SSH ownership capability requires both secure bootstrap flags', async () => {
diff --git a/apps/desktop/electron/remote-lifecycle.ts b/apps/desktop/electron/remote-lifecycle.ts
index e1098bdbdec..74a3c4611b1 100644
--- a/apps/desktop/electron/remote-lifecycle.ts
+++ b/apps/desktop/electron/remote-lifecycle.ts
@@ -113,6 +113,10 @@ function isLockfileSkew(lock) {
return Boolean(lock) && (lock as any).skew === true
}
+function connectReservationPath(ownershipId) {
+ return `${ownershipDirectory(ownershipId)}/.connect.lock`
+}
+
function spawnLogPath(ownershipId, spawnNonce) {
return `${ownershipDirectory(ownershipId)}/${validateSpawnNonce(spawnNonce)}.log`
}
@@ -286,6 +290,83 @@ async function probeRemoteHermesHome(ssh) {
}
}
+const REMOTE_UPDATE_MARKER_PROBE = String.raw`
+import errno,os,re,sys
+from pathlib import Path
+
+home=Path(os.path.expanduser(sys.argv[1]))
+if home.parent.name=='profiles':home=home.parent.parent
+marker=home/'.hermes-update-in-progress'
+try:
+ with marker.open('rb') as stream:raw=stream.read(257)
+except FileNotFoundError:
+ print('CLEAR');raise SystemExit
+except OSError:
+ print('UNCERTAIN');raise SystemExit
+if len(raw)>256:
+ print('UNCERTAIN');raise SystemExit
+match=re.fullmatch(rb'([1-9][0-9]*)\r?\n([0-9]+)(?:\r?\n)?',raw)
+if not match:
+ print('UNCERTAIN');raise SystemExit
+try:
+ owner=int(match.group(1));lease=int(match.group(2))
+ if owner<1 or owner>4294967295 or lease>9007199254740991:raise ValueError()
+except ValueError:
+ print('UNCERTAIN');raise SystemExit
+try:
+ os.kill(owner,0)
+except ProcessLookupError:
+ print('CLEAR')
+except PermissionError:
+ print('LIVE:'+str(owner))
+except OSError as error:
+ if error.errno==errno.ESRCH:print('CLEAR')
+ elif error.errno==errno.EPERM:print('LIVE:'+str(owner))
+ else:print('UNCERTAIN')
+else:
+ print('LIVE:'+str(owner))
+`
+
+/**
+ * Refuse normal SSH reuse/spawn while the remote install is being mutated.
+ *
+ * This probe intentionally uses only the host's system Python and raw marker
+ * bytes; it never imports or executes code from the changing Hermes checkout.
+ * Absence or a well-formed, confirmed-dead owner is clear. Every parse, read,
+ * probe, or transport uncertainty fails closed so a Desktop relaunch cannot
+ * start `serve` beside an updater that survived the old app process.
+ */
+async function assertRemoteInstallUpdateClear(ssh, hermesHome) {
+ const home = assertSafeRemoteHome(hermesHome)
+ let observation = ''
+
+ try {
+ observation =
+ String(await ssh.exec(`python3 -c ${shq(REMOTE_UPDATE_MARKER_PROBE)} ${expandRemotePath(home)}`))
+ .trim()
+ .split(/\r?\n/)
+ .pop() || ''
+ } catch (cause) {
+ const error: any = new Error('Could not prove that the remote Hermes install is clear for SSH startup.')
+ error.kind = 'update-in-progress'
+ error.cause = cause
+ throw error
+ }
+
+ if (observation === 'CLEAR') {
+ return
+ }
+
+ const live = /^LIVE:([1-9][0-9]*)$/.exec(observation)
+ const error: any = new Error(
+ live
+ ? `Remote Hermes update process ${live[1]} is still running; SSH startup is paused.`
+ : 'The remote Hermes update marker is unreadable or malformed; refusing SSH startup.'
+ )
+ error.kind = 'update-in-progress'
+ throw error
+}
+
async function listRemoteHermesProfiles(ssh) {
const home = assertSafeRemoteHome(await probeRemoteHermesHome(ssh))
const dir = expandRemotePath(`${home}/profiles`)
@@ -315,6 +396,12 @@ function assertSafeRemoteHome(home) {
return value.replace(/\/+$/, '')
}
+function remoteInstallRoot(home) {
+ const value = assertSafeRemoteHome(home)
+ const profile = value.match(/^(.*)\/profiles\/[^/]+$/)
+ return profile ? profile[1] : value
+}
+
async function readLockfile(ssh, ownershipId) {
const lpath = lockfilePath(ownershipId)
let raw
@@ -391,6 +478,13 @@ async function readLockfile(ssh, ownershipId) {
}
}
+ if (
+ parsed.creationTime !== undefined &&
+ (typeof parsed.creationTime !== 'string' || !/^(?:linux:[0-9]+|darwin:[A-Za-z0-9 :+-]+)$/.test(parsed.creationTime))
+ ) {
+ return null
+ }
+
return parsed
}
@@ -433,6 +527,45 @@ async function remotePidAlive(ssh, pid) {
}
}
+// Stable kernel process-start identity used to fence a later managed-update
+// termination against PID recycling. Linux exposes boot-relative start ticks;
+// Darwin's `ps lstart` is only second-resolution, so the signal boundary also
+// re-reads the complete argv and random ownership nonce in the same remote
+// command. A same-second PID reuse with a forged/repeated nonce remains a
+// residual limitation. Failure is represented as an empty string so SSH mode
+// remains compatible on unusual POSIX hosts, but a managed update then refuses
+// to kill that unproved serve.
+async function remoteProcessCreationTime(ssh, pid) {
+ if (!pid || !Number.isInteger(Number(pid))) {
+ return ''
+ }
+
+ const script =
+ 'import subprocess,sys\n' +
+ `pid=${Number(pid)}\n` +
+ 'value=""\n' +
+ 'if sys.platform.startswith("linux"):\n' +
+ ' try:\n' +
+ ' raw=open(f"/proc/{pid}/stat","r",encoding="ascii").read()\n' +
+ ' fields=raw[raw.rfind(")")+2:].split()\n' +
+ ' value="linux:"+fields[19]\n' +
+ ' except (OSError,IndexError,UnicodeError):pass\n' +
+ 'elif sys.platform=="darwin":\n' +
+ ' try:\n' +
+ ' started=subprocess.check_output(["ps","-o","lstart=","-p",str(pid)],text=True).strip()\n' +
+ ' if started:value="darwin:"+started\n' +
+ ' except (OSError,subprocess.CalledProcessError):pass\n' +
+ 'print(value)'
+
+ try {
+ const value = String(await ssh.exec(`python3 -c ${shq(script)}`)).trim()
+
+ return /^(?:linux:[0-9]+|darwin:[A-Za-z0-9 :+-]+)$/.test(value) ? value : ''
+ } catch {
+ return ''
+ }
+}
+
// A pid is "provably ours" only if its remote cmdline carries our dashboard
// args — never kill a pid we can't positively identify as our dashboard.
async function pidIsOurDashboard(
@@ -597,6 +730,294 @@ async function disconnect(ssh, ownershipId) {
await cleanupStale(ssh, ownershipId, lock, pidAlive)
}
+function buildOwnedStaleTerminationCommand(lock, ownershipId) {
+ const pid = Number(lock.pid)
+ const expectedPath = shq(expandRemotePath(lock.hermesPath))
+ const expectedHome = lock.hermesHome ? shq(expandRemotePath(lock.hermesHome)) : "''"
+ const expectedToken = shq(expandRemotePath(spawnTokenPath(ownershipId, lock.spawnNonce)))
+ const nonce = shq(lock.spawnNonce)
+ const profile = shq(lock.profile || '')
+ const command = `$(ps -ww -o command= -p ${pid} 2>/dev/null || true)`
+ const executableMatch = lock.hermesHome
+ ? `case "$cmd" in *"$path"*|*"$home"*) ;; *) printf REFUSED; exit 0;; esac; `
+ : `case "$cmd" in *"$path"*) ;; *) printf REFUSED; exit 0;; esac; `
+ const identity =
+ `cmd=${command}; ` +
+ `path=${expectedPath}; home=${expectedHome}; token=${expectedToken}; nonce=${nonce}; profile=${profile}; ` +
+ executableMatch +
+ `case "$cmd" in *" serve"*|*" serve "*) ;; *) printf REFUSED; exit 0;; esac; ` +
+ `case "$cmd" in *"--ssh-owner-nonce $nonce"*) ;; *) printf REFUSED; exit 0;; esac; ` +
+ `case "$cmd" in *"--ssh-session-token-file $token"*) ;; *) printf REFUSED; exit 0;; esac; ` +
+ `[ -n "$profile" ] && case "$cmd" in *"--profile $profile"*) ;; *) printf REFUSED; exit 0;; esac; `
+
+ // Legacy records do not have creationTime. Re-read argv immediately before
+ // signaling in this same shell command; never use the earlier probe's PID
+ // verdict as authority for the kill.
+ return (
+ `${identity} kill ${pid} && ` +
+ `i=0; while kill -0 ${pid} 2>/dev/null; do ` +
+ `i=$((i+1)); [ "$i" -ge 50 ] && printf TIMEOUT && exit 0; sleep 0.1; done; printf TERMINATED`
+ )
+}
+
+function lockMatchesManagedUpdateScope(lock, expected) {
+ return Boolean(
+ lock &&
+ expected &&
+ lock.ownershipId === expected.ownershipId &&
+ lock.pid === expected.pid &&
+ lock.spawnNonce === expected.spawnNonce &&
+ lock.startedAt === expected.startedAt &&
+ lock.creationTime === expected.creationTime &&
+ lock.profile === expected.profile &&
+ lock.hermesPath === expected.hermesPath &&
+ lock.hermesHome === expected.hermesHome
+ )
+}
+
+function buildOwnedTerminationCommand(lock, ownershipId) {
+ const pid = Number(lock.pid)
+ const py = value => JSON.stringify(String(value || ''))
+ const expectedToken = spawnTokenPath(ownershipId, lock.spawnNonce)
+ const script = `
+import os,select,shlex,signal,subprocess,sys,time
+pid=${pid}
+expected_creation=${py(lock.creationTime)}
+expected_path=os.path.expanduser(${py(lock.hermesPath)})
+hermes_home=os.path.expanduser(${py(lock.hermesHome)})
+expected_entries={expected_path,os.path.join(hermes_home,"hermes-agent","venv","bin","hermes")}
+expected_token=os.path.expanduser(${py(expectedToken)})
+expected_profile=${py(lock.profile)}
+nonce=${py(lock.spawnNonce)}
+
+def creation():
+ if sys.platform.startswith("linux"):
+ try:
+ raw=open(f"/proc/{pid}/stat","r",encoding="ascii").read()
+ return "linux:"+raw[raw.rfind(")")+2:].split()[19]
+ except (OSError,IndexError,UnicodeError):return ""
+ if sys.platform=="darwin":
+ try:
+ value=subprocess.check_output(["ps","-o","lstart=","-p",str(pid)],text=True).strip()
+ return "darwin:"+value if value else ""
+ except (OSError,subprocess.CalledProcessError):return ""
+ return ""
+
+def argv():
+ try:
+ raw=open(f"/proc/{pid}/cmdline","rb").read()
+ return [part.decode("utf-8","surrogateescape") for part in raw.split(b"\\0") if part]
+ except OSError:
+ try:return shlex.split(subprocess.check_output(["ps","-ww","-o","command=","-p",str(pid)],text=True).strip())
+ except (OSError,subprocess.CalledProcessError,ValueError):return []
+
+def identity_before_signal():
+ # Darwin's lstart has one-second resolution. Read the start time and the
+ # complete argv in one ps call immediately before signalling; the random
+ # ownership nonce is the discriminator for a same-second PID reuse. A
+ # same-second reuse with a forged/repeated nonce remains a residual limitation.
+ if sys.platform=="darwin":
+ try:
+ line=subprocess.check_output(["ps","-ww","-p",str(pid),"-o","lstart=","-o","command="],text=True).strip()
+ prefix=expected_creation.removeprefix("darwin:")
+ if not prefix or not line.startswith(prefix):return "",[]
+ return "darwin:"+prefix,shlex.split(line[len(prefix):].strip())
+ except (OSError,subprocess.CalledProcessError,ValueError):return "",[]
+ return creation(),argv()
+
+def owned(args):
+ try:
+ serve=args.index("serve")
+ owner=args.index("--ssh-owner-nonce",serve+1)
+ token=args.index("--ssh-session-token-file",serve+1)
+ isolated=args.index("--isolated",serve+1)
+ profile_arg=args.index("--profile") if expected_profile else -1
+ direct=args[0] in expected_entries
+ python_entry=len(args)>1 and args[1] in expected_entries and os.path.basename(args[0]).startswith("python")
+ profile_ok=(args.count("--profile")==1 and profile_arg<serve and args[profile_arg+1]==expected_profile) if expected_profile else args.count("--profile")==0
+ return ((direct or python_entry or (args[token+1]==expected_token and profile_ok)) and
+ args.count("serve")==1 and args.count("--ssh-owner-nonce")==1 and
+ args.count("--ssh-session-token-file")==1 and args.count("--isolated")==1 and
+ isolated>serve and args[owner+1]==nonce and args[token+1]==expected_token and profile_ok)
+ except (ValueError,IndexError):return False
+
+pidfd=None
+if sys.platform.startswith("linux"):
+ if not hasattr(os,"pidfd_open") or not hasattr(signal,"pidfd_send_signal"):
+ print("UNAVAILABLE");sys.exit(2)
+ try:pidfd=os.pidfd_open(pid,0)
+ except ProcessLookupError:print("ALREADY_STOPPED");sys.exit(0)
+ except (OSError,PermissionError):print("UNAVAILABLE");sys.exit(2)
+
+try:
+ live_creation,live_args=identity_before_signal()
+ if live_creation!=expected_creation or not owned(live_args):
+ print("REFUSED");sys.exit(3)
+ if (sys.platform=="darwin"):
+ # Darwin has no pidfd-style signal binding. Refuse instead of accepting the
+ # residual PID-reuse window between ps and os.kill; reconnect will surface
+ # the still-running remote owner for an explicit retry.
+ print("DARWIN_UNAVAILABLE");sys.exit(2)
+ try:
+ if pidfd is not None:signal.pidfd_send_signal(pidfd,signal.SIGTERM)
+ else:os.kill(pid,signal.SIGTERM)
+ except ProcessLookupError:print("ALREADY_STOPPED");sys.exit(0)
+ if pidfd is not None:
+ poller=select.poll();poller.register(pidfd,select.POLLIN)
+ if not poller.poll(10000):print("TIMEOUT");sys.exit(4)
+ else:
+ deadline=time.monotonic()+10
+ while time.monotonic()<deadline:
+ try:os.kill(pid,0)
+ except ProcessLookupError:break
+ except PermissionError:print("UNAVAILABLE");sys.exit(2)
+ time.sleep(.1)
+ else:print("TIMEOUT");sys.exit(4)
+ print("TERMINATED")
+finally:
+ if pidfd is not None:os.close(pidfd)
+`.trim()
+
+ return `python3 -c ${shq(script)}`
+}
+
+// The updater's Python _MarkerMutex uses the marker's .mutex sidecar and an
+// advisory flock. Keep that same descriptor locked while the remote shell does
+// the marker check, spawns the backend, and publishes its initial lockfile.
+// Python keeps the descriptor close-on-exec by default and passes it explicitly
+// only to the intended outer shell; each detached child closes it before
+// execing Hermes.
+function withRemoteUpdateMutex(command, mutexPath) {
+ const script = `
+import fcntl,os,subprocess,sys
+mutex_path=sys.argv[1]
+payload=sys.argv[2]
+parent=os.path.dirname(mutex_path)
+if parent:os.makedirs(parent,exist_ok=True)
+fd=os.open(mutex_path,os.O_RDWR|os.O_CREAT|os.O_CLOEXEC,0o600)
+fcntl.flock(fd,fcntl.LOCK_EX)
+result=None
+try:
+ result=subprocess.run(["sh","-c",payload,"hermes-update-mutex",str(fd)],pass_fds=(fd,),check=False)
+finally:
+ os.close(fd)
+sys.exit(result.returncode if result is not None else 1)
+`.trim()
+
+ return `python3 -c ${shq(script)} ${shq(mutexPath)} ${shq(command)}`
+}
+
+/**
+ * Stop one Desktop-owned POSIX serve before an install update.
+ *
+ * This is deliberately stricter than stale cleanup. The in-memory scope is a
+ * snapshot of the ownership record that established the forward; immediately
+ * before signalling we re-read that record, compare its PID + kernel creation
+ * identity and random argv nonce, and prove the live argv is the exact
+ * isolated serve Desktop launched. Any absence, parse failure, replacement,
+ * or transport uncertainty refuses the kill. The lock is intentionally left
+ * behind: the post-update reconnect reclaims the now-dead exact record, while
+ * an old cleanup can never unlink a replacement owner.
+ */
+async function terminateOwnedDashboardForUpdate(ssh, expected) {
+ const ownershipId = validateOwnershipId(expected?.ownershipId)
+
+ if (!expected?.creationTime) {
+ const error: any = new Error('The remote POSIX serve has no process creation-time proof.')
+ error.kind = 'ownership-changed'
+ throw error
+ }
+ let lock = await readLockfile(ssh, ownershipId)
+
+ if (!lock || !lockMatchesManagedUpdateScope(lock, expected)) {
+ const error: any = new Error('The remote POSIX ownership record changed before the managed update.')
+ error.kind = 'ownership-changed'
+ throw error
+ }
+
+ if (!(await remotePidAlive(ssh, lock.pid))) {
+ return { pid: lock.pid, terminated: false, alreadyStopped: true }
+ }
+
+ if ((await remoteProcessCreationTime(ssh, lock.pid)) !== lock.creationTime) {
+ const error: any = new Error('The remote POSIX PID creation time no longer matches its ownership record.')
+ error.kind = 'ownership-changed'
+ throw error
+ }
+
+ if (
+ !(await pidIsOurDashboard(
+ ssh,
+ lock.pid,
+ lock.spawnNonce,
+ lock.hermesPath,
+ lock.hermesHome,
+ ownershipId,
+ lock.profile
+ ))
+ ) {
+ const error: any = new Error('Refusing to terminate a remote process whose Desktop ownership is unproven.')
+ error.kind = 'foreign-backend'
+ throw error
+ }
+
+ // Re-read after the argv proof. A concurrent/replacement writer cannot turn
+ // proof of the old record into authority over its new PID.
+ lock = await readLockfile(ssh, ownershipId)
+
+ if (!lock || !lockMatchesManagedUpdateScope(lock, expected)) {
+ const error: any = new Error('The remote POSIX ownership record changed during process verification.')
+ error.kind = 'ownership-changed'
+ throw error
+ }
+
+ if (
+ (await remoteProcessCreationTime(ssh, lock.pid)) !== lock.creationTime ||
+ !(await pidIsOurDashboard(
+ ssh,
+ lock.pid,
+ lock.spawnNonce,
+ lock.hermesPath,
+ lock.hermesHome,
+ ownershipId,
+ lock.profile
+ ))
+ ) {
+ const error: any = new Error('The remote POSIX process identity changed during managed update drain.')
+ error.kind = 'ownership-changed'
+ throw error
+ }
+
+ try {
+ const result = String(await ssh.exec(buildOwnedTerminationCommand(lock, ownershipId))).trim()
+
+ if (result === 'ALREADY_STOPPED') {
+ return { pid: lock.pid, terminated: false, alreadyStopped: true }
+ }
+ if (result !== 'TERMINATED') {
+ const error: any = new Error(
+ result === 'REFUSED'
+ ? 'The remote POSIX process identity changed at the signal boundary.'
+ : result === 'DARWIN_UNAVAILABLE'
+ ? 'Darwin cannot atomically bind a signal to the verified PID; refusing termination.'
+ : 'The remote POSIX signal boundary was unavailable.'
+ )
+ error.kind = result === 'REFUSED' || result === 'DARWIN_UNAVAILABLE' ? 'ownership-changed' : 'transient-transport-error'
+ throw error
+ }
+ } catch (cause: any) {
+ if (cause?.kind === 'ownership-changed') {
+ throw cause
+ }
+ const error: any = new Error('Could not terminate the Desktop-owned remote serve for update.')
+ error.kind = 'transient-transport-error'
+ error.cause = cause
+ throw error
+ }
+
+ return { pid: lock.pid, terminated: true, alreadyStopped: false }
+}
+
// Detach so the backend survives the SSH channel closing: setsid (Linux)
// starts a new session; macOS has no setsid, so fall back to nohup (HUP-immune;
// fd-detachment is already handled by </dev/null + redirect + &).
@@ -608,14 +1029,67 @@ function buildSpawnCommand(hermesPath, profile, opts: any = {}) {
const tokenArg = tokenFilePath ? ` --ssh-session-token-file ${expandRemotePath(tokenFilePath)}` : ''
const ownerArg = opts.spawnNonce ? ` --ssh-owner-nonce ${validateSpawnNonce(opts.spawnNonce)}` : ''
const subCmd = `serve --isolated --host 127.0.0.1 --port 0${tokenArg}${ownerArg}`
+ const marker = expandRemotePath(`${remoteInstallRoot(opts.hermesHome || '~/.hermes')}/.hermes-update-in-progress`)
+ const updateMutex = expandRemotePath(
+ `${remoteInstallRoot(opts.hermesHome || '~/.hermes')}/.hermes-update-in-progress.mutex`
+ )
+ // The marker probe, ownership reservation, process creation, and initial
+ // lockfile publication must be one remote command. A second Desktop process
+ // can therefore never observe an empty lock and spawn before this one records
+ // its PID. The reservation is an atomic mkdir and is reclaimed only when its
+ // owning remote shell is dead.
+ const markerClear =
+ `marker_clear() { if [ ! -e ${marker} ]; then return 0; fi; ` +
+ `if [ ! -r ${marker} ]; then return 1; fi; ` +
+ `owner=$(IFS= read -r owner < ${marker} && printf '%s' "$owner"); ` +
+ `case "$owner" in ''|*[!0-9]*) return 1;; esac; if kill -0 "$owner" 2>/dev/null; then return 1; fi; return 0; }`
const dashCmd =
`ulimit -n ${REMOTE_NOFILE_SOFT_LIMIT} 2>/dev/null || true; ` +
`exec env HERMES_DESKTOP=1 ${hermes} ${profileArgs}${subCmd}`
- return (
- `mkdir -p "$(dirname ${logPath})" && ` +
- `"$(command -v setsid || echo nohup)" sh -c ${shq(`${dashCmd} </dev/null >> ${logPath} 2>&1 & echo $!`)}`
+ const detachedShell = `eval "exec $1>&-"; ${dashCmd} </dev/null >> ${logPath} 2>&1 & echo $!`
+ const detachedSpawn = `child=$("$(command -v setsid || echo nohup)" sh -c ${shq(detachedShell)} hermes-update-child "$1" & echo $!)`
+
+ if (!opts.ownershipId || !opts.lockMetadata) {
+ return withRemoteUpdateMutex(
+ `${markerClear}; marker_clear || exit 75; ` +
+ `mkdir -p "$(dirname ${logPath})" && ` +
+ `${detachedSpawn}; ` +
+ `marker_clear || { kill "$child" 2>/dev/null || true; wait "$child" 2>/dev/null || true; exit 75; }; echo "$child"`,
+ updateMutex
+ )
+ }
+
+ const reservation = expandRemotePath(connectReservationPath(opts.ownershipId))
+ const lockPath = expandRemotePath(lockfilePath(opts.ownershipId))
+ const tokenPath = tokenFilePath ? expandRemotePath(tokenFilePath) : ''
+ const ownerPath = `${reservation}/owner`
+ const metadata = JSON.stringify({ schemaVersion: LOCKFILE_SCHEMA_VERSION, ...opts.lockMetadata, pid: '__PID__' })
+ const reservationNonce = validateSpawnNonce(opts.reservationNonce || crypto.randomBytes(8).toString('hex'))
+
+ return withRemoteUpdateMutex(
+ `umask 077 && mkdir -p "$(dirname ${reservation})"; ` +
+ `reservation=${shq(reservation)}; lock=${shq(lockPath)}; owner_file=${shq(ownerPath)}; ` +
+ `reservation_nonce=${shq(reservationNonce)}; ` +
+ `i=0; while ! mkdir "$reservation" 2>/dev/null; do ` +
+ `owner_data=$(cat "$owner_file" 2>/dev/null || true); owner_pid=${'${owner_data%%:*}'}; ` +
+ `case "$owner_pid" in ''|*[!0-9]*) ;; *) kill -0 "$owner_pid" 2>/dev/null || { rm -rf "$reservation"; continue; };; esac; ` +
+ `i=$((i+1)); [ "$i" -ge 600 ] && exit 75; sleep 0.05; done; ` +
+ `printf '%s:%s' "$$" "$reservation_nonce" > "$owner_file"; ` +
+ `trap 'rm -rf "$reservation"' EXIT; ` +
+ `if [ -f "$lock" ]; then ` +
+ `existing_pid=$(sed -n 's/.*"pid":\\([0-9][0-9]*\\).*/\\1/p' "$lock" | head -n 1); ` +
+ `case "$existing_pid" in ''|*[!0-9]*) rm -f "$lock";; *) ` +
+ `if kill -0 "$existing_pid" 2>/dev/null; then ${tokenPath ? `rm -f ${tokenPath}; ` : ''}printf EXISTING; exit 0; fi; rm -f "$lock";; esac; fi; ` +
+ `${markerClear}; marker_clear || exit 75; mkdir -p "$(dirname ${logPath})" && ` +
+ `${detachedSpawn}; ` +
+ `marker_clear || { kill "$child" 2>/dev/null || true; wait "$child" 2>/dev/null || true; exit 75; }; ` +
+ `lock_json=${shq(metadata)}; lock_json=\${lock_json//__PID__/$child}; ` +
+ `temporary_lock="\${lock}.${reservationNonce}.tmp"; ` +
+ `printf '%s' "$lock_json" > "$temporary_lock" && mv -f "$temporary_lock" "$lock" || { kill "$child" 2>/dev/null || true; wait "$child" 2>/dev/null || true; exit 76; }; ` +
+ `echo "$child"`,
+ updateMutex
)
}
@@ -668,7 +1142,10 @@ async function scrapeReadyPort(ssh, logPath, { timeoutMs = DEFAULT_READY_TIMEOUT
throw err
}
-async function spawnRemoteDashboard(ssh, { hermesPath, profile, token, ownershipId }) {
+async function spawnRemoteDashboard(
+ ssh,
+ { hermesPath, profile, token, ownershipId, hermesHome = '~/.hermes', assertInstallClear = async () => {} }
+) {
if (!(await remoteSupportsSshOwnership(ssh, hermesPath))) {
const err: any = new Error(
'The remote Hermes install does not support --ssh-session-token-file and --ssh-owner-nonce. ' +
@@ -728,7 +1205,31 @@ async function spawnRemoteDashboard(ssh, { hermesPath, profile, token, ownership
let out
try {
- out = await ssh.exec(buildSpawnCommand(hermesPath, profile, { spawnNonce, tokenFilePath, logPath }))
+ // Close the marker race after the token-file write and immediately before
+ // process creation. The caller's probe imports no changing checkout code.
+ await assertInstallClear()
+ out = await ssh.exec(
+ buildSpawnCommand(hermesPath, profile, {
+ spawnNonce,
+ tokenFilePath,
+ logPath,
+ hermesHome,
+ ownershipId,
+ reservationNonce: spawnNonce,
+ lockMetadata: {
+ ownershipId,
+ spawnNonce,
+ port: 0,
+ profile,
+ hermesPath,
+ hermesHome,
+ logPath,
+ tokenFingerprint: fingerprintToken(token),
+ protocolVersion: PROTOCOL_VERSION,
+ startedAt: new Date().toISOString()
+ }
+ })
+ )
} catch (error) {
try {
await ssh.exec(`rm -f ${expandRemotePath(tokenFilePath)}`)
@@ -739,13 +1240,17 @@ async function spawnRemoteDashboard(ssh, { hermesPath, profile, token, ownership
throw error
}
- const pid = parseInt(
- String(out || '')
- .trim()
- .split('\n')
- .pop(),
- 10
- )
+ const outputLines = String(out || '')
+ .trim()
+ .split('\n')
+ .map(line => line.trim())
+ .filter(Boolean)
+
+ if (outputLines.at(-1) === 'EXISTING') {
+ return { existing: true }
+ }
+
+ const pid = parseInt(outputLines.at(-1) || '', 10)
if (!Number.isInteger(pid) || pid <= 0) {
try {
@@ -823,6 +1328,28 @@ async function adoptOwnedServedToken(adoptServedToken, baseUrl, expectedToken, s
return token
}
+async function waitForRemoteSpawnCompletion(ssh, ownershipId, timeoutMs) {
+ const deadline = Date.now() + timeoutMs
+
+ while (Date.now() < deadline) {
+ const lock = await readLockfile(ssh, ownershipId)
+
+ if (!lock) {
+ return false
+ }
+
+ if (lock.port > 0) {
+ return true
+ }
+
+ await new Promise(resolve => setTimeout(resolve, READY_POLL_INTERVAL_MS))
+ }
+
+ const error: any = new Error('Timed out waiting for the concurrent SSH connection to publish its backend.')
+ error.kind = 'spawn-failed'
+ throw error
+}
+
async function connect(deps) {
const {
ssh,
@@ -844,6 +1371,8 @@ async function connect(deps) {
assertBootstrapNotSuperseded(signal)
const platform = await probeRemotePlatform(ssh)
log(`remote platform ${platform.os}/${platform.arch}`)
+ const hermesHome = await probeRemoteHermesHome(ssh)
+ await assertRemoteInstallUpdateClear(ssh, hermesHome)
const hermesPath = await locateHermes(ssh, remoteHermesPath)
log(`located hermes at ${hermesPath}`)
const hermesVersion = await probeHermesVersion(ssh, hermesPath)
@@ -853,7 +1382,6 @@ async function connect(deps) {
}
const reuseToken = deps.reuseToken || ''
- const hermesHome = await probeRemoteHermesHome(ssh)
const lock = await readLockfile(ssh, ownershipId)
if (isLockfileSkew(lock)) {
@@ -902,7 +1430,14 @@ async function connect(deps) {
lock.hermesHome === hermesHome
if (reusable) {
+ const creationTime = lock.creationTime || (await remoteProcessCreationTime(ssh, lock.pid))
+
+ if (creationTime && !lock.creationTime) {
+ await writeLockfile(ssh, ownershipId, { ...lock, creationTime })
+ lock.creationTime = creationTime
+ }
assertBootstrapNotSuperseded(signal)
+ await assertRemoteInstallUpdateClear(ssh, hermesHome)
const localPort = await openForward(deps, lock.port)
try {
@@ -921,6 +1456,7 @@ async function connect(deps) {
if (reuseClassification === 'authenticated-stale') {
assertBootstrapNotSuperseded(signal)
await cancelForwardSafe(deps, localPort, lock.port)
+ await assertRemoteInstallUpdateClear(ssh, hermesHome)
await cleanupStale(ssh, ownershipId, lock)
} else if (reuseClassification === 'authenticated-ok') {
const token = await adoptOwnedServedToken(
@@ -948,7 +1484,10 @@ async function connect(deps) {
hermesVersion,
ownershipId,
spawnNonce: lock.spawnNonce,
- logPath: lock.logPath
+ logPath: lock.logPath,
+ hermesHome,
+ startedAt: lock.startedAt,
+ creationTime: lock.creationTime || ''
}
} else {
const error: any = new Error('SSH reuse proof returned an invalid classification.')
@@ -961,21 +1500,45 @@ async function connect(deps) {
}
} else {
assertBootstrapNotSuperseded(signal)
+ await assertRemoteInstallUpdateClear(ssh, hermesHome)
await cleanupStale(ssh, ownershipId, lock, pidAlive)
}
}
assertBootstrapNotSuperseded(signal)
+ await assertRemoteInstallUpdateClear(ssh, hermesHome)
const spawnToken = mintToken()
- const { pid, spawnNonce, logPath, tokenFilePath } = await spawnRemoteDashboard(ssh, {
+ const spawned = await spawnRemoteDashboard(ssh, {
hermesPath,
profile,
token: spawnToken,
- ownershipId
+ ownershipId,
+ hermesHome,
+ assertInstallClear: () => assertRemoteInstallUpdateClear(ssh, hermesHome)
})
+ if (spawned.existing) {
+ if (!reuseToken) {
+ const error: any = new Error(
+ 'Another SSH connection owns this remote dashboard; a session token is required to reuse it.'
+ )
+ error.kind = 'remote-ownership-contended'
+ throw error
+ }
+
+ const published = await waitForRemoteSpawnCompletion(ssh, ownershipId, readyTimeoutMs)
+
+ if (!published) {
+ return connect({ ...deps, reuseToken })
+ }
+
+ return connect({ ...deps, reuseToken })
+ }
+
+ const { pid, spawnNonce, logPath, tokenFilePath } = spawned
log(`spawned remote dashboard pid=${pid}`)
+ const creationTime = await remoteProcessCreationTime(ssh, pid)
const ownedSpawn = {
ownershipId,
@@ -988,7 +1551,8 @@ async function connect(deps) {
logPath,
tokenFingerprint: fingerprintToken(spawnToken),
protocolVersion: PROTOCOL_VERSION,
- startedAt: new Date().toISOString()
+ startedAt: new Date().toISOString(),
+ ...(creationTime ? { creationTime } : {})
}
let localPort = 0
@@ -1035,7 +1599,10 @@ async function connect(deps) {
hermesVersion,
ownershipId,
spawnNonce,
- logPath
+ logPath,
+ hermesHome,
+ startedAt: ownedSpawn.startedAt,
+ creationTime: ownedSpawn.creationTime || ''
}
} catch (error) {
if (localPort && remotePort) {
@@ -1055,10 +1622,12 @@ async function connect(deps) {
export {
adoptOwnedServedToken,
+ assertRemoteInstallUpdateClear,
buildSpawnCommand,
classifySshReuseProof,
cleanupStale,
connect,
+ connectReservationPath,
DEFAULT_READY_TIMEOUT_MS,
disconnect,
expandRemotePath,
@@ -1081,6 +1650,7 @@ export {
READY_RE,
REMOTE_LOCK_DIR,
remotePidAlive,
+ remoteProcessCreationTime,
remoteSupportsSshOwnership,
removeLockfile,
scrapeReadyPort,
@@ -1089,6 +1659,7 @@ export {
spawnRemoteDashboard,
spawnTokenPath,
SUPPORTED_REMOTE_OS,
+ terminateOwnedDashboardForUpdate,
validateRemotePath,
writeLockfile
}
diff --git a/apps/desktop/electron/windows-remote-lifecycle.test.ts b/apps/desktop/electron/windows-remote-lifecycle.test.ts
index b63d9c69bff..48df428834f 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.test.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.test.ts
@@ -4,18 +4,62 @@ import crypto from 'node:crypto'
import { test } from 'vitest'
import {
+ assertWindowsRemoteInstallUpdateClear,
+ atomicWindowsSpawnCommand,
buildWindowsInteractiveCommand,
+ connectWindowsRemote,
detectRemotePlatform,
encodedPowerShell,
helperCommand,
powerShellCommand,
+ probeWindowsRemote,
psLiteral,
reusableWindowsLock,
+ terminateOwnedWindowsDashboardForUpdate,
validLock
} from './windows-remote-lifecycle'
const ownershipId = '0123456789abcdef0123456789abcdef'
+test('Windows spawn holds the update mutex across marker check and helper spawn', () => {
+ const command = atomicWindowsSpawnCommand({
+ hermesHome: 'C:\\Users\\andre\\.hermes',
+ python: 'C:\\Users\\andre\\.hermes\\python.exe'
+ })
+
+ const encoded = command.match(/-EncodedCommand\s+([^\s]+)$/)?.[1]
+ const script = encoded ? Buffer.from(encoded, 'base64').toString('utf16le') : ''
+ assert.match(script, /\.hermes-update-in-progress/)
+ assert.match(script, /\$mutexPath=\$marker\+"\.mutex"/)
+ assert.match(script, /\.Lock\(0,1\)/)
+ assert.match(script, /windows_ssh_runtime.*spawn/)
+ assert.match(script, /remote update marker is present/)
+})
+
+test('Windows spawn publishes the initial ownership record before releasing the mutex', () => {
+ const command = atomicWindowsSpawnCommand(
+ {
+ hermesHome: 'C:\\Users\\andre\\.hermes',
+ python: 'C:\\Users\\andre\\.hermes\\python.exe'
+ },
+ {
+ ownershipId,
+ spawnNonce: '0123456789abcdef',
+ profile: 'default',
+ hermesPath: 'C:\\Hermes\\hermes.exe',
+ hermesHome: 'C:\\Users\\andre\\.hermes',
+ tokenFingerprint: 'a'.repeat(32),
+ startedAt: '2026-07-14T00:00:00.000Z'
+ }
+ )
+ const encoded = command.split(' ').at(-1) || ''
+ const script = encoded ? Buffer.from(encoded, 'base64').toString('utf16le') : ''
+
+ assert.match(script, /read-lock/)
+ assert.match(script, /write-lock/)
+ assert.ok(script.indexOf('write-lock') < script.indexOf('Unlock'))
+})
+
function sshWith(exec) {
return { exec }
}
@@ -26,6 +70,100 @@ test('PowerShell transport uses UTF-16LE encoded commands and literal escaping',
assert.match(powerShellCommand('Write-Output ok'), /^powershell\.exe -NoProfile -NonInteractive .* -EncodedCommand /)
})
+test('Windows relaunch gate refuses live and uncertain markers before executing the remote runtime', async () => {
+ for (const observation of ['LIVE:4242', 'UNCERTAIN']) {
+ const scripts: string[] = []
+ const ssh = sshWith(async command => {
+ const script = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')
+ scripts.push(script)
+
+ if (script.includes('Get-Command hermes.exe')) {
+ return JSON.stringify({
+ os: 'Windows',
+ arch: 'AMD64',
+ hermesHome: 'C:\\Users\\alice\\.hermes',
+ hermesPath: 'C:\\Hermes\\hermes.exe',
+ python: 'C:\\Hermes\\python.exe'
+ })
+ }
+ if (script.includes('.hermes-update-in-progress')) {
+ return observation
+ }
+ throw new Error(`unexpected command after update gate: ${script}`)
+ })
+
+ await assert.rejects(
+ () =>
+ connectWindowsRemote({
+ ssh,
+ ownershipId,
+ pickLocalPort: async () => 50000,
+ forward: async () => {},
+ cancelForward: async () => {},
+ waitForHermes: async () => {},
+ probeReuseProof: async () => 'authenticated-ok'
+ }),
+ (error: any) => error.kind === 'update-in-progress'
+ )
+ assert.equal(
+ scripts.some(script => script.includes('hermes_cli.windows_ssh_runtime')),
+ false
+ )
+ }
+})
+
+test('Windows relaunch gate uses strict install-wide marker parsing and fail-closed PID probing', async () => {
+ let script = ''
+ const ssh = sshWith(async command => {
+ script = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')
+
+ return 'CLEAR'
+ })
+
+ await assertWindowsRemoteInstallUpdateClear(ssh, 'C:\\Users\\alice\\.hermes\\profiles\\research')
+ assert.match(script, /\.hermes-update-in-progress/)
+ assert.match(script, /Split-Path -Leaf \$parent.*profiles/)
+ assert.match(script, /UTF8Encoding.*true/)
+ assert.match(script, /\\A\(\[1-9\]/)
+ assert.match(script, /GetProcessById/)
+ assert.doesNotMatch(script, /ErrorAction SilentlyContinue/)
+})
+
+test('Windows probe validates Hermes and Python topology before selection', async () => {
+ let script = ''
+ await probeWindowsRemote(
+ sshWith(async command => {
+ script = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')
+ return JSON.stringify({
+ os: 'Windows',
+ arch: 'AMD64',
+ hermesHome: 'C:\\\\h',
+ hermesPath: 'C:\\\\h\\\\hermes.exe',
+ python: 'C:\\\\h\\\\python.exe'
+ })
+ }),
+ 'C:\\\\h\\\\hermes.exe'
+ )
+
+ const explicitCheck = script.indexOf('if($explicit){Assert-NoReparse $explicit $false;')
+ const explicitPythonCheck = script.indexOf('Assert-NoReparse $explicitPython $false')
+ const fallbackJoin = script.indexOf('Join-Path $hermesHome')
+ const candidatePythonCheck = script.indexOf('Assert-NoReparse $candidatePython $true')
+ const candidateSelection = script.indexOf('Get-Item -LiteralPath $candidate')
+ const pythonJoin = script.indexOf('$python=[IO.Path]::Combine')
+ const pythonCheck = script.indexOf('Assert-NoReparse $python $false')
+ const output = script.indexOf('[ordered]@{')
+
+ assert.ok(explicitCheck >= 0)
+ assert.ok(explicitCheck < explicitPythonCheck)
+ assert.ok(explicitPythonCheck < fallbackJoin)
+ assert.ok(candidatePythonCheck >= 0)
+ assert.ok(candidatePythonCheck < candidateSelection)
+ assert.ok(pythonJoin >= 0)
+ assert.ok(pythonJoin < pythonCheck)
+ assert.ok(pythonCheck < output)
+})
+
test('platform detection preserves POSIX and falls back to Windows PowerShell', async () => {
assert.deepEqual(await detectRemotePlatform(sshWith(async () => 'Linux\nx86_64\n')), { os: 'Linux', arch: 'x86_64' })
const calls: string[] = []
@@ -147,3 +285,84 @@ test('Windows integrated terminal uses encoded PowerShell and preserves cwd as l
assert.match(script, /Set-Location -LiteralPath 'C:\\Users\\O''Brien\\repo'/)
assert.match(script, /powershell\.exe -NoLogo/)
})
+
+test('managed update drain preserves a Windows owner when creation time does not match', async () => {
+ const lock = {
+ schemaVersion: 2,
+ protocolVersion: 1,
+ ownershipId,
+ spawnNonce: '0123456789abcdef',
+ pid: 10,
+ creationTimeNs: '1784219690452757504',
+ port: 1234,
+ profile: 'default',
+ tokenFingerprint: 'a'.repeat(32),
+ hermesPath: 'C:\\h\\hermes.exe',
+ hermesHome: 'C:\\h'
+ }
+ const operations: string[] = []
+ const ssh = sshWith(async command => {
+ const script = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')
+ operations.push(script)
+
+ return JSON.stringify(lock)
+ })
+
+ await assert.rejects(
+ terminateOwnedWindowsDashboardForUpdate(
+ ssh,
+ { python: 'C:\\h\\python.exe' },
+ { ...lock, creationTimeNs: '1784219690452757505' }
+ ),
+ /ownership record changed/
+ )
+ assert.equal(
+ operations.some(operation => operation.includes("'terminate'")),
+ false
+ )
+ assert.equal(
+ operations.some(operation => operation.includes("'remove-lock'")),
+ false
+ )
+})
+
+test('managed update drain rechecks Windows PID/create-time ownership before exact terminate', async () => {
+ const lock = {
+ schemaVersion: 2,
+ protocolVersion: 1,
+ ownershipId,
+ spawnNonce: '0123456789abcdef',
+ pid: 10,
+ creationTimeNs: '1784219690452757504',
+ port: 1234,
+ profile: 'default',
+ tokenFingerprint: 'a'.repeat(32),
+ hermesPath: 'C:\\h\\hermes.exe',
+ hermesHome: 'C:\\h'
+ }
+ const operations: string[] = []
+ const ssh = sshWith(async command => {
+ const script = Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')
+ operations.push(script)
+
+ if (script.includes("'read-lock'")) {
+ return JSON.stringify(lock)
+ }
+ if (script.includes("'process-state'")) {
+ return JSON.stringify({ alive: true, owned: true, indeterminate: false })
+ }
+
+ return JSON.stringify({ ok: true })
+ })
+
+ const result = await terminateOwnedWindowsDashboardForUpdate(ssh, { python: 'C:\\h\\python.exe' }, lock)
+
+ assert.equal(result.terminated, true)
+ assert.equal(operations.filter(operation => operation.includes("'read-lock'")).length, 2)
+ assert.equal(operations.filter(operation => operation.includes("'process-state'")).length, 2)
+ assert.equal(operations.filter(operation => operation.includes("'terminate'")).length, 1)
+ assert.equal(
+ operations.some(operation => operation.includes("'remove-lock'")),
+ false
+ )
+})
diff --git a/apps/desktop/electron/windows-remote-lifecycle.ts b/apps/desktop/electron/windows-remote-lifecycle.ts
index 40d89b3ece4..fce6ec46701 100644
--- a/apps/desktop/electron/windows-remote-lifecycle.ts
+++ b/apps/desktop/electron/windows-remote-lifecycle.ts
@@ -24,26 +24,150 @@ async function probeWindowsRemote(ssh, explicitHermesPath = '') {
const script = [
'$ErrorActionPreference="Stop"',
+ 'function Assert-NoReparse([string]$candidate,[bool]$allowMissing=$false){',
+ 'if([string]::IsNullOrWhiteSpace($candidate)){return}',
+ '$current=[IO.Path]::GetFullPath($candidate);$first=$true',
+ 'while($true){',
+ 'try{$item=Get-Item -LiteralPath $current -Force -ErrorAction Stop}',
+ 'catch [Management.Automation.ItemNotFoundException]{if(-not $allowMissing -and $first){throw "Path was not found: $candidate"};$parent=[IO.Path]::GetDirectoryName($current);if(-not $parent -or $parent -eq $current){break};$current=$parent;$first=$false;continue}',
+ 'if(($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){throw "Path contains a link or reparse point: $current"}',
+ '$parent=$item.Parent.FullName;if(-not $parent -or $parent -eq $current){break};$current=$parent;$first=$false',
+ '}',
+ '}',
`$explicit=${explicit}`,
+ 'if($explicit){Assert-NoReparse $explicit $false;$explicitPython=[IO.Path]::Combine([IO.Path]::GetDirectoryName($explicit), "python.exe");Assert-NoReparse $explicitPython $false}',
'$hermesHome=$env:HERMES_HOME',
'if(-not $hermesHome){$hermesHome=Join-Path $env:LOCALAPPDATA "hermes"}',
+ 'Assert-NoReparse $hermesHome $true',
+ '$candidate=[IO.Path]::Combine($hermesHome, "hermes-agent\\venv\\Scripts\\hermes.exe")',
+ '$candidatePython=[IO.Path]::Combine([IO.Path]::GetDirectoryName($candidate), "python.exe")',
+ 'Assert-NoReparse $candidate $true',
+ 'Assert-NoReparse $candidatePython $true',
+ '$profileCandidate=[IO.Path]::Combine($HOME, "hermes-agent\\.venv\\Scripts\\hermes.exe")',
+ '$profileCandidatePython=[IO.Path]::Combine([IO.Path]::GetDirectoryName($profileCandidate), "python.exe")',
+ 'Assert-NoReparse $profileCandidate $true',
+ 'Assert-NoReparse $profileCandidatePython $true',
+ '$fallbackHomeCandidate=Join-Path $hermesHome "hermes-agent\\venv\\Scripts\\hermes.exe"',
+ '$fallbackProfileCandidate=Join-Path $HOME "hermes-agent\\.venv\\Scripts\\hermes.exe"',
'$candidates=@()',
'if($explicit){$candidates+=$explicit}',
'$cmd=Get-Command hermes.exe -ErrorAction SilentlyContinue',
- 'if($cmd){$candidates+=$cmd.Source}',
- '$candidates+=(Join-Path $hermesHome "hermes-agent\\venv\\Scripts\\hermes.exe")',
- '$candidates+=(Join-Path $HOME "hermes-agent\\.venv\\Scripts\\hermes.exe")',
- '$hermes=$candidates|Where-Object{Test-Path -LiteralPath $_ -PathType Leaf}|Select-Object -First 1',
+ 'if($cmd){Assert-NoReparse $cmd.Source $true;$cmdPython=[IO.Path]::Combine([IO.Path]::GetDirectoryName($cmd.Source), "python.exe");Assert-NoReparse $cmdPython $true;$candidates+=$cmd.Source}',
+ '$candidates+=$fallbackHomeCandidate',
+ '$candidates+=$fallbackProfileCandidate',
+ '$hermes=$null',
+ 'foreach($candidate in $candidates){Assert-NoReparse $candidate $true;$candidatePython=[IO.Path]::Combine([IO.Path]::GetDirectoryName($candidate), "python.exe");Assert-NoReparse $candidatePython $true;try{$item=Get-Item -LiteralPath $candidate -Force -ErrorAction Stop;if(($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq 0 -and -not $item.PSIsContainer){$hermes=$item.FullName;break}}catch [Management.Automation.ItemNotFoundException]{continue}}',
'if(-not $hermes){throw "Hermes is not installed on the remote Windows host."}',
+ 'Assert-NoReparse $hermes $false',
'if($explicit -and $hermes -ne $explicit){throw "The configured Hermes path is not an executable file."}',
- '$python=Join-Path (Split-Path $hermes) "python.exe"',
- 'if(-not (Test-Path -LiteralPath $python -PathType Leaf)){throw "The remote Hermes Python runtime was not found."}',
+ '$python=[IO.Path]::Combine([IO.Path]::GetDirectoryName($hermes), "python.exe")',
+ 'Assert-NoReparse $python $false',
'[ordered]@{os="Windows";arch=$env:PROCESSOR_ARCHITECTURE;hermesHome=$hermesHome;hermesPath=$hermes;python=$python}|ConvertTo-Json -Compress'
].join(';')
return JSON.parse((await ssh.exec(powerShellCommand(script))).trim())
}
+function windowsUpdateMarkerProbeCommand(hermesHome) {
+ const script = [
+ '$ErrorActionPreference="Stop"',
+ `Add-Type -TypeDefinition @'
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+public static class HermesMarkerNoFollow {
+ [DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
+ private static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
+ public static FileStream OpenRead(string name) {
+ var handle=CreateFile(name, 0x80000000, 0x00000007, IntPtr.Zero, 3, 0x00200000, IntPtr.Zero);
+ if(handle.IsInvalid) Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
+ return new FileStream(handle, FileAccess.Read);
+ }
+}
+'@
+`,
+ 'function Assert-NoReparse([string]$candidate,[bool]$allowMissing=$false){',
+ 'if([string]::IsNullOrWhiteSpace($candidate)){return}',
+ '$current=[IO.Path]::GetFullPath($candidate);$first=$true',
+ 'while($true){',
+ 'try{$item=Get-Item -LiteralPath $current -Force -ErrorAction Stop}',
+ 'catch [Management.Automation.ItemNotFoundException]{if(-not $allowMissing -and $first){throw "Path was not found: $candidate"};$parent=[IO.Path]::GetDirectoryName($current);if(-not $parent -or $parent -eq $current){break};$current=$parent;$first=$false;continue}',
+ 'if(($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){throw "Path contains a link or reparse point: $current"}',
+ '$parent=$item.Parent.FullName;if(-not $parent -or $parent -eq $current){break};$current=$parent;$first=$false',
+ '}',
+ '}',
+ `$home=${psLiteral(hermesHome)}`,
+ '$installRoot=$home',
+ '$parent=Split-Path -Parent $home',
+ 'if((Split-Path -Leaf $parent) -ieq "profiles"){$installRoot=Split-Path -Parent $parent}',
+ '$marker=Join-Path $installRoot ".hermes-update-in-progress"',
+ '$result="UNCERTAIN"',
+ '$stream=$null;$memory=$null',
+ 'try{',
+ 'Assert-NoReparse $marker $true',
+ 'if(-not (Test-Path -LiteralPath $marker -PathType Leaf)){$result="CLEAR"}else{$stream=[HermesMarkerNoFollow]::OpenRead($marker)',
+ 'Assert-NoReparse $marker $false',
+ '$memory=New-Object IO.MemoryStream;$stream.CopyTo($memory);$bytes=$memory.ToArray()',
+ 'if($bytes.Length -le 256){',
+ '$utf8=[Text.UTF8Encoding]::new($false,$true)',
+ '$text=$utf8.GetString($bytes)',
+ "$match=[regex]::Match($text,'\\A([1-9][0-9]*)\\r?\\n([0-9]+)(?:\\r?\\n)?\\z')",
+ '[uint32]$ownerPid=0',
+ '[uint64]$lease=0',
+ '$valid=$match.Success',
+ 'if($valid){$valid=[uint32]::TryParse($match.Groups[1].Value,[Globalization.NumberStyles]::None,[Globalization.CultureInfo]::InvariantCulture,[ref]$ownerPid)}',
+ 'if($valid){$valid=[uint64]::TryParse($match.Groups[2].Value,[Globalization.NumberStyles]::None,[Globalization.CultureInfo]::InvariantCulture,[ref]$lease)}',
+ 'if($valid -and $lease -le 9007199254740991){',
+ 'try{',
+ '$process=[Diagnostics.Process]::GetProcessById([int]$ownerPid)',
+ 'try{if($process.HasExited){$result="CLEAR"}else{$result="LIVE:"+[string]$ownerPid}}finally{$process.Dispose()}',
+ '}catch [ArgumentException]{$result="CLEAR"} catch{$result="UNCERTAIN"}',
+ '}',
+ '}',
+ '}}catch [IO.FileNotFoundException]{$result="CLEAR"}catch{$result="UNCERTAIN"}finally{if($memory){$memory.Dispose()};if($stream){$stream.Dispose()}}',
+ 'Write-Output $result'
+ ].join(';')
+
+ return powerShellCommand(script)
+}
+
+/**
+ * Fail-closed install marker gate for a fresh/relaunched Desktop process.
+ * This uses only PowerShell/.NET and therefore never imports the remote
+ * checkout while an updater may be replacing it.
+ */
+async function assertWindowsRemoteInstallUpdateClear(ssh, hermesHome) {
+ let observation = ''
+
+ try {
+ observation =
+ String(await ssh.exec(windowsUpdateMarkerProbeCommand(hermesHome)))
+ .replace(/^\uFEFF/, '')
+ .trim()
+ .split(/\r?\n/)
+ .pop() || ''
+ } catch (cause) {
+ const error: any = new Error('Could not prove that the remote Hermes install is clear for SSH startup.')
+ error.kind = 'update-in-progress'
+ error.cause = cause
+ throw error
+ }
+
+ if (observation === 'CLEAR') {
+ return
+ }
+
+ const live = /^LIVE:([1-9][0-9]*)$/.exec(observation)
+ const error: any = new Error(
+ live
+ ? `Remote Hermes update process ${live[1]} is still running; SSH startup is paused.`
+ : 'The remote Hermes update marker is unreadable or malformed; refusing SSH startup.'
+ )
+ error.kind = 'update-in-progress'
+ throw error
+}
+
const TRANSPORT_KINDS = new Set([
SSH_ERROR.AUTH_FAILED,
SSH_ERROR.HOST_KEY_CHANGED,
@@ -120,6 +244,64 @@ async function helper(ssh, runtime, operation, args = [], stdinData?) {
return parsed
}
+function atomicWindowsSpawnCommand(runtime, reservation: any = {}) {
+ const argv = [runtime.python, '-m', 'hermes_cli.windows_ssh_runtime', 'spawn']
+ const helper = operation => [runtime.python, '-m', 'hermes_cli.windows_ssh_runtime', operation]
+ const script = [
+ '$ErrorActionPreference="Stop"',
+ `$home=${psLiteral(runtime.hermesHome)}`,
+ '$installRoot=$home',
+ '$parent=Split-Path -Parent $home',
+ 'if((Split-Path -Leaf $parent) -ieq "profiles"){$installRoot=Split-Path -Parent $parent}',
+ '$marker=Join-Path $installRoot ".hermes-update-in-progress"',
+ '$mutexPath=$marker+".mutex"',
+ '$mutex=[IO.File]::Open($mutexPath,[IO.FileMode]::OpenOrCreate,[IO.FileAccess]::ReadWrite,[IO.FileShare]::ReadWrite)',
+ 'try{',
+ ' $mutex.Lock(0,1)',
+ ' if([IO.File]::Exists($marker)){throw "remote update marker is present"}',
+ reservation.ownershipId
+ ? ` $existingLines=@(& ${helper('read-lock').map(psLiteral).join(' ')} ${psLiteral(reservation.ownershipId)}); $existingExit=$LASTEXITCODE; ` +
+ ' if($existingExit -eq 0 -and $existingLines.Count -gt 0){try{$existing=$existingLines[-1]|ConvertFrom-Json}catch{$existing=$null}; ' +
+ 'if($existing -and [int]$existing.pid -gt 0){try{$p=[Diagnostics.Process]::GetProcessById([int]$existing.pid); ' +
+ 'if(-not $p.HasExited){[ordered]@{existing=$true}|ConvertTo-Json -Compress;exit 0}}catch{}finally{if($p){$p.Dispose()}}}; ' +
+ `& ${helper('remove-lock').map(psLiteral).join(' ')} ${psLiteral(reservation.ownershipId)}|Out-Null}`
+ : '',
+ reservation.ownershipId
+ ? ` $spawnLines=@(& ${argv.map(psLiteral).join(' ')}); $spawnExit=$LASTEXITCODE`
+ : ` & ${argv.map(psLiteral).join(' ')}`,
+ reservation.ownershipId
+ ? ' if($spawnExit -ne 0){exit $spawnExit}'
+ : ' if($LASTEXITCODE -ne 0){exit $LASTEXITCODE}',
+ reservation.ownershipId
+ ? ` $spawned=$spawnLines[-1]|ConvertFrom-Json; $lock=[ordered]@{schemaVersion=2;protocolVersion=1;ownershipId=${psLiteral(reservation.ownershipId)};spawnNonce=${psLiteral(reservation.spawnNonce)};pid=[int]$spawned.pid;creationTimeNs=[string]$spawned.creationTimeNs;port=0;profile=${psLiteral(reservation.profile)};hermesPath=${psLiteral(reservation.hermesPath)};hermesHome=${psLiteral(reservation.hermesHome)};tokenFingerprint=${psLiteral(reservation.tokenFingerprint)};startedAt=${psLiteral(reservation.startedAt)}}|ConvertTo-Json -Compress; ` +
+ ` & ${helper('write-lock').map(psLiteral).join(' ')} ${psLiteral(reservation.ownershipId)} $lock|Out-Null; if($LASTEXITCODE -ne 0){exit $LASTEXITCODE}; $spawnLines|Write-Output`
+ : '',
+ ' if([IO.File]::Exists($marker)){throw "remote update marker claimed during backend spawn"}',
+ '}finally{try{$mutex.Unlock(0,1)}catch{};$mutex.Dispose()}'
+ ]
+ .filter(line => line !== '')
+ .join(';')
+ return powerShellCommand(script)
+}
+
+async function atomicWindowsSpawn(ssh, runtime, stdinData, reservation: any = {}) {
+ const output = await ssh.exec(atomicWindowsSpawnCommand(runtime, reservation), { stdinData })
+ const lines = String(output || '')
+ .replace(/^\uFEFF/, '')
+ .trim()
+ .split(/\r?\n/)
+ .filter(Boolean)
+ const parsed = JSON.parse(lines[lines.length - 1] || 'null')
+
+ if (parsed?.error) {
+ const error: any = new Error(parsed.error)
+ error.kind = parsed.kind || 'remote-helper-error'
+ throw error
+ }
+
+ return parsed
+}
+
function fingerprintToken(token) {
return crypto
.createHash('sha256')
@@ -203,6 +385,77 @@ async function cleanupOwned(ssh, runtime, ownershipId, lock) {
await attempt(() => helper(ssh, runtime, 'remove-lock', [ownershipId]))
}
+function windowsLockMatchesManagedUpdateScope(lock, expected) {
+ return Boolean(
+ lock &&
+ expected &&
+ lock.ownershipId === expected.ownershipId &&
+ lock.pid === expected.pid &&
+ lock.spawnNonce === expected.spawnNonce &&
+ lock.creationTimeNs === expected.creationTimeNs &&
+ lock.profile === expected.profile &&
+ lock.hermesPath === expected.hermesPath &&
+ lock.hermesHome === expected.hermesHome
+ )
+}
+
+/**
+ * Terminate a Windows serve only after the persisted ownership record and the
+ * kernel creation-time proof still match the exact scope Desktop connected.
+ * Leave the record in place for the post-update reconnect to reclaim; this
+ * prevents a delayed cleanup from deleting a replacement owner's record.
+ */
+async function terminateOwnedWindowsDashboardForUpdate(ssh, runtime, expected) {
+ let lock = await helper(ssh, runtime, 'read-lock', [expected?.ownershipId || ''])
+
+ if (!validLock(lock, expected?.ownershipId) || !windowsLockMatchesManagedUpdateScope(lock, expected)) {
+ const error: any = new Error('The remote Windows ownership record changed before the managed update.')
+ error.kind = 'ownership-changed'
+ throw error
+ }
+
+ let state = await processState(ssh, runtime, lock)
+
+ if (state.indeterminate) {
+ const error: any = new Error('Could not prove the remote Windows process identity for the managed update.')
+ error.kind = 'transient-transport-error'
+ throw error
+ }
+ if (!state.alive) {
+ return { pid: lock.pid, terminated: false, alreadyStopped: true }
+ }
+ if (!state.owned) {
+ const error: any = new Error('Refusing to terminate a remote Windows process whose ownership is unproven.')
+ error.kind = 'foreign-backend'
+ throw error
+ }
+
+ // Fence the proof against a record replacement before signalling.
+ lock = await helper(ssh, runtime, 'read-lock', [expected.ownershipId])
+
+ if (!validLock(lock, expected.ownershipId) || !windowsLockMatchesManagedUpdateScope(lock, expected)) {
+ const error: any = new Error('The remote Windows ownership record changed during process verification.')
+ error.kind = 'ownership-changed'
+ throw error
+ }
+ state = await processState(ssh, runtime, lock)
+
+ if (state.indeterminate || !state.alive || !state.owned) {
+ const error: any = new Error('The remote Windows process identity changed during managed update drain.')
+ error.kind = state.indeterminate ? 'transient-transport-error' : 'ownership-changed'
+ throw error
+ }
+
+ await helper(ssh, runtime, 'terminate', [
+ String(lock.pid),
+ String(lock.creationTimeNs),
+ lock.hermesPath,
+ lock.spawnNonce
+ ])
+
+ return { pid: lock.pid, terminated: true, alreadyStopped: false }
+}
+
async function waitReady(ssh, runtime, ownershipId, lock, timeoutMs, signal) {
const deadline = Date.now() + timeoutMs
@@ -261,6 +514,28 @@ async function waitReady(ssh, runtime, ownershipId, lock, timeoutMs, signal) {
throw error
}
+async function waitForWindowsSpawnCompletion(ssh, runtime, ownershipId, timeoutMs) {
+ const deadline = Date.now() + timeoutMs
+
+ while (Date.now() < deadline) {
+ const lock = await helper(ssh, runtime, 'read-lock', [ownershipId])
+
+ if (!lock) {
+ return false
+ }
+
+ if (validLock(lock, ownershipId) && lock.port > 0) {
+ return true
+ }
+
+ await new Promise(resolve => setTimeout(resolve, READY_POLL_INTERVAL_MS))
+ }
+
+ const error: any = new Error('Timed out waiting for the concurrent Windows SSH connection to publish its backend.')
+ error.kind = 'spawn-failed'
+ throw error
+}
+
async function connectWindowsRemote(deps) {
const {
ssh,
@@ -280,6 +555,7 @@ async function connectWindowsRemote(deps) {
assertBootstrapNotSuperseded(signal)
const runtime = await probeWindowsRemote(ssh, remoteHermesPath)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
const inspection = await helper(ssh, runtime, 'inspect', [runtime.hermesPath])
if (!inspection.supported) {
@@ -293,6 +569,7 @@ async function connectWindowsRemote(deps) {
rememberLog(`[ssh-lifecycle] remote platform Windows/${runtime.arch}`)
rememberLog(`[ssh-lifecycle] located hermes at ${runtime.hermesPath}`)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
const lock = await helper(ssh, runtime, 'read-lock', [ownershipId])
if (validLock(lock, ownershipId)) {
@@ -307,6 +584,7 @@ async function connectWindowsRemote(deps) {
const reusable = reusableWindowsLock(lock, state, profile, reuseToken, runtime)
if (reusable) {
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
const localPort = await pickLocalPort()
await forward(localPort, lock.port)
@@ -327,7 +605,9 @@ async function connectWindowsRemote(deps) {
hermesVersion,
ownershipId,
spawnNonce: lock.spawnNonce,
- creationTimeNs: lock.creationTimeNs
+ creationTimeNs: lock.creationTimeNs,
+ hermesHome: runtime.hermesHome,
+ pythonPath: runtime.python
}
}
@@ -336,37 +616,71 @@ async function connectWindowsRemote(deps) {
}
await cancelForward(localPort, lock.port)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
await cleanupOwned(ssh, runtime, ownershipId, lock)
} catch (error) {
await cancelForward(localPort, lock.port)
throw error
}
} else {
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
await cleanupOwned(ssh, runtime, ownershipId, lock)
}
} else if (lock) {
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
await helper(ssh, runtime, 'remove-lock', [ownershipId])
}
assertBootstrapNotSuperseded(signal)
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
const token = crypto.randomBytes(32).toString('hex')
const spawnNonce = crypto.randomBytes(8).toString('hex')
await helper(ssh, runtime, 'upload-token', [ownershipId, spawnNonce], token)
+ const startedAt = new Date().toISOString()
+ const tokenFingerprint = fingerprintToken(token)
let spawned
try {
- spawned = await helper(
+ await assertWindowsRemoteInstallUpdateClear(ssh, runtime.hermesHome)
+ spawned = await atomicWindowsSpawn(
ssh,
runtime,
- 'spawn',
- [],
- JSON.stringify({ ownershipId, spawnNonce, profile, hermesPath: runtime.hermesPath })
+ JSON.stringify({ ownershipId, spawnNonce, profile, hermesPath: runtime.hermesPath }),
+ {
+ ownershipId,
+ spawnNonce,
+ profile,
+ hermesPath: runtime.hermesPath,
+ hermesHome: runtime.hermesHome,
+ tokenFingerprint,
+ startedAt
+ }
)
} catch (error) {
await helper(ssh, runtime, 'remove-token', [ownershipId, spawnNonce])
throw error
}
+ if (spawned.existing) {
+ await helper(ssh, runtime, 'remove-token', [ownershipId, spawnNonce])
+
+ if (!reuseToken) {
+ const error: any = new Error(
+ 'Another SSH connection owns this remote dashboard; a session token is required to reuse it.'
+ )
+ error.kind = 'remote-ownership-contended'
+ throw error
+ }
+
+ const published = await waitForWindowsSpawnCompletion(ssh, runtime, ownershipId, readyTimeoutMs)
+
+ if (!published) {
+ return connectWindowsRemote({ ...deps, reuseToken })
+ }
+
+ return connectWindowsRemote({ ...deps, reuseToken })
+ }
+
const owned = {
schemaVersion: LOCKFILE_SCHEMA_VERSION,
protocolVersion: PROTOCOL_VERSION,
@@ -378,8 +692,8 @@ async function connectWindowsRemote(deps) {
profile,
hermesPath: runtime.hermesPath,
hermesHome: runtime.hermesHome,
- tokenFingerprint: fingerprintToken(token),
- startedAt: new Date().toISOString()
+ tokenFingerprint,
+ startedAt
}
let localPort = 0
@@ -412,7 +726,9 @@ async function connectWindowsRemote(deps) {
hermesVersion,
ownershipId,
spawnNonce,
- creationTimeNs: spawned.creationTimeNs
+ creationTimeNs: spawned.creationTimeNs,
+ hermesHome: runtime.hermesHome,
+ pythonPath: runtime.python
}
} catch (error) {
if (localPort && remotePort) {
@@ -440,6 +756,8 @@ function buildWindowsInteractiveCommand(remoteCwd = '') {
}
export {
+ assertWindowsRemoteInstallUpdateClear,
+ atomicWindowsSpawnCommand,
buildWindowsInteractiveCommand,
connectWindowsRemote,
detectRemotePlatform,
@@ -450,5 +768,6 @@ export {
probeWindowsRemote,
psLiteral,
reusableWindowsLock,
+ terminateOwnedWindowsDashboardForUpdate,
validLock
}