The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: Desktop SSH marker readers judge the v2 marker with update_lock's one parser and identity rule
Teknium1f32d73ed881
diff --git a/apps/desktop/electron/managed-ssh-update.test.ts b/apps/desktop/electron/managed-ssh-update.test.tsindex 7a49f7a5887..d2999590d95 100644--- a/apps/desktop/electron/managed-ssh-update.test.ts+++ b/apps/desktop/electron/managed-ssh-update.test.ts@@ -656,7 +656,10 @@ test.runIf(process.platform !== 'win32')(try {await mkdir(profileHome, { recursive: true })- await writeFile(path.join(root, '.hermes-update-in-progress'), `${process.pid}\n1\n`)+ await writeFile(+ path.join(root, '.hermes-update-in-progress'),+ `${process.pid}\n${Math.floor(Date.now() / 1000)}\n`+ )const command = buildRemoteUpdateObservationCommand({diff --git a/apps/desktop/electron/managed-ssh-update.ts b/apps/desktop/electron/managed-ssh-update.tsindex 4a25c1e3b0f..0a8bde3907b 100644--- a/apps/desktop/electron/managed-ssh-update.ts+++ b/apps/desktop/electron/managed-ssh-update.ts@@ -15,6 +15,7 @@*/import { expandRemotePath, shq } from './remote-lifecycle'+import { REMOTE_MARKER_JUDGE_PY } from './remote-update-marker-programs'import { encodedPowerShell, powerShellCommand, psLiteral } from './windows-remote-lifecycle'const UPDATE_EXIT_INDEPENDENT_HANDOFF = 75@@ -331,6 +332,7 @@ function buildWindowsManagedUpdateLaunch(target: RemoteUpdateTarget, correlationconst OBSERVATION_SCRIPT = String.raw`import ctypes,json,os,re,sysfrom pathlib import Path+${REMOTE_MARKER_JUDGE_PY}home=Path(os.path.expanduser(sys.argv[1]))correlation=sys.argv[2]@@ -407,20 +409,11 @@ def marker_state():try:raw=marker_path.read_bytes()except FileNotFoundError:return {'state':'absent'}except OSError:return {'state':'unavailable'}- # v1 is "<pid>\n<started_at>\n"; v2 adds a creation-time line 3 and tagged lines 4+- # (the first well-formed "delegate:<pid> ct:<ct>" names a second live holder).- lines=[line[:-1] if line.endswith(b'\r') else line for line in raw.split(b'\n')]- if lines[-1]==b'':lines.pop()- if len(lines)<2 or not re.fullmatch(rb'[1-9][0-9]*',lines[0]) or not re.fullmatch(rb'[0-9]+',lines[1]):- return {'state':'malformed'}- delegates=[re.fullmatch(rb'delegate:([1-9][0-9]*) ct:[0-9]+(?:\.[0-9]+)?',line) for line in lines[3:]]- holders=[int(lines[0])]+[int(match.group(1)) for match in delegates if match][:1]- if any(pid>4294967295 for pid in holders) or int(lines[1])>9007199254740991:return {'state':'malformed'}- for pid in holders:- live=pid_alive(pid)- if live is None:return {'state':'unavailable','pid':pid}- if live:return {'state':'live','pid':pid}- return {'state':'dead','pid':holders[0]}+ # update_lock.judge_marker's parser and identity rule (owner or delegate, pid + creation time).+ verdict=marker_verdict(raw)+ if verdict=='UNCERTAIN':return {'state':'malformed'}+ if verdict=='CLEAR':return {'state':'dead'}+ return {'state':'live','pid':int(verdict[5:])}def terminal_code():try:raw=status_path.read_bytes()diff --git a/apps/desktop/electron/remote-lifecycle-spawn.test.ts b/apps/desktop/electron/remote-lifecycle-spawn.test.tsindex 56fc38eed24..8f2014698ce 100644--- a/apps/desktop/electron/remote-lifecycle-spawn.test.ts+++ b/apps/desktop/electron/remote-lifecycle-spawn.test.ts@@ -298,8 +298,30 @@ test.skipIf(process.platform === 'win32').each(variants)(async ({ launcher, owned }: SpawnVariant): Promise<void> => {const fixture: SpawnFixture = await spawnFixture(launcher, owned)+ // A live delegate under a dead owner still guards the install (update_lock.judge_marker).+ const exited: ChildProcess = spawn(process.execPath, ['-e', ''])+ await new Promise(resolve => exited.once('exit', resolve))++ const delegate: ChildProcess = spawn(+ 'python3',+ ['-c', 'import time;print(time.time(),flush=True);time.sleep(30)'],+ {+ stdio: ['ignore', 'pipe', 'ignore']+ }+ )+try {- for (const marker of [`${process.pid}\n0\n`, 'not-a-pid\n']) {+ const delegateCt: string = await new Promise(resolve =>+ delegate.stdout!.once('data', (chunk: Buffer) => resolve(String(chunk).trim()))+ )++ const now: number = Math.floor(Date.now() / 1000)++ for (const marker of [+ `${process.pid}\n${now}\n`,+ 'not-a-pid\n',+ `${exited.pid}\n${now}\nct:1700000000.125\ndelegate:${delegate.pid} ct:${delegateCt}\n`+ ]) {await writeFile(fixture.marker, marker, 'utf8')await assert.rejects(fixture.run(fixture.command), { code: 75, stdout: '' })assert.deepEqual(await reports(fixture), [])@@ -307,6 +329,7 @@ test.skipIf(process.platform === 'win32').each(variants)(await assert.rejects(readFile(fixture.localPath(lockfilePath(ownershipId))), { code: 'ENOENT' })}} finally {+ delegate.kill()await fixture.dispose()}},diff --git a/apps/desktop/electron/remote-lifecycle-v2-marker.test.ts b/apps/desktop/electron/remote-lifecycle-v2-marker.test.tsindex dcc13d4a5b9..a633a787ddb 100644--- a/apps/desktop/electron/remote-lifecycle-v2-marker.test.ts+++ b/apps/desktop/electron/remote-lifecycle-v2-marker.test.ts@@ -1,5 +1,6 @@import assert from 'node:assert/strict'import { exec as execCallback, spawn } from 'node:child_process'+import { randomUUID } from 'node:crypto'import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'import os from 'node:os'import path from 'node:path'@@ -7,6 +8,7 @@ import { promisify } from 'node:util'import { test } from 'vitest'+import { buildRemoteUpdateObservationCommand, parseRemoteUpdateObservation } from './managed-ssh-update'import { assertRemoteInstallUpdateClear } from './remote-lifecycle'const exec = promisify(execCallback)@@ -65,3 +67,63 @@ test.runIf(process.platform === 'linux')(// A held marker mutex makes the gate wait out its 10 s acquisition window before refusing.30_000)++// The shapes update_lock._parse_marker accepts (tests/fixtures/update_marker_corpus.json) through+// the real relaunch gate and managed observer: a dead claim is dead whatever its padding, and the+// first in-range delegate names the live holder (the embedded readers used to say UNCERTAIN).+test.runIf(process.platform === 'linux')(+ 'POSIX relaunch gate and managed observer read every corpus marker shape like update_lock',+ async () => {+ const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-v2-shapes-'))+ const marker = path.join(home, '.hermes-update-in-progress')+ const ssh = { exec: async (command: string) => (await exec(command, { shell: 'sh' })).stdout }+ const target = { ssh, platform: 'Linux', hermesPath: '/opt/hermes/hermes', hermesHome: home }+ const correlation = randomUUID()++ const observe = async () =>+ parseRemoteUpdateObservation(+ await ssh.exec(buildRemoteUpdateObservationCommand(target as any, correlation)),+ correlation+ )++ const exited = spawn(process.execPath, ['-e', ''])+ await new Promise(resolve => exited.once('exit', resolve))+ const dead = exited.pid+ const now = Math.floor(Date.now() / 1000)++ const holder = spawn('python3', ['-c', 'import time;print(time.time(),flush=True);time.sleep(30)'], {+ stdio: ['ignore', 'pipe', 'ignore']+ })++ try {+ const holderCt = await new Promise<string>(resolve =>+ holder.stdout!.once('data', chunk => resolve(String(chunk).trim()))+ )++ for (const claim of [+ `\ufeff${dead}\r\n${now}\r\nct:1700000000.125\r\n`,+ ` ${dead} \t\n\t${now} \nct:1700000000.125\n`,+ `0000${dead}\n${now}\nct:1700000000.125\n`,+ `${dead}\n18446744073709551615\nct:1700000000.125\n`+ ]) {+ await writeFile(marker, claim)+ assert.equal((await observe()).marker, 'dead', JSON.stringify(claim))+ await assertRemoteInstallUpdateClear(ssh, home)+ await assert.rejects(readFile(marker), `a dead claim is reclaimed: ${JSON.stringify(claim)}`)+ }++ const delegated = `${dead}\n${now}\nct:1700000000.125\ndelegate:4294967296 ct:1\ndelegate:${holder.pid} ct:${holderCt}\n`+ await writeFile(marker, delegated)+ assert.deepEqual(await observe().then(o => [o.marker, o.markerPid]), ['live', holder.pid])+ await assert.rejects(+ () => assertRemoteInstallUpdateClear(ssh, home),+ new RegExp(`process ${holder.pid} is still running`)+ )+ assert.equal(await readFile(marker, 'utf8'), delegated)+ } finally {+ holder.kill()+ await rm(home, { force: true, recursive: true })+ }+ },+ 30_000+)diff --git a/apps/desktop/electron/remote-lifecycle.test.ts b/apps/desktop/electron/remote-lifecycle.test.tsindex 66b88de9175..f2a4c97dcd8 100644--- a/apps/desktop/electron/remote-lifecycle.test.ts+++ b/apps/desktop/electron/remote-lifecycle.test.ts@@ -114,7 +114,7 @@ function fakeSsh(rules: any[] = []) {return !(mutexWrapped && matcher instanceof RegExp && /python3 -c/.test(matcher.source))})- if ((cmd.includes('os.kill(pid') && !cmd.includes('pidfd_open')) || cmd.includes('printf TERMINATED')) {+ if ((cmd.includes('os.kill(pid') && !/pidfd_open|marker_clear/.test(cmd)) || cmd.includes('printf TERMINATED')) {return 'TERMINATED'}@@ -188,7 +188,6 @@ test('POSIX relaunch gate permits absent/dead markers and normalizes named-profiassert.match(commands[0], /profiles/)assert.match(commands[0], /\.hermes-update-in-progress/)assert.match(commands[0], /marker\.unlink/)- assert.match(commands[0], /\/proc\/%d\/cmdline/)})test('POSIX relaunch gate rechecks after token upload immediately before process creation', async () => {diff --git a/apps/desktop/electron/remote-lifecycle.ts b/apps/desktop/electron/remote-lifecycle.tsindex c51cb08778a..02f64ec82f5 100644--- a/apps/desktop/electron/remote-lifecycle.ts+++ b/apps/desktop/electron/remote-lifecycle.ts@@ -30,6 +30,7 @@ import crypto from 'node:crypto'import { READY_IN_MERGED_OUTPUT_RE } from './backend-ready'import { parseRemoteProfileListing } from './connection-registry'import { backendProfileArg } from './profile-id-guard'+import { REMOTE_MARKER_JUDGE_PY } from './remote-update-marker-programs'import { assertBootstrapNotSuperseded, withRemoteTimeout } from './ssh-connection'const LOCKFILE_SCHEMA_VERSION = 2@@ -319,8 +320,10 @@ async function probeRemoteHermesHome(ssh) {}}-const REMOTE_UPDATE_MARKER_PROBE = String.raw`-import errno,fcntl,os,re,sys+// The relaunch gate: REMOTE_MARKER_JUDGE_PY (update_lock.judge_marker's parser and identity rule)+// judges the marker; a dead claim is deleted under the updaters' marker lock.+const REMOTE_UPDATE_MARKER_PROBE = `${REMOTE_MARKER_JUDGE_PY}${String.raw`+import fcntlfrom pathlib import Pathhome=Path(os.path.expanduser(sys.argv[1]))@@ -340,51 +343,30 @@ def clear():except OSError:uncertain()try:with marker.open('rb') as stream:- if stream.read(257)!=raw:uncertain()+ if stream.read(4097)!=raw:uncertain()marker.unlink()except FileNotFoundError:passexcept OSError:uncertain()finally:os.close(fd)print('CLEAR');raise SystemExittry:- with marker.open('rb') as stream:raw=stream.read(257)+ with marker.open('rb') as stream:raw=stream.read(4097)except FileNotFoundError:print('CLEAR');raise SystemExitexcept OSError:uncertain()-if len(raw)>256:- uncertain()-# v1 is "<pid>\n<started_at>\n"; v2 adds a creation-time line 3 and tagged lines 4+-# (the first well-formed "delegate:<pid> ct:<ct>" names a second live holder).-lines=[line[:-1] if line.endswith(b'\r') else line for line in raw.split(b'\n')]-if lines[-1]==b'':lines.pop()-if len(lines)<2 or not re.fullmatch(rb'[1-9][0-9]*',lines[0]) or not re.fullmatch(rb'[0-9]+',lines[1]):- uncertain()-delegates=[re.fullmatch(rb'delegate:([1-9][0-9]*) ct:[0-9]+(?:\.[0-9]+)?',line) for line in lines[3:]]-holders=[int(lines[0])]+[int(match.group(1)) for match in delegates if match][:1]-if any(pid>4294967295 for pid in holders) or int(lines[1])>9007199254740991:- uncertain()-def live(pid):- try:- os.kill(pid,0)- except ProcessLookupError:- return False- except PermissionError:- return True- except OSError as error:- if error.errno==errno.ESRCH:return False- if error.errno==errno.EPERM:return True- uncertain()- try:- cmd=open('/proc/%d/cmdline'%pid,'rb').read().replace(b'\0',b' ')- except OSError:- cmd=b''- return not cmd or b'update' in cmd-for pid in holders:- if live(pid):- print('LIVE:'+str(pid));raise SystemExit-clear()-`+verdict=marker_verdict(raw)+if verdict=='CLEAR':clear()+print(verdict)+`}`++// The spawn recheck: the same judgement, read-only (the relaunch gate above already reclaimed).+const REMOTE_MARKER_VERDICT_PY = `${REMOTE_MARKER_JUDGE_PY}${String.raw`+try:+ with open(sys.argv[1],'rb') as stream:raw=stream.read(4097)+except FileNotFoundError:raw=None+print(marker_verdict(raw))+`}`/*** Refuse normal SSH reuse/spawn while the remote install is being mutated.@@ -1204,9 +1186,7 @@ function buildSpawnCommand(hermesPath, profile, opts: any = {}) {// 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; }`+ `[ "$(python3 -c ${shq(REMOTE_MARKER_VERDICT_PY)} ${marker} 2>/dev/null)" = CLEAR ]; }`const dashCmd =`ulimit -n ${REMOTE_NOFILE_SOFT_LIMIT} 2>/dev/null || true; ` +diff --git a/apps/desktop/electron/remote-update-marker-programs.test.ts b/apps/desktop/electron/remote-update-marker-programs.test.tsnew file mode 100644index 00000000000..6aea230311d--- /dev/null+++ b/apps/desktop/electron/remote-update-marker-programs.test.ts@@ -0,0 +1,39 @@+import assert from 'node:assert/strict'+import { execFile as execFileCallback } from 'node:child_process'+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { promisify } from 'node:util'++import { test } from 'vitest'++import { REMOTE_MARKER_JUDGE_PY } from './remote-update-marker-programs'++const execFile = promisify(execFileCallback)+const corpusPath = path.resolve(__dirname, '../../../tests/fixtures/update_marker_corpus.json')++// Feed every corpus judge case, with its injected process table, through the+// exact Python an SSH remote runs: the remote reader obeys the shared contract.+const DRIVER = String.raw`+import json+corpus=json.load(open(sys.argv[1],encoding='utf-8'))+out={}+for case in corpus['judge']:+ live={int(pid):ct for pid,ct in case['live'].items()}+ own=case.get('our_ct',corpus['our_ct'])+ env={'our_pid':case.get('our_pid',corpus['our_pid']),'our_ct':lambda own=own:own,'alive':lambda pid,live=live:pid in live,'ct':lambda pid,live=live:live.get(pid),'now':corpus['now']}+ verdict,owner=marker_judge(case['text'],env)+ out[case['name']]={'verdict':verdict,'owner':owner}+print(json.dumps(out))+`++test.skipIf(process.platform === 'win32')('the remote marker judge agrees with every corpus judge case', async () => {+ const corpus = JSON.parse(readFileSync(corpusPath, 'utf8'))+ const { stdout } = await execFile('python3', ['-c', `${REMOTE_MARKER_JUDGE_PY}\n${DRIVER}`, corpusPath])++ const expected = Object.fromEntries(+ corpus.judge.map((c: any) => [c.name, { verdict: c.expect.verdict, owner: c.expect.owner }])+ )++ assert.ok(corpus.judge.length >= 40)+ assert.deepEqual(JSON.parse(stdout), expected)+})diff --git a/apps/desktop/electron/remote-update-marker-programs.ts b/apps/desktop/electron/remote-update-marker-programs.tsnew file mode 100644index 00000000000..75d1c8f0387--- /dev/null+++ b/apps/desktop/electron/remote-update-marker-programs.ts@@ -0,0 +1,106 @@+/**+ * The update-marker judge as a program that runs ON an SSH remote.+ *+ * One parser and one identity rule for every Desktop remote reader (the POSIX+ * relaunch gate, the spawn recheck, the managed-update observer), the same as+ * `hermes_cli/update_lock.py::judge_marker` and `tests/fixtures/update_marker_corpus.json`:+ * an identity (pid, ct) is live when the pid is alive and its creation time is+ * within 2 s of the recorded `ct:`; with no recorded/readable ct it is live only+ * while `now - started_at <= 1200`. Owner or delegate live => LIVE, both dead =>+ * CLEAR, malformed => UNCERTAIN. Only the host's system Python runs it: nothing+ * imports the checkout an updater may be replacing.+ *+ * The Python stays free of double quotes: managed-ssh-update ships it to Windows+ * as a PowerShell native argument, and PowerShell 5.1 does not escape them.+ */++/** Defines `marker_judge(text, env)` (corpus-shaped, injectable facts) and `marker_verdict(raw_bytes_or_None)`. */+export const REMOTE_MARKER_JUDGE_PY = String.raw`+import os,re,sys,time+MARKER_INT_RE=re.compile(r'[0-9]+')+MARKER_CT_RE=re.compile(r'ct:([0-9]+(?:\.[0-9]+)?)')+MARKER_DELEGATE_RE=re.compile(r'delegate:([0-9]+) ct:([0-9]+(?:\.[0-9]+)?)')++def marker_int(text):+ # int() refuses >4300 digits; past 20 significant digits nothing fits u64 anyway.+ text=text.lstrip('0') or '0'+ return int(text) if len(text)<=20 else None++def marker_identity_state(pid,ct,started,env):+ if pid==0:return 'dead'+ if pid==env['our_pid']:+ own=env['our_ct']()+ return 'ours' if ct is not None and own is not None and abs(ct-own)<=0.005 else 'dead'+ if not env['alive'](pid):return 'dead'+ actual=None if ct is None else env['ct'](pid)+ if ct is None or actual is None:return 'unknown' if env['now']-started<=1200 else 'dead'+ return 'match' if abs(ct-actual)<=2.0 else 'dead'++def marker_judge(text,env):+ if text.startswith('\ufeff'):text=text[1:]+ lines=[(line[:-1] if line.endswith('\r') else line).strip(' \t') for line in text.split('\n')]+ if len(lines)<2 or not MARKER_INT_RE.fullmatch(lines[0]) or not MARKER_INT_RE.fullmatch(lines[1]):return 'malformed',None+ pid=marker_int(lines[0]);started=marker_int(lines[1])+ if pid is None or pid>4294967295 or started is None or started>18446744073709551615:return 'malformed',None+ ct=MARKER_CT_RE.fullmatch(lines[2]) if len(lines)>2 else None+ ids=[(pid,float(ct.group(1)) if ct else None)]+ for line in lines[3:]:+ delegate=MARKER_DELEGATE_RE.fullmatch(line)+ delegate_pid=marker_int(delegate.group(1)) if delegate else None+ if delegate_pid is not None and delegate_pid<=4294967295:+ ids.append((delegate_pid,float(delegate.group(2))));break+ states=[marker_identity_state(p,c,started,env) for p,c in ids]+ live=[p for (p,_),state in zip(ids,states) if state!='dead']+ return ('ours' if 'ours' in states else 'live' if live else 'dead'),(live[0] if live else None)++def marker_stat(pid):+ raw=open('/proc/%d/stat'%pid).read()+ return raw[raw.rfind(')')+2:].split()++def marker_win(pid):+ # (alive, creation unix seconds or None); an open we are denied is alive with no ct.+ import ctypes+ from ctypes import wintypes+ k=ctypes.WinDLL('kernel32',use_last_error=True)+ k.OpenProcess.argtypes=[wintypes.DWORD,wintypes.BOOL,wintypes.DWORD];k.OpenProcess.restype=wintypes.HANDLE+ k.GetExitCodeProcess.argtypes=[wintypes.HANDLE,ctypes.POINTER(wintypes.DWORD)]+ k.GetProcessTimes.argtypes=[wintypes.HANDLE]+[ctypes.POINTER(wintypes.FILETIME)]*4+ k.CloseHandle.argtypes=[wintypes.HANDLE]+ handle=k.OpenProcess(0x1000,False,pid)+ if not handle:return ctypes.get_last_error()!=87,None+ try:+ code=wintypes.DWORD();times=[wintypes.FILETIME() for _ in range(4)]+ if k.GetExitCodeProcess(handle,ctypes.byref(code)) and code.value!=259:return False,None+ if not k.GetProcessTimes(handle,*[ctypes.byref(t) for t in times]):return True,None+ return True,((times[0].dwHighDateTime<<32)|times[0].dwLowDateTime)/1e7-11644473600+ finally:k.CloseHandle(handle)++def marker_alive(pid):+ if os.name=='nt':return marker_win(pid)[0]+ try:os.kill(pid,0)+ except (ProcessLookupError,OverflowError):return False+ except OSError:pass # EPERM or unprovable: alive (fail closed)+ try:return marker_stat(pid)[0]!='Z'+ except (OSError,IndexError):return True++def marker_ct(pid):+ # psutil.create_time() without psutil; unreadable => None => the v1 age ceiling.+ try:+ if os.name=='nt':return marker_win(pid)[1]+ if sys.platform.startswith('linux'):+ with open('/proc/stat') as stat:btime=next(int(line.split()[1]) for line in stat if line.startswith('btime '))+ return btime+int(marker_stat(pid)[19])/os.sysconf('SC_CLK_TCK')+ # UTC like update_lock._stdlib_create_time: a local-time lstart is ambiguous in the repeated DST hour.+ import calendar,subprocess+ out=subprocess.check_output(['ps','-o','lstart=','-p',str(pid)],env=dict(os.environ,LC_ALL='C',TZ='UTC0'),universal_newlines=True)+ return float(calendar.timegm(time.strptime(' '.join(out.split()),'%a %b %d %H:%M:%S %Y')))+ except Exception:return None++MARKER_ENV={'our_pid':os.getpid(),'our_ct':lambda:marker_ct(os.getpid()),'alive':marker_alive,'ct':marker_ct,'now':time.time()}++def marker_verdict(raw):+ if raw is None:return 'CLEAR'+ if len(raw)>4096:return 'UNCERTAIN'+ verdict,owner=marker_judge(raw.decode('utf-8','replace'),MARKER_ENV)+ return 'CLEAR' if verdict=='dead' else 'UNCERTAIN' if verdict=='malformed' else 'LIVE:%d'%owner+`