Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Hold Hermes admission until its session source is verified (#1097)

Dee806fe4914ac8
diff --git a/cli/e2e/hermesAdmission.e2e.ts b/cli/e2e/hermesAdmission.e2e.ts
new file mode 100644
index 000000000..d92e9dfd2
--- /dev/null
+++ b/cli/e2e/hermesAdmission.e2e.ts
@@ -0,0 +1,67 @@
+/** Private daemon, hook credential, process, tmux and Hermes home throughout. */
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+let daemon: IsolatedDaemon | undefined
+let client: LocalClient | undefined
+afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })
+
+it('holds unverified Hermes hooks while core remains ready, then rejects a child and admits a verified conversation', async () => {
+ const d = daemon = await IsolatedDaemon.create()
+ onTestFailed(() => console.log(d.log()))
+ d.env.HERMES_HOME = join(d.root, 'hermes')
+ d.env.HERMES_PATH = join(d.root, 'bin', 'hermes')
+ mkdirSync(d.env.HERMES_HOME)
+ const database = join(d.env.HERMES_HOME, 'state.db')
+ writeFileSync(database, 'unreadable SQLite fixture')
+ writeFileSync(d.env.HERMES_PATH, `#!${process.execPath}
+if (process.argv.includes('--version')) { console.log('1.0.0'); process.exit(0) }
+process.title = 'hermes'.padEnd(16)
+require('node:fs').writeFileSync(${JSON.stringify(join(d.root, 'hermes.pid'))}, String(process.pid))
+console.log('fake-hermes-ready\\n>')
+setInterval(() => {}, 1000)
+`, { mode: 0o755 })
+ const cwd = join(d.projectsDir, 'hermes'); mkdirSync(cwd, { recursive: true })
+ await d.start()
+ const c = client = await LocalClient.connect(d)
+ const created = await c.request('agent_create', { engine: 'hermes', cwd, bypassPermission: true }, 60_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agentId: string = created.agent.id
+ const pane = String(created.agent.terminal?.runtimes?.[0]?.paneId ?? created.agent.tmuxPane)
+ await until('the fixture process', async () => (await d.capture(pane)).includes('fake-hermes-ready') || null, 15_000, 100)
+ const callerPid = Number(readFileSync(join(d.root, 'hermes.pid'), 'utf8'))
+ const hook = async (sessionId: string) => {
+ const response = await fetch(`http://127.0.0.1:${d.port}/api/hook/session-start`, {
+ method: 'POST', headers: { 'content-type': 'application/json', 'x-harness-hook-token': d.hookCredential() },
+ body: JSON.stringify({ engine: 'hermes', sessionId, tmuxPane: pane, cwd, callerPid, hookEvent: 'SessionStart' }),
+ })
+ expect(response.status).toBe(200)
+ expect(await response.json()).toEqual({ pending: true })
+ }
+ const row = async () => (await c.request('agents_list', {})).agents.find((agent: { id: string }) => agent.id === agentId)
+ const child = '20261009_120000_aaaaaa', own = '20261009_120001_bbbbbb'
+ await hook(own)
+ await until('an explicit source hold', () => d.log().includes('held · Hermes session source is unavailable') || null, 10_000, 100)
+ // A delegated hook on the same pane must not erase its parent's held intent.
+ await hook(child)
+ expect((await row()).sessionId).toBeFalsy()
+ expect(readFileSync(database, 'utf8')).toBe('unreadable SQLite fixture')
+ expect((await fetch(`http://127.0.0.1:${d.port}/api/health`)).ok).toBe(true)
+ // Replace only this test's corrupt fixture. An old started_at prevents directory repair from
+ // guessing either conversation; these admissions must go through the authenticated hook path.
+ rmSync(database)
+ const { DatabaseSync } = process.getBuiltinModule('node:sqlite') as {
+ DatabaseSync: new (path: string) => { exec(sql: string): void; prepare(sql: string): { run(...args: string[]): void }; close(): void }
+ }
+ const db = new DatabaseSync(database)
+ db.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT, cwd TEXT, started_at REAL);'
+ + 'CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT, content TEXT, tool_call_id TEXT, tool_calls TEXT, tool_name TEXT, finish_reason TEXT, reasoning TEXT);')
+ const insert = db.prepare('INSERT INTO sessions VALUES (?, ?, ?, 0)')
+ insert.run(child, 'tool', cwd); insert.run(own, 'cli', cwd); db.close()
+ await until('automatic source recheck to reject the child', () => d.log().includes('ignored · hermes_subagent') || null, 10_000, 100)
+ await until('automatic parent binding after rejecting the child', async () => (await row()).sessionId === own || null, 10_000, 100)
+ expect(d.coresStarted()).toBe(1)
+}, 90_000)
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 1b6622862..a1ee0201b 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -262,7 +262,8 @@ function boundedPrompt(prompt) {
/**
* POST one hook event to the daemon. Resolves true when it answered 2xx, false when it could not be
- * reached or refused, and 'late' when it took the request but did not answer within the budget.
+ * reached or refused, 'held' for live admission backpressure, and 'late' when it took the request but
+ * did not answer within the budget. Neither live hold is permission for an offline registry write.
*
* 'late' is not "the daemon is down", and nothing may be written behind its back for it: the request is
* in its socket, and it handles it once it gets to it. A daemon whose event loop is held for a few
@@ -302,6 +303,9 @@ function post(port, path, body, onResponse) {
res.on('data', (chunk) => { if (response.length < 16_384) response += chunk })
res.on('end', () => {
const ok = (res.statusCode || 0) >= 200 && (res.statusCode || 0) < 300
+ let reply
+ try { if (response.length <= 16_384) reply = JSON.parse(response) } catch { /* no structured reply */ }
+ if (res.statusCode === 429 || (res.statusCode === 202 && reply?.retry === true)) { resolve('held'); return }
if (ok && onResponse && response.length <= 16_384) {
try { onResponse(JSON.parse(response)) } catch { /* Unavailable context never blocks a turn. */ }
}
@@ -1786,8 +1790,17 @@ async function main() {
model: modelName(input.model),
cliVersion: input.cli_version || input.cursor_version || input.version,
}
- const ok = await post(port, '/api/hook/session-start', body)
- if (ok === false) await fallbackRegister(input, engine, tmuxPane)
+ let ok = await post(port, '/api/hook/session-start', body)
+ let held = ok === 'held'
+ // A live core's bounded admission queue owns the existing candidates. Retry this
+ // delivery within the hook budget, never reconstruct registry state behind it.
+ for (let attempt = 0; engine === 'hermes' && ok === 'held' && attempt < 3 && remainingBudget() > 750; attempt++) {
+ await new Promise(resolve => setTimeout(resolve, 250))
+ ok = await post(port, '/api/hook/session-start', body)
+ held ||= ok === 'held'
+ }
+ if (held && ok !== true) process.stderr.write('[harness] Hermes admission is held; this delivery could not be confirmed. The current conversation is unchanged.\n')
+ if (ok === false && !held) await fallbackRegister(input, engine, tmuxPane)
}
main()
diff --git a/cli/scripts/handoff-2026-10-08/mutate-admission-hold.py b/cli/scripts/handoff-2026-10-08/mutate-admission-hold.py
new file mode 100644
index 000000000..8f66b887b
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-admission-hold.py
@@ -0,0 +1,66 @@
+"""Break admission evidence and publication guards; only assertion failures count as proof."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+golden = 'src/engines/otherAdmission.golden.spec.ts'
+mutations = [
+ ('failed store read admits', 'src/engines/kit/storeSource.ts',
+ "if (!result.ok) return { unavailable: true, reason: result.reason }", "if (!result.ok) return ''", golden),
+ ('absent source row admits', 'src/hookServer.ts',
+ "if (answer === null) continue", "if (answer === null) return { kind: 'accept', value: undefined }", golden),
+ ('late source reply publishes', 'src/core/engines/pendingAdmission.ts',
+ " if (!current(key, job)) { discard(key, job); return }\n // A newer",
+ " // A newer", 'src/core/engines/pendingAdmission.spec.ts'),
+ ('malformed source admits', 'src/engines/kit/storeSource.ts',
+ "return typeof source === 'string' ? source : { unavailable: true, reason: 'transient' }",
+ "return typeof source === 'string' ? source : ''", 'src/engines/kit/storeSource.spec.ts'),
+ ('incomplete homes admit', 'src/hookServer.ts',
+ "if (home !== env.HERMES_HOME && !complete) unavailable = true",
+ "if (false) unavailable = true", 'src/hookServer.hermes.spec.ts'),
+ ('stop loses admission fence', 'src/hookServer.ts',
+ "!isRecentlyDeleted(processAgent.agentId) && ", "", 'src/hookServer.hermes.spec.ts'),
+ ('unverified child erases parent', 'src/core/engines/pendingAdmission.ts',
+ "const queue = jobs.get(key) ?? []", "const queue: Job[] = []", 'src/core/engines/pendingAdmission.spec.ts'),
+ ('older retry replaces accepted conversation', 'src/core/engines/pendingAdmission.ts',
+ "const status = order.status(key, job.id, job.request.order)", "const status = 'current'", 'src/hookServer.hermes.spec.ts'),
+ ('live backpressure writes offline', 'hook/notify.mjs',
+ "if (res.statusCode === 429 || (res.statusCode === 202 && reply?.retry === true)) { resolve('held'); return }",
+ "if (false) { resolve('held'); return }", 'src/hookNotify.spec.ts', ['-t', 'Hermes live admission']),
+ ('held child is never revisited', 'src/core/engines/pendingAdmission.ts',
+ "const peer = leaders(key, job).find(other => other !== job)", "const peer: Job | undefined = undefined", 'src/core/engines/pendingAdmission.spec.ts'),
+ ('older duplicate downgrades intent', 'src/core/engines/pendingAdmission.ts',
+ "if (known !== undefined && (request.order.firedAt === undefined || request.order.firedAt < known)) return true",
+ "if (false) return true", 'src/core/engines/pendingAdmission.spec.ts'),
+ ('stale candidate hides refreshed authority', 'src/core/engines/pendingAdmission.ts',
+ "if (previous.request.current()) return true", "return true", 'src/core/engines/pendingAdmission.spec.ts'),
+ ('mixed order promotes older intent', 'src/core/engines/admissionOrder.ts',
+ "if (a.firedAt === undefined) return b.firedAt === undefined ? a.arrival - b.arrival : -1\n if (b.firedAt === undefined) return 1\n return a.firedAt - b.firedAt || a.arrival - b.arrival",
+ "return a.firedAt !== undefined && b.firedAt !== undefined ? a.firedAt - b.firedAt : a.arrival - b.arrival",
+ 'src/core/engines/pendingAdmission.spec.ts'),
+]
+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}
+env.pop('TMUX', None)
+env.pop('TMUX_PANE', None)
+command = ['node', 'node_modules/vitest/vitest.mjs', 'run', '--maxWorkers=1']
+baselines = [[*sorted({item[4] for item in mutations if len(item) == 5})]]
+baselines.extend([item[4], *item[5]] for item in mutations if len(item) == 6)
+for specs in baselines:
+ baseline = subprocess.run([*command, *specs], cwd=cli, env=env, capture_output=True, text=True, timeout=90)
+ if baseline.returncode:
+ sys.exit('Baseline failed; no mutations run.\n' + baseline.stdout[-5000:] + baseline.stderr[-5000:])
+for name, path, old, new, spec, *filters in mutations:
+ target = cli / path
+ source = target.read_text()
+ assert source.count(old) == 1, (name, source.count(old))
+ try:
+ target.write_text(source.replace(old, new))
+ result = subprocess.run([*command, spec, *(filters[0] if filters else [])], cwd=cli, env=env, capture_output=True, text=True, timeout=90)
+ caught = result.returncode != 0 and 'AssertionError' in result.stdout + result.stderr
+ print(f'{name}: {"caught by assertion" if caught else "NOT PROVEN"}', flush=True)
+ if not caught:
+ sys.exit(result.stdout[-5000:] + result.stderr[-5000:])
+ finally:
+ target.write_text(source)
diff --git a/cli/src/core/engines/admissionOrder.spec.ts b/cli/src/core/engines/admissionOrder.spec.ts
new file mode 100644
index 000000000..12d490662
--- /dev/null
+++ b/cli/src/core/engines/admissionOrder.spec.ts
@@ -0,0 +1,75 @@
+import { expect, it } from 'vitest'
+import { compareAdmissionOrder, createAdmissionOrder } from './admissionOrder.js'
+
+const stamp = (firedAt: number | undefined, arrival = 1, scope = 'process-1') => ({ firedAt, arrival, scope })
+
+it('keeps verified native order across retries, scopes it to the exact process, and clears on shutdown', () => {
+ const order = createAdmissionOrder()
+ expect(order.status('agent', 'a', stamp(10))).toBe('current')
+ order.accept('agent', 'b', stamp(20, 2))
+ expect(order.status('agent', 'a', stamp(10, 3))).toBe('older')
+ expect(order.status('agent', 'a', stamp(20, 4))).toBe('ambiguous')
+ expect(order.status('agent', 'a', stamp(21, 5))).toBe('current')
+ expect(order.status('agent', 'b', stamp(10, 6))).toBe('current')
+ order.accept('agent', 'b', stamp(10, 6))
+ expect(order.status('agent', 'a', stamp(15, 7))).toBe('older')
+ order.accept('agent', 'c', stamp(30, 8))
+ expect(order.status('agent', 'b', stamp(25, 9))).toBe('older')
+ expect(order.status('agent', 'a', stamp(1, 10, 'process-2'))).toBe('current')
+ order.accept('agent', 'a', stamp(1, 10, 'process-2'))
+ expect(order.status('agent', 'b', stamp(2, 11, 'process-2'))).toBe('current')
+ order.close()
+ expect(order.status('agent', 'old', stamp(1))).toBe('current')
+})
+
+it('uses arrival for already observed legacy deliveries but cannot infer that a late conflicting hook is newer', () => {
+ const order = createAdmissionOrder()
+ order.accept('agent', 'b', stamp(undefined, 2))
+ expect(order.status('agent', 'a', stamp(undefined, 1))).toBe('older')
+ expect(order.status('agent', 'a', stamp(undefined, 2))).toBe('older')
+ expect(order.status('agent', 'a', stamp(undefined, 3))).toBe('ambiguous')
+ expect(order.status('agent', 'a', stamp(50, 3))).toBe('ambiguous')
+ order.accept('agent', 'b', stamp(50, 4))
+ expect(order.status('agent', 'a', stamp(undefined, 5))).toBe('ambiguous')
+ order.accept('agent', 'b', stamp(undefined, 6))
+ expect(order.status('agent', 'a', stamp(40, 7))).toBe('older')
+ order.accept('legacy', 'b', stamp(undefined, 1))
+ order.accept('legacy', 'b', stamp(undefined, 2))
+ expect(order.status('legacy', 'a', stamp(undefined, 1))).toBe('older')
+ expect(compareAdmissionOrder(stamp(undefined, 1), stamp(50, 2))).toBeLessThan(0)
+ expect(compareAdmissionOrder(stamp(20, 9), stamp(30, 2))).toBeLessThan(0)
+})
+
+it('keeps native sorting transitive with a headerless delivery between two native events', () => {
+ const values = [stamp(20, 1), stamp(undefined, 2), stamp(10, 3)]
+ expect(values.sort(compareAdmissionOrder)).toEqual([stamp(undefined, 2), stamp(10, 3), stamp(20, 1)])
+ expect(compareAdmissionOrder(stamp(20, 1), stamp(20, 2))).toBeLessThan(0)
+ expect(compareAdmissionOrder(stamp(undefined, 1), stamp(undefined, 2))).toBeLessThan(0)
+})
+
+it('forgets removed process watermarks while retaining authority for a live process', () => {
+ const order = createAdmissionOrder(key => key === 'live')
+ order.accept('live', 'b', stamp(20))
+ order.accept('removed', 'b', stamp(20))
+ order.observe('live', 'process-1', undefined)
+ expect(order.status('live', 'a', stamp(10))).toBe('older')
+ expect(order.status('removed', 'a', stamp(10))).toBe('current')
+})
+
+it('retains current binding authority across a restart, external rebind and process replacement', () => {
+ const order = createAdmissionOrder()
+ order.observe('agent', 'process-1', undefined)
+ order.observe('agent', 'process-1', { id: '', at: null })
+ expect(order.status('agent', 'a', stamp(10))).toBe('current')
+ order.observe('agent', 'process-1', { id: 'b', at: 20 })
+ expect(order.status('agent', 'a', stamp(10))).toBe('older')
+ // The native timestamp of an accepted B is retained when its registry row is observed again.
+ order.accept('agent', 'b', stamp(25, 2))
+ order.observe('agent', 'process-1', { id: 'b', at: 20 })
+ expect(order.status('agent', 'a', stamp(23, 3))).toBe('older')
+ order.observe('agent', 'process-1', { id: 'c', at: 30 })
+ expect(order.status('agent', 'b', stamp(26, 4))).toBe('older')
+ order.observe('agent', 'process-2', { id: 'd', at: null })
+ expect(order.status('agent', 'd', stamp(10, 5, 'process-2'))).toBe('current')
+ expect(order.status('agent', 'a', stamp(10, 6, 'process-2'))).toBe('ambiguous')
+})
diff --git a/cli/src/core/engines/admissionOrder.ts b/cli/src/core/engines/admissionOrder.ts
new file mode 100644
index 000000000..1be7337ec
--- /dev/null
+++ b/cli/src/core/engines/admissionOrder.ts
@@ -0,0 +1,48 @@
+/** Native delivery time survives retries; arrival order only orders requests this core already saw. */
+export interface AdmissionOrder {
+ scope: string
+ firedAt: number | undefined
+ arrival: number
+}
+
+export function compareAdmissionOrder(a: AdmissionOrder, b: AdmissionOrder): number {
+ if (a.firedAt === undefined) return b.firedAt === undefined ? a.arrival - b.arrival : -1
+ if (b.firedAt === undefined) return 1
+ return a.firedAt - b.firedAt || a.arrival - b.arrival
+}
+
+/** Only verified acceptance advances this process-incarnation watermark, never a delegated child. */
+export function createAdmissionOrder(isProcessCurrent: (key: string, scope: string) => boolean = () => true) {
+ const accepted = new Map<string, { id: string; order: AdmissionOrder }>()
+ return {
+ observe(key: string, scope: string, binding: { id: string; at: number | null } | undefined): void {
+ // Opportunistic lifecycle cleanup bounds history by the processes still alive,
+ // rather than every agent ever seen by a long-running daemon.
+ for (const [owner, value] of accepted) if (!isProcessCurrent(owner, value.order.scope)) accepted.delete(owner)
+ if (!binding?.id) return
+ const last = accepted.get(key)
+ // A persisted binding protects a restarted core too. A changed binding made
+ // outside this queue is newer authority than its previous watermark.
+ if (!last || last.order.scope !== scope || last.id !== binding.id) {
+ accepted.set(key, { id: binding.id, order: { scope, firedAt: binding.at ?? undefined, arrival: 0 } })
+ }
+ },
+ status(key: string, id: string, order: AdmissionOrder): 'current' | 'older' | 'ambiguous' {
+ const last = accepted.get(key)
+ if (!last || last.order.scope !== order.scope || last.id === id) return 'current'
+ if (order.firedAt !== undefined && last.order.firedAt !== undefined) {
+ return order.firedAt < last.order.firedAt ? 'older' : order.firedAt === last.order.firedAt ? 'ambiguous' : 'current'
+ }
+ // A late headerless delivery is not evidence that another conversation is newer.
+ return order.arrival <= last.order.arrival ? 'older' : 'ambiguous'
+ },
+ accept(key: string, id: string, order: AdmissionOrder): void {
+ const last = accepted.get(key)
+ if (!last || last.order.scope !== order.scope
+ || ((order.firedAt !== undefined || last.order.firedAt === undefined) && compareAdmissionOrder(order, last.order) > 0)) {
+ accepted.set(key, { id, order })
+ }
+ },
+ close(): void { accepted.clear() },
+ }
+}
diff --git a/cli/src/core/engines/pendingAdmission.spec.ts b/cli/src/core/engines/pendingAdmission.spec.ts
new file mode 100644
index 000000000..9b7c2906a
--- /dev/null
+++ b/cli/src/core/engines/pendingAdmission.spec.ts
@@ -0,0 +1,315 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { createPendingAdmissions, type AdmissionDecision, type PendingAdmission } from './pendingAdmission.js'
+
+afterEach(() => vi.useRealTimers())
+let arrival = 0
+function request(overrides: Partial<PendingAdmission<string>> = {}): PendingAdmission<string> {
+ const sequence = ++arrival
+ return { order: { scope: 'process', firedAt: sequence, arrival: sequence }, current: () => true, inspect: vi.fn(async () => ({ kind: 'accept' as const, value: 'home' })),
+ accept: vi.fn(), reject: vi.fn(), held: vi.fn(), ...overrides }
+}
+const flush = async () => { await Promise.resolve(); await Promise.resolve() }
+
+describe('pending hook admission', () => {
+ it('rechecks an already-held equal-time child so its parent can recover', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions({ retryMs: 20 })
+ let readable = false
+ const child = request({ order: { scope: 'process', firedAt: 10, arrival: 1 },
+ inspect: async () => readable ? { kind: 'reject', reason: 'delegated' } : { kind: 'hold', reason: 'unreadable' } })
+ const parent = request({ order: { scope: 'process', firedAt: 10, arrival: 2 } })
+ queue.submit('agent', 'child', child); await flush()
+ queue.submit('agent', 'parent', parent); await flush()
+ expect(parent.accept).not.toHaveBeenCalled()
+ readable = true
+ await vi.advanceTimersByTimeAsync(40)
+ expect(child.reject).toHaveBeenCalledExactlyOnceWith('delegated')
+ expect(parent.accept).toHaveBeenCalledOnce()
+ queue.close()
+ })
+
+ it('keeps newer queued native evidence when an older or headerless duplicate arrives', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions({ retryMs: 20 })
+ let readable = false
+ const b = request({ order: { scope: 'process', firedAt: 20, arrival: 1 },
+ inspect: async () => readable ? { kind: 'accept', value: 'b20' } : { kind: 'hold', reason: 'unreadable' } })
+ const a = request({ order: { scope: 'process', firedAt: 15, arrival: 2 } })
+ const oldB = request({ order: { scope: 'process', firedAt: 10, arrival: 3 } })
+ const legacyB = request({ order: { scope: 'process', firedAt: undefined, arrival: 4 } })
+ queue.submit('agent', 'b', b); await flush()
+ queue.submit('agent', 'a', a); await flush()
+ queue.submit('agent', 'b', oldB); queue.submit('agent', 'b', legacyB)
+ await vi.advanceTimersByTimeAsync(20)
+ expect(a.inspect).not.toHaveBeenCalled()
+ expect(oldB.inspect).not.toHaveBeenCalled()
+ expect(legacyB.inspect).not.toHaveBeenCalled()
+ readable = true
+ await vi.advanceTimersByTimeAsync(20)
+ expect(b.accept).toHaveBeenCalledExactlyOnceWith('b20')
+ expect(a.accept).not.toHaveBeenCalled()
+ queue.close()
+ })
+
+ it.each([20, undefined])('refreshes stale authority for a same-delivery retry with timestamp %s', async firedAt => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions()
+ let live = true
+ const old = request({ order: { scope: 'process', firedAt, arrival: 1 }, current: () => live,
+ inspect: async () => ({ kind: 'hold', reason: 'unreadable' }) })
+ queue.submit('agent', 'session', old); await flush()
+ live = false
+ const fresh = request({ order: { scope: 'process', firedAt, arrival: 2 } })
+ queue.submit('agent', 'session', fresh); await flush()
+ expect(fresh.accept).toHaveBeenCalledOnce()
+ expect(old.accept).not.toHaveBeenCalled()
+ queue.close()
+ })
+
+ it('never selects known-older intent through a headerless candidate, and still drains verified children', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions({ retryMs: 20 })
+ let readable = false
+ const inspect = async (): Promise<AdmissionDecision<string>> => readable
+ ? { kind: 'reject', reason: 'delegated' } : { kind: 'hold', reason: 'unreadable' }
+ const b = request({ order: { scope: 'process', firedAt: 20, arrival: 1 }, inspect })
+ const legacy = request({ order: { scope: 'process', firedAt: undefined, arrival: 2 }, inspect })
+ const a = request({ order: { scope: 'process', firedAt: 10, arrival: 3 } })
+ queue.submit('agent', 'b', b); await flush()
+ queue.submit('agent', 'legacy', legacy); await flush()
+ queue.submit('agent', 'a', a); await flush()
+ await vi.advanceTimersByTimeAsync(40)
+ expect(a.inspect).not.toHaveBeenCalled()
+ readable = true
+ await vi.advanceTimersByTimeAsync(60)
+ expect(b.reject).toHaveBeenCalledOnce()
+ expect(legacy.reject).toHaveBeenCalledOnce()
+ expect(a.accept).toHaveBeenCalledOnce()
+ queue.close()
+ })
+
+ it('can finish rejecting an in-flight child before admitting its equal-time parent', async () => {
+ const queue = createPendingAdmissions()
+ let finish!: (answer: AdmissionDecision<string>) => void
+ const child = request({ order: { scope: 'process', firedAt: 10, arrival: 1 },
+ inspect: () => new Promise(resolve => { finish = resolve }) })
+ const parent = request({ order: { scope: 'process', firedAt: 10, arrival: 2 } })
+ queue.submit('agent', 'child', child)
+ queue.submit('agent', 'parent', parent)
+ finish({ kind: 'reject', reason: 'delegated' }); await flush(); await flush()
+ expect(child.reject).toHaveBeenCalledExactlyOnceWith('delegated')
+ expect(parent.accept).toHaveBeenCalledOnce()
+ queue.close()
+ })
+
+ it.each(['same', 'different'])('scopes pending candidates and acceptance to a replacement process with a %s session id', async id => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions()
+ let oldProcess = true
+ const old = request({ order: { scope: 'old-process', firedAt: 100, arrival: 1 }, current: () => oldProcess,
+ inspect: async () => ({ kind: 'hold', reason: 'unreadable' }) })
+ queue.submit('agent', 'old-session', old); await flush()
+ oldProcess = false
+ const replacement = request({ order: { scope: 'new-process', firedAt: 200, arrival: 2 } })
+ queue.submit('agent', id === 'same' ? 'old-session' : 'new-session', replacement); await flush()
+ expect(replacement.accept).toHaveBeenCalledOnce()
+ expect(old.accept).not.toHaveBeenCalled()
+ queue.close()
+ })
+
+ it('rejects older retries after the queue emptied and holds equal-time or unorderable conflicting intent', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions({ retryMs: 20 })
+ const b = request({ order: { scope: 'process', firedAt: 20, arrival: 2 } })
+ queue.submit('agent', 'b', b); await flush()
+ const older = request({ order: { scope: 'process', firedAt: 10, arrival: 3 } })
+ queue.submit('agent', 'a', older); await flush()
+ expect(older.reject).toHaveBeenCalledExactlyOnceWith('stale_hook')
+ expect(older.accept).not.toHaveBeenCalled()
+ const equal = request({ order: { scope: 'process', firedAt: 20, arrival: 4 } })
+ queue.submit('agent', 'a', equal); await flush()
+ expect(equal.held).toHaveBeenCalledWith(expect.stringContaining('hook order'))
+ expect(equal.accept).not.toHaveBeenCalled()
+ const noTimestamp = request({ order: { scope: 'process', firedAt: undefined, arrival: 5 } })
+ queue.submit('agent', 'legacy', noTimestamp); await flush()
+ await vi.advanceTimersByTimeAsync(20)
+ expect(noTimestamp.held).toHaveBeenCalledOnce()
+ queue.close()
+ })
+
+ it('does not promote an older delivery over newer pending intent, and holds equal-time candidates', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions({ retryMs: 20 })
+ const held = request({ order: { scope: 'process', firedAt: 20, arrival: 2 },
+ inspect: async () => ({ kind: 'hold', reason: 'waiting' }) })
+ queue.submit('agent', 'newer', held); await flush()
+ const older = request({ order: { scope: 'process', firedAt: 10, arrival: 3 } })
+ queue.submit('agent', 'older', older); await flush()
+ expect(older.inspect).not.toHaveBeenCalled()
+ const equal = request({ order: { scope: 'process', firedAt: 20, arrival: 4 } })
+ queue.submit('agent', 'equal', equal); await flush()
+ expect(equal.held).toHaveBeenCalledWith(expect.stringContaining('hook order'))
+ expect(equal.accept).not.toHaveBeenCalled()
+ // A fresh native hook disambiguates the intent and supersedes older candidates.
+ const fresh = request({ order: { scope: 'process', firedAt: 30, arrival: 5 } })
+ queue.submit('agent', 'newer', fresh); await flush()
+ expect(fresh.accept).toHaveBeenCalledOnce()
+ queue.close()
+ })
+
+ it('contains late async notifications without blocking reentrant admission or shutdown', async () => {
+ vi.useFakeTimers()
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const queue = createPendingAdmissions()
+ let reject!: (error: Error) => void
+ const newer = request({ order: { scope: 'process', firedAt: 2, arrival: 2 } })
+ const first = request({ order: { scope: 'process', firedAt: 1, arrival: 1 }, accept: () => {
+ queue.submit('agent', 'newer', newer)
+ return new Promise<void>((_, fail) => { reject = fail })
+ } })
+ queue.submit('agent', 'first', first); await flush(); await flush()
+ expect(newer.accept).toHaveBeenCalledOnce()
+ queue.close()
+ reject(new Error('late attachment failed')); await flush()
+ expect(warning).toHaveBeenCalledOnce()
+ expect(vi.getTimerCount()).toBe(0)
+ warning.mockRestore()
+ })
+
+ it('keeps an unresolved parent behind a child and applies backpressure without eviction', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions({ retryMs: 20, capacity: 2 })
+ const parentInspect = vi.fn<PendingAdmission<string>['inspect']>()
+ .mockResolvedValueOnce({ kind: 'hold', reason: 'unreadable' })
+ .mockResolvedValueOnce({ kind: 'accept', value: 'parent' })
+ const parent = request({ inspect: parentInspect })
+ expect(queue.submit('agent', 'parent', parent)).toBe(true); await flush()
+ const childInspect = vi.fn<PendingAdmission<string>['inspect']>()
+ .mockResolvedValueOnce({ kind: 'hold', reason: 'unreadable' })
+ .mockResolvedValueOnce({ kind: 'reject', reason: 'delegated' })
+ const child = request({ inspect: childInspect })
+ queue.submit('agent', 'child', child); await flush()
+ const overflow = request()
+ expect(queue.submit('agent', 'overflow', overflow)).toBe(false)
+ expect(overflow.inspect).not.toHaveBeenCalled()
+ // Repeating a delivery keeps its original place and timer without consuming another slot.
+ expect(queue.submit('agent', 'child', child)).toBe(true); await flush(); await flush()
+ await vi.advanceTimersByTimeAsync(20)
+ expect(child.reject).toHaveBeenCalledExactlyOnceWith('delegated')
+ expect(parent.accept).toHaveBeenCalledExactlyOnceWith('parent')
+ expect(vi.getTimerCount()).toBe(0)
+ queue.close()
+ })
+
+ it('pauses an in-flight older candidate and discards it only after verified newer acceptance', async () => {
+ const queue = createPendingAdmissions()
+ let finish!: (answer: AdmissionDecision<string>) => void
+ const old = request({ inspect: () => new Promise(resolve => { finish = resolve }) })
+ const newer = request()
+ queue.submit('agent', 'old', old)
+ queue.submit('agent', 'newer', newer)
+ expect(newer.inspect).not.toHaveBeenCalled()
+ finish({ kind: 'accept', value: 'old' }); await flush(); await flush()
+ expect(old.accept).not.toHaveBeenCalled()
+ expect(newer.accept).toHaveBeenCalledOnce()
+ queue.close()
+ })
+
+ it('isolates a failed notification without repeating publication or losing a held retry', async () => {
+ vi.useFakeTimers()
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const queue = createPendingAdmissions({ retryMs: 20 })
+ const failure = () => { throw new Error('notification failed') }
+ const accept = vi.fn(failure)
+ queue.submit('accepted', 'session', request({ accept })); await flush()
+ const inspect = vi.fn<PendingAdmission<string>['inspect']>()
+ .mockResolvedValueOnce({ kind: 'hold', reason: 'unavailable' })
+ .mockResolvedValueOnce({ kind: 'accept', value: 'recovered' })
+ const held = request({ inspect, held: failure })
+ queue.submit('held', 'session', held); await flush()
+ await vi.advanceTimersByTimeAsync(20)
+ expect(held.accept).toHaveBeenCalledExactlyOnceWith('recovered')
+ expect(accept).toHaveBeenCalledOnce()
+ expect(warning).toHaveBeenCalledTimes(2)
+ expect(vi.getTimerCount()).toBe(0)
+ queue.close(); warning.mockRestore()
+ })
+
+ it('holds without publishing, logs a reason once, and automatically admits after recovery', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions()
+ const inspect = vi.fn<PendingAdmission<string>['inspect']>()
+ .mockResolvedValueOnce({ kind: 'hold', reason: 'store unavailable' })
+ .mockResolvedValueOnce({ kind: 'hold', reason: 'store unavailable' })
+ .mockResolvedValueOnce({ kind: 'hold', reason: 'waiting for its row' })
+ .mockResolvedValueOnce({ kind: 'accept', value: 'own home' })
+ const r = request({ inspect })
+ queue.submit('agent', 'session', r); await flush()
+ expect(r.accept).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(3_000)
+ expect(r.held).toHaveBeenCalledTimes(2)
+ expect(r.accept).toHaveBeenCalledExactlyOnceWith('own home')
+ expect(r.reject).not.toHaveBeenCalled()
+ expect(vi.getTimerCount()).toBe(0)
+ queue.close()
+ })
+
+ it('rejects a verified child and keeps unexpected read failures pending', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions({ retryMs: 20 })
+ const inspect = vi.fn<PendingAdmission<string>['inspect']>()
+ .mockRejectedValueOnce(new Error('broken reader'))
+ .mockResolvedValueOnce({ kind: 'reject', reason: 'delegated' })
+ const r = request({ inspect })
+ queue.submit('agent', 'session', r); await flush()
+ expect(r.held).toHaveBeenCalledWith('The session source could not be read.')
+ await vi.advanceTimersByTimeAsync(20)
+ expect(r.reject).toHaveBeenCalledExactlyOnceWith('delegated')
+ expect(r.accept).not.toHaveBeenCalled()
+ queue.close()
+ })
+
+ it('fences an old hook, a changed binding, and shutdown during the read', async () => {
+ vi.useFakeTimers()
+ for (const change of ['replace', 'binding', 'close'] as const) {
+ const queue = createPendingAdmissions()
+ let finish!: (value: AdmissionDecision<string>) => void
+ let current = true
+ const old = request({ current: () => current, inspect: () => new Promise(resolve => { finish = resolve }) })
+ queue.submit('agent', 'session', old)
+ const newer = request()
+ if (change === 'replace') queue.submit('agent', 'session', newer)
+ if (change === 'binding') current = false
+ if (change === 'close') queue.close()
+ finish({ kind: 'accept', value: 'stale' }); await flush()
+ expect(old.accept).not.toHaveBeenCalled()
+ expect(old.held).not.toHaveBeenCalled()
+ if (change === 'replace') expect(newer.accept).toHaveBeenCalledOnce()
+ queue.close()
+ }
+ })
+
+ it('drops stale work before lookup and clears replaced or closed retry timers', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions()
+ const stale = request({ current: () => false })
+ queue.submit('stale', 'session', stale)
+ expect(stale.inspect).not.toHaveBeenCalled()
+ let active = true
+ const held = request({ current: () => active, inspect: async () => ({ kind: 'hold', reason: 'unreadable' }) })
+ queue.submit('first', 'session', held); await flush()
+ queue.submit('first', 'session', request()); await flush()
+ expect(vi.getTimerCount()).toBe(0)
+ queue.submit('first', 'session', held); await flush()
+ active = false
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(vi.getTimerCount()).toBe(0)
+ active = true
+ queue.submit('first', 'session', held); await flush()
+ queue.close()
+ expect(vi.getTimerCount()).toBe(0)
+ const after = request()
+ queue.submit('after', 'session', after)
+ expect(after.inspect).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/core/engines/pendingAdmission.ts b/cli/src/core/engines/pendingAdmission.ts
new file mode 100644
index 000000000..f9c0fa3a7
--- /dev/null
+++ b/cli/src/core/engines/pendingAdmission.ts
@@ -0,0 +1,141 @@
+/** Core owns pending hook admission. A late lookup cannot replace a newer hook or binding. */
+import { compareAdmissionOrder, createAdmissionOrder, type AdmissionOrder } from './admissionOrder.js'
+
+export type AdmissionDecision<T> =
+ | { kind: 'accept'; value: T }
+ | { kind: 'reject'; reason: string }
+ | { kind: 'hold'; reason: string }
+
+export interface PendingAdmission<T> {
+ order: AdmissionOrder
+ binding?: { id: string; at: number | null }
+ current: () => boolean
+ inspect: () => Promise<AdmissionDecision<T>>
+ accept: (value: T) => void | Promise<void>
+ reject: (reason: string) => void | Promise<void>
+ held: (reason: string) => void | Promise<void>
+}
+
+export function createPendingAdmissions({ retryMs = 1_000, capacity = 64, isProcessCurrent }: {
+ retryMs?: number; capacity?: number; isProcessCurrent?: (key: string, scope: string) => boolean
+} = {}) {
+ type Job = { id: string; request: PendingAdmission<unknown>; timer: ReturnType<typeof setTimeout> | null; reason?: string }
+ const jobs = new Map<string, Job[]>()
+ const running = new Set<string>()
+ const order = createAdmissionOrder(isProcessCurrent)
+ let closed = false
+ const current = (key: string, job: Job) => !closed && !!jobs.get(key)?.includes(job) && job.request.current()
+ const selected = (key: string) => jobs.get(key)?.at(-1)
+ // Known older intents wait behind the greatest native timestamp. Headerless and
+ // equal-time candidates remain incomparable, so each must get a chance to prove
+ // delegation or cancellation before another can publish.
+ const leaders = (key: string, job: Job): Job[] => {
+ const candidates = jobs.get(key)!.filter(other => other.request.order.scope === job.request.order.scope)
+ const latest = Math.max(...candidates.map(other => other.request.order.firedAt ?? -Infinity))
+ return candidates.filter(other => other.request.order.firedAt === undefined || other.request.order.firedAt === latest)
+ }
+ const clearTimer = (job: Job) => { if (job.timer) { clearTimeout(job.timer); job.timer = null } }
+ const discard = (key: string, job: Job) => {
+ const queue = jobs.get(key)
+ if (!queue) return
+ const index = queue.indexOf(job)
+ if (index !== -1) queue.splice(index, 1)
+ if (!queue.length) jobs.delete(key)
+ }
+ const report = (error: unknown) => console.warn('[hooks] pending admission callback failed', error)
+ // Notification can await optional interpretation. Its failure is contained, but it
+ // cannot block the next core admission or cause a committed binding to be retried.
+ const notified = (result: void | Promise<void>) => { void Promise.resolve(result).catch(report) }
+ const run = async (key: string, job: Job, retry = false): Promise<void> => {
+ running.add(key)
+ try {
+ if (retry && current(key, job)) {
+ const peer = leaders(key, job).find(other => other !== job)
+ if (peer) {
+ const queue = jobs.get(key)!
+ queue.splice(queue.indexOf(peer), 1); queue.push(peer)
+ job = peer
+ }
+ }
+ await inspect(key, job)
+ } catch (error) {
+ // A notification may throw after publication. Never retry that publication or
+ // let its exception take down the daemon; a held read already has its retry.
+ if (!job.timer) discard(key, job)
+ report(error)
+ } finally {
+ running.delete(key)
+ const next = selected(key)
+ if (next && !next.timer) void run(key, next)
+ }
+ }
+ const inspect = async (key: string, job: Job): Promise<void> => {
+ if (!current(key, job)) { discard(key, job); return }
+ order.observe(key, job.request.order.scope, job.request.binding)
+ let decision: AdmissionDecision<unknown>
+ try { decision = await job.request.inspect() } catch {
+ decision = { kind: 'hold', reason: 'The session source could not be read.' }
+ }
+ if (!current(key, job)) { discard(key, job); return }
+ // A newer unverified hook pauses this candidate; it does not erase it. Hermes
+ // children use their parent's process, and a rejected child must leave the parent pending.
+ if (selected(key) !== job && decision.kind !== 'reject') return
+ const status = order.status(key, job.id, job.request.order)
+ if (status === 'older') decision = { kind: 'reject', reason: 'stale_hook' }
+ else if (decision.kind === 'accept') {
+ const unresolved = leaders(key, job).some(other => other !== job)
+ if (status === 'ambiguous' || unresolved) decision = { kind: 'hold', reason: 'Waiting for unambiguous Hermes hook order; keeping the current conversation.' }
+ }
+ if (decision.kind === 'hold') {
+ job.timer = setTimeout(() => { job.timer = null; void run(key, job, true) }, retryMs)
+ job.timer.unref()
+ if (job.reason !== decision.reason) {
+ job.reason = decision.reason
+ notified(job.request.held(decision.reason))
+ }
+ return
+ }
+ if (decision.kind === 'accept') {
+ order.accept(key, job.id, job.request.order)
+ jobs.delete(key)
+ notified(job.request.accept(decision.value))
+ } else {
+ discard(key, job)
+ notified(job.request.reject(decision.reason))
+ }
+ }
+ return {
+ /** False means backpressure: nothing was queued or evicted, so the sender must retry. */
+ submit<T>(key: string, id: string, request: PendingAdmission<T>): boolean {
+ if (closed) return false
+ const queue = jobs.get(key) ?? []
+ const duplicate = queue.findIndex(job => job.id === id)
+ if (duplicate === -1 && queue.length >= capacity) return false
+ if (duplicate !== -1 && queue[duplicate]!.request.order.scope === request.order.scope) {
+ const previous = queue[duplicate]!
+ const known = previous.request.order.firedAt
+ if (known !== undefined && (request.order.firedAt === undefined || request.order.firedAt < known)) return true
+ if (known === request.order.firedAt) {
+ if (previous.request.current()) return true
+ // Same delivery, freshly verified after its old binding/route became stale.
+ request = { ...request, order: { ...request.order, arrival: previous.request.order.arrival } }
+ }
+ }
+ if (duplicate !== -1) { clearTimer(queue[duplicate]!); queue.splice(duplicate, 1) }
+ const previous = queue.at(-1)
+ if (previous) clearTimer(previous)
+ const job: Job = { id, request: request as PendingAdmission<unknown>, timer: null }
+ queue.push(job)
+ queue.sort((a, b) => compareAdmissionOrder(a.request.order, b.request.order))
+ jobs.set(key, queue)
+ if (!running.has(key)) void run(key, selected(key)!)
+ return true
+ },
+ close(): void {
+ closed = true
+ for (const queue of jobs.values()) for (const job of queue) clearTimer(job)
+ jobs.clear()
+ order.close()
+ },
+ }
+}
diff --git a/cli/src/engines/__fixtures__/other-admission.golden.json b/cli/src/engines/__fixtures__/other-admission.golden.json
index 6fe5d0f0e..38cd09fad 100644
--- a/cli/src/engines/__fixtures__/other-admission.golden.json
+++ b/cli/src/engines/__fixtures__/other-admission.golden.json
@@ -113,15 +113,20 @@
{
"pending": true
},
+ [],
[
- {
- "sessionId": "20261008_100009_999999",
- "engine": "hermes",
- "hermesHome": null
- }
- ],
+ "[hooks] 20261008 SessionStart held · Waiting for the Hermes session source record; keeping the current conversation."
+ ]
+ ],
+ [
+ "one whose candidate store cannot be read",
+ 200,
+ {
+ "pending": true
+ },
+ [],
[
- "[hooks] 20261008 SessionStart · engine=hermes · isNew=true · after a source check"
+ "[hooks] 20261008 SessionStart held · Hermes session source is unavailable; keeping the current conversation."
]
]
],
diff --git a/cli/src/engines/__fixtures__/other-identity.golden.json b/cli/src/engines/__fixtures__/other-identity.golden.json
index bbe2d1c73..6ccfc9a51 100644
--- a/cli/src/engines/__fixtures__/other-identity.golden.json
+++ b/cli/src/engines/__fixtures__/other-identity.golden.json
@@ -1,4 +1,71 @@
{
+ "Hermes id rules": [
+ [
+ "20261008_110000_a1b2",
+ true,
+ true
+ ],
+ [
+ "20261008_110000_ABCDEF",
+ true,
+ true
+ ],
+ [
+ "20261008_110000_0123456789abcdef",
+ true,
+ true
+ ],
+ [
+ "20261008_110000_abc",
+ false,
+ false
+ ],
+ [
+ "20261008_110000_0123456789abcdef0",
+ false,
+ false
+ ],
+ [
+ "20261008_110000_ghijkl",
+ false,
+ false
+ ],
+ [
+ "0b6f4f2e-6c1a-4c55-9a51-000000000001",
+ true,
+ false
+ ],
+ [
+ "0B6F4F2E-6C1A-4C55-9A51-000000000001",
+ true,
+ false
+ ],
+ [
+ "",
+ false,
+ false
+ ],
+ [
+ "../escape",
+ false,
+ false
+ ],
+ [
+ "20261008_110000_a1b2.jsonl",
+ false,
+ false
+ ],
+ [
+ " 20261008_110000_a1b2",
+ false,
+ false
+ ],
+ [
+ "20261008_110000_a1b2\n",
+ false,
+ false
+ ]
+ ],
"register": [
[
"commandcode",
diff --git a/cli/src/engines/kit/storeHomes.spec.ts b/cli/src/engines/kit/storeHomes.spec.ts
new file mode 100644
index 000000000..ef0dfd7d7
--- /dev/null
+++ b/cli/src/engines/kit/storeHomes.spec.ts
@@ -0,0 +1,39 @@
+import { afterEach, expect, it, vi } from 'vitest'
+import { readdir, stat } from 'node:fs/promises'
+import { join } from 'node:path'
+import { forgetStoreHomes, listStoreHomes, readStoreHomes } from './storeHomes.js'
+
+vi.mock('node:fs/promises', () => ({ readdir: vi.fn(), stat: vi.fn() }))
+const declared = { profiles: 'profiles', store: (home: string) => join(home, 'state.db'), max: 2, ttlMs: 30_000 }
+const directory = (name: string) => ({ name, isDirectory: () => true })
+const entries = (...names: string[]) => vi.mocked(readdir).mockResolvedValue(names.map(directory) as never)
+afterEach(() => { vi.resetAllMocks(); forgetStoreHomes(declared) })
+
+it('uses fresh admission evidence even when optional readers have a cached listing', async () => {
+ entries()
+ expect(await listStoreHomes(declared, '/home')).toEqual(['/home'])
+ entries('new')
+ vi.mocked(stat).mockResolvedValue({ isFile: () => true } as never)
+ expect(await readStoreHomes(declared, '/home')).toEqual({ homes: ['/home', '/home/profiles/new'], complete: true })
+ expect(await listStoreHomes(declared, '/home')).toEqual(['/home'])
+})
+
+it('distinguishes known absence from incomplete enumeration, unreadable stores and truncation', async () => {
+ for (const code of ['ENOENT', 'EACCES']) {
+ vi.mocked(readdir).mockRejectedValueOnce(Object.assign(new Error('directory read failed'), { code }))
+ expect(await readStoreHomes(declared, '/home')).toEqual({ homes: ['/home'], complete: code === 'ENOENT' })
+ }
+ entries('a', 'b')
+ vi.mocked(stat).mockRejectedValueOnce(Object.assign(new Error('missing'), { code: 'ENOENT' }))
+ .mockResolvedValueOnce({ isFile: () => true } as never)
+ expect(await readStoreHomes(declared, '/home')).toEqual({ homes: ['/home', '/home/profiles/b'], complete: true })
+ vi.mocked(stat).mockRejectedValueOnce(Object.assign(new Error('denied'), { code: 'EACCES' }))
+ .mockResolvedValueOnce({ isFile: () => true } as never)
+ expect(await readStoreHomes(declared, '/home')).toEqual({ homes: ['/home', '/home/profiles/b'], complete: false })
+ entries('a', 'b', 'omitted')
+ vi.mocked(stat).mockResolvedValue({ isFile: () => true } as never)
+ expect(await readStoreHomes(declared, '/home')).toEqual({ homes: ['/home', '/home/profiles/a', '/home/profiles/b'], complete: false })
+ vi.mocked(readdir).mockResolvedValue([{ name: 'ordinary-file', isDirectory: () => false }, directory('bad-store')] as never)
+ vi.mocked(stat).mockResolvedValue({ isFile: () => false } as never)
+ expect(await readStoreHomes(declared, '/home')).toEqual({ homes: ['/home'], complete: false })
+})
diff --git a/cli/src/engines/kit/storeHomes.ts b/cli/src/engines/kit/storeHomes.ts
index f21507efb..1fc336c3d 100644
--- a/cli/src/engines/kit/storeHomes.ts
+++ b/cli/src/engines/kit/storeHomes.ts
@@ -22,6 +22,29 @@ export interface StoreHomes {
const listings = new WeakMap<StoreHomes, { at: number; homes: string[] }>()
+/** Fresh evidence for admission. An incomplete profile list cannot authorize a profile binding. */
+export async function readStoreHomes(declared: StoreHomes, defaultHome: string): Promise<{ homes: string[]; complete: boolean }> {
+ const homes = [defaultHome]
+ let complete = true
+ try {
+ const entries = await readdir(join(defaultHome, declared.profiles), { withFileTypes: true })
+ if (entries.length > declared.max) complete = false
+ for (const entry of entries.slice(0, declared.max)) {
+ if (!entry.isDirectory()) continue
+ const home = join(defaultHome, declared.profiles, entry.name)
+ try {
+ if ((await stat(declared.store(home))).isFile()) homes.push(home)
+ else complete = false
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false
+ }
+ }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') complete = false
+ }
+ return { homes, complete }
+}
+
/** Every home, the default first. */
export async function listStoreHomes(declared: StoreHomes, defaultHome: string): Promise<string[]> {
const now = Date.now()
diff --git a/cli/src/engines/kit/storeSource.spec.ts b/cli/src/engines/kit/storeSource.spec.ts
new file mode 100644
index 000000000..4a839109b
--- /dev/null
+++ b/cli/src/engines/kit/storeSource.spec.ts
@@ -0,0 +1,47 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { stat } from 'node:fs/promises'
+import { sqliteReadAll } from '../../lib/sqliteRead.js'
+import { isInteractiveSource, readStoreSessionSource, storeSessionSource } from './storeSource.js'
+
+vi.mock('node:fs/promises', () => ({ stat: vi.fn(async () => ({})) }))
+vi.mock('../../lib/sqliteRead.js', () => ({ sqliteReadAll: vi.fn() }))
+const rule = { id: /^session$/, query: 'SELECT source FROM sessions WHERE id = ?', column: 'source', interactive: ['', 'cli'], maxBuffer: 1024 }
+afterEach(() => { vi.mocked(stat).mockReset().mockResolvedValue({} as never); vi.mocked(sqliteReadAll).mockReset() })
+
+describe('store source evidence', () => {
+ it('keeps unsupported id behavior without consulting storage', async () => {
+ expect(await readStoreSessionSource(rule, '/fixture/store', 'other')).toBe('')
+ expect(stat).not.toHaveBeenCalled()
+ expect(sqliteReadAll).not.toHaveBeenCalled()
+ expect(isInteractiveSource(rule, '')).toBe(true)
+ expect(isInteractiveSource(rule, 'tool')).toBe(false)
+ })
+
+ it('separates missing stores, unreadable files, and failed readers', async () => {
+ vi.mocked(stat).mockRejectedValueOnce(Object.assign(new Error('gone'), { code: 'ENOENT' }))
+ expect(await readStoreSessionSource(rule, '/fixture/store', 'session')).toBeNull()
+ vi.mocked(stat).mockRejectedValueOnce(Object.assign(new Error('denied'), { code: 'EACCES' }))
+ expect(await readStoreSessionSource(rule, '/fixture/store', 'session')).toEqual({ unavailable: true, reason: 'transient' })
+ for (const reason of ['missing', 'transient'] as const) {
+ vi.mocked(sqliteReadAll).mockResolvedValueOnce({ ok: false, reason })
+ expect(await readStoreSessionSource(rule, '/fixture/store', 'session')).toEqual({ unavailable: true, reason })
+ }
+ })
+
+ it('accepts only an actual row as source evidence and preserves optional-reader unknowns', async () => {
+ for (const [rows, expected] of [[[], null], [[{ source: 'cli' }], 'cli'], [[{ source: 'tool' }], 'tool'], [[{ source: '' }], ''], [[{}], null]] as const) {
+ vi.mocked(sqliteReadAll).mockResolvedValueOnce({ ok: true, rows: [...rows], via: 'builtin' })
+ expect(await storeSessionSource(rule, '/fixture/store', 'session')).toBe(expected)
+ }
+ vi.mocked(sqliteReadAll).mockResolvedValueOnce({ ok: false, reason: 'transient' })
+ expect(await storeSessionSource(rule, '/fixture/store', 'session')).toBeNull()
+ expect(sqliteReadAll).toHaveBeenCalledWith('/fixture/store', rule.query, ['session'], { maxBuffer: 1024 })
+ })
+
+ it('holds malformed source values instead of turning them into the interactive empty string', async () => {
+ for (const source of [undefined, null, 42, Buffer.from('cli')]) {
+ vi.mocked(sqliteReadAll).mockResolvedValueOnce({ ok: true, rows: [{ source }], via: 'builtin' })
+ expect(await readStoreSessionSource(rule, '/fixture/store', 'session')).toEqual({ unavailable: true, reason: 'transient' })
+ }
+ })
+})
diff --git a/cli/src/engines/kit/storeSource.ts b/cli/src/engines/kit/storeSource.ts
index d6324f261..90c5f5a83 100644
--- a/cli/src/engines/kit/storeSource.ts
+++ b/cli/src/engines/kit/storeSource.ts
@@ -1,13 +1,15 @@
/**
* Whether a hook's session is a pane's own or one a session delegated to, read from the engine's store as its
* contract declares (Hermes: `sessions.source`). A delegated session runs its hooks from the parent's pane, so the
- * hook server settles this before the session may take the pane (hookServer.ts `awaitHermesKind`).
+ * hook server verifies this before the session may take the pane (hookServer.ts `inspectHermesKind`).
*
- * Moved from engines/hermes/reader.ts (`hermesSessionSource`, `isHermesInteractiveSource`), unchanged but for the
- * declaration it reads. Read through `lib/sqliteRead` like every other query against such a store: the engine
+ * The source rule is declared by the engine. Read through `lib/sqliteRead` like every other query against such a store: the engine
* writes to it constantly, and the read's busy wait is bounded there so a contended lookup cannot park the daemon.
*/
import { sqliteReadAll } from '../../lib/sqliteRead.js'
+import { stat } from 'node:fs/promises'
+
+export type StoreSessionSource = string | null | { unavailable: true; reason: 'missing' | 'transient' }
export interface StoreSourceRule {
/** The ids a pane's own session has. Any other (an editor's) reads as a pane's own: `''`. */
@@ -28,13 +30,23 @@ export interface StoreSourceRule {
* its row, so an immediate lookup said "not a sub-agent" and the child took over the pane. Callers that can afford
* to wait should treat null as "ask again shortly".
*/
-export async function storeSessionSource(rule: StoreSourceRule, dbPath: string, sessionId: string): Promise<string | null> {
+export async function readStoreSessionSource(rule: StoreSourceRule, dbPath: string, sessionId: string): Promise<StoreSessionSource> {
if (!rule.id.test(sessionId)) return ''
+ // A home with no store yet is different from a store whose rows cannot be verified.
+ try { await stat(dbPath) } catch (error) {
+ return (error as NodeJS.ErrnoException).code === 'ENOENT' ? null : { unavailable: true, reason: 'transient' }
+ }
const result = await sqliteReadAll(dbPath, rule.query, [sessionId], { maxBuffer: rule.maxBuffer })
- if (!result.ok) return '' // no reader / db locked — treat as a normal session, exactly as before
+ if (!result.ok) return { unavailable: true, reason: result.reason }
if (result.rows.length === 0) return null
const source = result.rows[0]?.[rule.column]
- return typeof source === 'string' ? source : ''
+ return typeof source === 'string' ? source : { unavailable: true, reason: 'transient' }
+}
+
+/** Compatibility for optional readers: unknown stays unknown, never an interactive source. */
+export async function storeSessionSource(rule: StoreSourceRule, dbPath: string, sessionId: string): Promise<string | null> {
+ const source = await readStoreSessionSource(rule, dbPath, sessionId)
+ return source !== null && typeof source === 'object' ? null : source
}
/** Whether a source is a pane's own session's. */
diff --git a/cli/src/engines/otherAdmission.golden.spec.ts b/cli/src/engines/otherAdmission.golden.spec.ts
index f0235e628..31ae86b2f 100644
--- a/cli/src/engines/otherAdmission.golden.spec.ts
+++ b/cli/src/engines/otherAdmission.golden.spec.ts
@@ -48,6 +48,7 @@ function check(key: string, value: unknown): void {
}
const saved: Record<string, string | undefined> = {}
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
type Modules = {
registry: typeof import('../lib/registry.js')
hookServer: typeof import('../hookServer.js')
@@ -58,6 +59,7 @@ let m: Modules
const home = (...parts: string[]) => join(root, 'home', ...parts)
beforeAll(async () => {
+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })
root = realpathSync(mkdtempSync(join(tmpdir(), 'other-admission-golden-')))
const env: Record<string, string | undefined> = {
HOME: home(), ADAPTER_DATA_DIR: join(root, 'data'), ADAPTER_RUNTIME_DIR: join(root, 'runtime'), HERMES_HOME: home('.hermes'),
@@ -80,6 +82,7 @@ beforeAll(async () => {
})
afterAll(() => {
+ Object.defineProperty(process, 'platform', platform)
for (const [name, value] of Object.entries(saved)) if (value === undefined) delete process.env[name]; else process.env[name] = value
if (root) rmSync(root, { recursive: true, force: true })
if (RECORD) writeFileSync(GOLDEN, JSON.stringify(recorded, null, 1) + '\n')
@@ -124,9 +127,19 @@ describe('how the core admits a Hermes session and learns its home', () => {
['one in both homes: the default asked first', '20261008_100002_dddddd'],
['an editor\'s session, whose id is a uuid', '0b6f4f2e-6c1a-4c55-9a51-000000000001'],
['one no store holds yet', '20261008_100009_999999'],
+ ['one whose candidate store cannot be read', '20261008_100010_aaaaaa'],
] as const
let pane = 0
for (const [label, sessionId] of cases) {
+ if (label === 'one whose candidate store cannot be read') {
+ // Added only after the existing cases; preserve their former inputs and outcomes.
+ // Invalid SQLite bytes are unreadable on every host, including privileged CI users.
+ mkdirSync(home('.hermes', 'profiles', 'unreadable'), { recursive: true })
+ writeFileSync(home('.hermes', 'profiles', 'unreadable', 'state.db'), 'not a SQLite database')
+ const { forgetStoreHomes } = await import('./kit/storeHomes.js')
+ const { HERMES_HOMES } = await import('./hermes/contract.js')
+ forgetStoreHomes(HERMES_HOMES)
+ }
const tmuxPane = `%${++pane}`
m.registry.registry.openProcessAgent({ engine: 'hermes', tmuxPane, cwd: '/work/h', processIdentity: { pid: 20_000 + pane, startMarker: START, executable: 'python3' } })
registered.length = 0
@@ -135,9 +148,9 @@ describe('how the core admits a Hermes session and learns its home', () => {
method: 'POST', headers, body: JSON.stringify({ engine: 'hermes', tmuxPane, sessionId, cwd: '/work/h', hookEvent: 'SessionStart' }),
})
const answer = await response.json()
- // Settled off the HTTP path: registered, or ignored, within the bounded wait for a row.
+ // Settled off the HTTP path: verified, rejected, or explicitly held without a registry write.
const deadline = Date.now() + 10_000
- while (!registered.length && !logs.some((line) => line.includes('ignored')) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20))
+ while (!registered.length && !logs.some((line) => line.includes('ignored') || line.includes(' held ·')) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 20))
results.push([label, response.status, answer, [...registered], logs.filter((line) => line.startsWith('[hooks]'))])
}
check('admission', results)
diff --git a/cli/src/engines/otherIdentity.golden.spec.ts b/cli/src/engines/otherIdentity.golden.spec.ts
index ec9f4fcc6..5cf96a717 100644
--- a/cli/src/engines/otherIdentity.golden.spec.ts
+++ b/cli/src/engines/otherIdentity.golden.spec.ts
@@ -11,20 +11,33 @@
* - Cursor's homes, and the hook command that names them.
*
* Every home is under a throwaway root named through the environment, which is pinned whatever the host sets;
- * file times are set, the clock and `process.platform` pinned (agy is asked about a process that does not exist,
- * through /proc, on every host), `TZ` is UTC, and no path's length matters. Results name the root `<root>`. One case
- * runs on the host's own platform: agy's lock, held open by this very process, read as each platform reads it.
+ * file times are set, the clock and `process.platform` pinned, `TZ` is UTC, and no path's length matters. Results
+ * name the root `<root>`. Agy's Linux descriptor lookup reads controlled /proc entries, never host processes.
*
* `RECORD_OTHER_ENGINES_GOLDEN=1` writes the fixture. Record it again only for a change meant to alter where these
* engines' conversations are found, and say so in that change.
*/
-import { closeSync, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import type { AgentEngine } from './types.js'
+const descriptors = vi.hoisted(() => new Map<string, string[]>())
+vi.mock('fs/promises', async (original) => {
+ const fs = await original<typeof import('node:fs/promises')>()
+ return { ...fs,
+ readdir: async (path: string, ...args: unknown[]) => /^\/proc\/\d+\/fd$/.test(String(path))
+ ? (descriptors.get(String(path)) ?? []).map((_, index) => String(index))
+ : Reflect.apply(fs.readdir, fs, [path, ...args]),
+ readlink: async (path: string, ...args: unknown[]) => {
+ const match = /^(\/proc\/\d+\/fd)\/(\d+)$/.exec(String(path))
+ return match ? descriptors.get(match[1]!)?.[Number(match[2])] ?? '' : Reflect.apply(fs.readlink, fs, [path, ...args])
+ },
+ }
+})
+
const GOLDEN = fileURLToPath(new URL('./__fixtures__/other-identity.golden.json', import.meta.url))
const RECORD = process.env.RECORD_OTHER_ENGINES_GOLDEN === '1'
const NOW = Date.parse('2026-10-08T12:00:00.000Z')
@@ -59,6 +72,7 @@ type Modules = {
bind: typeof import('../core/agents/bind.js')
notify: typeof import('./kit/notifyHooks.js')
home: typeof import('./cursor/home.js')
+ hermes: typeof import('./hermes/contract.js')
}
let m: Modules
@@ -88,6 +102,7 @@ beforeAll(async () => {
bind: await import('../core/agents/bind.js'),
notify: await import('./kit/notifyHooks.js'),
home: await import('./cursor/home.js'),
+ hermes: await import('./hermes/contract.js'),
}
m.registry.registry.load()
golden = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8')) as Record<string, unknown>
@@ -113,6 +128,13 @@ function register(engine: AgentEngine, input: { sessionId: string; cwd?: string;
}
describe('where the core finds the other engines\' conversations', () => {
+ it('distinguishes Hermes history ids from ids admitted by a terminal hook', () => {
+ const ids = ['20261008_110000_a1b2', '20261008_110000_ABCDEF', '20261008_110000_0123456789abcdef',
+ '20261008_110000_abc', '20261008_110000_0123456789abcdef0', '20261008_110000_ghijkl', UUID(1), UUID(1).toUpperCase(),
+ '', '../escape', '20261008_110000_a1b2.jsonl', ' 20261008_110000_a1b2', '20261008_110000_a1b2\n']
+ check('Hermes id rules', ids.map(id => [id, m.hermes.HERMES_HISTORY_ID_RE.test(id), m.hermes.HERMES_SOURCE.id.test(id)]))
+ })
+
it('derives each layout\'s transcript for a hook that names none, and takes one it names only in its own folder', () => {
const cwds = ['/work/My Project', '/work/camelCaseRepo', '/work/über-ünïcødé', '/', '/work/a/../b']
const results: unknown[] = []
@@ -248,20 +270,17 @@ describe('where the core finds the other engines\' conversations', () => {
check('repair', results)
}, 60_000)
- it('repairs agy\'s session from the lock its live process holds open, read as the host reads it', async () => {
+ it('repairs agy\'s session from controlled Linux descriptor evidence of its held lock', async () => {
const id = UUID(50)
file(home('.gemini', 'antigravity-cli', 'brain', id, '.system_generated', 'logs', 'transcript_full.jsonl'), '{}\n')
const lock = file(home('.gemini', 'antigravity-cli', 'presence', `${id}.lock`))
const results: unknown[] = []
- // Linux reads /proc, any other host lsof: this process's own descriptors, the same on both.
- Object.defineProperty(process, 'platform', platform)
+ descriptors.set('/proc/4242/fd', [lock])
try {
- const held = openSync(lock, 'r')
- try {
- results.push(['held', await m.repair.findLiveSession('agy', '/work/r', T0, { pid: process.pid })])
- } finally { closeSync(held) }
- results.push(['let go', await m.repair.findLiveSession('agy', '/work/r', T0, { pid: process.pid })])
- } finally { Object.defineProperty(process, 'platform', { ...platform, value: 'linux' }) }
+ results.push(['held', await m.repair.findLiveSession('agy', '/work/r', T0, { pid: 4242 })])
+ descriptors.delete('/proc/4242/fd')
+ results.push(['let go', await m.repair.findLiveSession('agy', '/work/r', T0, { pid: 4242 })])
+ } finally { descriptors.clear() }
check('repair agy lock', results)
}, 60_000)
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index b1726b86a..96e09876f 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -733,6 +733,41 @@ describe('hook notify terminal scope', () => {
}
})
+ it.each(['recovers', 'full', 'resolving', 'disconnects'] as const)('Hermes live admission %s retries within a bound and never writes an offline registry', async outcome => {
+ const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-hermes-held-'))
+ tmpDirs.push(dir)
+ const dataDir = join(dir, 'data')
+ mkdirSync(dataDir)
+ writeLegacyStateFile(join(dataDir, 'registry.json'), '[]')
+ let attempts = 0
+ const firedAt: unknown[] = []
+ const server = createServer((req, res) => {
+ if (req.method !== 'POST') { req.resume(); res.writeHead(405).end(); return }
+ req.resume()
+ req.on('end', () => {
+ attempts++
+ firedAt.push(req.headers['x-harness-hook-fired-at'])
+ if (outcome === 'disconnects' && attempts > 1) { res.destroy(); return }
+ if (outcome === 'recovers' && attempts === 3) { res.end(JSON.stringify({ pending: true })); return }
+ res.writeHead(outcome === 'resolving' ? 202 : 429)
+ res.end(JSON.stringify({ pending: false, retry: true, error: 'HOOK_ADMISSION_BUSY' }))
+ })
+ })
+ servers.push(server)
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
+ const address = server.address()
+ if (!address || typeof address === 'string') throw new Error('private fixture did not bind')
+ expect(await runHook({ port: address.port, tmuxPane: '%82', engine: 'hermes', processEngine: 'hermes',
+ processExecutable: 'python3', processArgs: 'python3 /opt/venvs/hermes/lib/python3.12/site-packages/hermes-agent/hermes',
+ dataDir, hermesHome: join(dir, 'hermes'), hermesSource: 'cli',
+ input: { hook_event_name: 'on_session_start', session_id: '20260810_120000_a1b2c3' },
+ })).toBe('{}\n')
+ expect(attempts).toBe(outcome === 'recovers' ? 3 : outcome === 'disconnects' ? 2 : 4)
+ expect(new Set(firedAt).size).toBe(1)
+ expect(readFileSync(join(dataDir, 'registry.json'), 'utf8')).toBe('[]')
+ expect(() => statSync(join(dataDir, 'registry-boot'))).toThrow()
+ })
+
it.each([
"import sys, runpy; sys.path.insert(0, '/opt/custom'); runpy.run_module('hermes_cli.main', run_name='__main__')",
"import os, re, sys; sys.path.insert(0, '/opt/custom'); import hermes_bootstrap; from hermes_cli.main import main; sys.exit(main())",
diff --git a/cli/src/hookServer.hermes.spec.ts b/cli/src/hookServer.hermes.spec.ts
new file mode 100644
index 000000000..44c97a73e
--- /dev/null
+++ b/cli/src/hookServer.hermes.spec.ts
@@ -0,0 +1,254 @@
+/** Real hook admission and private SQLite homes; no daemon, tmux server or native user home. */
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import type { Server } from 'node:http'
+
+const failures = vi.hoisted(() => new Map<string, string>())
+vi.mock('node:fs/promises', async original => {
+ const fs = await original<typeof import('node:fs/promises')>()
+ const guarded = (name: 'stat' | 'readdir') => async (path: string, ...args: unknown[]) => {
+ const code = failures.get(`${name}:${path}`)
+ if (code) throw Object.assign(new Error('controlled filesystem failure'), { code })
+ return Reflect.apply(fs[name], fs, [path, ...args])
+ }
+ return { ...fs, stat: guarded('stat'), readdir: guarded('readdir') }
+})
+
+let root = ''
+let server: Server | undefined
+afterEach(async () => {
+ if (server) await new Promise<void>(resolve => server!.close(() => resolve()))
+ server = undefined
+ vi.restoreAllMocks(); vi.unstubAllEnvs()
+ failures.clear()
+ if (root) rmSync(root, { recursive: true, force: true })
+})
+async function fixture(options: { waitOnResolution?: number } = {}) {
+ root = mkdtempSync(join(tmpdir(), 'hermes-admission-'))
+ for (const [key, value] of Object.entries({ HOME: join(root, 'home'), HERMES_HOME: join(root, 'home', '.hermes'),
+ ADAPTER_DATA_DIR: join(root, 'data'), ADAPTER_RUNTIME_DIR: join(root, 'runtime') })) vi.stubEnv(key, value)
+ vi.resetModules()
+ const { registry } = await import('./lib/registry.js')
+ const { startHookServer } = await import('./hookServer.js')
+ const { readHookCredential } = await import('./lib/hookAuth.js')
+ const { markDeleted } = await import('./lib/deletedSessions.js')
+ const { DatabaseSync } = process.getBuiltinModule('node:sqlite') as {
+ DatabaseSync: new (path: string) => { exec(sql: string): void; prepare(sql: string): { run(...args: string[]): void }; close(): void }
+ }
+ const home = join(root, 'home', '.hermes')
+ const store = (dir: string, rows: Array<[string, string]>) => {
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'state.db')
+ rmSync(file, { force: true })
+ const db = new DatabaseSync(file)
+ db.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY, source TEXT)')
+ const insert = db.prepare('INSERT INTO sessions VALUES (?, ?)')
+ for (const row of rows) insert.run(...row)
+ db.close()
+ }
+ const processIdentity = { pid: 4242, startMarker: 'Thu Oct 8 12:00:00 2026', executable: 'hermes' }
+ const { entry: agent } = registry.openProcessAgent({ engine: 'hermes', tmuxPane: '%1', cwd: root, processIdentity })!
+ const registered = vi.fn()
+ const logs: string[] = []
+ vi.spyOn(console, 'log').mockImplementation((...args) => { logs.push(args.map(String).join(' ')) })
+ let resume!: () => void
+ let resolutions = 0
+ const started = await startHookServer(0, { onRegistered: registered, onSessionEnd: () => {},
+ ...(options.waitOnResolution ? { resolveHookAgent: async ({ onWait }: { onWait?: () => void }) => {
+ if (++resolutions === options.waitOnResolution) { onWait?.(); await new Promise<void>(resolve => { resume = resolve }) }
+ return registry.byAgent(agent.agentId) ?? null
+ } } : {}),
+ })
+ server = started.server
+ let firedAt = Date.now()
+ const hook = async (sessionId: string, status = 200, fired = ++firedAt) => {
+ const response = await fetch(`http://127.0.0.1:${started.port}/api/hook/session-start`, {
+ method: 'POST', headers: { 'content-type': 'application/json', 'x-harness-hook-token': readHookCredential(join(root, 'data'))!,
+ 'x-harness-hook-fired-at': String(fired) },
+ body: JSON.stringify({ engine: 'hermes', tmuxPane: '%1', sessionId, cwd: root, hookEvent: 'SessionStart' }),
+ })
+ expect(response.status).toBe(status)
+ const body = await response.json()
+ if (status === 200) expect(body).toEqual({ pending: true })
+ return body
+ }
+ const current = () => registry.byAgent(agent.agentId)!
+ return { home, store, hook, current, registered, logs, markDeleted, resume: () => resume(),
+ seed: (sessionId: string) => registry.register({ engine: 'hermes', sessionId, tmuxPane: '%1', cwd: root, processIdentity }),
+ }
+}
+
+it('holds an unreadable store without binding and retries after the store recovers', async () => {
+ const f = await fixture()
+ const previous = '20261009_115900_eeeeee'
+ f.store(f.home, [[previous, 'cli']])
+ await f.hook(previous)
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(previous))
+ f.registered.mockClear()
+ writeFileSync(join(f.home, 'state.db'), 'not SQLite')
+ const wanted = '20261009_120000_aaaaaa'
+ await f.hook(wanted)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('held · Hermes session source is unavailable'))).toBe(true))
+ expect(f.current().sessionId).toBe(previous)
+ expect(f.current().hermesHome).toBeNull()
+ expect(f.registered).not.toHaveBeenCalled()
+ f.store(f.home, [[wanted, 'cli']])
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(wanted), { timeout: 4_000 })
+ expect(f.registered).toHaveBeenCalledOnce()
+})
+
+it('cannot let an unreadable home hide a delegated session in a healthy profile', async () => {
+ const f = await fixture()
+ mkdirSync(f.home, { recursive: true })
+ writeFileSync(join(f.home, 'state.db'), 'not SQLite')
+ const child = '20261009_120000_bbbbbb'
+ f.store(join(f.home, 'profiles', 'work'), [[child, 'tool']])
+ await f.hook(child)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('ignored · hermes_subagent'))).toBe(true))
+ expect(f.current().sessionId).toBe('')
+ expect(f.registered).not.toHaveBeenCalled()
+})
+
+it('keeps a missing source row pending and replaces an older pending hook', async () => {
+ const f = await fixture()
+ f.store(f.home, [])
+ const old = '20261009_120000_cccccc', newer = '20261009_120000_dddddd'
+ await f.hook(old)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('held · Waiting for the Hermes session source record'))).toBe(true))
+ expect(f.current().sessionId).toBe('')
+ f.store(f.home, [[old, 'cli'], [newer, 'cli']])
+ await f.hook(newer)
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(newer))
+ await new Promise(resolve => setTimeout(resolve, 1_100))
+ expect(f.current().sessionId).toBe(newer)
+ expect(f.registered).toHaveBeenCalledOnce()
+})
+
+it('recovers a held parent after rejecting its newer delegated hook', async () => {
+ const f = await fixture()
+ mkdirSync(f.home, { recursive: true })
+ writeFileSync(join(f.home, 'state.db'), 'not SQLite')
+ const parent = '20261009_120000_111111', child = '20261009_120000_222222'
+ await f.hook(parent)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('held ·'))).toBe(true))
+ await f.hook(child)
+ f.store(f.home, [[parent, 'cli'], [child, 'tool']])
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(parent), { timeout: 4_000 })
+ expect(f.registered).toHaveBeenCalledOnce()
+ expect(f.logs.some(line => line.includes('ignored · hermes_subagent'))).toBe(true)
+})
+
+it('recovers an equal-time parent after its child has already been held', async () => {
+ const f = await fixture()
+ f.store(f.home, [])
+ const parent = '20261009_120000_121212', child = '20261009_120000_343434'
+ await f.hook(child, 200, 1000)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('held ·'))).toBe(true))
+ f.store(f.home, [[parent, 'cli']])
+ await f.hook(parent, 200, 1000)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('unambiguous Hermes hook order'))).toBe(true))
+ f.store(f.home, [[parent, 'cli'], [child, 'tool']])
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(parent), { timeout: 4_000 })
+ expect(f.registered).toHaveBeenCalledOnce()
+})
+
+it.each(['stat', 'readdir'] as const)('holds incomplete %s evidence, then discovers the recovered profile afresh', async operation => {
+ const f = await fixture()
+ f.store(f.home, [])
+ const wanted = '20261009_120000_333333'
+ const first = join(f.home, 'profiles', 'a'), second = join(f.home, 'profiles', 'b')
+ f.store(first, [[wanted, 'cli']]); f.store(second, [[wanted, 'cli']])
+ failures.set(operation === 'stat' ? `stat:${join(first, 'state.db')}` : `readdir:${join(f.home, 'profiles')}`, 'EACCES')
+ await f.hook(wanted)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('held · Hermes session source is unavailable'))).toBe(true))
+ expect(f.current().sessionId).toBe('')
+ expect(f.current().hermesHome).toBeNull()
+ expect(f.registered).not.toHaveBeenCalled()
+ failures.clear()
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(wanted), { timeout: 4_000 })
+ expect(f.current().hermesHome).toBe(first)
+})
+
+it('cannot publish a different pending conversation after Stop tombstones the agent', async () => {
+ const f = await fixture()
+ const previous = '20261009_120000_444444', pending = '20261009_120000_555555'
+ f.store(f.home, [[previous, 'cli']])
+ await f.hook(previous)
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(previous))
+ f.registered.mockClear()
+ await f.hook(pending)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('held ·'))).toBe(true))
+ f.markDeleted(f.current().agentId)
+ f.store(f.home, [[previous, 'cli'], [pending, 'cli']])
+ await new Promise(resolve => setTimeout(resolve, 1_100))
+ expect(f.current().sessionId).toBe(previous)
+ expect(f.registered).not.toHaveBeenCalled()
+})
+
+it('contains an asynchronous onRegistered rejection after publishing exactly once', async () => {
+ const f = await fixture()
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ f.registered.mockRejectedValue(new Error('attachment unavailable'))
+ const wanted = '20261009_120000_666666'
+ f.store(f.home, [[wanted, 'cli']])
+ await f.hook(wanted)
+ await vi.waitFor(() => expect(warning).toHaveBeenCalledWith('[hooks] pending admission callback failed', expect.any(Error)))
+ expect(f.current().sessionId).toBe(wanted)
+ expect(f.registered).toHaveBeenCalledOnce()
+})
+
+it.each([false, true])('reports capacity backpressure without claiming the extra hook was queued (resolution waits: %s)', async waits => {
+ const f = await fixture(waits ? { waitOnResolution: 65 } : {})
+ f.store(f.home, [])
+ for (let i = 0; i < 64; i++) await f.hook(`20261009_120000_${i.toString(16).padStart(6, '0')}`)
+ if (waits) {
+ expect(await f.hook('20261009_120000_ffffff', 202)).toMatchObject({ pending: false, retry: true })
+ f.resume()
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('this hook was not queued'))).toBe(true))
+ } else expect(await f.hook('20261009_120000_ffffff', 429)).toEqual({
+ pending: false, error: 'HOOK_ADMISSION_BUSY', detail: expect.stringContaining('was not queued'),
+ })
+ expect(f.current().sessionId).toBe('')
+ expect(f.registered).not.toHaveBeenCalled()
+})
+
+it('does not make a verified default-home binding depend on unavailable profiles', async () => {
+ const f = await fixture()
+ const own = '20261009_120000_777777'
+ f.store(f.home, [[own, 'cli']])
+ failures.set(`readdir:${join(f.home, 'profiles')}`, 'EACCES')
+ await f.hook(own)
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(own))
+ expect(f.current().hermesHome).toBeNull()
+})
+
+it('never lets delayed process resolution or a retry of A replace a newer accepted B', async () => {
+ const f = await fixture({ waitOnResolution: 1 })
+ const a = '20261009_120000_888888', b = '20261009_120000_999999'
+ f.store(f.home, [[a, 'cli'], [b, 'cli']])
+ expect(await f.hook(a, 202, 1000)).toMatchObject({ pending: false, retry: true })
+ await f.hook(b, 200, 2000)
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(b))
+ f.resume()
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('ignored · stale_hook'))).toBe(true))
+ await f.hook(a, 200, 1000)
+ await vi.waitFor(() => expect(f.logs.filter(line => line.includes('ignored · stale_hook'))).toHaveLength(2))
+ expect(f.current().sessionId).toBe(b)
+ expect(f.registered).toHaveBeenCalledOnce()
+})
+
+it('starts with the existing binding as authority when no hook watermark exists yet', async () => {
+ const f = await fixture()
+ const a = '20261009_120000_aaaaaa', b = '20261009_120000_bbbbbb'
+ f.store(f.home, [[a, 'cli'], [b, 'cli']])
+ f.seed(b)
+ const boundAt = f.current().boundAt!
+ await f.hook(a, 200, boundAt - 1)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('ignored · stale_hook'))).toBe(true))
+ expect(f.current().sessionId).toBe(b)
+ await f.hook(a, 200, boundAt + 1)
+ await vi.waitFor(() => expect(f.current().sessionId).toBe(a))
+ expect(f.registered).toHaveBeenCalledOnce()
+})
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 4daa4f7d0..fbb1ad4e4 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -10,8 +10,11 @@ import http from 'node:http'
import type { AddressInfo } from 'node:net'
import { admitHook, hooksFor } from './engines/hooks.js'
import { HERMES_HOMES, HERMES_SOURCE, hermesDbPath } from './engines/hermes/contract.js'
-import { listStoreHomes } from './engines/kit/storeHomes.js'
-import { isInteractiveSource, storeSessionSource } from './engines/kit/storeSource.js'
+import { readStoreHomes } from './engines/kit/storeHomes.js'
+import { isInteractiveSource, readStoreSessionSource } from './engines/kit/storeSource.js'
+import { createPendingAdmissions, type AdmissionDecision } from './core/engines/pendingAdmission.js'
+import { paneReadIdentity } from './core/transcripts/readIdentity.js'
+import { processIdentityKey } from './lib/terminalRuntime.js'
import { isRecentlyDeleted } from './lib/deletedSessions.js'
import { registry, type RegisterInput, type RegisteredSession } from './lib/registry.js'
import { sid } from './lib/log.js'
@@ -68,7 +71,7 @@ export interface HookServerHandlers {
orphaned?: { agentId: string; sessionId: string } | null
hookEvent?: string
},
- ) => void
+ ) => void | Promise<void>
/** SessionEnd — a reconciliation hint only; it is never process-lifetime authority. */
onSessionEnd: (sessionId: string, reason: string | undefined) => void
@@ -307,8 +310,6 @@ async function verifiedBoundMutation(
*/
/** How long to keep waiting for an engine to write the transcript it just announced. */
const TRANSCRIPT_WAIT_MS = 500
-const HERMES_KIND_TRIES = 6
-const HERMES_KIND_WAIT_MS = 120
const TRANSCRIPT_WAIT_TRIES = 20
function registeredHookProcess(body: RegisterInput, engine: AgentEngine): RegisteredSession | undefined {
@@ -323,6 +324,11 @@ function registeredHookProcess(body: RegisterInput, engine: AgentEngine): Regist
return body.tmuxPane ? registry.byPaneEngine(body.tmuxPane, engine) : undefined
}
+function admissionProcessScope(session: RegisteredSession | undefined): string | undefined {
+ if (!session?.active) return undefined
+ return session.processIdentity ? processIdentityKey(session.engine, session.processIdentity) : session.agentId
+}
+
/** The engine may correct an announcement; a failed correction leaves registration's checks intact. */
export function knownTranscriptFor(body: RegisterInput, agent: RegisteredSession | undefined): string | undefined {
const engine = body.engine ?? 'claude'
@@ -358,42 +364,23 @@ async function awaitTranscript(body: RegisterInput, handlers: HookServerHandlers
console.warn(`[hooks] ${sid(body.sessionId ?? '?')} announced a transcript that never appeared: ${body.transcriptPath}`)
}
-/**
- * Re-check a hermes session whose `sessions` row had not landed yet, then register it only if it turns
- * out to be the user's own CLI session. Bounded: if the row never appears we register anyway, which is
- * exactly the behaviour before this guard existed.
- */
-async function awaitHermesKind(body: RegisterInput, handlers: HookServerHandlers): Promise<void> {
- // EVERY home, not just the default. A `hermes -p <name>` session's row lives in that profile's own
- // store, so asking the default one answered `null` (unknown) six times and fell through — and, worse,
- // the home found here is the one the whole row then reads its history from (openharness#191). Hermes's homes
- // and the source that tells a delegated session are declared (engines/hermes/contract.ts) and read by the kit:
- // admission never waits for Hermes's code.
- const homes = await listStoreHomes(HERMES_HOMES, env.HERMES_HOME)
- let hermesHome: string | undefined
- for (let i = 0; i < HERMES_KIND_TRIES; i++) {
- if (i > 0) await new Promise((resolve) => { const t = setTimeout(resolve, HERMES_KIND_WAIT_MS); t.unref?.() })
- if (!registeredHookProcess(body, 'hermes')) return
- if (isRecentlyDeleted(body.sessionId)) return
- let source: string | null = null
- for (const home of homes) {
- const answer = await storeSessionSource(HERMES_SOURCE, hermesDbPath(home), body.sessionId ?? '')
- if (answer === null) continue // not in this store — try the next home
- source = answer
- if (home !== env.HERMES_HOME) hermesHome = home
- break
- }
- if (source === null) continue
- if (!isInteractiveSource(HERMES_SOURCE, source)) {
- console.log(`[hooks] ${sid(body.sessionId ?? '?')} ${body.hookEvent ?? 'session-start'} ignored · hermes_subagent`)
- return
- }
+/** Read source evidence without binding. Unreadable stores never authorize a conversation. */
+async function inspectHermesKind(sessionId: string): Promise<AdmissionDecision<string | undefined>> {
+ const { homes, complete } = await readStoreHomes(HERMES_HOMES, env.HERMES_HOME)
+ let unavailable = false
+ for (const home of homes) {
+ if (home !== env.HERMES_HOME && !complete) unavailable = true
+ const answer = await readStoreSessionSource(HERMES_SOURCE, hermesDbPath(home), sessionId)
+ if (answer === null) continue
+ if (typeof answer === 'object') { unavailable = true; continue }
+ if (!isInteractiveSource(HERMES_SOURCE, answer)) return { kind: 'reject', reason: 'hermes_subagent' }
+ // An earlier unreadable home may hold the same id; preserve the declared lookup order.
+ if (!unavailable) return { kind: 'accept', value: home === env.HERMES_HOME ? undefined : home }
break
}
- const result = registry.register(hermesHome ? { ...body, hermesHome } : body)
- if (!result) return
- console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=hermes · isNew=${result.isNew} · after a source check${hermesHome ? ` · home=${hermesHome}` : ''}`)
- handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })
+ return { kind: 'hold', reason: unavailable || !complete
+ ? 'Hermes session source is unavailable; keeping the current conversation.'
+ : 'Waiting for the Hermes session source record; keeping the current conversation.' }
}
export interface HookServerOptions {
@@ -409,6 +396,8 @@ export function startHookServer(
options: HookServerOptions = {},
): Promise<{ server: http.Server; port: number; localSocket: LocalSocketServer | null }> {
const hookCredential = loadOrCreateHookCredential(env.ADAPTER_DATA_DIR)
+ const admissions = createPendingAdmissions({ isProcessCurrent: (key, scope) => admissionProcessScope(registry.byAgent(key)) === scope })
+ let admissionArrival = 0
// Filled in once the port is bound: the Host a request must name is the port actually taken.
let hosts: ReadonlySet<string> = new Set()
let lastRefusalLogAt = 0
@@ -517,6 +506,8 @@ export function startHookServer(
console.warn('[hooks] restart the pane (or reload its plugins) to pick up the current build')
}
const engine = body.engine ?? 'claude'
+ // Capture before process resolution yields. Native time is unchanged across client retries.
+ const admissionOrder = { firedAt: hookFiredAt(req), arrival: ++admissionArrival }
const processAgent = handlers.resolveHookAgent
? await handlers.resolveHookAgent({
engine,
@@ -529,7 +520,11 @@ export function startHookServer(
// (hook/notify.mjs, fallbackRegister), with a row of its own in place of the agent's, which
// the running daemon's next save took in. Told the registration is pending, it writes nothing,
// as for a transcript not yet written below, and the wait goes on here.
- onWait: () => answer(200, { pending: true }),
+ // Hermes admission has a separate bounded queue after resolution. Do not
+ // claim a slot before one exists: its hook client can retry this live hold.
+ onWait: () => engine === 'hermes'
+ ? answer(202, { pending: false, retry: true, detail: 'Waiting for the Hermes process record; admission is not queued yet.' })
+ : answer(200, { pending: true }),
})
: body.tmuxPane ? registry.byPaneEngine(body.tmuxPane, engine) ?? null : null
if (!processAgent || processAgent.engine !== engine) { ignore('no_matching_engine_process'); return }
@@ -550,8 +545,29 @@ export function startHookServer(
// Settled off the HTTP path entirely: the answer needs a SQLite read, and the row may not even
// be written yet (measured: a child's hook beat its own INSERT by 110ms). Registering
// optimistically would hand the parent's pane to a sub-agent.
- answer(200, { pending: true })
- void awaitHermesKind(body, handlers)
+ const identity = paneReadIdentity(processAgent)
+ const queued = admissions.submit(processAgent.agentId, body.sessionId!, {
+ order: { ...admissionOrder, scope: admissionProcessScope(processAgent) ?? processAgent.agentId },
+ binding: { id: processAgent.sessionId, at: processAgent.boundAt },
+ current: () => !isRecentlyDeleted(processAgent.agentId) && !isRecentlyDeleted(body.sessionId)
+ && paneReadIdentity(registeredHookProcess(body, 'hermes')) === identity,
+ inspect: () => inspectHermesKind(body.sessionId!),
+ held: (reason) => console.log(`[hooks] ${sid(body.sessionId!)} ${body.hookEvent ?? 'session-start'} held · ${reason}`),
+ reject: (reason) => console.log(`[hooks] ${sid(body.sessionId!)} ${body.hookEvent ?? 'session-start'} ignored · ${reason}`),
+ accept: (hermesHome) => {
+ const result = registry.register(hermesHome ? { ...body, hermesHome } : body)
+ if (!result) return
+ console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=hermes · isNew=${result.isNew} · after a source check${hermesHome ? ` · home=${hermesHome}` : ''}`)
+ return handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound,
+ orphaned: result.orphaned, hookEvent: body.hookEvent })
+ },
+ })
+ if (queued) answer(200, { pending: true })
+ else {
+ const reason = 'Too many unverified Hermes hooks are pending; this hook was not queued. Retry after source recovery.'
+ console.log(`[hooks] ${sid(body.sessionId!)} ${body.hookEvent ?? 'session-start'} held · ${reason}`)
+ answer(429, { pending: false, error: 'HOOK_ADMISSION_BUSY', detail: reason })
+ }
return
}
if (body.hookEvent === 'UserPromptSubmit') {
@@ -905,6 +921,7 @@ export function startHookServer(
})
}
const server = http.createServer(handle)
+ server.once('close', () => admissions.close())
return new Promise((resolve, reject) => {
let fellBack = false
diff --git a/docs/research/2026-10-09-eager-session-control.md b/docs/research/2026-10-09-eager-session-control.md
new file mode 100644
index 000000000..cb857c2ca
--- /dev/null
+++ b/docs/research/2026-10-09-eager-session-control.md
@@ -0,0 +1,21 @@
+# Eager session control follow-up
+
+The major daemon separation steps and pane-name collision fix have landed. The remaining audit follows the owner's stricter rule: binding, discovery, resume, launch, hook admission and turn closing must not depend on a worker or lazy module. The older other-engine extraction plan allowed lazy helpers in several of these paths; that is no longer the intended boundary. Optional interpretation remains separate.
+
+Before moving identity helpers, the identity and admission goldens were re-recorded from main `d4a0fdea4`. Existing outcomes are unchanged. Added cases cover Hermes history-versus-hook ID rules and an unreadable candidate SQLite store. Platform and environment are pinned, native homes are disposable, and hooks use a private credential on port zero.
+
+The new unreadable-store case exposed a pre-existing bug: `storeSessionSource` maps a failed SQLite read to an empty source, which the Hermes contract treats as interactive. Admission can therefore bind an unverified session and assign the unreadable home. Placing that store before a healthy profile also bypasses the healthy profile's delegated-session rejection. This needs an explicit behavior correction before the mechanical identity move. Its former behavior is recorded separately; the intended correction must retain the current binding and say why admission is pending.
+
+The admission correction distinguishes a verified string source, an absent row, and unavailable or malformed evidence. An explicit empty string retains its declared interactive meaning; NULL, numeric, BLOB and missing source values cannot authorize a binding. A missing or unreadable source leaves the existing binding and home untouched, records the hold reason in the daemon log, and retries automatically. It no longer treats six missed reads as permission to bind. Admission enumerates profiles afresh; incomplete enumeration, failed profile stats and truncated listings hold profile admission. Optional readers retain their existing listing cache. A verified default-home source does not depend on profile enumeration. A verified delegated source is rejected even if an earlier home was unreadable; an interactive profile after unavailable evidence stays held because the home order is unresolved. No native database is written by admission.
+
+The core owns one in-flight lookup and at most 64 unresolved candidates per agent, deduplicated by session ID. Newest candidates are checked first. A rejected child leaves its parent's intent pending; only verified interactive acceptance supersedes older candidates. Capacity backpressure preserves existing candidates and answers the extra delivery with HTTP 429 and an explicit reason, without claiming it was queued. Process or binding changes, Stop's agent tombstone and server shutdown invalidate a lookup before publication. Synchronous and asynchronous notification failures are contained without waiting for optional attachment or retrying a committed binding. HTTP acknowledgement and daemon readiness do not wait for the source lookup. The two golden outcomes for missing and unreadable source evidence change deliberately for this safety fix; all other recorded admission outcomes stay unchanged. `mutate-admission-hold.py` must catch unsafe unavailable-store and absent-row admission, malformed sources, incomplete profiles, a lost held parent, a lost Stop fence, and late publication through assertion failures.
+
+The installed hook treats live backpressure as a hold, makes at most three retries within its existing time budget, and never runs the offline registry writer after that hold, even if a retry disconnects. Before process resolution finishes, Hermes receives HTTP 202 with `pending: false` and an explicit retry response; that early reply cannot falsely promise queue capacity. An exhausted delivery reports the hold to stderr while keeping the vendor hook's no-op JSON output.
+
+Native fired-at timestamps are captured before process resolution and retained across retries. The core keeps a verified-acceptance watermark for each exact process incarnation, seeded from a current persisted binding when needed. Older deliveries cannot replace a newer accepted conversation after resolution, a retry, an emptied queue or a core restart. Rejected children never advance that watermark. Equal-time conflicting candidates and headerless late conflicts stay held until order can be established; arrival order only orders legacy requests this core already observed. Repeated deliveries keep their original position. Additional mutations must catch a lost ordering watermark and live backpressure falling through to the offline writer.
+
+Retry selection visits all incomparable candidates: a child that already returned hold still gets rechecked and rejected after recovery, allowing its equal-time parent to proceed. Known timestamps keep a total order even beside headerless hooks; unknown candidates cannot promote a known older intent. An older duplicate cannot downgrade newer queued evidence, and an equal-stamp retry refreshes stale binding/route authority without promotion. Watermarks for removed or replaced processes are pruned during subsequent admission work, while live-process authority is retained. Four further mutations exercise these ordering and recovery guarantees.
+
+The identity fixture now supplies controlled Linux descriptor entries for Agy's held-lock case. Its recorded result is unchanged and it no longer depends on the host's process table or `lsof`.
+
+The planned identity move keeps filesystem and process mechanics eager and bounded, driven by the existing engine layouts. It removes lazy dependencies from the four transcript finders, Copilot's in-process resume lock, Muse repair, Agy lock lookup, Pi resume/close lookup and Hermes home discovery. Launch helpers, declared Stop rules and submission policies follow separately, each with former-code goldens and mutation checks. Line counts are reference only.