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.

Keep native hook admission atomic through delayed Stop and recovery (#1137)

Dee9618c2e2c09c
diff --git a/cli/e2e/enginehomes.e2e.ts b/cli/e2e/enginehomes.e2e.ts
index 2e56623aa..20085def8 100644
--- a/cli/e2e/enginehomes.e2e.ts
+++ b/cli/e2e/enginehomes.e2e.ts
@@ -487,7 +487,8 @@ describe('the person\'s engines keeping their data elsewhere', () => {
expect(held?.engine).toBe('claude')
expect(held?.sessionId).toBeFalsy()
expect(held?.status).toBe('active')
- const sibling = await client.request('agent_create', { engine: 'codex', cwd: d.projectsDir, bypassPermission: true }, 90_000)
+ // This sibling's explicit profile is independent of the deliberately unreadable home catalog.
+ const sibling = await client.request('agent_create', { engine: 'codex', cwd: d.projectsDir, codexHome: d.env.CODEX_HOME, bypassPermission: true }, 90_000)
expect(sibling.error, JSON.stringify(sibling)).toBeUndefined()
await until('the independent sibling to bind', async () => (await row(client, sibling.agent.id))?.sessionId, 45_000)
const stopped = await client.request('agent_delete', { agentId: tile.id }, 60_000)
diff --git a/cli/e2e/hookclient.e2e.ts b/cli/e2e/hookclient.e2e.ts
index 153d6c8d2..db8003152 100644
--- a/cli/e2e/hookclient.e2e.ts
+++ b/cli/e2e/hookclient.e2e.ts
@@ -16,7 +16,7 @@
* conversation the hook named, with everything the daemon kept for it, and working.
*/
import { execFileSync } from 'node:child_process'
-import { mkdirSync, readFileSync, statSync } from 'node:fs'
+import { appendFileSync, mkdirSync, readFileSync, renameSync, rmdirSync, statSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
import { LocalClient, type Frame } from './harness/client.js'
@@ -126,6 +126,91 @@ describe('the hook client', () => {
return d
}
+ it('keeps a real native prompt visibly held through an unavailable registry and admits it after recovery', async () => {
+ const d = await fresh(), client = await LocalClient.connect(d)
+ const agent = await create(d, client, 'codex', 'held-native-admission')
+ await turn(client, agent.id, 'before registry hold')
+ const file = join(d.dataDir, 'registry.json'), backup = file + '.fixture-backup'
+ const accepted = () => [...d.log().matchAll(new RegExp(`\\[hooks\\] ${agent.sessionId.slice(0, 8)} UserPromptSubmit · engine=codex`, 'g'))].length
+ await until('the first native prompt acknowledgement', () => accepted() === 1)
+ // The fixture owns this entire data directory. A directory at the file's path
+ // makes reads/writes fail even under a privileged CI account; no host chmod assumptions.
+ renameSync(file, backup); mkdirSync(file)
+ try {
+ await type(d, agent.tmuxPane, 'typed during registry hold')
+ await expect(until('admission hold to reach the actual session frame', async () => {
+ const current = await row(client, agent.id)
+ return current?.identityHold?.includes('durable hook admission') ? current : null
+ }, 30_000)).resolves.toMatchObject({ sessionId: agent.sessionId, status: 'active', name: agent.name, permissionMode: MODE.codex.mode })
+ expect(accepted()).toBe(1)
+ expect(statSync(file).isDirectory()).toBe(true)
+ } finally { rmdirSync(file); renameSync(backup, file) }
+ await until('the exact pending native prompt acknowledgement', () => accepted() === 2, 30_000)
+ await until('admission hold to clear after the durable commit', async () => !(await row(client, agent.id))?.identityHold, 30_000)
+ expect(rowOnDisk(d, agent.id)).toMatchObject({ sessionId: agent.sessionId, permissionMode: MODE.codex.mode })
+ expect((await row(client, agent.id))?.name).toBe(agent.name)
+ client.close()
+ })
+
+ it('keeps a later Cursor turn open when Cancel superseded its linked Stop registration', async () => {
+ const d = daemon = await IsolatedDaemon.create()
+ onTestFailed(() => console.log(d.log()))
+ const home = join(d.root, 'cursor'), binary = join(d.root, 'bin', 'cursor-agent')
+ Object.assign(d.env, { CURSOR_HOME: home, CURSOR_CONFIG_DIR: home, CURSOR_DATA_DIR: home, CURSOR_PATH: binary })
+ mkdirSync(home, { recursive: true })
+ const pidFile = join(d.root, 'cursor.pid')
+ writeFileSync(binary, `#!${process.execPath}
+if (process.argv.includes('--version')) { console.log('2026.10.10'); process.exit(0) }
+if (process.argv.includes('--help')) { console.log('--force --resume'); process.exit(0) }
+process.title = 'cursor-agent'.padEnd(120)
+require('node:fs').writeFileSync(${JSON.stringify(pidFile)}, String(process.pid))
+process.on('SIGINT', () => {})
+console.log('fixture-cursor-ready')
+setInterval(() => {}, 1000)
+`, { mode: 0o755 })
+ const cwd = join(d.projectsDir, 'cursor'); mkdirSync(cwd)
+ const sessionId = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa'
+ const transcriptDir = join(home, 'projects', 'fixture', 'agent-transcripts', sessionId)
+ mkdirSync(transcriptDir, { recursive: true })
+ const transcriptPath = join(transcriptDir, sessionId + '.jsonl')
+ const prompt = (text: string) => JSON.stringify({ role: 'user', message: { content: [{ type: 'text', text }] } }) + '\n'
+ writeFileSync(transcriptPath, prompt('first Cursor turn'))
+ await d.start()
+ const client = await LocalClient.connect(d)
+ try {
+ const created = await client.request('agent_create', { engine: 'cursor', cwd, bypassPermission: true }, 60_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agentId = created.agent.id, pane = created.agent.terminal?.runtimes?.[0]?.paneId ?? created.agent.tmuxPane
+ await until('the private Cursor process', async () => (await d.capture(pane)).includes('fixture-cursor-ready'), 20_000)
+ const callerPid = Number(readFileSync(pidFile, 'utf8'))
+ const hook = async (event: string, delivery?: string, firedAt?: number, endpoint = 'session-start') => {
+ const response = await fetch(`http://127.0.0.1:${d.port}/api/hook/${endpoint}`, {
+ method: 'POST', headers: { 'content-type': 'application/json', 'x-harness-hook-token': d.hookCredential(),
+ ...(delivery ? { 'x-harness-hook-delivery-id': delivery } : {}),
+ ...(firedAt ? { 'x-harness-hook-fired-at': String(firedAt) } : {}) },
+ body: JSON.stringify({ engine: 'cursor', sessionId, tmuxPane: pane, cwd, callerPid, transcriptPath, hookEvent: event }),
+ })
+ return { status: response.status, body: await response.json() }
+ }
+ const initial = await hook('sessionStart')
+ expect(initial.status, JSON.stringify(initial)).toBeLessThan(300)
+ expect(initial.body.ignored, JSON.stringify(initial)).toBeUndefined()
+ await bound(client, agentId, sessionId)
+ await until('the existing Cursor parser', () => new RegExp(`\\[agent\\] ${agentId.slice(0, 8)} attached · engine=cursor`).test(d.log()), 20_000)
+ const delivery = 'fixture-cursor-stop-0001', firedAt = Date.now()
+ expect(await hook('stop', delivery, firedAt)).toEqual({ status: 200, body: { ok: true } })
+ const cancelled = client.next(frame => frame.agentId === agentId && frame.type === 'agent_activity'
+ && frame.payload?.activity?.state === 'idle', 20_000)
+ client.send('cancel', { agentId }); await cancelled
+ const later = client.next(isTurn('turn_started', agentId), 20_000)
+ appendFileSync(transcriptPath, prompt('later Cursor turn'))
+ expect((await later).payload?.userMessage).toBe('later Cursor turn')
+ expect(await hook('stop', delivery, firedAt, 'turn-stop')).toEqual({ status: 200, body: { ok: true, duplicate: true } })
+ expect((await row(client, agentId))?.identityHold).toBeFalsy()
+ expect(d.coresStarted()).toBe(1)
+ } finally { client.close() }
+ })
+
it.each(engines)('%s: an answer later than 500 ms is not an outage, and the hook leaves the registry to the daemon', async (engine) => {
const d = await fresh()
const client = await LocalClient.connect(d)
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index a1ee0201b..2abd12d1a 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -273,6 +273,7 @@ function boundedPrompt(prompt) {
* (e2e/stall.e2e.ts).
*/
/** This process's start, epoch ms: the engine ran the hook then. */
+const DELIVERY_ID = randomUUID()
const FIRED_AT = Date.now() - Math.round(process.uptime() * 1000)
function post(port, path, body, onResponse) {
@@ -294,6 +295,7 @@ function post(port, path, body, onResponse) {
// When the engine ran this hook: this process's start, not its arrival, which can be seconds later on
// a loaded machine, after the engine has moved on to its next prompt (src/hookServer.ts hookFiredAt).
'X-Harness-Hook-Fired-At': String(FIRED_AT),
+ 'X-Harness-Hook-Delivery-Id': DELIVERY_ID,
},
timeout: Math.max(1, Math.min(500, remainingBudget())),
},
@@ -306,6 +308,8 @@ function post(port, path, body, onResponse) {
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 (path === '/api/hook/turn-stop' && ok && reply?.pending === true) { resolve('held'); return }
+ if (path === '/api/hook/turn-stop' && ok && reply?.duplicate === true) { resolve('duplicate'); return }
if (ok && onResponse && response.length <= 16_384) {
try { onResponse(JSON.parse(response)) } catch { /* Unavailable context never blocks a turn. */ }
}
@@ -1709,6 +1713,7 @@ async function main() {
engine,
hookEvent: event,
sessionId,
+ status: input.status,
transcriptPath: input.transcript_path,
cwd: Array.isArray(input.workspace_roots) ? input.workspace_roots[0] : input.cwd,
...terminalHookFields(tmuxPane),
@@ -1744,6 +1749,7 @@ async function main() {
engine,
hookEvent: event,
sessionId: input.session_id,
+ status: event === 'StopFailure' ? 'error' : undefined,
transcriptPath: existsPath(input.transcript_path) ? input.transcript_path : undefined,
cwd: input.cwd,
...terminalHookFields(tmuxPane),
diff --git a/cli/scripts/handoff-2026-10-08/mutate-native-admission.py b/cli/scripts/handoff-2026-10-08/mutate-native-admission.py
new file mode 100644
index 000000000..9c14cf2d7
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-native-admission.py
@@ -0,0 +1,141 @@
+"""Owned disposable worktree only. A passing baseline and assertion failure are mandatory."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+registry = 'src/lib/registry.ts'
+http = 'src/hookServer.ts'
+queue = 'src/core/engines/pendingAdmission.ts'
+spec = 'src/lib/registry.admission.spec.ts'
+mutations = [
+ ('registration grants stale readers the new binding', registry,
+ 'replaceLive: true', 'replaceLive: false', 'src/lib/runtimeProfileRegistry.spec.ts', ''),
+ ('registration publishes before durability', registry,
+ 'this.save(true, false, undefined, { agentId, candidate: entry, displaced, replaceLive: true, verify: () => proof?.verify() })',
+ 'this.agents.set(agentId, entry); this.save(true, false, undefined, { agentId, candidate: entry, displaced, replaceLive: true, verify: () => proof?.verify() })', spec, 'failure|fails|failed'),
+ ('displaced owner changes before commit', registry,
+ 'displaced = { agentId: stolenFrom.agentId, candidate: stolenFrom.active ? released : null }',
+ 'this.agents.set(stolenFrom.agentId, released); displaced = { agentId: stolenFrom.agentId, candidate: stolenFrom.active ? released : null }', spec, 'failure|fails|failed'),
+ ('registration native recheck omitted', registry,
+ 'this.save(true, false, undefined, { agentId, candidate: entry, displaced, replaceLive: true, verify: () => proof?.verify() })',
+ 'this.save(true, false, undefined, { agentId, candidate: entry, displaced, replaceLive: true, verify: () => {} })', spec, 'under|proof'),
+ ('reported path borrows unwritten locator authority', registry,
+ "!transcriptPath && derived === effectiveTranscriptPath ? 'derived' : false", "'derived'", spec, 'unwritten derived locator'),
+ ('unwritten locator accepts a dangling directory', 'src/engines/transcriptBindings.ts',
+ 'if (suffix.length && !files.paths.absentLeaf(join(location.path, suffix[0])))', 'if (false)',
+ 'src/engines/transcriptBindings.spec.ts', 'dangling directory'),
+ ('unconfirmed serialized image stays mutable', registry,
+ 'image: JSON.parse(JSON.stringify(serialized)), prior: JSON.parse(JSON.stringify([...prior.values()]))',
+ 'image: serialized, prior: [...prior.values()]', spec, 'mutable|nested'),
+ ('peer ownership recovery skips displaced draft', registry,
+ '|| bindingCommit?.displaced !== undefined && unconfirmed.affected.has(bindingCommit.displaced.agentId)',
+ '|| false', spec, 'displaced-owner'),
+ ('prompt credit disconnected', http,
+ "optional(() => handlers.onPromptSubmitted?.(result.entry.agentId, body.prompt ?? ''))", 'void 0', 'src/hookAdmission.golden.spec.ts', ''),
+ ('first admission notification disconnected', http,
+ "optional(() => handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound,\n orphaned: result.orphaned, hookEvent: body.hookEvent }))", 'void 0', 'src/hookAdmission.golden.spec.ts', ''),
+ ('commit failure loses queued delivery', queue,
+ "catch (error) { decision = { kind: 'hold', reason: `Waiting for durable hook admission:",
+ "catch (error) { decision = { kind: 'reject', reason: `Waiting for durable hook admission:", 'src/core/engines/pendingAdmission.spec.ts', 'durable commit'),
+ ('conversation FIFO disconnected', queue,
+ 'return newest && queue!.find(job => conversation(job) === conversation(newest))',
+ 'return newest', spec, 'held predecessor'),
+ ('delegated peer is never revisited', queue,
+ 'const peer = leaders(key, job).find(other => conversation(other) !== conversation(job))',
+ 'const peer: Job | undefined = undefined', 'src/core/engines/pendingAdmission.spec.ts', 'rechecks an already-held equal-time child'),
+ ('native order ignored', queue,
+ 'const status = order.status(key, conversation(job), job.request.order)',
+ "const status: string = 'current'", spec, 'delayed older'),
+ ('duplicate completion acknowledgement ignored', http,
+ 'const completed = history.records.get(deliveryId)', "const completed = history.records.get('fixture-missing-delivery')", spec, 'acknowledges a repeated delivery'),
+ ('completed acknowledgement tied to routes', http,
+ 'row.agentId, row.engine, row.processIdentity ? processIdentityKey(row.engine, row.processIdentity) : null,',
+ 'row.agentId, row.engine, row.processIdentity ? processIdentityKey(row.engine, row.processIdentity) : null, row.runtimes, row.primaryRuntimeKey,',
+ spec, 'completed delivery acknowledgement'),
+ ('payload backpressure disconnected', http,
+ 'receiptBytes + retainedBytes > bytesCapacity', 'false', spec, 'payload bytes'),
+ ('matched process snapshot is still live', 'src/core/engines/hooks.ts',
+ 'const candidate = structuredClone(live)', 'const candidate = live', spec, 'resolver continuation'),
+ ('inspection binding authority ignored', http,
+ 'if (!current() || paneReadIdentity(live()) !== inspectionIdentity)', 'if (!current())', 'src/hookServer.hermes.spec.ts', 'known home changes during source inspection'),
+ ('Stop admission fence disconnected', http,
+ 'if (handlers.hookAdmissionBlocked?.(processAgent.agentId))', 'if (false)', spec, 'actual Stop job'),
+ ('unmatched Stop claim forgotten', http,
+ 'if (stopUnmatched && !stopRetained)', 'if (false)', spec, 'retains .* Stop before'),
+ ('linked Stop invocation duplicated', http,
+ 'if (stopInvocationClaimed) return { status: 200, reply: { ok: true, duplicate: true } }',
+ 'stopInvocationClaimed = false', spec, 'claims an immediate'),
+ ('missing parser loses native completion', 'src/core/transcripts/attach.ts',
+ '!unmatched && normalizers.sessionTurnState(session.sessionId) !== undefined', '!unmatched',
+ 'src/core/transcripts/attach.spec.ts', 'catch-hook completion'),
+ ('pending Stop erases Cursor tasks', 'hook/notify.mjs',
+ "if (path === '/api/hook/turn-stop' && ok && reply?.pending === true) { resolve('held'); return }", '',
+ 'src/hookNotify.spec.ts', 'Cursor Task/stop'),
+ ('remaining admission hold hidden', http,
+ "const reason = [...admissionHolds.get(processAgent.agentId)?.values() ?? []].at(-1)",
+ 'const reason = undefined', spec, 'older hold visible'),
+ ('overtaking resolution forgets Stop', http,
+ 'if (stopProvenance(stop, firedAt) !== originalStop) return conflict\n deferred = true',
+ 'if (stopProvenance(stop, firedAt) !== originalStop) return conflict', spec, 'overtaking Stop'),
+ ('queued parser reconstruction grants completion', 'src/core/transcripts/attach.ts',
+ '&& !pendingAttaches.has(session.sessionId)', '', 'src/core/transcripts/attach.spec.ts', 'existing interpretation has a queued'),
+ ('same-owner reconstruction loses completion', http,
+ 'stopRetained = handlers.onAdmissionStop?.(live()!, true) ?? false', 'stopRetained = false', spec, 'same-owner linked Stop'),
+ ('duplicate Stop erases Cursor tasks', 'hook/notify.mjs',
+ "if (path === '/api/hook/turn-stop' && ok && reply?.duplicate === true) { resolve('duplicate'); return }", '',
+ 'src/hookNotify.spec.ts', 'Cursor Task/stop'),
+ ('refused registration falls through to Stop', http,
+ "if (/^[a-zA-Z0-9_-]{16,96}$/.test(delivery) && (body.engine === 'cursor' || body.engine === 'commandcode'))",
+ 'if (false)', spec, 'bypass refused admission'),
+ ('Cancel witness wiring disconnected', 'src/core/main.ts',
+ 'captureAdmissionStop: attach.captureAdmissionStop,', '', 'e2e/hookclient.e2e.ts', 'later Cursor turn open'),
+ ('admission status wiring disconnected', 'src/core/main.ts',
+ 'onAdmissionHeld: engineHooks.onAdmissionHeld,', '', 'e2e/hookclient.e2e.ts', 'real native prompt visibly held'),
+]
+selected = set(sys.argv[2:])
+if selected:
+ assert selected <= {entry[0] for entry in mutations}, 'Unknown mutation label'
+ mutations = [entry for entry in mutations if entry[0] in selected]
+environment = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}
+for key in list(environment):
+ if key in ['TMUX', 'TMUX_PANE'] or key.startswith('RECORD_'):
+ environment.pop(key)
+assert Path(environment.get('TMUX_TMPDIR', '/missing')).is_dir(), 'Private TMUX_TMPDIR is required'
+
+
+def run(targets, pattern=''):
+ native = any(target.startswith('e2e/') for target in targets)
+ lane = ['--config', 'vitest.e2e.config.ts'] if native else []
+ return subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', *lane, *targets,
+ *(['--testNamePattern', pattern] if pattern else []), '--maxWorkers=1'],
+ cwd=cli, env=environment, text=True, capture_output=True, timeout=180)
+
+
+for native in [False, True]:
+ targets = sorted({entry[4] for entry in mutations if entry[4].startswith('e2e/') == native})
+ if targets:
+ baseline = run(targets, 'real native prompt visibly held|later Cursor turn open' if native else '')
+ if baseline.returncode:
+ raise SystemExit('Baseline failed; no mutants ran.\n' + baseline.stdout + baseline.stderr)
+print('Unchanged baselines passed', flush=True)
+failures = []
+for label, relative, before, after, target, pattern in mutations:
+ path = cli / relative
+ original = path.read_text()
+ expected = 2 if label in ['Stop admission fence disconnected', 'linked Stop invocation duplicated'] else 1
+ assert original.count(before) == expected, (label, original.count(before))
+ try:
+ path.write_text(original.replace(before, after))
+ result = run([target], pattern)
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError' not in output:
+ failures.append(label)
+ print(label + ': not caught by an assertion\n' + output, flush=True)
+ else:
+ print(label + ': caught by assertion', flush=True)
+ finally:
+ path.write_text(original)
+if failures:
+ raise SystemExit('Mutations without assertion proof: ' + ', '.join(failures))
diff --git a/cli/src/backendSocket.history.spec.ts b/cli/src/backendSocket.history.spec.ts
index 649789c6a..ce2a79c12 100644
--- a/cli/src/backendSocket.history.spec.ts
+++ b/cli/src/backendSocket.history.spec.ts
@@ -42,15 +42,21 @@ describe.each([
mkdirSync(root, { recursive: true })
dir = mkdtempSync(join(root, 'history-'))
file = join(dir, 'transcript.jsonl')
- writeFileSync(file, scenario().join('\n') + '\n')
+ const paneId = `%${++pane}`
+ sessionId = `${engine}-history-${pane}`
+ const lines = scenario()
+ if (engine === 'codex') {
+ const header = JSON.parse(lines[0])
+ header.payload.id = sessionId
+ lines[0] = JSON.stringify(header)
+ }
+ writeFileSync(file, lines.join('\n') + '\n')
socket = relaySocket('fixture')
bindHistory(socket)
frames = []
socket.registerLocalClient('local:history', { sendFrame: (frame) => { frames.push(frame as never); return true }, sendBinary: () => true })
- const paneId = `%${++pane}`
agentId = registry.openPendingAgent({ engine, runtimes: [{ backend: 'tmux', paneId }], cwd: dir })!.agentId
- sessionId = `${engine}-history-${pane}`
- registry.register({ engine, sessionId, transcriptPath: file, tmuxPane: paneId, cwd: dir })
+ expect(registry.register({ engine, sessionId, transcriptPath: file, tmuxPane: paneId, cwd: dir })).not.toBeNull()
})
afterEach(async () => {
diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.ts
index e7510d7e9..b7a7a93f0 100644
--- a/cli/src/core/engines/hooks.spec.ts
+++ b/cli/src/core/engines/hooks.spec.ts
@@ -50,8 +50,10 @@ const hint = (paneId: string) => ({ backend: 'tmux' as const, paneId })
function setup(onPane: Record<string, RegisteredSession> = {}, over: Partial<EngineHookDeps> = {}) {
const deps: EngineHookDeps = {
tmuxBackend: {},
+ syncSession: vi.fn(),
agentReconciler: { triggerHint: vi.fn(async () => true), trigger: vi.fn(async () => true) } as unknown as EngineHookDeps['agentReconciler'],
- registry: { byRuntimeEngine: vi.fn((runtime: { paneId: string }) => onPane[runtime.paneId]) } as unknown as EngineHookDeps['registry'],
+ registry: { byRuntimeEngine: vi.fn((runtime: { paneId: string }) => onPane[runtime.paneId]),
+ byAgent: vi.fn((id: string) => Object.values(onPane).find(row => row.agentId === id)) } as unknown as EngineHookDeps['registry'],
...over,
}
return { deps, hooks: createEngineHooks(deps) }
@@ -72,7 +74,7 @@ describe('which agent a hook belongs to', () => {
const { deps, hooks } = setup({ '%1': a1 })
vi.mocked(processRows).mockResolvedValueOnce(tree([300, 200], [200, 100], [100, 1]) as never)
const onWait = vi.fn()
- expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300, onWait })).toBe(a1)
+ expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300, onWait })).toEqual(a1)
// Matched at once: nothing to wait for, and the hook is answered with its agent.
expect(onWait).not.toHaveBeenCalled()
expect(deps.agentReconciler.triggerHint).toHaveBeenCalledWith({ backend: 'tmux', paneId: '%1' }, 'claude')
@@ -80,12 +82,33 @@ describe('which agent a hook belongs to', () => {
expect(console.log).not.toHaveBeenCalled()
})
+ it('does not give a delayed hook to a replacement with the same PID', async () => {
+ const original = agent('original', 100)
+ const replacement = { ...agent('replacement', 100), processIdentity: { pid: 100, startMarker: 'replacement' } } as RegisteredSession
+ const panes = { '%1': original }
+ vi.mocked(processRows).mockResolvedValueOnce(tree([300, 100], [100, 1]) as never)
+ const { hooks } = setup(panes, { agentReconciler: {
+ triggerHint: vi.fn(async () => { panes['%1'] = replacement; return true }), trigger: vi.fn(),
+ } as unknown as EngineHookDeps['agentReconciler'] })
+ expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })).toBeNull()
+ })
+
+ it('copies the arriving process identities before asynchronous reconciliation changes its table', async () => {
+ const original = agent('original', 100)
+ const rows = tree([300, 100], [100, 1])
+ vi.mocked(processRows).mockResolvedValueOnce(rows as never)
+ const { hooks } = setup({ '%1': original }, { agentReconciler: {
+ triggerHint: vi.fn(async () => { await Promise.resolve(); rows[1]!.startMarker = 'replacement'; return true }), trigger: vi.fn(),
+ } as unknown as EngineHookDeps['agentReconciler'] })
+ expect(await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })).toEqual(original)
+ })
+
it('reads the table again when the one in flight began before the hook\'s own process, and matches it', async () => {
const a1 = agent('a1', 100)
vi.mocked(processRows)
.mockResolvedValueOnce(tree([200, 100], [100, 1]) as never)
.mockResolvedValueOnce(tree([300, 200], [200, 100], [100, 1]) as never)
- expect(await setup({ '%1': a1 }).hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })).toBe(a1)
+ expect(await setup({ '%1': a1 }).hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })).toEqual(a1)
expect(processRows).toHaveBeenCalledTimes(2)
expect(console.log).not.toHaveBeenCalled()
})
@@ -103,7 +126,7 @@ describe('which agent a hook belongs to', () => {
it('a Cursor agent on the pane alone, saying the caller is outside its process tree', async () => {
const c1 = { ...agent('cursor-1'), engine: 'cursor' } as RegisteredSession
vi.mocked(processRows).mockResolvedValueOnce(tree([300, 1]) as never)
- expect(await setup({ '%1': c1 }).hooks.resolveHookAgent({ engine: 'cursor', runtimeHints: [hint('%1')], callerPid: 300 })).toBe(c1)
+ expect(await setup({ '%1': c1 }).hooks.resolveHookAgent({ engine: 'cursor', runtimeHints: [hint('%1')], callerPid: 300 })).toEqual(c1)
expect(console.log).toHaveBeenCalledWith('[hooks] cursor hook accepted on runtime evidence alone · agent=cursor-1 · caller=300 is outside that engine\'s process tree')
})
@@ -132,7 +155,7 @@ describe('which agent a hook belongs to', () => {
expect(admitted).not.toHaveBeenCalled()
commit()
await finished
- expect(await resolution).toBe(['committed', 'no acknowledgement'].includes(outcome) ? c1 : null)
+ expect(await resolution).toEqual(['committed', 'no acknowledgement'].includes(outcome) ? c1 : null)
vi.mocked(processRows).mockReset().mockResolvedValue([])
},
)
@@ -464,3 +487,35 @@ describe('installing every engine\'s hooks', () => {
for (const install of installs) expect(install).toHaveBeenCalledTimes(1)
})
})
+
+
+it('returns an immutable authority snapshot across the resolver continuation', async () => {
+ const row = agent('original', 100)
+ row.runtimes = [{ backend: 'tmux', paneId: '%1' }]
+ vi.mocked(processRows).mockResolvedValueOnce(tree([300, 100], [100, 1]) as never)
+ const { hooks } = setup({}, { registry: { byAgent: vi.fn(), byRuntimeEngine: () => {
+ queueMicrotask(() => {
+ row.processIdentity!.startMarker = 'replacement'
+ row.runtimes[0]!.paneId = '%2'
+ })
+ return row
+ } } })
+ const result = await hooks.resolveHookAgent({ engine: 'claude', runtimeHints: [hint('%1')], callerPid: 300 })
+ expect(row.processIdentity!.startMarker).toBe('replacement')
+ expect(result?.processIdentity?.startMarker).toBe('m')
+ expect(result?.runtimes[0]?.paneId).toBe('%1')
+ expect(result).not.toBe(row)
+})
+
+it('publishes admission holds without changing binding authority and contains removed rows', () => {
+ const row = agent('original', 100)
+ row.evidenceRevision = 17
+ const { hooks, deps } = setup({ '%1': row })
+ hooks.onAdmissionHeld('original', 'Waiting for complete native evidence.')
+ expect(row.admissionHold).toBe('Waiting for complete native evidence.')
+ expect(row.evidenceRevision).toBe(17)
+ hooks.onAdmissionHeld('original', undefined)
+ expect(row.admissionHold).toBeUndefined()
+ hooks.onAdmissionHeld('removed', 'Waiting')
+ expect(deps.syncSession).toHaveBeenCalledTimes(2)
+})
diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.ts
index 022718121..12e8864b8 100644
--- a/cli/src/core/engines/hooks.ts
+++ b/cli/src/core/engines/hooks.ts
@@ -26,7 +26,8 @@ export interface EngineHookDeps {
/** Hints name tmux panes; without tmux there is nothing they can point at. */
tmuxBackend: unknown
agentReconciler: Pick<TerminalAgentReconciler, 'triggerHint' | 'trigger'>
- registry: Pick<typeof registry, 'byRuntimeEngine'>
+ registry: Pick<typeof registry, 'byRuntimeEngine' | 'byAgent'>
+ syncSession: (row: RegisteredSession) => void
}
/**
@@ -47,14 +48,14 @@ type HookQuery = Parameters<ResolveHookAgent>[0]
const recordKey = (session: RegisteredSession | undefined): string =>
session ? `${session.agentId}\u0000${session.processIdentity?.pid ?? ''}\u0000${session.processIdentity?.startMarker ?? ''}` : ''
-export function createEngineHooks({ tmuxBackend, agentReconciler, registry, panePending }: EngineHookDeps) {
+export function createEngineHooks({ tmuxBackend, agentReconciler, registry, panePending, syncSession }: EngineHookDeps) {
/**
* The agents on the hinted panes: those whose recorded process the caller descends from, the rest,
* and of the rest those with no live process recorded at all (none yet, or one that has exited).
* `ancestry` is the hook's own process and those it descends from, read as the hook arrived
* (`resolveHookAgent`); `table`, the process table to judge the recorded processes by, else a new read.
*/
- const matchCaller = async (resolved: TerminalRuntimeRef[], engine: HookQuery['engine'], ancestry: ReadonlySet<number>, table?: ProcessRow[]) => {
+ const matchCaller = async (resolved: TerminalRuntimeRef[], engine: HookQuery['engine'], ancestry: ReadonlyMap<number, ProcessRow>, table?: ProcessRow[]) => {
const rows = table ?? await processRows()
if (!rows) return null
const recordedAlive = (session: RegisteredSession): boolean => {
@@ -63,7 +64,8 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry, pane
}
const callerBelongsTo = (session: RegisteredSession): boolean => {
const expectedPid = session.processIdentity?.pid
- return !!expectedPid && ancestry.has(expectedPid)
+ const original = expectedPid && ancestry.get(expectedPid)
+ return !!original && sameProcessIdentity(original, session.processIdentity)
}
const candidates = new Map<string, RegisteredSession>()
/**
@@ -81,12 +83,16 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry, pane
const onHintedRuntime = new Map<string, RegisteredSession>()
const unrecorded: RegisteredSession[] = []
for (const runtime of resolved) {
- const candidate = registry.byRuntimeEngine(runtime, engine)
- if (!candidate) continue
+ const live = registry.byRuntimeEngine(runtime, engine)
+ if (!live) continue
+ // The caller resumes after this async function returns. Capture at the
+ // ancestry check, before that continuation can observe a replacement row.
+ const candidate = structuredClone(live)
if (callerBelongsTo(candidate)) candidates.set(candidate.agentId, candidate)
else {
onHintedRuntime.set(candidate.agentId, candidate)
- if (!recordedAlive(candidate)) unrecorded.push(candidate)
+ // A reused PID is positive evidence of another process, not an unrecorded launch.
+ if (!recordedAlive(candidate) && !ancestry.has(candidate.processIdentity?.pid ?? 0)) unrecorded.push(candidate)
}
}
return { candidates, onHintedRuntime, unrecorded }
@@ -111,7 +117,7 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry, pane
// shell that exits with the hook (its 500ms, or `onWait`'s answer); read after the reconcile pass or
// the wait, the ancestry stopped at a pid already gone and a restart's new conversation was never
// bound (e2e/updates.e2e.ts). macOS's /bin/sh is a bash that execs the hook: never seen there.
- const arrival = processRows()
+ const arrival = processRows().then(rows => rows?.map(row => ({ ...row })) ?? null)
const resolved: TerminalRuntimeRef[] = []
for (const hint of runtimeHints ?? []) {
if (tmuxBackend) resolved.push({ backend: 'tmux', paneId: hint.paneId })
@@ -124,9 +130,14 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry, pane
// A `ps` already running (processRows shares it) may predate the hook's process; the next read has it.
if (table && !table.some((row) => row.pid === callerPid)) table = await processRows()
if (!table) return null
- const parents = new Map(table.map((row) => [row.pid, row.parentPid]))
- const ancestry = new Set<number>()
- for (let pid = callerPid; pid > 0 && !ancestry.has(pid); pid = parents.get(pid) ?? 0) ancestry.add(pid)
+ const parents = new Map(table.map(row => [row.pid, row]))
+ const ancestry = new Map<number, ProcessRow>()
+ for (let pid = callerPid; pid > 0 && !ancestry.has(pid);) {
+ const row = parents.get(pid)
+ if (!row) break
+ ancestry.set(pid, { ...row })
+ pid = row.parentPid
+ }
let found = (await matchCaller(resolved, engine, ancestry, table))!
let choice = chooseHookAgent([...found.candidates.values()], [...found.onHintedRuntime.values()], engine)
@@ -184,7 +195,14 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry, pane
const onSessionEnd = (_sessionId: string, _reason: string | undefined): void => {
void agentReconciler.trigger()
}
- return { resolveHookAgent, onSessionEnd }
+ const onAdmissionHeld = (id: string, reason: string | undefined): void => {
+ const row = registry.byAgent(id)
+ if (!row) return
+ if (reason) row.admissionHold = reason
+ else delete row.admissionHold
+ syncSession(row)
+ }
+ return { resolveHookAgent, onSessionEnd, onAdmissionHeld }
}
/**
diff --git a/cli/src/core/engines/pendingAdmission.spec.ts b/cli/src/core/engines/pendingAdmission.spec.ts
index 9b7c2906a..c03afc3fa 100644
--- a/cli/src/core/engines/pendingAdmission.spec.ts
+++ b/cli/src/core/engines/pendingAdmission.spec.ts
@@ -11,6 +11,40 @@ function request(overrides: Partial<PendingAdmission<string>> = {}): PendingAdmi
const flush = async () => { await Promise.resolve(); await Promise.resolve() }
describe('pending hook admission', () => {
+ it.each(['held', 'throws', 'throws a non-Error'] as const)('retains the exact candidate until its %s durable commit succeeds', async failure => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions({ retryMs: 20 })
+ let writable = false
+ const commit = vi.fn((): AdmissionDecision<string> => {
+ if (writable) return { kind: 'accept', value: 'committed' }
+ if (failure === 'throws') throw new Error('durable registry unavailable')
+ if (failure === 'throws a non-Error') throw 'unavailable'
+ return { kind: 'hold', reason: 'durable registry unavailable' }
+ })
+ const held = request({ commit })
+ queue.submit('agent', 'delivery', held); await flush()
+ expect(held.accept).not.toHaveBeenCalled()
+ expect(held.held).toHaveBeenCalledWith(expect.stringContaining('durable'))
+ writable = true
+ await vi.advanceTimersByTimeAsync(20)
+ expect(commit).toHaveBeenCalledTimes(2)
+ expect(held.accept).toHaveBeenCalledExactlyOnceWith('committed')
+ queue.close()
+ })
+
+ it('does not advance order when the durable commit conclusively refuses admission', async () => {
+ const queue = createPendingAdmissions()
+ const refused = request({ order: { scope: 'process', firedAt: 20, arrival: 1 },
+ commit: () => ({ kind: 'reject', reason: 'confirmed-invalid' }) })
+ queue.submit('agent', 'invalid', refused); await flush()
+ expect(refused.accept).not.toHaveBeenCalled()
+ expect(refused.reject).toHaveBeenCalledExactlyOnceWith('confirmed-invalid')
+ const older = request({ order: { scope: 'process', firedAt: 10, arrival: 2 } })
+ queue.submit('agent', 'parent', older); await flush()
+ expect(older.accept).toHaveBeenCalledOnce()
+ queue.close()
+ })
+
it('rechecks an already-held equal-time child so its parent can recover', async () => {
vi.useFakeTimers()
const queue = createPendingAdmissions({ retryMs: 20 })
@@ -262,7 +296,7 @@ describe('pending hook admission', () => {
.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.')
+ expect(r.held).toHaveBeenCalledWith('The session source could not be read. broken reader')
await vi.advanceTimersByTimeAsync(20)
expect(r.reject).toHaveBeenCalledExactlyOnceWith('delegated')
expect(r.accept).not.toHaveBeenCalled()
@@ -313,3 +347,47 @@ describe('pending hook admission', () => {
expect(after.inspect).not.toHaveBeenCalled()
})
})
+
+
+it('retains distinct prompts for one conversation in order through source recovery', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions({ retryMs: 20 })
+ let readable = false
+ const accepted: string[] = []
+ const first = request({ conversationId: 'conversation', binding: () => undefined,
+ inspect: async () => { if (!readable) throw 'source unavailable'; return { kind: 'accept', value: 'first' } },
+ accept: value => { accepted.push(value) } })
+ const second = request({ conversationId: 'conversation', binding: () => ({ id: 'conversation', at: 1 }),
+ inspect: async () => readable ? { kind: 'accept', value: 'second' } : { kind: 'hold', reason: 'source unavailable' },
+ accept: value => { accepted.push(value) } })
+ queue.submit('agent', 'delivery-one', first); await flush()
+ queue.submit('agent', 'delivery-two', second); await flush()
+ expect(accepted).toEqual([])
+ expect(first.held).toHaveBeenCalledWith(expect.stringContaining('Native evidence unavailable'))
+ readable = true
+ await vi.advanceTimersByTimeAsync(40)
+ expect(accepted).toEqual(['first', 'second'])
+ queue.close()
+})
+
+
+it('rotates conversation groups so a newer delegated candidate cannot starve two parent prompts', async () => {
+ vi.useFakeTimers()
+ const queue = createPendingAdmissions({ retryMs: 20 })
+ let readable = false
+ const accepted: string[] = []
+ const a1 = request({ conversationId: 'parent', order: { scope: 'process', firedAt: 10, arrival: 1 },
+ inspect: async () => readable ? { kind: 'accept', value: 'a1' } : { kind: 'hold', reason: 'unavailable' }, accept: value => { accepted.push(value) } })
+ const a2 = request({ conversationId: 'parent', order: { scope: 'process', firedAt: 20, arrival: 2 },
+ accept: () => { accepted.push('a2') } })
+ const b = request({ conversationId: 'child', order: { scope: 'process', firedAt: 20, arrival: 3 },
+ inspect: async () => readable ? { kind: 'reject', reason: 'delegated' } : { kind: 'hold', reason: 'unavailable' } })
+ queue.submit('agent', 'a1', a1); await flush()
+ queue.submit('agent', 'a2', a2); await flush()
+ queue.submit('agent', 'b', b); await flush()
+ readable = true
+ await vi.advanceTimersByTimeAsync(100)
+ expect(b.reject).toHaveBeenCalledExactlyOnceWith('delegated')
+ expect(accepted).toEqual(['a1', 'a2'])
+ queue.close()
+})
diff --git a/cli/src/core/engines/pendingAdmission.ts b/cli/src/core/engines/pendingAdmission.ts
index f9c0fa3a7..00b69a228 100644
--- a/cli/src/core/engines/pendingAdmission.ts
+++ b/cli/src/core/engines/pendingAdmission.ts
@@ -8,9 +8,14 @@ export type AdmissionDecision<T> =
export interface PendingAdmission<T> {
order: AdmissionOrder
- binding?: { id: string; at: number | null }
+ /** Delivery IDs distinguish prompts; ordering compares their native conversation. */
+ conversationId?: string
+ binding?: { id: string; at: number | null } | (() => { id: string; at: number | null } | undefined)
current: () => boolean
inspect: () => Promise<AdmissionDecision<T>>
+ /** Synchronous durable publication. Uncertainty retains this candidate and its place. */
+ commit?: (value: T) => AdmissionDecision<T>
+ /** Optional notification after durable acceptance; never the publication itself. */
accept: (value: T) => void | Promise<void>
reject: (reason: string) => void | Promise<void>
held: (reason: string) => void | Promise<void>
@@ -25,7 +30,14 @@ export function createPendingAdmissions({ retryMs = 1_000, capacity = 64, isProc
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)
+ const conversation = (job: Job) => job.request.conversationId ?? job.id
+ const selected = (key: string) => {
+ const queue = jobs.get(key)
+ const newest = queue?.at(-1)
+ // Distinct prompts for one conversation retain delivery order. A newer
+ // conversation still gets first chance to establish or refuse its ownership.
+ return newest && queue!.find(job => conversation(job) === conversation(newest))
+ }
// 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.
@@ -36,6 +48,7 @@ export function createPendingAdmissions({ retryMs = 1_000, capacity = 64, isProc
}
const clearTimer = (job: Job) => { if (job.timer) { clearTimeout(job.timer); job.timer = null } }
const discard = (key: string, job: Job) => {
+ clearTimer(job)
const queue = jobs.get(key)
if (!queue) return
const index = queue.indexOf(job)
@@ -49,12 +62,16 @@ export function createPendingAdmissions({ retryMs = 1_000, capacity = 64, isProc
const run = async (key: string, job: Job, retry = false): Promise<void> => {
running.add(key)
try {
+ // One lookup owns the key. A group rotation or a new prompt may select an
+ // already-held job; none of its old timers may start a concurrent lookup.
+ for (const pending of jobs.get(key)!) clearTimer(pending)
if (retry && current(key, job)) {
- const peer = leaders(key, job).find(other => other !== job)
+ const peer = leaders(key, job).find(other => conversation(other) !== conversation(job))
if (peer) {
const queue = jobs.get(key)!
- queue.splice(queue.indexOf(peer), 1); queue.push(peer)
- job = peer
+ const group = queue.filter(other => conversation(other) === conversation(peer))
+ jobs.set(key, [...queue.filter(other => conversation(other) !== conversation(peer)), ...group])
+ job = group[0]!
}
}
await inspect(key, job)
@@ -70,21 +87,27 @@ export function createPendingAdmissions({ retryMs = 1_000, capacity = 64, isProc
}
}
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)
+ if (!current(key, job)) { discard(key, job); notified(job.request.reject('stale_hook')); return }
+ order.observe(key, job.request.order.scope, typeof job.request.binding === 'function' ? job.request.binding() : 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.' }
+ try { decision = await job.request.inspect() } catch (error) {
+ decision = { kind: 'hold', reason: `The session source could not be read. ${error instanceof Error ? error.message : 'Native evidence unavailable.'}`.slice(0, 1024) }
}
- if (!current(key, job)) { discard(key, job); return }
+ if (!current(key, job)) { discard(key, job); notified(job.request.reject('stale_hook')); 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)
+ const status = order.status(key, conversation(job), 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.' }
+ const unresolved = leaders(key, job).some(other => other !== job && conversation(other) !== conversation(job))
+ if (status === 'ambiguous' || unresolved) decision = { kind: 'hold', reason:
+ 'Waiting for unambiguous native hook order; keeping the current conversation.'
+ + (job.request.order.firedAt === undefined ? ' This hook has no native timestamp; reload or restart the engine with updated hooks.' : '') }
+ }
+ if (decision.kind === 'accept' && job.request.commit) {
+ try { decision = job.request.commit(decision.value) }
+ catch (error) { decision = { kind: 'hold', reason: `Waiting for durable hook admission: ${error instanceof Error ? error.message : 'commit unavailable'}`.slice(0, 1024) } }
}
if (decision.kind === 'hold') {
job.timer = setTimeout(() => { job.timer = null; void run(key, job, true) }, retryMs)
@@ -96,8 +119,8 @@ export function createPendingAdmissions({ retryMs = 1_000, capacity = 64, isProc
return
}
if (decision.kind === 'accept') {
- order.accept(key, job.id, job.request.order)
- jobs.delete(key)
+ order.accept(key, conversation(job), job.request.order)
+ discard(key, job)
notified(job.request.accept(decision.value))
} else {
discard(key, job)
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 71443e646..6ca4beba9 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1697,7 +1697,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
dataDir: env.ADAPTER_DATA_DIR,
})
// Which agent a hook belongs to, and what a SessionEnd means (core/engines/hooks.ts).
- const engineHooks = createEngineHooks({ tmuxBackend, agentReconciler, registry, panePending: restorePanes.pending })
+ const engineHooks = createEngineHooks({ tmuxBackend, agentReconciler, registry, panePending: restorePanes.pending, syncSession })
const { server: hookServer, port: hookPort, localSocket } = await startHookServer(daemonPort(), {
onAutonomousDeviceRequest: async (method, target, body) => {
// Until the pieces below are built; after, a piece that could not be is refused by the requests
@@ -1726,6 +1726,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
}, method, target, body)
},
resolveHookAgent: engineHooks.resolveHookAgent,
+ hookAdmissionBlocked: id => launchCancelled(id),
+ onAdmissionHeld: engineHooks.onAdmissionHeld,
+ onAdmissionStop: attach.holdAdmissionStop,
+ captureAdmissionStop: attach.captureAdmissionStop,
onRegistered: handleRegistered,
onPromptSubmitted: (id, text) => teams.started(id, text, 'hook', registry.byAgent(id)?.engine),
onSessionEnd: engineHooks.onSessionEnd,
diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.ts
index a377e3530..d44d82aef 100644
--- a/cli/src/core/transcripts/attach.spec.ts
+++ b/cli/src/core/transcripts/attach.spec.ts
@@ -1366,6 +1366,81 @@ it('keeps normal Stop on its existing path and contains a rejected recovery sche
expect(row.interpretationHold).toBe('waiting for evidence')
run.attach.forget(row.sessionId)
})
+it.each(['cursor', 'commandcode'] as const)('holds a %s catch-hook completion before a missing parser can hydrate a newer turn', async engine => {
+ const run = setup(), row = session(engine, transcript([{ open: true, events: [started('newer turn')] }]))
+ expect(run.attach.holdAdmissionStop(row, false)).toBe(true)
+ expect(row.interpretationHold).toContain('Stop could not be matched')
+ await run.attach.attachSession(row, true)
+ expect(row.interpretationHold).toContain('Stop could not be matched')
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
+it('holds rebuilt admission interpretation even when a parser still exists, preserving normal immediate Stop', async () => {
+ const run = setup(), row = session('commandcode', transcript([]))
+ await run.attach.attachSession(row)
+ expect(run.attach.holdAdmissionStop(row, false)).toBe(false)
+ row.identityHold = 'native source unavailable'
+ expect(run.attach.holdAdmissionStop(row, false)).toBe(true)
+ delete row.identityHold
+ row.interpretationHold = 'rebuilding interpretation'
+ expect(run.attach.holdAdmissionStop(row, false)).toBe(true)
+ delete row.interpretationHold
+ expect(run.attach.holdAdmissionStop(row, true)).toBe(true)
+ run.attach.forget(row.sessionId)
+})
+it.each(['queued', 'running', 'relaunch'] as const)('retains a Stop while existing interpretation has a %s replacement', async phase => {
+ const marks = createRelaunchMarks(), run = setup({ relaunchMarks: marks, concurrency: 1 })
+ const row = session('commandcode', transcript([{ open: true, events: [started('later turn')] }]))
+ await run.attach.attachSession(row)
+ vi.mocked(run.deps.emit).mockClear()
+ let finish!: () => void
+ let blocker: Promise<boolean> | undefined, reset: Promise<boolean> | undefined
+ if (phase === 'relaunch') marks.note(row.sessionId, 0, true)
+ else {
+ vi.mocked(run.deps.terminalGone).mockImplementationOnce(() => new Promise(resolve => { finish = () => resolve(false) }))
+ if (phase === 'queued') blocker = run.attach.attachSession(session('claude', transcript([])))
+ reset = run.attach.attachSession(row, true)
+ }
+ expect(run.attach.holdAdmissionStop(row, false)).toBe(true)
+ expect(row.interpretationHold).toContain('Stop could not be matched')
+ if (finish) finish()
+ await blocker; await reset
+ await run.attach.attachSession(row, true)
+ expect(row.interpretationHold).toBeTruthy()
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
+it('acknowledges retained Stop despite an announcement failure so later Cancel remains authoritative', async () => {
+ const announceSession = vi.fn((): void => { throw new Error('fixture announcement failed') })
+ const run = setup({ announceSession }), row = session('claude', transcript([CLAUDE_PROMPT]))
+ expect(run.attach.holdAdmissionStop(row, true)).toBe(true)
+ expect(row.interpretationHold).toContain('Stop could not be matched')
+ announceSession.mockImplementation(() => {})
+ run.attach.beforeCancel(row)
+ run.normalizers.closeTurns(row.sessionId)
+ await run.attach.attachSession(row, true)
+ expect(row.interpretationHold).toBeUndefined()
+ expect(run.normalizers.sessionTurnOpen(row.sessionId)).toBe(false)
+ run.attach.forget(row.sessionId)
+})
+it('revokes captured Stop admission on Cancel, a new conversation and forget without revoking a sibling', () => {
+ const run = setup(), row = session('cursor'), sibling = session('commandcode')
+ const first = run.attach.captureAdmissionStop(row), same = run.attach.captureAdmissionStop(row)
+ const other = run.attach.captureAdmissionStop(sibling)
+ expect(first()).toBe(true); expect(same()).toBe(true)
+ run.attach.beforeCancel(row)
+ expect(first()).toBe(false); expect(same()).toBe(false); expect(other()).toBe(true)
+ const next = run.attach.captureAdmissionStop(row)
+ expect(next()).toBe(true)
+ const rebound = run.attach.captureAdmissionStop({ ...row, sessionId: 'new-conversation' })
+ expect(next()).toBe(false); expect(rebound()).toBe(true)
+ run.attach.forget(row.sessionId)
+ expect(rebound()).toBe(true)
+ run.attach.forget('new-conversation')
+ expect(rebound()).toBe(false); expect(other()).toBe(true)
+ run.attach.forget(sibling.sessionId)
+ expect(other()).toBe(false)
+})
it('recovers a legacy reader without control cuts and holds one that cannot replay them', async () => {
const run = setup(), row = session('muse', transcript([]), { evidenceRevision: 2, interpretationHold: 'pending' })
await run.attach.attachSession(row)
diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.ts
index 9138b70ce..1af95dfea 100644
--- a/cli/src/core/transcripts/attach.ts
+++ b/cli/src/core/transcripts/attach.ts
@@ -84,11 +84,24 @@ export function createAttach({
const readerLoads = createReaderLoads(readerLoadWaitMs)
const turnReplacements = createTurnReplacements(normalizers)
const recoveryRetries = new Map<string, ReturnType<typeof setTimeout>>()
+ const pendingAttaches = new Map<string, number>()
+ const admissionStops = new Map<string, { sessionId: string }>()
+ const captureAdmissionStop = (session: RegisteredSession): (() => boolean) => {
+ const agentId = session.agentId
+ let token = admissionStops.get(agentId)
+ if (token?.sessionId !== session.sessionId) {
+ token = { sessionId: session.sessionId }
+ admissionStops.set(agentId, token)
+ }
+ const captured = token
+ return () => admissionStops.get(agentId) === captured
+ }
const lifetimes = new Map<string, object>()
const forget = (sessionId: string): void => {
readerLoads.forget(sessionId)
lifetimes.delete(sessionId)
turnReplacements.forget(sessionId)
+ for (const [agentId, token] of admissionStops) if (token.sessionId === sessionId) admissionStops.delete(agentId)
clearTimeout(recoveryRetries.get(sessionId))
recoveryRetries.delete(sessionId)
}
@@ -98,6 +111,7 @@ export function createAttach({
return true
}
const beforeCancel = (session: RegisteredSession): void => {
+ admissionStops.delete(session.agentId)
if (session.identityHold || session.interpretationHold) turnReplacements.stage(session)
else if (session.transcriptPath || turnReplacements.retains(session)) {
const reason = turnReplacements.cancel(session)
@@ -108,7 +122,10 @@ export function createAttach({
turnReplacements.stage(session)
if (setInterpretationHold(session.agentId, session.evidenceRevision, reason, true)) {
const latest = resolve(session.agentId)!
- announceSession(latest)
+ // The control obligation already exists. A failed status notification must
+ // never make its caller replay that Stop after a later explicit Cancel.
+ try { announceSession(latest) }
+ catch (error) { console.warn('[agent] interpretation hold notification failed', error) }
void attachSession(latest, true).catch(error => console.warn(`[agent] recovery held: ${String(error)}`))
}
}
@@ -119,6 +136,14 @@ export function createAttach({
return true
}
const afterStop = (session: RegisteredSession): void => { turnReplacements.stop(session) }
+ const holdAdmissionStop = (session: RegisteredSession, unmatched: boolean): boolean => {
+ // A catch hook can supply the first transcript path, or arrive before a
+ // parser exists. Retain that completion before any recovered fold starts.
+ if (!unmatched && normalizers.sessionTurnState(session.sessionId) !== undefined
+ && !session.identityHold && !session.interpretationHold && !pendingAttaches.has(session.sessionId)
+ && !relaunchMarks?.read(session.sessionId)) return false
+ return holdStop(session, true)
+ }
/**
* Sessions that attached before their transcript existed, so nothing was folded and nothing has ever
* been streamed for them.
@@ -660,6 +685,8 @@ export function createAttach({
void cursorDiscovery.add(session.sessionId).catch(error => console.error(
`[cursor-discovery] lookup failed: ${error instanceof Error ? error.message : error}`))
}
+ const key = session.sessionId
+ pendingAttaches.set(key, (pendingAttaches.get(key) ?? 0) + 1)
return attaches.attach(session, reset, async () => {
// A normal attach may have taken the import's result while this retry waited for its slot.
if (retryCurrent && !retryCurrent()) return false
@@ -701,9 +728,13 @@ export function createAttach({
recoveryRetries.get(session.sessionId)!.unref()
}
}
- }, authority)
+ }, authority).finally(() => {
+ const pending = pendingAttaches.get(key)! - 1
+ if (pending) pendingAttaches.set(key, pending)
+ else pendingAttaches.delete(key)
+ })
}
- return { attachSession, attaches, neverFoldedHistory, replayedFirstTurn, forget, beforeCancel, afterStop, holdStop, holdInterpretation }
+ return { attachSession, attaches, neverFoldedHistory, replayedFirstTurn, forget, beforeCancel, afterStop, holdStop, holdAdmissionStop, holdInterpretation, captureAdmissionStop }
}
export type Attach = ReturnType<typeof createAttach>
diff --git a/cli/src/engines/transcriptBindings.spec.ts b/cli/src/engines/transcriptBindings.spec.ts
index b7b6475f7..34febfffd 100644
--- a/cli/src/engines/transcriptBindings.spec.ts
+++ b/cli/src/engines/transcriptBindings.spec.ts
@@ -27,6 +27,8 @@ beforeEach(async () => {
home = join(root, 'codex'); file = join(home, 'sessions', 'day', `rollout-${A}.jsonl`)
vi.stubEnv('ADAPTER_DATA_DIR', join(root, 'data')); vi.stubEnv('CODEX_HOME', home)
vi.stubEnv('CLAUDE_PROJECTS_DIR', join(root, 'claude', 'projects'))
+ vi.stubEnv('COMMANDCODE_HOME', join(root, 'commandcode')); vi.stubEnv('GROK_HOME', join(root, 'grok'))
+ vi.stubEnv('AGY_HOME', join(root, 'agy')); vi.stubEnv('COPILOT_HOME', join(root, 'copilot'))
write(join(root, 'data', 'engine-homes.json'), '{}'); write(file)
vi.resetModules(); bindings = await import('./transcriptBindings.js')
})
@@ -89,6 +91,55 @@ it('does not authorize a dangling leaf alias through its original parent', () =>
fs.symlinkSync(join(root, 'outside-absent.jsonl'), path)
expect(() => bindings.transcriptEvidence('codex', path, undefined, true)).toThrow('absent leaf')
})
+it.each([
+ ['commandcode', 'commandcode/projects/project/session.jsonl'],
+ ['grok', 'grok/sessions/project/session/updates.jsonl'],
+ ['agy', 'agy/brain/session/transcript.jsonl'],
+ ['copilot', 'copilot/session-state/session/events.jsonl'],
+] as const)('fences the unwritten %s derived locator before its root exists', (engine, suffix) => {
+ const path = join(root, suffix)
+ expect(bindings.transcriptEvidence(engine, path).valid).toBe(false)
+ const result = bindings.transcriptEvidence(engine, path, undefined, 'derived')
+ expect(result.valid).toBe(true); result.verify()
+ fs.mkdirSync(dirname(path), { recursive: true })
+ expect(() => result.verify()).toThrow('changed')
+ const parentOnly = bindings.transcriptEvidence(engine, path, undefined, 'derived')
+ expect(parentOnly.valid).toBe(true); parentOnly.verify()
+ write(path, '')
+ expect(() => parentOnly.verify()).toThrow('changed')
+ expect(bindings.transcriptEvidence(engine, path).valid).toBe(true)
+})
+it('does not let an unwritten locator borrow a dangling directory or leaf alias', () => {
+ const base = join(root, 'commandcode', 'projects')
+ fs.mkdirSync(base, { recursive: true })
+ for (const [path, link] of [[join(base, 'project', 'session.jsonl'), join(base, 'project')],
+ [join(base, 'session.jsonl'), join(base, 'session.jsonl')]]) {
+ fs.symlinkSync(join(root, 'outside-absent'), link)
+ expect(() => bindings.transcriptEvidence('commandcode', path, undefined, 'derived')).toThrow('absent leaf')
+ fs.rmSync(link)
+ }
+})
+it('requires owned surviving ancestry and keeps a derived locator inside its declared root', () => {
+ const path = join(root, 'commandcode', 'projects', 'project', 'session.jsonl')
+ const result = bindings.transcriptEvidence('commandcode', path, undefined, 'derived')
+ vi.mocked(fs.lstatSync).mockImplementation(((at: fs.PathLike, ...args: unknown[]) => {
+ const info = Reflect.apply(actual.lstatSync, actual, [at, ...args])
+ return String(at) === root ? Object.assign(info, { uid: info.uid + 1n }) : info
+ }) as typeof fs.lstatSync)
+ expect(() => result.verify()).toThrow('changed')
+ expect(() => bindings.transcriptEvidence('commandcode', path, undefined, 'derived')).toThrow('owner')
+ vi.mocked(fs.lstatSync).mockImplementation(actual.lstatSync)
+ expect(bindings.transcriptEvidence('commandcode', join(root, 'outside', 'session.jsonl'), undefined, 'derived').valid).toBe(false)
+})
+it('does not treat an existing unreadable derived transcript as an unwritten locator', () => {
+ const path = join(root, 'commandcode', 'projects', 'project', 'session.jsonl')
+ write(path, '')
+ vi.mocked(fs.openSync).mockImplementation(((at: fs.PathLike, ...args: unknown[]) => {
+ if (String(at) === path) throw Object.assign(new Error('fixture denied'), { code: 'EACCES' })
+ return Reflect.apply(actual.openSync, actual, [at, ...args])
+ }) as typeof fs.openSync)
+ expect(() => bindings.transcriptEvidence('commandcode', path, undefined, 'derived')).toThrow('could not be read')
+})
it.each(['', '{', record().slice(0, -4), ' '.repeat(128 * 1024) + record(), record(A, { future: 'unknown' })])('holds an incomplete or unknown native header', text => {
fs.writeFileSync(file, text)
expect(proof).toThrow()
diff --git a/cli/src/engines/transcriptBindings.ts b/cli/src/engines/transcriptBindings.ts
index d80fdf09a..b31cb5666 100644
--- a/cli/src/engines/transcriptBindings.ts
+++ b/cli/src/engines/transcriptBindings.ts
@@ -1,5 +1,5 @@
/** Eager native transcript authority shared by binding, Stop and resume preflight. */
-import { basename, dirname, join } from 'node:path'
+import { basename, dirname, isAbsolute, join, relative } from 'node:path'
import { env } from '../config/env.js'
import { engineHomeSnapshot, sessionRoots, type EngineHomeSnapshot } from '../lib/engineHomes.js'
import { cursorDataDir } from './cursor/contract.js'
@@ -42,13 +42,49 @@ export function transcriptRootEvidence(engine: AgentEngine, profile?: string, sn
return { directories, verify(): void { files.verify(); ownSnapshot?.verify() } }
}
-/** A caller can supply its explicit synchronous batch proofs and verify them before publication. */
+/** A deterministic engine locator can precede its directories. Retain the first
+ * missing component and its owned ancestor; a dangling alias is not absence. */
+function futureDirectory(files: NativeFiles, path: string): { path: string; present: boolean } {
+ if (path.split('/').includes('..')) return nativeUnavailable('an unwritten transcript has an unresolved parent step')
+ const suffix: string[] = []
+ for (let at = path;; at = dirname(at)) {
+ files.budget.step()
+ const location = files.locate(at, true)
+ if (location) {
+ if (!location.info.isDirectory()) return nativeUnavailable('the announced transcript ancestor is not a directory')
+ if (typeof process.getuid === 'function' && location.info.uid !== BigInt(process.getuid())) {
+ return nativeUnavailable('the announced transcript ancestor has an unconfirmed owner')
+ }
+ if (suffix.length && !files.paths.absentLeaf(join(location.path, suffix[0]))) {
+ return nativeUnavailable('the announced transcript ancestor is not a proven absent leaf')
+ }
+ return { path: join(location.path, ...suffix), present: !suffix.length }
+ }
+ if (suffix.length >= 64 || at === dirname(at)) return nativeUnavailable('the unwritten transcript ancestor limit was reached')
+ suffix.unshift(basename(at))
+ }
+}
+
+/** A caller can supply its explicit synchronous batch proofs and verify them before publication.
+ * Only core-derived locators may name directories that the engine has not written yet. */
export function transcriptEvidence(engine: AgentEngine, path: string, profile?: string,
- allowMissing = false, snapshot?: EngineHomeSnapshot, roots?: ReturnType<typeof transcriptRootEvidence>,
+ allowMissing: boolean | 'derived' = false, snapshot?: EngineHomeSnapshot, roots?: ReturnType<typeof transcriptRootEvidence>,
) {
const files = new NativeFiles(), root = transcriptRoot[engine]
const scope = roots ?? transcriptRootEvidence(engine, profile, snapshot)
const location = root ? files.file(path, true) : null
+ if (!location && allowMissing === 'derived') {
+ if (typeof root !== 'function') return nativeUnavailable('the unwritten transcript has no deterministic root')
+ const parent = futureDirectory(files, dirname(path)), declared = futureDirectory(files, root())
+ const actual = join(parent.path, basename(path))
+ if (parent.present && !files.paths.absentLeaf(actual)) {
+ return nativeUnavailable('the announced transcript is not a proven absent leaf')
+ }
+ const member = relative(declared.path, actual)
+ return { valid: !!member && member !== '..' && !member.startsWith('../') && !isAbsolute(member), files,
+ matchingRoots: scope.directories,
+ verify(selected = path): void { files.verify(selected); if (!roots) scope.verify() } }
+ }
const parent = !location && allowMissing ? files.locate(dirname(path), true) : null
if (parent && !parent.info.isDirectory()) return nativeUnavailable('the announced transcript parent is not a directory')
if (parent && typeof process.getuid === 'function' && parent.info.uid !== BigInt(process.getuid())) {
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index 96e09876f..9392ad918 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -279,19 +279,22 @@ describe('hook notify terminal scope', () => {
expect(statSync(credential).isFIFO()).toBe(true)
})
- it('forwards Cursor Task/stop hooks, journals the launcher, and always prints JSON', async () => {
+ it.each(['applied', 'pending', 'duplicate'])('forwards Cursor Task/stop hooks and retains tasks unless completion was applied: %s', async acknowledgement => {
const dir = mkdtempSync(join(tmpdir(), 'adapter-hook-cursor-'))
tmpDirs.push(dir)
const dataDir = join(dir, 'data')
const cursorHome = join(dir, 'cursor')
const requests: Array<{ url: string; body: Record<string, unknown> }> = []
+ const deliveries: unknown[] = []
const server = createServer((req, res) => {
if (req.method !== 'POST') { res.writeHead(405).end(); return }
let raw = ''
req.on('data', (chunk) => { raw += chunk.toString() })
req.on('end', () => {
requests.push({ url: req.url ?? '', body: JSON.parse(raw) as Record<string, unknown> })
- res.end('{}')
+ deliveries.push([req.headers['x-harness-hook-delivery-id'], req.headers['x-harness-hook-fired-at']])
+ res.end(req.url === '/api/hook/turn-stop' && acknowledgement !== 'applied'
+ ? JSON.stringify({ [acknowledgement]: true }) : '{}')
})
})
servers.push(server)
@@ -334,6 +337,7 @@ describe('hook notify terminal scope', () => {
}])
requests.splice(0)
+ deliveries.splice(0)
await runHook({
port: address.port,
tmuxPane: '%21',
@@ -342,6 +346,7 @@ describe('hook notify terminal scope', () => {
cursorHome,
input: {
hook_event_name: 'stop',
+ status: 'error',
session_id: 'cursor-session',
workspace_roots: ['/tmp/cursor-workspace'],
cursor_version: '2026.07.20-8cc9c0b',
@@ -351,7 +356,13 @@ describe('hook notify terminal scope', () => {
'/api/hook/session-start',
'/api/hook/turn-stop',
])
- expect(() => readFileSync(join(dataDir, 'cursor-pending-tasks.json'), 'utf8')).toThrow()
+ expect(requests.map(request => request.body.status)).toEqual(['error', 'error'])
+ expect(deliveries[0]).toEqual(deliveries[1])
+ if (acknowledgement !== 'applied') {
+ expect(() => readFileSync(join(dataDir, 'cursor-pending-tasks.json'), 'utf8')).not.toThrow()
+ expect(JSON.parse(readFileSync(join(dataDir, 'cursor-pending-tasks.json'), 'utf8'))).toHaveLength(1)
+ }
+ else expect(() => readFileSync(join(dataDir, 'cursor-pending-tasks.json'), 'utf8')).toThrow()
})
it('keeps a Cursor session\'s tasks when its end was not answered in time', async () => {
@@ -741,12 +752,14 @@ describe('hook notify terminal scope', () => {
writeLegacyStateFile(join(dataDir, 'registry.json'), '[]')
let attempts = 0
const firedAt: unknown[] = []
+ const deliveryIds: 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'])
+ deliveryIds.push(req.headers['x-harness-hook-delivery-id'])
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)
@@ -764,6 +777,8 @@ describe('hook notify terminal scope', () => {
})).toBe('{}\n')
expect(attempts).toBe(outcome === 'recovers' ? 3 : outcome === 'disconnects' ? 2 : 4)
expect(new Set(firedAt).size).toBe(1)
+ expect(new Set(deliveryIds).size).toBe(1)
+ expect(deliveryIds[0]).toMatch(/^[a-f0-9-]{36}$/)
expect(readFileSync(join(dataDir, 'registry.json'), 'utf8')).toBe('[]')
expect(() => statSync(join(dataDir, 'registry-boot'))).toThrow()
})
diff --git a/cli/src/hookServer.hermes.spec.ts b/cli/src/hookServer.hermes.spec.ts
index 7ce815dda..891e5dd05 100644
--- a/cli/src/hookServer.hermes.spec.ts
+++ b/cli/src/hookServer.hermes.spec.ts
@@ -6,12 +6,15 @@ import { afterEach, expect, it, vi } from 'vitest'
import type { Server } from 'node:http'
const failures = vi.hoisted(() => new Map<string, string>())
+const inspection = vi.hoisted(() => ({ read: undefined as ((path: string) => void) | undefined }))
vi.mock('node:fs/promises', async original => {
const fs = await original<typeof import('node:fs/promises')>()
const guarded = (name: 'lstat' | 'opendir') => 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])
+ const result = await Reflect.apply(fs[name], fs, [path, ...args])
+ inspection.read?.(path)
+ return result
}
return { ...fs, lstat: guarded('lstat'), opendir: guarded('opendir') }
})
@@ -23,6 +26,7 @@ afterEach(async () => {
server = undefined
vi.restoreAllMocks(); vi.unstubAllEnvs()
failures.clear()
+ inspection.read = undefined
if (root) rmSync(root, { recursive: true, force: true })
})
async function fixture(options: { waitOnResolution?: number } = {}) {
@@ -81,6 +85,22 @@ async function fixture(options: { waitOnResolution?: number } = {}) {
}
}
+it('holds when the known home changes during source inspection instead of publishing the old proof', async () => {
+ const f = await fixture()
+ const own = '20261009_120000_aabbcc', other = join(root, 'another-home')
+ f.store(f.home, [[own, 'cli']])
+ f.store(other, [])
+ inspection.read = path => {
+ if (path !== join(f.home, 'state.db')) return
+ inspection.read = undefined
+ f.knownHome(other)
+ }
+ await f.hook(own)
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('fresh evidence after the binding changed'))).toBe(true))
+ expect(f.current()).toMatchObject({ sessionId: '', hermesHome: other })
+ expect(f.registered).not.toHaveBeenCalled()
+})
+
it('holds an unreadable store without binding and retries after the store recovers', async () => {
const f = await fixture()
const previous = '20261009_115900_eeeeee'
@@ -183,7 +203,7 @@ it('recovers an equal-time parent after its child has already been held', async
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))
+ await vi.waitFor(() => expect(f.logs.some(line => line.includes('unambiguous native 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()
@@ -232,7 +252,7 @@ it('contains an asynchronous onRegistered rejection after publishing exactly onc
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)))
+ await vi.waitFor(() => expect(warning).toHaveBeenCalledWith('[hooks] committed admission notification failed', expect.any(Error)))
expect(f.current().sessionId).toBe(wanted)
expect(f.registered).toHaveBeenCalledOnce()
})
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index 12efc1686..7ff6a0ecf 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -13,6 +13,7 @@ import { engineHooks } from './engines/hooks.js'
let server: Server | null = null
afterEach(async () => {
+ vi.restoreAllMocks()
if (!server) return
await new Promise<void>((resolve) => server!.close(() => resolve()))
server = null
@@ -40,11 +41,13 @@ describe('process-owned hook server', () => {
it('honors engine admission before registering or announcing a prompt, including a failed check', async () => {
const admit = vi.spyOn(engineHooks.codex, 'admit')
.mockReturnValueOnce({ accepted: false, reason: 'codex_subagent' })
- .mockImplementationOnce(() => { throw new Error('rollout unavailable') })
+ .mockImplementation(() => { throw new Error('rollout unavailable') })
+ const agent = { engine: 'codex', agentId: 'parent', runtimes: [{ backend: 'tmux', paneId: '%41' }], primaryRuntimeKey: 'tmux\u0000%41', processIdentity: { pid: 4242, startMarker: 'fixture', executable: '<codex>' } } as RegisteredSession
+ const byAgent = vi.spyOn(registry, 'byAgent').mockReturnValue(agent)
try {
const onPromptSubmitted = vi.fn()
const { handlers, base, headers } = await start({
- resolveHookAgent: async () => ({ engine: 'codex', agentId: 'parent' }) as RegisteredSession,
+ resolveHookAgent: async () => agent,
onPromptSubmitted,
})
for (const reason of ['codex_subagent', 'engine_hook_failed']) {
@@ -52,11 +55,11 @@ describe('process-owned hook server', () => {
method: 'POST', headers,
body: JSON.stringify({ engine: 'codex', tmuxPane: '%41', sessionId: 'child', hookEvent: 'UserPromptSubmit' }),
})
- expect(await response.json()).toEqual({ ignored: true, reason })
+ expect(await response.json()).toEqual(reason === 'engine_hook_failed' ? { pending: true } : { ignored: true, reason })
}
expect(handlers.onRegistered).not.toHaveBeenCalled()
expect(onPromptSubmitted).not.toHaveBeenCalled()
- } finally { admit.mockRestore() }
+ } finally { admit.mockRestore(); byAgent.mockRestore() }
})
it('runs targeted resolution and rejects a hook without a matching pane engine process', async () => {
@@ -126,7 +129,8 @@ describe('process-owned hook server', () => {
new Promise<'held'>((resolve) => setTimeout(() => resolve('held'), 2_000)),
])
expect(reply).not.toBe('held')
- expect(await (reply as Response).json()).toEqual({ pending: true })
+ expect((reply as Response).status).toBe(202)
+ expect(await (reply as Response).json()).toMatchObject({ pending: false, retry: true })
// The wait ends with no agent for it: said in the log, and nothing is answered twice.
found(null)
await vi.waitFor(() => expect(log).toHaveBeenCalledWith('[hooks] session- session-start ignored · no_matching_engine_process'))
@@ -167,9 +171,10 @@ describe('process-owned hook server', () => {
it('treats SessionEnd as a reconciliation hint and exposes no launcher websocket endpoint', async () => {
const onSessionEnd = vi.fn()
- const resolveHookAgent = vi.fn(async () => ({
- engine: 'claude', sessionId: 'session-1', agentId: 'agent-1',
- } as never))
+ const agent = { engine: 'claude', sessionId: 'session-1', agentId: 'agent-1', runtimes: [], processIdentity: null } as unknown as RegisteredSession
+ vi.spyOn(registry, 'bySession').mockReturnValue(agent)
+ vi.spyOn(registry, 'byAgent').mockReturnValue(agent)
+ const resolveHookAgent = vi.fn(async () => agent)
const { base, headers } = await start({ onSessionEnd, resolveHookAgent })
const ended = await fetch(`${base}/api/hook/session-end`, {
method: 'POST',
@@ -240,7 +245,10 @@ describe('process-owned hook server', () => {
it('hands a Stop on with when its engine ran it, and holds it as long as a test asks', async () => {
const onTurnStop = vi.fn()
- const resolveHookAgent = vi.fn(async () => ({ engine: 'claude', sessionId: 'real-session', agentId: 'agent-1' } as never))
+ const agent = { engine: 'claude', sessionId: 'real-session', agentId: 'agent-1', runtimes: [], processIdentity: null } as unknown as RegisteredSession
+ vi.spyOn(registry, 'bySession').mockReturnValue(agent)
+ vi.spyOn(registry, 'byAgent').mockReturnValue(agent)
+ const resolveHookAgent = vi.fn(async () => agent)
const stop = (base: string, headers: Record<string, string>) => fetch(`${base}/api/hook/turn-stop`, {
method: 'POST', headers, body: JSON.stringify({ engine: 'claude', sessionId: 'real-session', tmuxPane: '%1', callerPid: 123 }),
})
@@ -389,13 +397,13 @@ describe('knownTranscriptFor', () => {
expect(knownTranscriptFor({ engine: 'claude', sessionId, transcriptPath: known }, { ...row, transcriptPath: join(root, 'other.jsonl') })).toBe(known)
})
- it('keeps the announcement if the engine lookup fails', () => {
+ it('retains a failed native correction as unavailable evidence', () => {
const lookup = vi.spyOn(engineHooks.claude, 'transcriptFor')
.mockImplementationOnce(() => { throw new Error('lookup failed') })
.mockImplementationOnce(() => { throw 'lookup failed again' })
try {
- expect(knownTranscriptFor({ sessionId, transcriptPath: announced }, row)).toBe(announced)
- expect(knownTranscriptFor({ sessionId, transcriptPath: announced }, row)).toBe(announced)
+ expect(() => knownTranscriptFor({ sessionId, transcriptPath: announced }, row)).toThrow()
+ expect(() => knownTranscriptFor({ sessionId, transcriptPath: announced }, row)).toThrow()
} finally { lookup.mockRestore() }
})
@@ -519,7 +527,8 @@ describe('requests must name this server', () => {
const hook = await fetch(`${base}/api/hook/session-start`, {
method: 'POST', headers, body: JSON.stringify({ engine: 'codex', tmuxPane: '%41', sessionId: '019fea92-e31a-7692-9c35-f616e9d458b7' }),
})
- expect(await hook.json()).toEqual({ pending: true })
+ expect(hook.status).toBe(202)
+ expect(await hook.json()).toMatchObject({ pending: false, retry: true })
expect(error).toHaveBeenCalledWith('[hooks] GET /api/status failed:', 'status read failed')
expect(error).toHaveBeenCalledWith('[hooks] GET /api/status failed:', expect.stringContaining('BigInt'))
await vi.waitFor(() => expect(error).toHaveBeenCalledWith('[hooks] POST /api/hook/session-start failed:', 'resolution failed after the answer'))
@@ -702,3 +711,21 @@ describe('the device history and dismiss endpoints', () => {
expect((await post({ confirm: true, head: 'x' })).status).toBe(400)
})
})
+
+
+it.each(['/api/hook/session-end', '/api/hook/turn-start', '/api/hook/tool-start', '/api/hook/turn-stop'])(
+ 'refuses a binding changed during process resolution on %s', async path => {
+ const row = { engine: 'claude', sessionId: 'race-session', agentId: 'race-agent', runtimes: [], processIdentity: null,
+ evidenceRevision: 1 } as unknown as RegisteredSession
+ vi.spyOn(registry, 'bySession').mockReturnValue(row)
+ vi.spyOn(registry, 'byAgent').mockReturnValue(row)
+ const mutation = vi.fn()
+ const { base, headers } = await start({ onSessionEnd: mutation, onTurnStart: mutation, onToolStart: mutation, onTurnStop: mutation,
+ resolveHookAgent: async () => { await Promise.resolve(); row.evidenceRevision = 2; return row } })
+ const response = await fetch(`${base}${path}`, { method: 'POST', headers,
+ body: JSON.stringify({ engine: 'claude', sessionId: row.sessionId, tmuxPane: '%1', callerPid: 4242,
+ toolUseId: 'fixture-tool', toolName: 'Task' }) })
+ expect(response.status).toBe(403)
+ expect(mutation).not.toHaveBeenCalled()
+ },
+)
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index 8c44dda95..9768b1cbd 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -4,7 +4,7 @@
* UI is gone; only these two endpoints remain local.
*/
-import { existsSync } from 'node:fs'
+import { createHash, randomUUID } from 'node:crypto'
import { join } from 'node:path'
import http from 'node:http'
import type { AddressInfo } from 'node:net'
@@ -87,6 +87,13 @@ export interface HookServerHandlers {
/** A turn is now running (Command Code's PreToolUse — its only live turn-open signal). Idempotent:
* it fires once per tool call, and every call after the first in a turn must be a no-op. */
onTurnStart?: (body: { sessionId: string }) => void
+ /** Core lifecycle admission fence; Stop owns the pane before its first asynchronous capture. */
+ hookAdmissionBlocked?: (agentId: string) => boolean
+ onAdmissionHeld?: (agentId: string, reason: string | undefined) => void
+ /** Retain an uncorrelated native Stop before attaching a newly admitted conversation. */
+ onAdmissionStop?: (entry: RegisteredSession, unmatched: boolean) => boolean
+ /** Captured before a same-conversation registration waits; Cancel or forget supersedes that Stop. */
+ captureAdmissionStop?: (entry: RegisteredSession) => () => boolean
onPromptSubmitted?: (agentId: string, prompt: string) => void
/** A session's UserPromptSubmit hook, and when its engine ran it (`X-Harness-Hook-Fired-At`): what a Stop
* that arrives late is told apart from the turn the prompt opened by (core/turns/turnHooks.ts). */
@@ -287,6 +294,9 @@ async function verifiedBoundMutation(
handlers: HookServerHandlers,
): Promise<RegisteredSession | null> {
if (!body.sessionId || !body.engine) return null
+ const initial = registry.bySession(body.sessionId)
+ if (!initial || initial.engine !== body.engine) return null
+ const identity = paneReadIdentity(initial)
const runtimeHints = normalizedRuntimeHints(body)
if (!runtimeHints.length) return null
const processAgent = handlers.resolveHookAgent
@@ -298,7 +308,9 @@ async function verifiedBoundMutation(
})
: body.tmuxPane ? registry.byPaneEngine(body.tmuxPane, body.engine) ?? null : null
return processAgent?.engine === body.engine && processAgent.sessionId === body.sessionId
- ? processAgent
+ && processAgent.agentId === initial.agentId && paneReadIdentity(processAgent) === identity
+ && paneReadIdentity(registry.byAgent(initial.agentId)) === identity
+ ? registry.byAgent(initial.agentId)!
: null
}
@@ -307,60 +319,14 @@ async function verifiedBoundMutation(
* a leftover daemon un-findable by `lsof :<port>`). Rejects with EADDRINUSE if the port is taken (the
* CLI reports it as "another adapter already running"). Resolves with the bound port.
*/
-/** How long to keep waiting for an engine to write the transcript it just announced. */
-const TRANSCRIPT_WAIT_MS = 500
-const TRANSCRIPT_WAIT_TRIES = 20
-
-function registeredHookProcess(body: RegisterInput, engine: AgentEngine): RegisteredSession | undefined {
- if (body.processIdentity) {
- const processAgent = registry.byProcess(engine, body.processIdentity)
- if (processAgent) return processAgent
- }
- for (const runtime of body.runtimes ?? []) {
- const processAgent = registry.byRuntimeEngine(runtime, engine)
- if (processAgent) return processAgent
- }
- 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. */
+/** A failed native correction is incomplete evidence, never the original announcement. */
export function knownTranscriptFor(body: RegisterInput, agent: RegisteredSession | undefined): string | undefined {
- const engine = body.engine ?? 'claude'
- try { return hooksFor(engine)?.transcriptFor?.(body, agent) ?? body.transcriptPath } catch (error) {
- console.warn(`[hooks] ${engine} transcript lookup failed:`, error instanceof Error ? error.message : error)
- return body.transcriptPath
- }
-}
-
-/**
- * Register once the announced transcript exists.
- *
- * Runs detached from the HTTP reply on purpose: this is a SessionStart hook, and the engine is blocked
- * until the response comes back. Bounded — an announcement whose file never appears is dropped, which is
- * the same outcome as before, just after giving the engine a fair chance to finish starting up.
- */
-async function awaitTranscript(body: RegisterInput, handlers: HookServerHandlers): Promise<void> {
- for (let i = 0; i < TRANSCRIPT_WAIT_TRIES; i++) {
- await new Promise((resolve) => { const t = setTimeout(resolve, TRANSCRIPT_WAIT_MS); t.unref?.() })
- const engine = body.engine ?? 'claude'
- const processAgent = registeredHookProcess(body, engine)
- if (!processAgent) return
- if (isRecentlyDeleted(body.sessionId)) return
- body.transcriptPath = knownTranscriptFor(body, processAgent)
- if (!body.transcriptPath || !existsSync(body.transcriptPath)) continue
- const result = registry.register(body)
- if (!result) return
- console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=${result.entry.engine}`
- + ` · isNew=${result.isNew} · after waiting ${((i + 1) * TRANSCRIPT_WAIT_MS) / 1000}s for its transcript`)
- handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })
- return
- }
- console.warn(`[hooks] ${sid(body.sessionId ?? '?')} announced a transcript that never appeared: ${body.transcriptPath}`)
+ return hooksFor(body.engine ?? 'claude')?.transcriptFor?.(body, agent) ?? body.transcriptPath
}
/** Read source evidence without binding. Unreadable stores never authorize a conversation. */
@@ -390,6 +356,10 @@ export interface HookServerOptions {
socketPath?: string | null
/** A private socket identifies this user's daemon even when another OS user holds the TCP port. */
allowPortFallback?: boolean
+ /** Completed acknowledgements are retained for a live process, never evicted to admit another hook. */
+ admissionReceiptCapacity?: number
+ /** Bound native payload and provenance retained by pending admission or linked Stop. */
+ admissionBytesCapacity?: number
}
export function startHookServer(
@@ -400,6 +370,21 @@ export function startHookServer(
const hookCredential = loadOrCreateHookCredential(env.ADAPTER_DATA_DIR)
const admissions = createPendingAdmissions({ isProcessCurrent: (key, scope) => admissionProcessScope(registry.byAgent(key)) === scope })
let admissionArrival = 0
+ const admissionHolds = new Map<string, Map<string, string>>()
+ type StopAcknowledgement = { status: number; reply: unknown }
+ type LinkedStop = (body: BoundHookBody, firedAt: number | undefined) => StopAcknowledgement | Promise<StopAcknowledgement>
+ type Receipt = { fingerprint: string; status: number; reply: unknown; pending: boolean; bytes: number; linkedStop?: LinkedStop }
+ const admissionReceipts = new Map<string, { scope: string; records: Map<string, Receipt> }>()
+ const resolvingStops = new Map<string, { fingerprint: string; stop: LinkedStop }>()
+ let receiptCount = 0, receiptBytes = 0
+ const saveReceipt = (records: Map<string, Receipt>, id: string, next?: Receipt) => {
+ const before = records.get(id)
+ if (before) { receiptCount--; receiptBytes -= before.bytes }
+ if (next) { records.set(id, next); receiptCount++; receiptBytes += next.bytes }
+ else records.delete(id)
+ }
+ const receiptCapacity = options.admissionReceiptCapacity ?? 65_536
+ const bytesCapacity = options.admissionBytesCapacity ?? 16 * 1024 * 1024
// 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
@@ -508,7 +493,39 @@ export function startHookServer(
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
+ const fingerprint = createHash('sha256').update(JSON.stringify([body, admissionOrder.firedAt])).digest('hex')
+ const deliveryHeader = req.headers['x-harness-hook-delivery-id']
+ const nativeDeliveryId = typeof deliveryHeader === 'string' && /^[a-zA-Z0-9_-]{16,96}$/.test(deliveryHeader) ? deliveryHeader : undefined
+ const deliveryId = nativeDeliveryId ?? randomUUID()
+ const carriesStop = !!nativeDeliveryId && (engine === 'cursor' && body.hookEvent === 'stop'
+ || engine === 'commandcode' && (body.hookEvent === 'Stop' || body.hookEvent === 'StopFailure'))
+ const stopProvenance = (value: BoundHookBody, firedAt: number | undefined) => JSON.stringify([
+ value.engine, value.sessionId, value.callerPid, normalizedRuntimeHints(value), firedAt, value.status,
+ ])
+ const originalStop = stopProvenance(body, admissionOrder.firedAt)
+ const conflict = { status: 409, reply: { pending: false, error: 'HOOK_DELIVERY_CONFLICT' } }
+ const scopeOf = (row: RegisteredSession | undefined) => row && JSON.stringify([
+ row.agentId, row.engine, row.processIdentity ? processIdentityKey(row.engine, row.processIdentity) : null,
+ ])
+ const resolving = resolvingStops.get(deliveryId)
+ if (resolving) {
+ const reply = resolving.fingerprint === fingerprint ? await resolving.stop(body, admissionOrder.firedAt) : conflict
+ answer(reply.status, reply.reply); return
+ }
+ // A preliminary lookup grants no binding authority. It only remembers
+ // cancellation before process resolution yields; the proved owner below
+ // must match this exact process/conversation before the witness applies.
+ const preliminary = carriesStop && body.sessionId ? registry.bySession(body.sessionId) : undefined
+ const stopScope = preliminary?.engine === engine ? scopeOf(preliminary) : undefined
+ const stopWitness = stopScope ? handlers.captureAdmissionStop?.(preliminary!) : undefined
+ let deferred = false
+ if (carriesStop) resolvingStops.set(deliveryId, { fingerprint, stop: (stop, firedAt) => {
+ if (stopProvenance(stop, firedAt) !== originalStop) return conflict
+ deferred = true
+ return { status: 202, reply: { pending: false, retry: true, detail: 'Waiting for the engine process record; Stop admission is not queued yet.' } }
+ } })
+ let processAgent: RegisteredSession | null
+ try { processAgent = handlers.resolveHookAgent
? await handlers.resolveHookAgent({
engine,
tmuxPane: body.tmuxPane,
@@ -522,79 +539,198 @@ export function startHookServer(
// as for a transcript not yet written below, and the wait goes on here.
// 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 }),
+ onWait: () => { deferred = true; answer(202, { pending: false, retry: true, detail: 'Waiting for the engine process record; admission is not queued yet.' }) },
})
: body.tmuxPane ? registry.byPaneEngine(body.tmuxPane, engine) ?? null : null
+ } finally { if (carriesStop) resolvingStops.delete(deliveryId) }
if (!processAgent || processAgent.engine !== engine) { ignore('no_matching_engine_process'); return }
- // The process scanner is authoritative. Never accept a hook's legacy launcher id or a stale PID.
- body.processIdentity = processAgent.processIdentity ?? undefined
- body.runtimes = processAgent.runtimes
+ // Own the process incarnation. Each inspection refreshes its routing,
+ // but can never follow the original hinted pane to a replacement process.
+ body.processIdentity = processAgent.processIdentity ? { ...processAgent.processIdentity } : undefined
+ body.runtimes = processAgent.runtimes.map(runtime => ({ ...runtime }))
body.primaryRuntimeKey = processAgent.primaryRuntimeKey
- body.transcriptPath = knownTranscriptFor(body, processAgent)
- // Deleting an agent no longer kills its pane, so the engine lives on for a moment and its catch
- // hook still fires — and the exact process may remain alive during SIGTERM grace. Without
- // this the tile the user just deleted re-registers itself and comes back.
if (isRecentlyDeleted(body.sessionId)) { ignore('deleted'); return }
- const admission = admitHook(engine, body)
- if (!admission.accepted) { ignore(admission.reason); return }
- // Same story for hermes, which reaches here through its own hooks rather than a transcript file:
- // every delegated sub-agent is a hermes session that runs those hooks from the parent's pane.
- if (body.engine === 'hermes' && body.sessionId) {
- // 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.
- const identity = paneReadIdentity(processAgent)
- const knownHome = processAgent.hermesHome ?? undefined
- 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!, knownHome),
- 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 })
- }
+ const scope = scopeOf(processAgent)!
+ if (carriesStop && stopScope !== scope) deferred = true
+ if (scopeOf(registry.byAgent(processAgent.agentId)) !== scope) { ignore('stale_hook'); return }
+ // Pending jobs and completed receipts survive routing observations within
+ // this process incarnation. Native hints are rechecked before every commit.
+ const receiptScope = scopeOf
+ for (const [id, history] of admissionReceipts) if (receiptScope(registry.byAgent(id)) !== history.scope) {
+ for (const delivery of history.records.keys()) saveReceipt(history.records, delivery)
+ admissionReceipts.delete(id)
+ }
+ const history = admissionReceipts.get(processAgent.agentId) ?? { scope: receiptScope(processAgent)!, records: new Map() }
+ admissionReceipts.set(processAgent.agentId, history)
+ const completed = history.records.get(deliveryId)
+ if (completed) {
+ if (completed.fingerprint === fingerprint) answer(completed.status, completed.reply)
+ else answer(409, { pending: false, error: 'HOOK_DELIVERY_CONFLICT' })
return
}
- if (body.hookEvent === 'UserPromptSubmit') {
- handlers.onPromptSubmitted?.(processAgent.agentId, body.prompt ?? '')
- const fired = hookFiredAt(req)
- if (fired && body.sessionId) handlers.onPromptHook?.(body.sessionId, fired)
+ // Strings can occupy two bytes per code unit; include the immutable
+ // process snapshot and fixed closure/record overhead in this admission budget.
+ const retainedBytes = 2 * (JSON.stringify(body).length + JSON.stringify(processAgent).length) + 2_048
+ if (receiptCount >= receiptCapacity || receiptBytes + retainedBytes > bytesCapacity) {
+ answer(429, { pending: false, error: 'HOOK_ADMISSION_BUSY', detail: 'Hook acknowledgement storage is full; this delivery was not queued.' })
+ return
}
- let result = registry.register(body)
- if (!result && body.transcriptPath && !existsSync(body.transcriptPath)) {
- // The engine announced the session BEFORE writing its transcript. Measured on claude: the hook
- // arrived at 13:03:31 and the file appeared at 13:03:34, so registration was refused (a session
- // is only accepted with a real file behind it) and the agent stayed off the list until something
- // else noticed it. Wait for the file instead of dropping the announcement — in the background,
- // because a SessionStart hook blocks the CLI that is waiting on this reply.
+ let inspectionIdentity: string | undefined
+ let prepared: RegisterInput = body
+ let committed: ReturnType<typeof registry.register> = null
+ let settled = false, stopRetained = false, stopUnmatched = false, stopInvocationClaimed = false
+ const stopCurrent = processAgent.sessionId === body.sessionId && stopScope === scope ? stopWitness : undefined
+ let followupFingerprint: string | undefined, committedIdentity: string | undefined
+ const live = () => registry.byAgent(processAgent.agentId)
+ const current = () => !isRecentlyDeleted(processAgent.agentId) && !isRecentlyDeleted(body.sessionId)
+ && live()?.active !== false && scopeOf(live()) === scope
+ const publishHold = () => {
+ const reason = [...admissionHolds.get(processAgent.agentId)?.values() ?? []].at(-1)
+ try { handlers.onAdmissionHeld?.(processAgent.agentId, reason) }
+ catch (error) { console.warn('[hooks] admission status notification failed', error) }
+ }
+ const held = (reason: string) => {
+ deferred = true
+ const holds = admissionHolds.get(processAgent.agentId) ?? new Map<string, string>()
+ holds.set(deliveryId, reason); admissionHolds.set(processAgent.agentId, holds)
+ publishHold()
+ console.log(`[hooks] ${sid(body.sessionId ?? '?')} ${body.hookEvent ?? 'session-start'} held · ${reason}`)
answer(200, { pending: true })
- void awaitTranscript(body, handlers)
- return
}
- if (!result) {
- console.warn(`[hooks] ${sid(body.sessionId ?? '?')} REJECTED · engine=${body.engine} pane=${body.tmuxPane}`)
- answer(400, { error: 'invalid session registration' })
- return
+ const clearHold = () => {
+ const holds = admissionHolds.get(processAgent.agentId)
+ if (!holds?.delete(deliveryId)) return
+ if (!holds.size) admissionHolds.delete(processAgent.agentId)
+ publishHold()
+ }
+ const completedReply = (status: number, reply: unknown) => {
+ // A pruned old process cannot reinsert its receipts from a late callback.
+ if (admissionReceipts.get(processAgent.agentId) === history) saveReceipt(history.records, deliveryId,
+ { ...history.records.get(deliveryId)!, status, reply, pending: false, bytes: carriesStop ? retainedBytes : 0 })
+ settled = true
+ answer(status, reply)
+ }
+ const linkedStop: LinkedStop = async (stop, firedAt) => {
+ if (stopProvenance(stop, firedAt) !== originalStop) return conflict
+ const sent = createHash('sha256').update(JSON.stringify(stop)).digest('hex')
+ if (followupFingerprint && sent !== followupFingerprint) return conflict
+ followupFingerprint = sent
+ // The registration itself owns this native Stop, even if its second
+ // HTTP delivery outruns source recovery. Never close a later live turn.
+ if (!settled || stopRetained) {
+ deferred = true
+ return { status: 200, reply: { pending: true } }
+ }
+ if (stopCurrent && !stopCurrent()) stopInvocationClaimed = true
+ if (stopInvocationClaimed) return { status: 200, reply: { ok: true, duplicate: true } }
+ const owner = await verifiedBoundMutation(stop, handlers)
+ if (stopCurrent && !stopCurrent()) stopInvocationClaimed = true
+ if (stopInvocationClaimed) return { status: 200, reply: { ok: true, duplicate: true } }
+ if (stopRetained) return { status: 200, reply: { pending: true } }
+ if (!current() || live()?.sessionId !== body.sessionId) {
+ return { status: 403, reply: { error: 'UNBOUND_HOOK' } }
+ }
+ if (!owner || paneReadIdentity(owner) !== committedIdentity) {
+ // The original delivery still belongs to this process/conversation,
+ // but its parser or routing was rebuilt. Preserve completion without
+ // applying it to whichever turn the replacement happened to load.
+ stopRetained = handlers.onAdmissionStop?.(live()!, true) ?? false
+ return stopRetained ? { status: 200, reply: { pending: true } }
+ : { status: 202, reply: { pending: false, retry: true, detail: 'Waiting for core ownership of the unmatched Stop.' } }
+ }
+ if (!stopInvocationClaimed) {
+ // Claim after the final authority fence, before optional async drains.
+ stopInvocationClaimed = true
+ handlers.onTurnStop?.({ sessionId: owner.sessionId, status: stop.status,
+ transcriptPath: stop.transcriptPath, ...(firedAt ? { firedAt } : {}) })
+ return { status: 200, reply: { ok: true } }
+ }
+ return { status: 200, reply: { ok: true, duplicate: true } }
+ }
+ const prepare = (): AdmissionDecision<string | undefined> | null => {
+ if (!current()) return { kind: 'reject', reason: 'stale_hook' }
+ if (handlers.hookAdmissionBlocked?.(processAgent.agentId)) return { kind: 'hold', reason: 'Waiting for Stop to settle before admitting the hook.' }
+ const row = live()!
+ if (!runtimeHints.some(hint => row.runtimes.some(runtime => runtime.backend === hint.backend && runtime.paneId === hint.paneId))) {
+ return { kind: 'hold', reason: 'Waiting for the original hook pane to belong to its engine process.' }
+ }
+ inspectionIdentity = paneReadIdentity(row)
+ prepared = { ...body, processIdentity: row.processIdentity ? { ...row.processIdentity } : undefined,
+ runtimes: row.runtimes.map(runtime => ({ ...runtime })), primaryRuntimeKey: row.primaryRuntimeKey,
+ transcriptPath: knownTranscriptFor(body, row) }
+ const admission = admitHook(engine, prepared)
+ if (!admission.accepted) return admission.reason === 'engine_hook_failed'
+ ? { kind: 'hold', reason: 'Waiting for complete native hook evidence.' } : { kind: 'reject', reason: admission.reason }
+ return null
+ }
+ const commit = (hermesHome: string | undefined): AdmissionDecision<string | undefined> => {
+ if (!current() || paneReadIdentity(live()) !== inspectionIdentity) return { kind: 'hold', reason: 'Waiting for fresh evidence after the binding changed.' }
+ if (handlers.hookAdmissionBlocked?.(processAgent.agentId)) return { kind: 'hold', reason: 'Waiting for Stop to settle before admitting the hook.' }
+ const prior = live()
+ const before = prior && { sessionId: prior.sessionId, transcriptPath: prior.transcriptPath,
+ held: !!(prior.identityHold || prior.interpretationHold) }
+ committed = registry.register(hermesHome ? { ...prepared, hermesHome } : prepared, { verifiedNativeSource: true })
+ if (stopCurrent && !stopCurrent()) stopInvocationClaimed = true
+ if (committed && carriesStop && !stopRetained && !stopInvocationClaimed) {
+ stopUnmatched ||= deferred || before?.sessionId !== committed.entry.sessionId
+ || before?.transcriptPath !== committed.entry.transcriptPath || before?.held === true
+ if (!handlers.onAdmissionStop && stopUnmatched) return { kind: 'hold', reason: 'Waiting for core ownership of the unmatched Stop.' }
+ stopRetained = handlers.onAdmissionStop?.(committed.entry, stopUnmatched) ?? false
+ if (stopUnmatched && !stopRetained) return { kind: 'hold', reason: 'Waiting for core ownership of the unmatched Stop.' }
+ }
+ if (committed) committedIdentity = paneReadIdentity(committed.entry)
+ return committed ? { kind: 'accept', value: hermesHome } : { kind: 'reject', reason: 'invalid_session_registration' }
}
- console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=${result.entry.engine} · isNew=${result.isNew}`)
- handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound, orphaned: result.orphaned, hookEvent: body.hookEvent })
- answer(200, { ok: true })
+ const notify = () => {
+ const result = committed!
+ clearHold()
+ console.log(`[hooks] ${sid(result.entry.sessionId)} ${body.hookEvent ?? 'session-start'} · engine=${result.entry.engine} · isNew=${result.isNew}`
+ + (engine === 'hermes' ? ` · after a source check${result.entry.hermesHome ? ` · home=${result.entry.hermesHome}` : ''}` : ''))
+ const optional = (call: () => void | Promise<void>) => {
+ try { void Promise.resolve(call()).catch(error => console.warn('[hooks] committed admission notification failed', error)) }
+ catch (error) { console.warn('[hooks] committed admission notification failed', error) }
+ }
+ // Native prompt credit follows the durable bind, never an attempted one.
+ if (body.hookEvent === 'UserPromptSubmit') {
+ optional(() => handlers.onPromptSubmitted?.(result.entry.agentId, body.prompt ?? ''))
+ if (admissionOrder.firedAt && body.sessionId) optional(() => handlers.onPromptHook?.(body.sessionId!, admissionOrder.firedAt!))
+ }
+ optional(() => handlers.onRegistered(result.entry, { isNew: result.isNew, evicted: result.evicted, rebound: result.rebound,
+ orphaned: result.orphaned, hookEvent: body.hookEvent }))
+ }
+ const enqueue = () => {
+ saveReceipt(history.records, deliveryId, { fingerprint, status: 200, reply: { pending: true }, pending: true, bytes: retainedBytes,
+ ...(carriesStop ? { linkedStop } : {}) })
+ const queued = admissions.submit(processAgent.agentId, deliveryId, {
+ conversationId: body.sessionId,
+ order: { ...admissionOrder, scope: admissionProcessScope(processAgent) ?? processAgent.agentId },
+ binding: () => { const row = live(); return row && { id: row.sessionId, at: row.boundAt } },
+ current,
+ inspect: async () => prepare() ?? (engine === 'hermes' && body.sessionId
+ ? await inspectHermesKind(body.sessionId, live()?.hermesHome ?? undefined) : { kind: 'accept', value: undefined }),
+ commit,
+ held,
+ reject: reason => {
+ clearHold()
+ console.log(`[hooks] ${sid(body.sessionId ?? '?')} ${body.hookEvent ?? 'session-start'} ignored · ${reason}`)
+ if (reason === 'invalid_session_registration') completedReply(400, { error: 'invalid session registration' })
+ else completedReply(200, { ignored: true, reason })
+ },
+ accept: () => { completedReply(200, { ok: true }); notify() },
+ })
+ if (queued) {
+ // Synchronous native admission settles in this turn's microtasks. A
+ // queued predecessor or asynchronous source gets an owned pending reply.
+ if (engine === 'hermes') answer(200, { pending: true })
+ else setImmediate(() => { if (!settled) deferred = true; answer(200, { pending: true }) })
+ } else {
+ saveReceipt(history.records, deliveryId)
+ const detail = 'Too many unverified hooks are pending; this hook was not queued. Retry after recovery.'
+ console.log(`[hooks] ${sid(body.sessionId ?? '?')} held · ${detail}`)
+ answer(429, { pending: false, error: 'HOOK_ADMISSION_BUSY', detail })
+ }
+ }
+ enqueue()
return
}
@@ -659,12 +795,28 @@ export function startHookServer(
if (!validHookBody(parsed)) { json(400, { error: 'invalid hook body' }); return }
body = parsed
} catch { json(400, { error: 'bad json' }); return }
- if (!await verifiedBoundMutation(body, handlers)) { json(403, { error: 'UNBOUND_HOOK' }); return }
+ const delivery = req.headers['x-harness-hook-delivery-id']
+ if (typeof delivery === 'string') {
+ const pending = resolvingStops.get(delivery)?.stop ?? [...admissionReceipts.values()]
+ .map(history => history.records.get(delivery)?.linkedStop).find(Boolean)
+ const acknowledgement = await pending?.(body, hookFiredAt(req))
+ if (acknowledgement) { json(acknowledgement.status, acknowledgement.reply); return }
+ if (/^[a-zA-Z0-9_-]{16,96}$/.test(delivery) && (body.engine === 'cursor' || body.engine === 'commandcode')) {
+ // These native clients register this same delivery before Stop. A
+ // refused queue or a restarted core has no completion authority yet.
+ json(202, { pending: false, retry: true, detail: 'Waiting for the linked Stop registration to be admitted.' }); return
+ }
+ }
+ const owner = await verifiedBoundMutation(body, handlers)
+ if (!owner) { json(403, { error: 'UNBOUND_HOOK' }); return }
if (body.sessionId) {
+ const identity = paneReadIdentity(owner)
console.log(`[hooks] ${sid(body.sessionId)} turn-stop${body.status ? ` · status=${body.status}` : ''}`)
const fired = hookFiredAt(req)
const stop = { sessionId: body.sessionId, status: body.status, transcriptPath: body.transcriptPath, ...(fired ? { firedAt: fired } : {}) }
- if (handlers.stopHookDelayMs) setTimeout(() => handlers.onTurnStop?.(stop), handlers.stopHookDelayMs)
+ if (handlers.stopHookDelayMs) setTimeout(() => {
+ if (paneReadIdentity(registry.byAgent(owner.agentId)) === identity) handlers.onTurnStop?.(stop)
+ }, handlers.stopHookDelayMs)
else handlers.onTurnStop?.(stop)
}
json(200, { ok: true })
diff --git a/cli/src/lib/__fixtures__/registry-admission.golden.json b/cli/src/lib/__fixtures__/registry-admission.golden.json
new file mode 100644
index 000000000..6779c8303
--- /dev/null
+++ b/cli/src/lib/__fixtures__/registry-admission.golden.json
@@ -0,0 +1,354 @@
+{
+ "linux:first": {
+ "entry": {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null
+ },
+ "linux:same-preserves-folder": {
+ "entry": {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ "isNew": false,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null
+ },
+ "linux:rotation": {
+ "entry": {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ "isNew": true,
+ "evicted": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "rebound": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "orphaned": null
+ },
+ "linux:terminal-promotion": {
+ "entry": {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": true
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null
+ },
+ "linux:move-active": {
+ "entry": {
+ "agent": "codex",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null
+ },
+ "linux:after-active-move": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ {
+ "agent": "codex",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "",
+ "transcript": null,
+ "cwd": "<root>",
+ "source": null,
+ "active": true,
+ "terminalHost": true
+ }
+ ],
+ "linux:move-dormant": {
+ "entry": {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": true
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": {
+ "agentId": "<codex>",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ }
+ },
+ "linux:delegated-rejected": null,
+ "linux:final-live": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": true
+ }
+ ],
+ "linux:final-saved": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": true
+ }
+ ],
+ "darwin:first": {
+ "entry": {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null
+ },
+ "darwin:same-preserves-folder": {
+ "entry": {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ "isNew": false,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null
+ },
+ "darwin:rotation": {
+ "entry": {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ "isNew": true,
+ "evicted": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "rebound": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "orphaned": null
+ },
+ "darwin:terminal-promotion": {
+ "entry": {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": true
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null
+ },
+ "darwin:move-active": {
+ "entry": {
+ "agent": "codex",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null
+ },
+ "darwin:after-active-move": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ {
+ "agent": "codex",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "",
+ "transcript": null,
+ "cwd": "<root>",
+ "source": null,
+ "active": true,
+ "terminalHost": true
+ }
+ ],
+ "darwin:move-dormant": {
+ "entry": {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": true
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": {
+ "agentId": "<codex>",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ }
+ },
+ "darwin:delegated-rejected": null,
+ "darwin:final-live": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": true
+ }
+ ],
+ "darwin:final-saved": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": false
+ },
+ {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "source": "fixture",
+ "active": true,
+ "terminalHost": true
+ }
+ ]
+}
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index 529bcebdc..78e23a854 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -217,7 +217,7 @@ export async function agentFrame(
closePlan: s.closePlan ? { state: s.closePlan.state, ...(s.closePlan.detail ? { detail: s.closePlan.detail } : {}) } : null,
closeSupported: true,
launch: s.launch ?? { state: 'ready' },
- ...((s.identityHold || s.interpretationHold) ? { identityHold: s.identityHold || s.interpretationHold } : {}),
+ ...((s.identityHold || s.interpretationHold || s.admissionHold) ? { identityHold: s.identityHold || s.interpretationHold || s.admissionHold } : {}),
createdAt: new Date(s.registeredAt).toISOString(),
updatedAt: new Date(updatedAt).toISOString(),
// Null, never omitted, for the reason the module doc gives: a push without the key would erase
diff --git a/cli/src/lib/registry.admission.spec.ts b/cli/src/lib/registry.admission.spec.ts
new file mode 100644
index 000000000..8ef16fa39
--- /dev/null
+++ b/cli/src/lib/registry.admission.spec.ts
@@ -0,0 +1,841 @@
+import type { Server } from 'node:http'
+import type { HookServerHandlers } from '../hookServer.js'
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+const fault = vi.hoisted(() => ({ file: '', rename: false, directorySync: false, renamed: false,
+ afterProof: undefined as (() => void) | undefined, beforeVerify: undefined as (() => void) | undefined }))
+vi.mock('fs', async original => {
+ const actual = await original<typeof import('node:fs')>()
+ return { ...actual, renameSync: (...args: Parameters<typeof actual.renameSync>) => {
+ if (fault.rename && String(args[1]) === fault.file) throw new Error('fixture registry write failure')
+ const result = actual.renameSync(...args)
+ if (String(args[1]) === fault.file) fault.renamed = true
+ return result
+ }, fsyncSync: (fd: number) => {
+ if (fault.directorySync && fault.renamed && actual.fstatSync(fd).isDirectory()) throw new Error('fixture directory sync failure')
+ return actual.fsyncSync(fd)
+ } }
+})
+vi.mock('./bootId.js', async original => ({ ...await original<object>(), currentBootId: () => 'fixture-boot', bootChanged: () => false }))
+vi.mock('./processLiveness.js', async original => ({ ...await original<object>(),
+ processLockIdentity: () => ({ startMarker: 'fixture-start', generationMarker: 'fixture-generation' }), lockOwnerAlive: () => true,
+}))
+function observeNativeProof(): void { vi.doMock('../engines/transcriptBindings.js', async original => {
+ const actual = await original<typeof import('../engines/transcriptBindings.js')>()
+ return { ...actual, transcriptEvidence: (...args: Parameters<typeof actual.transcriptEvidence>) => {
+ const proof = actual.transcriptEvidence(...args)
+ fault.afterProof?.()
+ return { ...proof, verify: (...selected: Parameters<typeof proof.verify>) => { fault.beforeVerify?.(); proof.verify(...selected) } }
+ } }
+}) }
+const A = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa', B = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
+let server: Server | undefined
+let root: string, home: string, file: string, transcript: string
+let registry: typeof import('./registry.js')['registry'], target: string, source: string
+const header = (id = A, delegated = false) => JSON.stringify({ type: 'session_meta', payload: {
+ id, cwd: root, source: delegated ? { subagent: { thread_spawn: { parent_thread_id: B, depth: 1 } } } : 'cli',
+} }) + '\n'
+const input = (id = A, path = transcript, pane = '%1') => ({ engine: 'codex' as const, sessionId: id,
+ transcriptPath: path, tmuxPane: pane, cwd: root,
+ processIdentity: { pid: pane === '%1' ? 5101 : 5102, startMarker: 'fixture-start', executable: '<codex>' } })
+const snapshot = () => ({ live: JSON.stringify(registry.list()), disk: readFileSync(file, 'utf8') })
+const unchanged = (before: ReturnType<typeof snapshot>) => {
+ expect(JSON.stringify(registry.list())).toBe(before.live)
+ expect(readFileSync(file, 'utf8')).toBe(before.disk)
+}
+beforeEach(async () => {
+ fault.rename = false; fault.directorySync = false; fault.renamed = false; fault.afterProof = undefined; fault.beforeVerify = undefined
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'registry-admission-')))
+ home = join(root, 'codex'); file = join(root, 'data', 'registry.json'); fault.file = file
+ mkdirSync(join(home, 'sessions'), { recursive: true }); mkdirSync(join(root, 'data'))
+ for (const [key, value] of Object.entries({ HOME: root, ADAPTER_DATA_DIR: join(root, 'data'),
+ ADAPTER_RUNTIME_DIR: join(root, 'runtime'), CODEX_HOME: home, CLAUDE_CONFIG_DIR: join(root, 'claude'),
+ COMMANDCODE_HOME: join(root, 'commandcode'), GROK_HOME: join(root, 'grok'),
+ AGY_HOME: join(root, 'agy'), COPILOT_HOME: join(root, 'copilot') })) vi.stubEnv(key, value)
+ writeFileSync(join(root, 'data', 'engine-homes.json'), '{}')
+ transcript = join(home, 'sessions', `rollout-${A}.jsonl`); writeFileSync(transcript, header())
+ vi.resetModules(); observeNativeProof(); ({ registry } = await import('./registry.js'))
+ target = registry.openProcessAgent({ engine: 'terminal', tmuxPane: '%1', cwd: root,
+ processIdentity: { pid: 4101, startMarker: 'fixture-start', executable: '<shell>' } })!.entry.agentId
+ source = registry.openProcessAgent({ engine: 'codex', tmuxPane: '%2', cwd: root, processIdentity: input(A, transcript, '%2').processIdentity })!.entry.agentId
+})
+afterEach(async () => {
+ if (server) await new Promise<void>(resolve => server!.close(() => resolve()))
+ server = undefined
+ fault.rename = false; fault.directorySync = false; fault.renamed = false; fault.afterProof = undefined; fault.beforeVerify = undefined
+ vi.restoreAllMocks(); vi.doUnmock('../engines/transcriptBindings.js'); vi.unstubAllEnvs(); vi.resetModules(); rmSync(root, { recursive: true, force: true })
+})
+
+it.each(['', '{', '{"type":"session_meta"}\n'])('holds incomplete native evidence without promoting the terminal: %s', text => {
+ writeFileSync(transcript, text)
+ const before = snapshot()
+ expect(() => registry.register(input())).toThrow()
+ unchanged(before)
+ expect(registry.byRuntimeTerminal({ backend: 'tmux', paneId: '%1' })?.agentId).toBe(target)
+})
+it.each(['different-id', 'delegated'])('refuses confirmed %s without changing the terminal or its durable row', kind => {
+ writeFileSync(transcript, header(kind === 'different-id' ? B : A, kind === 'delegated'))
+ const before = snapshot()
+ expect(registry.register(input())).toBeNull()
+ unchanged(before)
+})
+it.each(['terminal', 'active-owner', 'dormant-owner'])('keeps every live and durable owner when the %s commit fails', kind => {
+ if (kind !== 'terminal') {
+ expect(registry.register(input(A, transcript, '%2'))).not.toBeNull()
+ if (kind === 'dormant-owner') registry.setActive(source, false)
+ }
+ const before = snapshot(); fault.rename = true
+ expect(() => registry.register(input())).toThrow('fixture registry write failure')
+ unchanged(before)
+ expect(registry.byAgent(target)?.engine).toBe('terminal')
+ if (kind !== 'terminal') expect(registry.bySession(A)?.agentId).toBe(source)
+})
+it('rechecks the native header under the write lock before publishing any registration', () => {
+ const before = snapshot()
+ let checked = false
+ fault.beforeVerify = () => {
+ checked = true
+ expect(JSON.parse(readFileSync(join(file + '.lock', 'owner.json'), 'utf8')).pid).toBe(process.pid)
+ writeFileSync(transcript, header(B))
+ }
+ expect(() => registry.register(input())).toThrow('header changed')
+ expect(checked).toBe(true)
+ unchanged(before)
+})
+it('never overwrites a different durable admission that arrived during inspection', () => {
+ const peer = new (registry.constructor as new () => typeof registry)(); peer.load()
+ const other = join(home, 'sessions', `rollout-${B}.jsonl`); writeFileSync(other, header(B))
+ const before = JSON.stringify(registry.list())
+ let committed = ''
+ fault.afterProof = () => {
+ fault.afterProof = undefined
+ expect(peer.register(input(B, other))).not.toBeNull()
+ committed = readFileSync(file, 'utf8')
+ }
+ expect(() => registry.register(input())).toThrow('saved binding changed')
+ expect(JSON.stringify(registry.list())).toBe(before)
+ expect(readFileSync(file, 'utf8')).toBe(committed)
+ expect(peer.bySession(B)?.agentId).toBe(target)
+})
+it('returns the committed live row and publishes only after the registry write', () => {
+ const former = registry.byAgent(target)!, before = structuredClone(former)
+ const entered: string[] = []
+ registry.onEnter = engine => {
+ const saved = JSON.parse(readFileSync(file, 'utf8')) as Array<{ agentId: string; sessionId: string }>
+ expect(saved.find(row => row.agentId === target)?.sessionId).toBe(A)
+ entered.push(engine)
+ }
+ const result = registry.register(input())!
+ expect(result.entry).not.toBe(former)
+ expect(former).toEqual(before)
+ expect(result.entry).toBe(registry.byAgent(target))
+ expect(result.entry.sessionId).toBe(A)
+ expect(registry.bySession(A)).toBe(result.entry)
+ expect(entered).toContain('codex')
+})
+
+
+it('publishes all displaced owners before optional entry notification and contains its failure', () => {
+ expect(registry.register(input(A, transcript, '%2'))).not.toBeNull()
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const observations: string[] = []
+ registry.onEnter = engine => {
+ expect(registry.bySession(A)?.agentId).toBe(target)
+ expect(registry.byAgent(source)?.sessionId).toBe('')
+ expect(registry.byAgent(target)?.engine).toBe('codex')
+ observations.push(engine)
+ throw new Error('optional engine startup unavailable')
+ }
+ const result = registry.register(input())!
+ expect(result.entry).toBe(registry.byAgent(target))
+ expect(observations.length).toBe(2)
+ expect(warning).toHaveBeenCalledTimes(2)
+ const rows = JSON.parse(readFileSync(file, 'utf8')) as Array<{ agentId: string; sessionId: string }>
+ expect(rows.find(row => row.agentId === target)?.sessionId).toBe(A)
+ expect(rows.find(row => row.agentId === source)?.sessionId).toBe('')
+})
+
+
+it.each(['terminal', 'active-owner', 'dormant-owner'])('reconciles its own post-rename uncertainty for %s before publishing', kind => {
+ if (kind !== 'terminal') {
+ expect(registry.register(input(A, transcript, '%2'))).not.toBeNull()
+ if (kind === 'dormant-owner') registry.setActive(source, false)
+ }
+ const before = JSON.stringify(registry.list())
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(input())).toThrow('fixture directory sync failure')
+ expect(JSON.stringify(registry.list())).toBe(before)
+ const written = readFileSync(file, 'utf8')
+ expect(JSON.parse(written).find((row: { agentId: string }) => row.agentId === target).sessionId).toBe(A)
+ fault.directorySync = false
+ const result = registry.register(input())!
+ expect(result.entry.sessionId).toBe(A)
+ expect(result.entry).toBe(registry.byAgent(target))
+ expect(readFileSync(file, 'utf8')).toBe(written)
+ if (kind === 'active-owner') expect(registry.byAgent(source)?.sessionId).toBe('')
+ if (kind === 'dormant-owner') expect(registry.byAgent(source)).toBeUndefined()
+})
+
+it('does not consume post-rename uncertainty as success after a local removal changes ownership', () => {
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(input())).toThrow('fixture directory sync failure')
+ fault.directorySync = false
+ const written = readFileSync(file, 'utf8')
+ registry.removeAgent(target)
+ expect(registry.register(input())).toBeNull()
+ expect(registry.byAgent(target)).toBeUndefined()
+ const saved = JSON.parse(readFileSync(file, 'utf8')).find((row: { agentId: string }) => row.agentId === target)
+ expect(saved).toBeUndefined()
+ expect(readFileSync(file, 'utf8')).not.toBe(written)
+})
+
+it.each(['rename', 'changed-proof', 'peer-commit'])('keeps a resumed binding intact when mismatch refusal meets %s', mode => {
+ expect(registry.register(input())).not.toBeNull()
+ const row = registry.byAgent(target)!
+ row.resumeOnly = true; row.lastHookAt = 0; row.launch = { state: 'starting' }; registry.flush()
+ const other = join(home, 'sessions', `rollout-${B}.jsonl`); writeFileSync(other, header(B))
+ const before = snapshot()
+ if (mode === 'rename') fault.rename = true
+ if (mode === 'changed-proof') fault.beforeVerify = () => writeFileSync(other, header(A))
+ let peerDisk: string | undefined
+ if (mode === 'peer-commit') {
+ const peer = new (registry.constructor as new () => typeof registry)(); peer.load()
+ fault.afterProof = () => { fault.afterProof = undefined; peer.setLaunch(target, { state: 'ready' }); peerDisk = readFileSync(file, 'utf8') }
+ }
+ expect(() => registry.register(input(B, other))).toThrow()
+ expect(JSON.stringify(registry.list())).toBe(before.live)
+ expect(readFileSync(file, 'utf8')).toBe(peerDisk ?? before.disk)
+})
+
+it('cannot flush an unrelated stale discovery claim over a newer durable peer', async () => {
+ const peer = new (registry.constructor as new () => typeof registry)(); peer.load()
+ let peerDisk = ''
+ await registry.transaction(async () => {
+ registry.updateRuntimes(source, [{ backend: 'tmux', paneId: '%3' }], 'tmux\u0000%3')
+ const third = peer.openProcessAgent({ engine: 'claude', tmuxPane: '%3', cwd: root,
+ processIdentity: { pid: 9103, startMarker: 'fixture-peer', executable: '<claude>' } })!
+ peerDisk = readFileSync(file, 'utf8')
+ expect(third.entry.agentId).not.toBe(source)
+ const live = JSON.stringify(registry.list())
+ expect(() => registry.register(input())).toThrow()
+ expect(JSON.stringify(registry.list())).toBe(live)
+ expect(readFileSync(file, 'utf8')).toBe(peerDisk)
+ // Finish the observation without the stale route; it never earns a write through registration.
+ registry.updateRuntimes(source, [{ backend: 'tmux', paneId: '%2' }], 'tmux\u0000%2')
+ })
+ expect(JSON.parse(readFileSync(file, 'utf8')).some((row: { tmuxPane: string; agentId: string }) => row.tmuxPane === '%3' && row.agentId !== source)).toBe(true)
+})
+
+
+it('rolls back only its unpublished image before a different local write and then retries the held admission', () => {
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(input())).toThrow('fixture directory sync failure')
+ fault.directorySync = false
+ registry.setCwd(source, '/fixture/next-folder')
+ expect(registry.byAgent(target)?.engine).toBe('terminal')
+ expect(registry.byAgent(source)?.cwd).toBe('/fixture/next-folder')
+ const result = registry.register(input())!
+ expect(result.entry.sessionId).toBe(A)
+ expect(registry.byAgent(source)?.cwd).toBe('/fixture/next-folder')
+ expect(JSON.parse(readFileSync(file, 'utf8')).find((row: { agentId: string }) => row.agentId === source).cwd).toBe('/fixture/next-folder')
+})
+
+it('contains another directory failure while reversing an unpublished binding for removal', () => {
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(input())).toThrow('fixture directory sync failure')
+ registry.removeAgent(target)
+ fault.directorySync = false
+ registry.flush()
+ expect(registry.register(input())).toBeNull()
+ const saved = JSON.parse(readFileSync(file, 'utf8')).find((row: { agentId: string }) => row.agentId === target)
+ expect(saved).toBeUndefined()
+})
+
+it('reconciles a peer-changed ownership group and allows unrelated strict writes and fresh admission', () => {
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(input())).toThrow('fixture directory sync failure')
+ fault.directorySync = false
+ const peerRows = JSON.parse(readFileSync(file, 'utf8'))
+ peerRows.find((row: { agentId: string }) => row.agentId === target).cwd = '/fixture/peer-folder'
+ writeFileSync(file, JSON.stringify(peerRows, null, 2))
+ const peerDisk = readFileSync(file, 'utf8')
+ expect(() => registry.register(input())).toThrow('different durable owner')
+ expect(readFileSync(file, 'utf8')).toBe(peerDisk)
+ expect(registry.byAgent(target)?.engine).toBe('codex')
+ expect(registry.byAgent(target)?.identityHold).toContain('concurrent binding')
+ const other = join(home, 'sessions', `rollout-${B}.jsonl`); writeFileSync(other, header(B))
+ expect(registry.register(input(B, other, '%2'))?.entry.sessionId).toBe(B)
+ expect(registry.byAgent(target)?.cwd).toBe('/fixture/peer-folder')
+ expect(registry.register(input())?.entry.sessionId).toBe(A)
+ expect(registry.bySession(B)?.agentId).toBe(source)
+})
+
+it('confirms an unpublished group while retaining an unrelated peer write', () => {
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(input())).toThrow('fixture directory sync failure')
+ fault.directorySync = false
+ const peerRows = JSON.parse(readFileSync(file, 'utf8'))
+ peerRows.find((row: { agentId: string }) => row.agentId === source).cwd = '/fixture/peer-folder'
+ writeFileSync(file, JSON.stringify(peerRows, null, 2))
+ expect(registry.register(input())?.entry.sessionId).toBe(A)
+ expect(registry.byAgent(source)?.cwd).toBe('/fixture/peer-folder')
+ expect(JSON.parse(readFileSync(file, 'utf8')).find((row: { agentId: string }) => row.agentId === source).cwd).toBe('/fixture/peer-folder')
+})
+
+it('keeps its unconfirmed image independent of mutable input objects', () => {
+ const pending = input()
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(pending)).toThrow('fixture directory sync failure')
+ const written = readFileSync(file, 'utf8')
+ pending.processIdentity.startMarker = 'mutated-after-write'
+ fault.directorySync = false
+ expect(() => registry.register(input())).not.toThrow()
+ expect(registry.byAgent(target)?.sessionId).toBe(A)
+ expect(readFileSync(file, 'utf8')).toBe(written)
+})
+
+it('lets a late hook recover a launch timeout while its live process remains the owner', () => {
+ registry.setLaunch(source, { state: 'failed', error: 'START_TIMEOUT' })
+ expect(registry.register(input(A, transcript, '%2'))?.entry.sessionId).toBe(A)
+})
+
+
+it('does not acknowledge a Close plan discarded by peer ownership recovery', () => {
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(input())).toThrow('fixture directory sync failure')
+ fault.directorySync = false
+ const peerRows = JSON.parse(readFileSync(file, 'utf8'))
+ peerRows.find((row: { agentId: string }) => row.agentId === target).cwd = '/fixture/peer-folder'
+ writeFileSync(file, JSON.stringify(peerRows, null, 2))
+ const disk = readFileSync(file, 'utf8')
+ const plan = { id: 'cccccccc-3333-4333-8333-cccccccccccc', state: 'waiting' as const, identity: 'fixture-binding', requestedAt: Date.now() }
+ expect(() => registry.setClosePlan(target, plan)).toThrow('different durable owner')
+ expect(registry.byAgent(target)?.closePlan).toBeUndefined()
+ expect(readFileSync(file, 'utf8')).toBe(disk)
+ expect(registry.setClosePlan(source, plan)?.closePlan).toEqual(plan)
+})
+
+it('does not authorize an external dispatch discarded by recovery of a staged batch', () => {
+ const external = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%3' }],
+ externalResume: { token: 'cccccccc-3333-4333-8333-cccccccccccc', request: { engine: 'codex', sessionId: B }, takeOver: null, phase: 'waiting' } })!
+ registry.setExternalResume(external.agentId, { ...external.externalResume!, phase: 'admitted', session: {
+ engine: 'codex', sessionId: B, cwd: root, origin: 'terminal', title: 'fixture', mtime: 1, transcriptPath: null,
+ } })
+ registry.byAgent(external.agentId)!.cwd = '/fixture/staged-folder'
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(input())).toThrow('fixture directory sync failure')
+ fault.directorySync = false
+ const peerRows = JSON.parse(readFileSync(file, 'utf8'))
+ peerRows.find((row: { agentId: string }) => row.agentId === external.agentId).cwd = '/fixture/peer-folder'
+ writeFileSync(file, JSON.stringify(peerRows, null, 2))
+ const disk = readFileSync(file, 'utf8')
+ expect(() => registry.beginExternalDispatch(external.agentId)).toThrow('different durable owner')
+ expect(registry.byAgent(external.agentId)?.externalResume?.dispatched).toBeUndefined()
+ expect(registry.byAgent(external.agentId)?.launch?.state).toBe('held')
+ expect(registry.byAgent(external.agentId)?.cwd).toBe('/fixture/peer-folder')
+ expect(readFileSync(file, 'utf8')).toBe(disk)
+})
+
+
+it('reconciles a whole alias-only ownership transfer after an unconfirmed write', () => {
+ const alias = 'shared-alias'
+ const previous = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%3' }],
+ externalResume: { token: 'cccccccc-3333-4333-8333-cccccccccccc', request: { engine: 'codex', sessionId: B }, takeOver: null, phase: 'waiting' } })!
+ registry.setExternalResume(previous.agentId, { ...previous.externalResume!, phase: 'admitted', session: {
+ engine: 'codex', sessionId: B, aliases: [alias], cwd: root, origin: 'terminal', title: 'fixture', mtime: 1, transcriptPath: null,
+ } })
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(input())).toThrow('fixture directory sync failure')
+ fault.directorySync = false
+ const peerRows = JSON.parse(readFileSync(file, 'utf8'))
+ peerRows.find((row: { agentId: string }) => row.agentId === previous.agentId).externalResume.session.aliases = []
+ peerRows.find((row: { agentId: string }) => row.agentId === target).externalResume = {
+ token: 'dddddddd-4444-4444-8444-dddddddddddd', request: { engine: 'codex', sessionId: A }, takeOver: null, phase: 'admitted',
+ session: { engine: 'codex', sessionId: A, aliases: [alias], cwd: root, origin: 'terminal', title: 'fixture', mtime: 1, transcriptPath: transcript },
+ }
+ writeFileSync(file, JSON.stringify(peerRows, null, 2))
+ const disk = readFileSync(file, 'utf8')
+ expect(() => registry.register(input())).toThrow('different durable owner')
+ expect(readFileSync(file, 'utf8')).toBe(disk)
+ expect(registry.externalConflict([alias])?.agentId).toBe(target)
+ expect(registry.byAgent(previous.agentId)?.externalResume?.session?.aliases).toEqual([])
+ expect(registry.register(input())?.entry.sessionId).toBe(A)
+})
+
+
+
+async function httpFixture(blocked: (agentId: string) => boolean = () => false, admissionReceiptCapacity = 65_536,
+ overrides: Partial<HookServerHandlers> = {}, admissionBytesCapacity?: number) {
+ const { startHookServer } = await import('../hookServer.js')
+ const { readHookCredential } = await import('./hookAuth.js')
+ const prompts: string[] = [], registered = vi.fn(), reasons: Array<string | undefined> = []
+ const started = await startHookServer(0, { onRegistered: registered, onSessionEnd: () => {},
+ hookAdmissionBlocked: blocked,
+ onPromptSubmitted: (_id, text) => prompts.push(text),
+ onAdmissionHeld: (_id, reason) => reasons.push(reason),
+ ...overrides,
+ }, { admissionReceiptCapacity, admissionBytesCapacity })
+ server = started.server
+ const post = async (override: Record<string, unknown> = {}, order: { id?: string; firedAt?: number } = {}, path = 'session-start') => {
+ const response = await fetch(`http://127.0.0.1:${started.port}/api/hook/${path}`, {
+ method: 'POST', headers: { 'content-type': 'application/json',
+ 'x-harness-hook-token': readHookCredential(join(root, 'data'))!,
+ ...(order.id ? { 'x-harness-hook-delivery-id': order.id } : {}),
+ ...(order.firedAt ? { 'x-harness-hook-fired-at': String(order.firedAt) } : {}),
+ },
+ body: JSON.stringify({ engine: 'codex', sessionId: A, transcriptPath: transcript,
+ tmuxPane: '%2', cwd: root, hookEvent: 'UserPromptSubmit', prompt: 'fixture prompt', ...override }),
+ })
+ return { status: response.status, body: await response.json() }
+ }
+ return { post, prompts, registered, reasons }
+}
+
+it('keeps each prompt through an HTTP registration write failure and credits it only after recovery', async () => {
+ const f = await httpFixture()
+ const before = readFileSync(file, 'utf8')
+ fault.rename = true
+ expect(await f.post({ prompt: 'first prompt' })).toEqual({ status: 200, body: { pending: true } })
+ expect(await f.post({ prompt: 'second prompt' })).toEqual({ status: 200, body: { pending: true } })
+ expect(f.prompts).toEqual([])
+ expect(f.registered).not.toHaveBeenCalled()
+ expect(registry.byAgent(source)?.sessionId).toBe('')
+ expect(readFileSync(file, 'utf8')).toBe(before)
+ expect(f.reasons.some(reason => reason?.includes('registry write failure'))).toBe(true)
+ fault.rename = false
+ await vi.waitFor(() => expect(f.prompts).toEqual(['first prompt', 'second prompt']), { timeout: 4_000 })
+ expect(f.registered).toHaveBeenCalledTimes(2)
+ expect(registry.bySession(A)?.agentId).toBe(source)
+})
+
+it('holds a missing announced transcript on the actual HTTP path and retries complete evidence', async () => {
+ const f = await httpFixture()
+ rmSync(transcript)
+ expect(await f.post()).toEqual({ status: 200, body: { pending: true } })
+ expect(f.prompts).toEqual([])
+ writeFileSync(transcript, header())
+ await vi.waitFor(() => expect(f.prompts).toEqual(['fixture prompt']), { timeout: 4_000 })
+ expect(registry.bySession(A)?.agentId).toBe(source)
+})
+
+it.each(['commandcode', 'grok', 'agy', 'copilot'] as const)('admits the %s SessionStart before its deterministic transcript directories exist', async engine => {
+ const agent = registry.openProcessAgent({ engine, tmuxPane: '%3', cwd: root,
+ processIdentity: { pid: 5103, startMarker: 'fixture-start', executable: `<${engine}>` } })!.entry
+ const f = await httpFixture()
+ expect(await f.post({ engine, tmuxPane: '%3', transcriptPath: undefined, hookEvent: 'SessionStart', prompt: undefined }))
+ .toEqual({ status: 200, body: { ok: true } })
+ expect(registry.byAgent(agent.agentId)?.sessionId).toBe(A)
+ expect(registry.byAgent(agent.agentId)?.transcriptPath).toContain(join(root, engine))
+ expect(f.registered).toHaveBeenCalledOnce()
+ expect(f.prompts).toEqual([])
+})
+
+it('rechecks an unwritten derived locator proof under the lock and never grants it to a reported path', () => {
+ const agent = registry.openProcessAgent({ engine: 'commandcode', tmuxPane: '%3', cwd: root,
+ processIdentity: { pid: 5103, startMarker: 'fixture-start', executable: '<commandcode>' } })!.entry
+ const body = { engine: 'commandcode' as const, sessionId: A, tmuxPane: '%3', cwd: root, processIdentity: agent.processIdentity! }
+ const before = snapshot()
+ expect(() => registry.register({ ...body, transcriptPath: join(root, 'commandcode', 'projects', 'announced.jsonl') })).toThrow('not yet available')
+ unchanged(before)
+ fault.beforeVerify = () => {
+ expect(JSON.parse(readFileSync(join(file + '.lock', 'owner.json'), 'utf8')).pid).toBe(process.pid)
+ mkdirSync(join(root, 'commandcode'))
+ }
+ expect(() => registry.register(body)).toThrow('changed')
+ unchanged(before)
+ fault.beforeVerify = undefined
+ expect(registry.register(body)?.entry.sessionId).toBe(A)
+})
+
+it('the actual Stop job blocks hook admission before its first asynchronous step settles', async () => {
+ const { createStopAgentService } = await import('./stopAgentService.js')
+ const stopJobs = new Map<string, Promise<void>>()
+ let fail!: (error: Error) => void
+ const never = vi.fn(() => { throw new Error('native mutation is forbidden in this fixture') })
+ const stop = createStopAgentService({ registry, stopJobs,
+ settlePane: () => new Promise((_resolve, reject) => { fail = reject }),
+ restartJobs: { cancel: vi.fn() } as unknown as import('./restartAgent.js').AgentRestartCoordinator,
+ stoppedAgents: { save: never } as unknown as import('./stoppedAgents.js').StoppedAgentStore,
+ tmuxBackend: { kill: never }, agentReconciler: { suppress: never, holdRoute: never, releaseRoute: never, trigger: never },
+ forgetSession: never, markDeleted: never, clearDeleted: never, stopNative: never,
+ })
+ const f = await httpFixture(id => stopJobs.has(id))
+ const stopping = stop(source)
+ const refused = expect(stopping).rejects.toThrow('fixture Stop did not proceed')
+ expect(await f.post()).toEqual({ status: 200, body: { pending: true } })
+ expect(f.prompts).toEqual([])
+ expect(registry.byAgent(source)?.sessionId).toBe('')
+ expect(f.reasons.some(reason => reason?.includes('Stop'))).toBe(true)
+ expect(never).not.toHaveBeenCalled()
+ fail(new Error('fixture Stop did not proceed'))
+ await refused
+})
+
+it('recovers a peer-changed fileless binding only after fresh native source admission', () => {
+ registry.removeAgent(target)
+ const agent = registry.openProcessAgent({ engine: 'hermes', tmuxPane: '%1', cwd: root,
+ processIdentity: { pid: 6101, startMarker: 'fixture-start', executable: '<hermes>' } })!.entry
+ const body = { engine: 'hermes' as const, tmuxPane: '%1', sessionId: '20261010_050000_abcdef', cwd: root, processIdentity: agent.processIdentity! }
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register(body)).toThrow('fixture directory sync failure')
+ fault.directorySync = false
+ const peerRows = JSON.parse(readFileSync(file, 'utf8'))
+ peerRows.find((row: { agentId: string }) => row.agentId === agent.agentId).cwd = '/fixture/peer-folder'
+ writeFileSync(file, JSON.stringify(peerRows, null, 2))
+ expect(() => registry.register(body)).toThrow('different durable owner')
+ expect(registry.register(body)?.entry.identityHold).toContain('concurrent binding')
+ const result = registry.register(body, { verifiedNativeSource: true })!
+ expect(result.entry.identityHold).toBeUndefined()
+ expect(result.entry.interpretationHold).toBeTruthy()
+})
+
+it('revokes a stale displaced-owner draft when a peer gave that owner another conversation', () => {
+ expect(registry.register(input(A, transcript, '%2'))).not.toBeNull()
+ registry.setActive(source, false)
+ fault.directorySync = true; fault.renamed = false
+ expect(() => registry.register({ ...input(A, transcript, '%2'), title: 'unconfirmed title' })).toThrow('fixture directory sync failure')
+ fault.directorySync = false
+ const other = join(home, 'sessions', `rollout-${B}.jsonl`); writeFileSync(other, header(B))
+ const peerRows = JSON.parse(readFileSync(file, 'utf8'))
+ Object.assign(peerRows.find((row: { agentId: string }) => row.agentId === source), { sessionId: B, transcriptPath: other })
+ writeFileSync(file, JSON.stringify(peerRows, null, 2))
+ const disk = readFileSync(file, 'utf8')
+ // This draft's target is outside the recovered group, but its displaced owner is
+ // inside it. Returning stale orphan metadata would let binding delete that owner.
+ expect(() => registry.register(input())).toThrow('different durable owner')
+ expect(registry.byAgent(target)?.engine).toBe('terminal')
+ expect(registry.bySession(B)?.agentId).toBe(source)
+ expect(readFileSync(file, 'utf8')).toBe(disk)
+ expect(registry.register(input())?.orphaned).toBeNull()
+ expect(registry.bySession(B)?.agentId).toBe(source)
+})
+
+
+it('does not let a newly healthy prompt bypass its already-held predecessor', async () => {
+ const f = await httpFixture()
+ fault.rename = true
+ expect((await f.post({ prompt: 'first' })).body).toEqual({ pending: true })
+ fault.rename = false
+ await f.post({ prompt: 'second' })
+ await vi.waitFor(() => expect(f.prompts).toEqual(['first', 'second']), { timeout: 4_000 })
+})
+
+it('keeps the older hold visible when a competing delegated delivery is refused', async () => {
+ const f = await httpFixture(), firedAt = Date.now()
+ fault.rename = true
+ await f.post({ prompt: 'parent' }, { firedAt })
+ const child = join(home, 'sessions', `rollout-${B}.jsonl`); writeFileSync(child, '{\n')
+ await f.post({ sessionId: B, transcriptPath: child, prompt: 'child' }, { firedAt: firedAt + 1 })
+ writeFileSync(child, header(B, true))
+ await vi.waitFor(() => expect(f.reasons.at(-1)).toContain('registry write failure'), { timeout: 3_000 })
+ expect(f.prompts).toEqual([])
+ fault.rename = false
+ await vi.waitFor(() => expect(f.prompts).toEqual(['parent']), { timeout: 3_000 })
+ expect(f.reasons.at(-1)).toBeUndefined()
+})
+
+it('contains a failed status publisher without losing durable prompt notification', async () => {
+ const f = await httpFixture(() => false, 65_536, { onAdmissionHeld: () => { throw Error('fixture status unavailable') } })
+ fault.rename = true
+ await f.post()
+ fault.rename = false
+ await vi.waitFor(() => expect(f.prompts).toEqual(['fixture prompt']), { timeout: 3_000 })
+ expect(f.registered).toHaveBeenCalledOnce()
+})
+
+it('does not let a delayed older ordinary hook replace a newer accepted conversation', async () => {
+ registry.register(input(A, transcript, '%2'))
+ const f = await httpFixture()
+ const other = join(home, 'sessions', `rollout-${B}.jsonl`); writeFileSync(other, header(B))
+ const time = Date.now() + 10_000
+ expect((await f.post({ sessionId: B, transcriptPath: other, prompt: 'newer' }, { firedAt: time + 1 })).body).toEqual({ ok: true })
+ expect((await f.post({ prompt: 'older' }, { firedAt: time })).body).toEqual({ ignored: true, reason: 'stale_hook' })
+ expect(registry.byAgent(source)?.sessionId).toBe(B)
+ expect(f.prompts).toEqual(['newer'])
+})
+
+it('acknowledges a repeated delivery both while held and after acceptance without crediting it twice', async () => {
+ const f = await httpFixture()
+ const delivery = { id: 'fixture-delivery-0001' }
+ fault.rename = true
+ expect((await f.post({}, delivery)).body).toEqual({ pending: true })
+ expect((await f.post({}, delivery)).body).toEqual({ pending: true })
+ expect(await f.post({ prompt: 'conflicting prompt' }, delivery)).toEqual({ status: 409, body: { pending: false, error: 'HOOK_DELIVERY_CONFLICT' } })
+ fault.rename = false
+ await vi.waitFor(() => expect(f.prompts).toHaveLength(1), { timeout: 4_000 })
+ expect((await f.post({}, delivery)).body).toEqual({ ok: true })
+ expect(f.prompts).toEqual(['fixture prompt'])
+ expect(f.registered).toHaveBeenCalledOnce()
+})
+
+it('holds new deliveries at receipt capacity without evicting completed acknowledgements', async () => {
+ const f = await httpFixture(() => false, 1)
+ const original = { id: 'fixture-delivery-0001' }
+ expect((await f.post({}, original)).body).toEqual({ ok: true })
+ expect((await f.post({}, { id: 'fixture-delivery-0002' })).status).toBe(429)
+ expect((await f.post({}, original)).body).toEqual({ ok: true })
+ expect(f.prompts).toHaveLength(1)
+})
+
+it('bounds retained native payload bytes without dropping an already-owned prompt', async () => {
+ const f = await httpFixture(() => false, 65_536, {}, 100_000)
+ fault.rename = true
+ const delivery = { id: 'fixture-delivery-0001' }
+ const prompt = 'x'.repeat(40_000)
+ expect((await f.post({ prompt }, delivery)).body).toEqual({ pending: true })
+ expect((await f.post({ prompt }, { id: 'fixture-delivery-0002' })).status).toBe(429)
+ fault.rename = false
+ await vi.waitFor(() => expect(f.prompts).toEqual([prompt]), { timeout: 3_000 })
+ expect((await f.post({ prompt }, delivery)).body).toEqual({ ok: true })
+ expect((await f.post({ prompt }, { id: 'fixture-delivery-0002' })).body).toEqual({ ok: true })
+})
+
+it('keeps a completed delivery acknowledgement when the same process gains another route', async () => {
+ const f = await httpFixture()
+ const delivery = { id: 'fixture-delivery-0001' }
+ expect((await f.post({}, delivery)).body).toEqual({ ok: true })
+ const row = registry.byAgent(source)!
+ row.runtimes.push({ backend: 'tmux', paneId: '%3' })
+ row.primaryRuntimeKey = 'tmux\u0000%3'
+ expect((await f.post({}, delivery)).body).toEqual({ ok: true })
+ expect(f.prompts).toEqual(['fixture prompt'])
+ expect(f.registered).toHaveBeenCalledOnce()
+})
+
+it('refuses an HTTP hook whose matched process changed at the real core resolver continuation', async () => {
+ const discovery = await import('./terminalAgentDiscovery.js')
+ vi.spyOn(discovery, 'processRows').mockResolvedValue([
+ { pid: 6102, parentPid: 5102, startMarker: 'fixture-start', executable: '<hook>', args: '' },
+ { pid: 5102, parentPid: 1, startMarker: 'fixture-start', executable: '<codex>', args: '' },
+ ])
+ const { createEngineHooks } = await import('../core/engines/hooks.js')
+ const row = registry.byAgent(source)!
+ const hooks = createEngineHooks({ tmuxBackend: {}, syncSession: vi.fn(), registry: { byAgent: registry.byAgent, byRuntimeEngine: () => {
+ queueMicrotask(() => { row.processIdentity!.startMarker = 'replacement' })
+ return row
+ } }, agentReconciler: { triggerHint: vi.fn(async () => true), trigger: vi.fn() } as never })
+ const f = await httpFixture(() => false, 65_536, { resolveHookAgent: hooks.resolveHookAgent })
+ expect((await f.post({ callerPid: 6102 })).body).toEqual({ ignored: true, reason: 'stale_hook' })
+ expect(f.prompts).toEqual([])
+ expect(f.registered).not.toHaveBeenCalled()
+ expect(row.sessionId).toBe('')
+})
+
+it.each(['cursor', 'commandcode'] as const)('retains %s Stop before recovered registration can attach or close a newer turn', async engine => {
+ if (engine === 'commandcode') {
+ const { commandcodeTranscriptPath } = await import('../engines/commandcode/contract.js')
+ const path = commandcodeTranscriptPath(root, A)!
+ mkdirSync(join(path, '..'), { recursive: true }); writeFileSync(path, '{}\n')
+ }
+ const owner = registry.openProcessAgent({ engine, tmuxPane: '%3', cwd: root,
+ processIdentity: { pid: 7103, startMarker: 'fixture-start', executable: '<engine>' } })!.entry
+ const onTurnStop = vi.fn(), order: string[] = []
+ let retain = false
+ const onAdmissionStop = vi.fn((_row, unmatched) => { expect(unmatched).toBe(true); order.push('retain'); return retain })
+ const f = await httpFixture(() => false, 65_536, { onTurnStop, onAdmissionStop,
+ onRegistered: () => { order.push('attach'); expect(order[order.length - 2]).toBe('retain') } })
+ const delivery = { id: 'fixture-stop-delivery-01', firedAt: Date.now() }
+ const body = { engine, sessionId: A, transcriptPath: undefined, tmuxPane: '%3', callerPid: 7203,
+ hookEvent: engine === 'cursor' ? 'stop' : 'Stop', prompt: undefined, status: 'error' }
+ fault.rename = true
+ expect((await f.post(body, delivery)).body).toEqual({ pending: true })
+ expect((await f.post(body, delivery, 'turn-stop')).body).toEqual({ pending: true })
+ expect(onAdmissionStop).not.toHaveBeenCalled()
+ fault.rename = false
+ await vi.waitFor(() => expect(onAdmissionStop).toHaveBeenCalled(), { timeout: 3_000 })
+ expect(order).not.toContain('attach')
+ // Native binding is durable now, but a refused completion claim remains pending.
+ expect(registry.byAgent(owner.agentId)?.sessionId).toBe(A)
+ retain = true
+ await vi.waitFor(() => expect(order).toContain('attach'), { timeout: 3_000 })
+ expect(onTurnStop).not.toHaveBeenCalled()
+ expect((await f.post(body, delivery, 'turn-stop')).body).toEqual({ pending: true })
+ expect((await f.post({ ...body, status: 'done' }, delivery, 'turn-stop')).status).toBe(409)
+ expect((await f.post({ ...body, transcriptPath: '/fixture/changed' }, delivery, 'turn-stop')).status).toBe(409)
+ expect(onTurnStop).not.toHaveBeenCalled()
+})
+
+it('claims an immediate already-bound linked Stop once, including concurrent retries', async () => {
+ const owner = registry.openProcessAgent({ engine: 'cursor', tmuxPane: '%3', cwd: root,
+ processIdentity: { pid: 7103, startMarker: 'fixture-start', executable: '<engine>' } })!.entry
+ registry.register({ engine: 'cursor', sessionId: A, tmuxPane: '%3', cwd: root, processIdentity: owner.processIdentity! })
+ const onTurnStop = vi.fn()
+ const f = await httpFixture(() => false, 65_536, { onTurnStop, onAdmissionStop: (_row, unmatched) => {
+ expect(unmatched).toBe(false); return false
+ } })
+ const delivery = { id: 'fixture-stop-delivery-02', firedAt: Date.now() }
+ const body = { engine: 'cursor', sessionId: A, transcriptPath: undefined, tmuxPane: '%3', hookEvent: 'stop', prompt: undefined }
+ expect((await f.post(body, delivery)).body).toEqual({ ok: true })
+ expect((await Promise.all([f.post(body, delivery, 'turn-stop'), f.post(body, delivery, 'turn-stop')])).map(value => value.body))
+ .toEqual([{ ok: true }, { ok: true, duplicate: true }])
+ expect((await f.post(body, delivery, 'turn-stop')).body).toEqual({ ok: true, duplicate: true })
+ expect(onTurnStop).toHaveBeenCalledExactlyOnceWith({ sessionId: A, status: undefined, transcriptPath: undefined, firedAt: delivery.firedAt })
+})
+
+it.each([false, true])('retains an overtaking Stop after process resolution recovers, with onWait: %s', async waiting => {
+ const owner = registry.openProcessAgent({ engine: 'cursor', tmuxPane: '%3', cwd: root,
+ processIdentity: { pid: 7103, startMarker: 'fixture-start', executable: '<engine>' } })!.entry
+ registry.register({ engine: 'cursor', sessionId: A, tmuxPane: '%3', cwd: root, processIdentity: owner.processIdentity! })
+ let finish: ((row: typeof owner) => void) | undefined
+ const held = vi.fn(() => true), stopped = vi.fn()
+ const f = await httpFixture(() => false, 65_536, { onAdmissionStop: held, onTurnStop: stopped,
+ resolveHookAgent: async ({ onWait }) => { if (waiting) onWait?.(); return new Promise(resolve => { finish = resolve }) } })
+ const delivery = { id: 'fixture-stop-delivery-03', firedAt: Date.now() }
+ const body = { engine: 'cursor', sessionId: A, transcriptPath: undefined, tmuxPane: '%3', hookEvent: 'stop', prompt: undefined }
+ const registration = f.post(body, delivery)
+ if (waiting) expect(await registration).toMatchObject({ status: 202, body: { pending: false, retry: true } })
+ await vi.waitFor(() => expect(finish).toBeDefined())
+ expect(await f.post(body, delivery, 'turn-stop')).toMatchObject({ status: 202, body: { pending: false, retry: true } })
+ finish!(structuredClone(registry.byAgent(owner.agentId)!))
+ await registration
+ await vi.waitFor(() => expect(held).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ agentId: owner.agentId }), true))
+ expect(stopped).not.toHaveBeenCalled()
+})
+
+it.each([false, true])('keeps a held delivery through route changes and requires its original pane: %s', async removeHint => {
+ const f = await httpFixture(), delivery = { id: 'fixture-held-route-01', firedAt: Date.now() }
+ fault.rename = true
+ expect((await f.post({}, delivery)).body).toEqual({ pending: true })
+ fault.rename = false
+ registry.updateRuntimes(source, removeHint ? [{ backend: 'tmux', paneId: '%3' }]
+ : [{ backend: 'tmux', paneId: '%2' }, { backend: 'tmux', paneId: '%3' }], 'tmux\u0000%3')
+ if (removeHint) {
+ await vi.waitFor(() => expect(f.reasons.some(reason => reason?.includes('original hook pane'))).toBe(true), { timeout: 3_000 })
+ expect(f.prompts).toEqual([])
+ registry.updateRuntimes(source, [{ backend: 'tmux', paneId: '%2' }, { backend: 'tmux', paneId: '%3' }], 'tmux\u0000%3')
+ }
+ expect((await f.post({}, delivery)).body).toEqual({ pending: true })
+ await vi.waitFor(() => expect(f.prompts).toEqual(['fixture prompt']), { timeout: 3_000 })
+ expect(registry.byAgent(source)?.primaryRuntimeKey).toBe('tmux\u0000%3')
+ expect(registry.byAgent(source)?.runtimes).toEqual([{ backend: 'tmux', paneId: '%2' }, { backend: 'tmux', paneId: '%3' }])
+ expect((await f.post({}, delivery)).body).toEqual({ ok: true })
+ expect(f.registered).toHaveBeenCalledOnce()
+})
+
+it('holds a same-owner linked Stop after interpretation recovered, without closing its later turn', async () => {
+ const owner = registry.openProcessAgent({ engine: 'cursor', tmuxPane: '%3', cwd: root,
+ processIdentity: { pid: 7103, startMarker: 'fixture-start', executable: '<engine>' } })!.entry
+ registry.register({ engine: 'cursor', sessionId: A, tmuxPane: '%3', cwd: root, processIdentity: owner.processIdentity! })
+ const onTurnStop = vi.fn(), holds: boolean[] = []
+ const f = await httpFixture(() => false, 65_536, { onTurnStop, onAdmissionStop: (row, unmatched) => {
+ holds.push(unmatched)
+ if (unmatched) row.interpretationHold = 'Stop could not be matched to its turn'
+ return unmatched
+ } })
+ const delivery = { id: 'fixture-stop-recovered-01', firedAt: Date.now() }
+ const body = { engine: 'cursor', sessionId: A, transcriptPath: undefined, tmuxPane: '%3', hookEvent: 'stop', prompt: undefined }
+ expect((await f.post(body, delivery)).body).toEqual({ ok: true })
+ const row = registry.byAgent(owner.agentId)!
+ row.identityHold = 'native source unavailable'
+ row.evidenceRevision = (row.evidenceRevision ?? 0) + 1
+ delete row.identityHold
+ row.evidenceRevision++
+ expect((await f.post(body, delivery, 'turn-stop')).body).toEqual({ pending: true })
+ expect(row.interpretationHold).toContain('could not be matched')
+ expect(holds).toEqual([false, true])
+ expect(onTurnStop).not.toHaveBeenCalled()
+ // A later Cancel clears interpretation; a duplicate must not recreate the old obligation.
+ delete row.interpretationHold
+ expect((await f.post(body, delivery, 'turn-stop')).body).toEqual({ pending: true })
+ expect(row.interpretationHold).toBeUndefined()
+ expect(holds).toEqual([false, true])
+})
+
+it.each(['before-followup', 'during-followup', 'during-registration', 'during-initial-resolution'] as const)('Cancel supersedes original Stop %s without closing a newer turn', async phase => {
+ const { createAttach } = await import('../core/transcripts/attach.js')
+ const { createSessionNormalizers } = await import('../core/transcripts/normalizers.js')
+ const owner = registry.openProcessAgent({ engine: 'cursor', tmuxPane: '%3', cwd: root,
+ processIdentity: { pid: 7103, startMarker: 'fixture-start', executable: '<engine>' } })!.entry
+ registry.register({ engine: 'cursor', sessionId: A, tmuxPane: '%3', cwd: root, processIdentity: owner.processIdentity! })
+ const row = registry.byAgent(owner.agentId)!
+ // Only the core's eager cancellation fence is needed. Unexpected attachment
+ // or native interpretation would fail this fixture before any external access.
+ const attach = createAttach({ normalizers: createSessionNormalizers(), resolve: registry.byAgent } as import('../core/transcripts/attach.js').AttachDeps)
+ let laterTurnOpen = false, resolutions = 0
+ let finish: (() => void) | undefined
+ const onTurnStop = vi.fn(() => { laterTurnOpen = false })
+ const onAdmissionStop = vi.fn(() => false)
+ const f = await httpFixture(() => false, 65_536, { onTurnStop, onAdmissionStop,
+ captureAdmissionStop: attach.captureAdmissionStop,
+ resolveHookAgent: async () => {
+ resolutions++
+ if (phase === 'during-followup' && resolutions === 2 || phase === 'during-initial-resolution' && resolutions === 1) {
+ await new Promise<void>(resolve => { finish = resolve })
+ }
+ return structuredClone(registry.byAgent(row.agentId)!)
+ } })
+ const delivery = { id: 'fixture-stop-cancelled-01', firedAt: Date.now() }
+ const body = { engine: 'cursor', sessionId: A, transcriptPath: undefined, tmuxPane: '%3', hookEvent: 'stop', prompt: undefined }
+ if (phase === 'during-registration') fault.rename = true
+ const registration = f.post(body, delivery)
+ if (phase === 'during-initial-resolution') await vi.waitFor(() => expect(finish).toBeDefined())
+ else expect((await registration).body).toEqual(phase === 'during-registration' ? { pending: true } : { ok: true })
+ const followup = phase === 'during-followup' ? f.post(body, delivery, 'turn-stop') : undefined
+ if (followup) await vi.waitFor(() => expect(finish).toBeDefined())
+ attach.beforeCancel(row)
+ laterTurnOpen = true
+ if (phase === 'during-initial-resolution') {
+ // A retry must share the original cancellation witness, even when it could
+ // resolve sooner after Cancel than the first request that was already taken.
+ expect(await f.post(body, delivery)).toMatchObject({ status: 202, body: { pending: false, retry: true } })
+ expect(await f.post({ ...body, title: 'different delivery' }, delivery)).toMatchObject({ status: 409 })
+ expect(resolutions).toBe(1)
+ }
+ fault.rename = false
+ finish?.()
+ await registration
+ if (phase === 'during-registration') await vi.waitFor(() => expect(f.registered).toHaveBeenCalledOnce(), { timeout: 3_000 })
+ expect((await (followup ?? f.post(body, delivery, 'turn-stop'))).body).toEqual({ ok: true, duplicate: true })
+ expect(onTurnStop).not.toHaveBeenCalled()
+ expect(onAdmissionStop).toHaveBeenCalledTimes(phase === 'during-registration' || phase === 'during-initial-resolution' ? 0 : 1)
+ expect(laterTurnOpen).toBe(true)
+ attach.forget(A)
+})
+
+it('rechecks the completion claim after a concurrent duplicate waits across recovery', async () => {
+ const owner = registry.openProcessAgent({ engine: 'cursor', tmuxPane: '%3', cwd: root,
+ processIdentity: { pid: 7103, startMarker: 'fixture-start', executable: '<engine>' } })!.entry
+ registry.register({ engine: 'cursor', sessionId: A, tmuxPane: '%3', cwd: root, processIdentity: owner.processIdentity! })
+ const finishes: Array<() => void> = [], onAdmissionStop = vi.fn(() => false)
+ let resolutions = 0
+ const onTurnStop = vi.fn(() => {
+ const row = registry.byAgent(owner.agentId)!
+ row.evidenceRevision = (row.evidenceRevision ?? 0) + 1
+ })
+ const f = await httpFixture(() => false, 65_536, { onTurnStop, onAdmissionStop,
+ resolveHookAgent: async () => {
+ if (++resolutions > 1) await new Promise<void>(resolve => finishes.push(resolve))
+ return structuredClone(registry.byAgent(owner.agentId)!)
+ } })
+ const delivery = { id: 'fixture-stop-concurrent-01', firedAt: Date.now() }
+ const body = { engine: 'cursor', sessionId: A, transcriptPath: undefined, tmuxPane: '%3', hookEvent: 'stop', prompt: undefined }
+ expect((await f.post(body, delivery)).body).toEqual({ ok: true })
+ const first = f.post(body, delivery, 'turn-stop')
+ await vi.waitFor(() => expect(finishes).toHaveLength(1))
+ const duplicate = f.post(body, delivery, 'turn-stop')
+ await vi.waitFor(() => expect(finishes).toHaveLength(2))
+ finishes[0]()
+ expect((await first).body).toEqual({ ok: true })
+ finishes[1]()
+ expect((await duplicate).body).toEqual({ ok: true, duplicate: true })
+ expect(onTurnStop).toHaveBeenCalledOnce()
+ expect(onAdmissionStop).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ sessionId: A }), false)
+})
+
+it.each(['records', 'bytes'] as const)('never lets a linked Stop bypass refused admission at %s capacity', async capacity => {
+ const owner = registry.openProcessAgent({ engine: 'cursor', tmuxPane: '%3', cwd: root,
+ processIdentity: { pid: 7103, startMarker: 'fixture-start', executable: '<engine>' } })!.entry
+ registry.register({ engine: 'cursor', sessionId: A, tmuxPane: '%3', cwd: root, processIdentity: owner.processIdentity! })
+ const onTurnStop = vi.fn()
+ const f = await httpFixture(() => false, capacity === 'records' ? 0 : 65_536, { onTurnStop }, capacity === 'bytes' ? 0 : undefined)
+ const delivery = { id: 'fixture-unowned-stop-01', firedAt: Date.now() }
+ const body = { engine: 'cursor', sessionId: A, transcriptPath: undefined, tmuxPane: '%3', hookEvent: 'stop', prompt: undefined }
+ expect(await f.post(body, delivery)).toMatchObject({ status: 429, body: { pending: false } })
+ expect(await f.post(body, delivery, 'turn-stop')).toMatchObject({ status: 202, body: { pending: false, retry: true } })
+ expect(onTurnStop).not.toHaveBeenCalled()
+ expect(await f.post(body, {}, 'turn-stop')).toMatchObject({ status: 200, body: { ok: true } })
+ expect(onTurnStop).toHaveBeenCalledOnce()
+})
diff --git a/cli/src/lib/registry.binding.spec.ts b/cli/src/lib/registry.binding.spec.ts
index 3eb3e44d3..a3eff3b9b 100644
--- a/cli/src/lib/registry.binding.spec.ts
+++ b/cli/src/lib/registry.binding.spec.ts
@@ -201,7 +201,8 @@ it.each(['identity', 'interpretation', 'unbound'] as const)('does not transfer t
writeFileSync(path, header(id))
const result = registry.register({ engine: 'codex', sessionId: id, transcriptPath: path, tmuxPane: '%1', cwd: root })!
expect(result.isNew).toBe(true)
- expect(result.entry).toMatchObject({ sessionId: id, evidenceRevision: revision })
+ // The staged commit replaces the binding in place and revokes every old read.
+ expect(result.entry).toMatchObject({ sessionId: id, evidenceRevision: revision! + 1 })
expect(result.entry.identityHold).toBeUndefined(); expect(result.entry.interpretationHold).toBeUndefined()
const { createBinding } = await import('../core/agents/bind.js')
const attachSession = vi.fn(async () => true)
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 86718bbed..7f199b02f 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -273,7 +273,7 @@ describe('registry remote display names', () => {
const sessionsDir = join(dataDir, 'sessions')
const transcriptPath = join(sessionsDir, 'codex-session.jsonl')
mkdirSync(sessionsDir)
- writeFileSync(transcriptPath, '{}\n')
+ writeFileSync(transcriptPath, JSON.stringify({ type: 'session_meta', payload: { id: 'codex-session', cwd: '/tmp/codex', source: 'cli' } }) + '\n')
const { registry } = await loadRegistryModule()
registry.load()
@@ -709,12 +709,12 @@ describe('a Command Code session without a transcript path', () => {
engine: 'commandcode',
sessionId: 'ae93cc89-0dff-452a-a875-33b1516bbc80',
tmuxPane: '%9',
- cwd: '/Users/me/Working/Tmux/Agent-6',
+ cwd: '/workspace/project',
})
// The file does not exist yet — that is the whole point. The watcher opens at offset 0 and chokidar
// delivers the lines when the CLI finally writes them.
expect(registered?.entry.transcriptPath).toBe(
- join(dataDir, 'projects', 'users-me-working-tmux-agent-6', 'ae93cc89-0dff-452a-a875-33b1516bbc80.jsonl'),
+ join(dataDir, 'projects', 'workspace-project', 'ae93cc89-0dff-452a-a875-33b1516bbc80.jsonl'),
)
})
@@ -730,7 +730,7 @@ describe('a Command Code session without a transcript path', () => {
engine: 'commandcode',
sessionId: 'reported',
tmuxPane: '%9',
- cwd: '/Users/me/Working/Tmux/Agent-6',
+ cwd: '/workspace/project',
transcriptPath: reported,
})
expect(registered?.entry.transcriptPath).toBe(reported)
@@ -1434,7 +1434,7 @@ describe('agent identity: the process owns the agent, the session is bound to it
const transcriptFile = join(profile, 'sessions', 'rollout-x.jsonl')
mkdirSync(join(transcriptFile, '..'), { recursive: true })
- writeFileSync(transcriptFile, '{}\n')
+ writeFileSync(transcriptFile, JSON.stringify({ type: 'session_meta', payload: { id: 'sess-1', cwd: '/tmp/demo', source: 'cli' } }) + '\n')
const result = registry.register({
engine: 'codex',
@@ -1461,7 +1461,7 @@ describe('agent identity: the process owns the agent, the session is bound to it
const rollout = (id: string, source: unknown): string => {
const file = join(profile, 'sessions', `rollout-${id}.jsonl`)
mkdirSync(join(file, '..'), { recursive: true })
- writeFileSync(file, JSON.stringify({ type: 'session_meta', payload: { id, source } }) + '\n')
+ writeFileSync(file, JSON.stringify({ type: 'session_meta', payload: { id, cwd: '/tmp/demo', source } }) + '\n')
return file
}
const register = (sessionId: string, transcriptPath: string) => registry.register({
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 19748f14b..bff1a274c 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -44,7 +44,6 @@ import { engineHomeSnapshot, sessionRoots, type EngineHomeSnapshot } from './eng
import { transcriptRoot as TRANSCRIPT_ROOT, needsHomeCatalog, savedTranscriptEvidence, transcriptEvidence, transcriptRootEvidence } from '../engines/transcriptBindings.js'
export { engineKeepsTranscriptFile } from '../engines/transcriptBindings.js'
import { sessionStoreOf } from '../engines/sessionStoreContracts.js'
-import { admitHook } from '../engines/hooks.js'
import { ENGINES, isTerminalEngine, type AgentEngine } from '../engines/types.js'
import type { GridAssignment } from './gridAssignment.js'
import { parseGridLaunchOverride, type GridLaunchOverride, type GridLaunchRecord, type GridWebSearchStatus } from './gridLaunchWire.js'
@@ -93,6 +92,8 @@ export interface RegisteredSession {
launch?: AgentLaunch
/** Fresh evidence is unavailable; retain the binding and expose its reason without persisting an authority verdict. */
identityHold?: string
+ /** Pending native hook evidence; it does not revoke an already-bound conversation. */
+ admissionHold?: string
/** Monotonic process-local authority: a hold/recovery cycle must never revive an older read. */
evidenceRevision?: number
/** Native identity recovered; interpretation stays paused until its replacement tail is installed. */
@@ -474,6 +475,14 @@ function rowFingerprint(row: unknown): string {
? Object.fromEntries(Object.keys(value).sort().map((key) => [key, value[key]])) : value)
}
+/** The new image is visible, but its directory has not confirmed durability yet. */
+const BINDING_RECOVERY_HOLD = 'Waiting for native evidence after a concurrent binding write.'
+class RegistryOwnershipChanged extends IdentityReadUnavailable {}
+
+class AtomicWriteUnconfirmed extends Error {
+ constructor(cause: unknown) { super(cause instanceof Error ? cause.message : String(cause), { cause }) }
+}
+
export function atomicWriteJson(file: string, value: unknown, exclusive = false): void {
const exists = hardenPrivateStateFileIfPresent(file)
if (exclusive && exists) return
@@ -490,6 +499,9 @@ export function atomicWriteJson(file: string, value: unknown, exclusive = false)
renamed = true
const directoryFd = openSync(dirname(file), 'r')
try { fsyncSync(directoryFd) } finally { closeSync(directoryFd) }
+ } catch (error) {
+ if (renamed) throw new AtomicWriteUnconfirmed(error)
+ throw error
} finally {
if (!renamed) rmSync(temporary, { force: true })
}
@@ -557,7 +569,7 @@ function tmuxProjection(runtimes: readonly TerminalRuntimeRef[]): string {
}
function persistedRow(entry: RegisteredSession): RegisteredSession | Omit<RegisteredSession, 'tmuxPane'> {
- const { identityHold: _hold, evidenceRevision: _revision, interpretationHold: _interpretation, ...saved } = entry
+ const { identityHold: _hold, evidenceRevision: _revision, interpretationHold: _interpretation, admissionHold: _admission, ...saved } = entry
if (saved.tmuxPane) return { ...saved, runtimes: saved.runtimes.map((runtime) => ({ ...runtime })) }
const { tmuxPane: _legacy, ...row } = saved
return { ...row, runtimes: row.runtimes.map((runtime) => ({ ...runtime })) }
@@ -595,7 +607,7 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {
// Taken out of the spread and put back only when it is a real moment: the spread would otherwise
// carry a hand-edited string or a negative number straight into the frame's `toISOString()`.
// `forkedFrom` is out too, so an invalid one is dropped rather than spread back in as-is.
- const { identityHold: _identityHold, evidenceRevision: _revision, interpretationHold: _interpretation, lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, externalResume: _externalResume, ...rest } = row
+ const { identityHold: _identityHold, evidenceRevision: _revision, interpretationHold: _interpretation, admissionHold: _admission, lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, externalResume: _externalResume, ...rest } = row
const lastOpenedAt = normalizedOpenedAt(rawOpenedAt)
// Out of the spread for the same reason: a half-formed record is dropped, never relaunched with.
const scmLaunch = parseScmLaunchRecord(rawScmLaunch)
@@ -1014,6 +1026,10 @@ class Registry {
private persistedBaseline = new Map<string, string>()
/** Exact bytes of our last durable save; checked against the file, never just its mtime. */
private persistedContents: string | null = null
+ // A post-rename failure is not absence. Only the same immutable binding intent,
+ // unchanged local owners and these exact affected rows can confirm that write.
+ private unconfirmedBinding: { image: ReturnType<typeof persistedRow>[]; prior: unknown[]; before: Map<string, string>;
+ agentId: string; intent: string | null; affected: Set<string> } | null = null
/**
* Fields a caller set on purpose since the last save, by agent: written as they are now, whatever the
* file says. The merge alone keeps the file's value wherever this view matches what it last saved, so
@@ -1036,12 +1052,17 @@ class Registry {
*/
onEnter: ((engine: AgentEngine) => void) | null = null
- private index(entry: RegisteredSession): void {
+ private index(entry: RegisteredSession, notify = true): void {
this.agents.set(entry.agentId, entry)
if (entry.sessionId) this.sessionIndex.set(entry.sessionId, entry.agentId)
for (const runtime of entry.runtimes) this.runtimeIndex.set(terminalRouteKey(runtime), entry.agentId)
if (entry.processIdentity) this.processIndex.set(processIdentityKey(entry.engine, entry.processIdentity), entry.agentId)
- this.onEnter?.(entry.engine)
+ if (notify) this.entered(entry.engine)
+ }
+
+ private entered(engine: AgentEngine): void {
+ try { this.onEnter?.(engine) }
+ catch (error) { console.warn('[registry] engine entry notification failed:', error) }
}
private drop(entry: RegisteredSession | undefined): void {
@@ -1088,6 +1109,7 @@ class Registry {
this.rebooted = false
this.persistedBaseline.clear()
this.persistedContents = null
+ this.unconfirmedBinding = null
this.intended.clear()
try {
secureStateDirectory(env.ADAPTER_DATA_DIR)
@@ -1367,6 +1389,7 @@ class Registry {
this.processIndex.clear()
this.persistedBaseline.clear()
this.persistedContents = null
+ this.unconfirmedBinding = null
this.intended.clear()
const aside = `${FILE}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`
try {
@@ -1730,7 +1753,7 @@ class Registry {
* showing two tiles. Returns { entry, isNew, evicted } — isNew=false on a re-register (so callers
* can skip re-announcing), evicted = the sessionId displaced from this pane (caller removes it).
*/
- register(input: RegisterInput): {
+ register(input: RegisterInput, options: { verifiedNativeSource?: boolean } = {}): {
entry: RegisteredSession
isNew: boolean
evicted: string | null
@@ -1749,7 +1772,7 @@ class Registry {
orphaned: { agentId: string; sessionId: string } | null
} | null {
- if (this.writeBlocked) return null
+ if (this.writeBlocked) throw new IdentityReadUnavailable('the saved session registry is unavailable')
const transcriptPath = input.transcriptPath
const sessionId =
input.sessionId || (transcriptPath ? basename(transcriptPath).replace(/\.jsonl$/, '') : '')
@@ -1768,7 +1791,6 @@ class Registry {
?? (isTerminalEngine(engine) ? undefined : inputRuntimes
.map((runtime) => this.byRuntimeTerminal(runtime))
.filter((agent): agent is RegisteredSession => !!agent)
- .map((agent) => this.adoptEngine(agent.agentId, engine, validProcessIdentity(input.processIdentity) ? input.processIdentity : null))
.find((agent): agent is RegisteredSession => !!agent))
const agentId = processAgent?.agentId ?? ''
// An inert adoption pane cannot bind a hook before core has admitted its external conversation.
@@ -1788,33 +1810,10 @@ class Registry {
|| (engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && engine !== 'grok' && engine !== 'agy' && engine !== 'copilot' && !transcriptPath)
// The already-registered agent (opened at agent_create time) already carries its own
// CODEX_HOME profile, if it has one other than the default — see RegisteredSession.codexHome.
- || (transcriptPath && !validTranscriptPath(engine, transcriptPath, processAgent?.codexHome ?? undefined))
) return null
- // A delegated session is never registered, by any caller: the same admission the hook server asks before
- // it credits a prompt (hookServer.ts), so that the two can never disagree.
- if (transcriptPath && !admitHook(engine, { transcriptPath }).accepted) return null
const now = Date.now()
const existing = this.agents.get(agentId)
- // A resumed row that has not yet been told, by a hook, which conversation it actually reopened.
- // Two ways to be in that state, and both have to count:
- // - `lastHookAt === 0` — a resume allocated by `resumePendingAgent` and not yet hooked. Its
- // `launch` may ALREADY read `ready`, because a resume is confirmed by its own live engine
- // process now (`resumeStoppedAgent.ts`) and that is usually earlier than the hook. Reading
- // only `launch` here disarmed this guard for exactly the resumes it exists to protect.
- // - a launch that is not `ready` — a row put back by the post-reboot restore, which relaunches
- // `--resume` against a row that kept `lastHookAt` from its previous life.
- if (existing?.resumeOnly && (existing.lastHookAt === 0 || (existing.launch && existing.launch.state !== 'ready'))) {
- // A native startup hook, carrying the verified process, must confirm this exact history —
- // but only where an exact history was asked for. A resume that opened a NEW conversation (an
- // engine with no resume argv, or a row with no id to reopen) reports a different id BECAUSE
- // it did what it was told; failing it there would refuse the resume the caller requested.
- if (sessionId !== existing.sessionId && resumesConversation(engine, existing.sessionId)) {
- this.setLaunch(agentId, { state: 'failed', error: 'RESUME_SESSION_MISMATCH', detail: 'The agent reported a different conversation. The requested conversation is still saved.' })
- return null
- }
- if (!validProcessIdentity(input.processIdentity)) return null
- }
// `isNew` still means "this SESSION id was not bound here before" — a rotation counts as new, which is
// what makes the caller announce the newly bound session. The agent itself may be long-lived.
const isNew = !existing || existing.sessionId !== sessionId
@@ -1826,18 +1825,14 @@ class Registry {
// newest bind wins; the old process agent remains visible but becomes unbound.
let orphaned: { agentId: string; sessionId: string } | null = null
const stolenFrom = this.bySession(sessionId)
+ let displaced: { agentId: string; candidate: RegisteredSession | null } | undefined
if (stolenFrom && stolenFrom.agentId !== agentId) {
- console.log(`[registry] session ${sessionId.slice(0, 8)} moved from agent ${stolenFrom.agentId.slice(0, 8)} to ${agentId.slice(0, 8)}`)
- const wasDormant = !stolenFrom.active
- this.releaseBinding(stolenFrom)
- // The verified canonical conversation moved. Its old row no longer owns the admission or
- // its aliases, and cannot later replay that resume as though it still owned the conversation.
- if (stolenFrom.externalResume) { delete stolenFrom.externalResume; delete stolenFrom.resumeOnly }
- if (wasDormant) {
- orphaned = { agentId: stolenFrom.agentId, sessionId }
- this.drop(stolenFrom)
- this.terminalAvailableAgents.delete(stolenFrom.agentId)
- }
+ const released = { ...stolenFrom, sessionId: '', boundAt: null, transcriptPath: null,
+ source: null, lastTranscriptAt: now }
+ delete released.externalResume; delete released.resumeOnly
+ delete released.identityHold; delete released.interpretationHold
+ displaced = { agentId: stolenFrom.agentId, candidate: stolenFrom.active ? released : null }
+ if (!stolenFrom.active) orphaned = { agentId: stolenFrom.agentId, sessionId }
}
@@ -1869,7 +1864,42 @@ class Registry {
: !transcriptPath && engine === 'copilot'
? copilotTranscriptPath(env.COPILOT_HOME, sessionId)
: null
- const effectiveTranscriptPath = transcriptPath ?? existing?.transcriptPath ?? derived ?? null
+ const effectiveTranscriptPath = transcriptPath ?? (sameSession ? existing.transcriptPath : null) ?? derived ?? null
+ // Native evidence is staged before terminal adoption, displacement or any live publication.
+ const proof = effectiveTranscriptPath ? transcriptEvidence(engine, effectiveTranscriptPath,
+ processAgent?.codexHome ?? undefined, !transcriptPath && derived === effectiveTranscriptPath ? 'derived' : false) : undefined
+ if (proof && !proof.valid) {
+ proof.verify()
+ if (!proof.files.file(effectiveTranscriptPath!, true)) throw new IdentityReadUnavailable('the announced transcript is not yet available')
+ return null
+ }
+ const first = sessionStoreOf(engine)?.first
+ if (proof && first) {
+ const meta = proof.files.header(effectiveTranscriptPath!, first)
+ if (meta.isSubagent || meta.id !== sessionId) { proof.verify(); return null }
+ }
+ // A resumed row that has not yet been told, by a hook, which conversation it actually reopened.
+ // Two ways to be in that state, and both have to count:
+ // - `lastHookAt === 0` — a resume allocated by `resumePendingAgent` and not yet hooked. Its
+ // `launch` may ALREADY read `ready`, because a resume is confirmed by its own live engine
+ // process now (`resumeStoppedAgent.ts`) and that is usually earlier than the hook. Reading
+ // only `launch` here disarmed this guard for exactly the resumes it exists to protect.
+ // - a launch that is not `ready` — a row put back by the post-reboot restore, which relaunches
+ // `--resume` against a row that kept `lastHookAt` from its previous life.
+ if (existing?.resumeOnly && (existing.lastHookAt === 0 || (existing.launch && existing.launch.state !== 'ready'))) {
+ // A native startup hook, carrying the verified process, must confirm this exact history —
+ // but only where an exact history was asked for. A resume that opened a NEW conversation (an
+ // engine with no resume argv, or a row with no id to reopen) reports a different id BECAUSE
+ // it did what it was told; failing it there would refuse the resume the caller requested.
+ if (!validProcessIdentity(input.processIdentity)) return null
+ if (sessionId !== existing.sessionId && resumesConversation(engine, existing.sessionId)) {
+ const failed: RegisteredSession = { ...existing, active: false, touchedAt: now,
+ launch: { state: 'failed', error: 'RESUME_SESSION_MISMATCH', detail: 'The agent reported a different conversation. The requested conversation is still saved.' } }
+ this.save(true, false, undefined, { agentId, candidate: failed, verify: () => proof?.verify() })
+ this.traceLaunch(agentId, existing.launch, failed.launch, 'resume conversation mismatch')
+ return null
+ }
+ }
// Even a first bind can carry a drifted cwd (a fork inherits its source's; `claude --resume` typed
// from a subfolder). Claude's transcript never moves from the project dir it was started in, so a
// cwd that does not round-trip to that directory name is not this session's folder — the row's own
@@ -1884,7 +1914,7 @@ class Registry {
const retainEvidence = sameSession && existing.engine === engine && existing.transcriptPath === effectiveTranscriptPath
const entry: RegisteredSession = {
schemaVersion: 2,
- active: existing?.active ?? true,
+ active: existing && isTerminalEngine(existing.engine) ? true : existing?.active ?? true,
...(existing?.evidenceRevision === undefined ? {} : { evidenceRevision: existing.evidenceRevision }),
...(retainEvidence && existing.identityHold ? { identityHold: existing.identityHold } : {}),
...(retainEvidence && existing.interpretationHold ? { interpretationHold: existing.interpretationHold } : {}),
@@ -1942,7 +1972,7 @@ class Registry {
...(existing?.resumeOnly ? { resumeOnly: true, launch: { state: 'ready' as const } } : {}),
// Keep alias reservations and profile arguments across the first hook and daemon restart.
...(existing?.externalResume && existing.engine === engine ? { externalResume: existing.externalResume } : {}),
- ...(existing?.terminalHost ? { terminalHost: true } : {}),
+ ...(existing?.terminalHost || existing && isTerminalEngine(existing.engine) ? { terminalHost: true } : {}),
processIdentity: validProcessIdentity(input.processIdentity) ? input.processIdentity : existing?.processIdentity ?? null,
registeredAt: existing?.registeredAt ?? now,
touchedAt: now,
@@ -1956,14 +1986,21 @@ class Registry {
}
entry.tmuxPane = tmuxProjection(entry.runtimes)
entry.primaryRuntimeKey = selectedRuntimeKey(entry.runtimes, input.primaryRuntimeKey || existing?.primaryRuntimeKey)
- // A bind REBUILDS the row, and the rebuild carries no `launch` unless the row is resume-only:
- // an engine reporting for duty is the end of any launch. Traced like the setters, because this
- // is the one that changes the state without naming it.
- this.traceLaunch(agentId, existing?.launch, entry.launch, `register ${engine} (${isNew ? 'new session' : 're-register'})`)
- if (rebound) this.sessionIndex.delete(rebound)
- this.index(entry)
- this.save()
- return { entry, isNew, evicted, rebound, orphaned }
+ const previousLaunch = existing?.launch, promoted = !!existing && isTerminalEngine(existing.engine)
+ this.save(true, false, undefined, { agentId, candidate: entry, displaced, replaceLive: true, verify: () => proof?.verify() })
+ const committed = this.agents.get(agentId)!
+ // Fileless sources cannot use transcript revalidation. A fresh native hook
+ // source/process check can recover this precise peer-write hold only after
+ // its registration has been committed. It cannot clear unrelated holds.
+ if (!committed.transcriptPath && options.verifiedNativeSource && committed.identityHold === BINDING_RECOVERY_HOLD) {
+ delete committed.identityHold
+ committed.evidenceRevision = ++this.evidenceRevision
+ committed.interpretationHold = 'Waiting for transcript interpretation to recover.'
+ }
+ if (orphaned) this.terminalAvailableAgents.delete(orphaned.agentId)
+ if (promoted) this.terminalAvailableAgents.add(agentId)
+ this.traceLaunch(agentId, previousLaunch, committed.launch, `register ${engine} (${isNew ? 'new session' : 're-register'})`)
+ return { entry: committed, isNew, evicted, rebound, orphaned }
}
remove(sessionId: string): boolean {
@@ -2181,8 +2218,7 @@ class Registry {
this.drop(row)
this.index(next)
try { this.save(true, false, agentId) } catch (error) {
- this.drop(next)
- this.index(row)
+ if (!(error instanceof RegistryOwnershipChanged)) { this.drop(next); this.index(row) }
throw error
}
return this.byAgent(agentId) ?? null
@@ -2195,7 +2231,7 @@ class Registry {
const available = this.terminalAvailable(agentId)
this.drop(row); this.terminalAvailableAgents.delete(agentId)
try { this.save(true, false, agentId) } catch (error) {
- this.index(row); if (available) this.terminalAvailableAgents.add(agentId)
+ if (!(error instanceof RegistryOwnershipChanged)) { this.index(row); if (available) this.terminalAvailableAgents.add(agentId) }
throw error
}
return true
@@ -2220,7 +2256,7 @@ class Registry {
const intended = this.intended.get(agentId) ?? new Set<string>()
intended.add('closePlan')
this.intended.set(agentId, intended)
- try { this.save(true) } catch (error) {
+ try { this.save(true, false, undefined, undefined, agentId) } catch (error) {
if (previous) entry.closePlan = previous
else delete entry.closePlan
intended.delete('closePlan')
@@ -2518,8 +2554,56 @@ class Registry {
this.saveNames()
}
+ /** Adopt a peer's complete ownership group without granting native control. */
+ private reconcileUnconfirmed(latest: Map<string, Record<string, unknown>>, affected: Set<string>): void {
+ const selected = new Map(this.list().map(row => [row.agentId, row]))
+ // Follow the same process, terminal and owned/provisional conversation
+ // identities as validatedRows, including external canonical IDs and aliases.
+ const peer = new Map([...latest].map(([id, value]) => [id, strictPersistedRow(value)]))
+ const claims = (row: RegisteredSession): string[] => [
+ ...(row.processIdentity ? [`p:${processIdentityKey(row.engine, row.processIdentity)}`] : []),
+ ...row.runtimes.map(runtime => `r:${terminalRouteKey(runtime)}`),
+ ...externalReservations(row).map(id => `${externalResumePending(row.externalResume) ? 'i' : 's'}:${id}`),
+ ]
+ const owners = new Map<string, Set<string>>()
+ for (const row of [...selected.values(), ...peer.values()]) if (row) {
+ for (const claim of claims(row)) {
+ const ids = owners.get(claim) ?? new Set<string>()
+ ids.add(row.agentId); owners.set(claim, ids)
+ }
+ }
+ for (const id of affected) for (const row of [selected.get(id), peer.get(id)]) if (row) {
+ for (const claim of claims(row)) for (const otherId of owners.get(claim)!) affected.add(otherId)
+ }
+ for (const id of affected) {
+ const row = strictPersistedRow(latest.get(id))
+ if (row) selected.set(id, row)
+ else selected.delete(id)
+ }
+ if (!validatedRows([...selected.values()].map(persistedRow))) {
+ throw new IdentityReadUnavailable('the recovered ownership group is incomplete')
+ }
+ for (const id of affected) {
+ const old = this.agents.get(id)
+ if (old) this.drop(old)
+ }
+ for (const id of affected) {
+ const row = selected.get(id)
+ if (row) {
+ if (row.sessionId) row.identityHold = BINDING_RECOVERY_HOLD
+ row.evidenceRevision = ++this.evidenceRevision
+ this.index(row, false)
+ this.persistedBaseline.set(id, rowFingerprint(persistedRow(row)))
+ } else this.persistedBaseline.delete(id)
+ this.intended.delete(id)
+ }
+ this.persistedContents = null
+ }
+
private save(strict = false, exiting = false, externalAgentId?: string,
- bindingCommit?: { agentId: string; candidate: RegisteredSession; verify: () => void }): void {
+ bindingCommit?: { agentId: string; candidate: RegisteredSession; verify: () => void; replaceLive?: boolean;
+ displaced?: { agentId: string; candidate: RegisteredSession | null } },
+ mutationAgentId = externalAgentId ?? bindingCommit?.agentId): void {
// Discovery batches observations, but a recovered binding must be durable before interpretation
// resumes. Commit a complete batch now; an incomplete batch remains held and retries next pass.
if (this.transactionDepth > 0 && !exiting && !bindingCommit) {
@@ -2533,13 +2617,25 @@ class Registry {
return
}
if (this.namesUnsaved) this.saveNames()
+ const entered: AgentEngine[] = []
try {
secureStateDirectory(env.ADAPTER_DATA_DIR)
const currentRows = new Map(this.list().map((entry) => {
const row = persistedRow(entry) as unknown as Record<string, unknown>
return [entry.agentId, row] as const
}))
- if (bindingCommit) currentRows.set(bindingCommit.agentId, persistedRow(bindingCommit.candidate) as unknown as Record<string, unknown>)
+ const beforeCommit = new Map([...currentRows].map(([id, row]) => [id, rowFingerprint(row)]))
+ const intent = bindingCommit ? rowFingerprint({ ...persistedRow(bindingCommit.candidate),
+ touchedAt: 0, boundAt: 0, lastHookAt: 0 }) : undefined
+ let unconfirmed = this.unconfirmedBinding
+ let confirming = !!unconfirmed && !!bindingCommit && unconfirmed.agentId === bindingCommit.agentId && unconfirmed.intent === intent
+ && [...unconfirmed.affected].every(id => beforeCommit.get(id) === unconfirmed!.before.get(id))
+ if (bindingCommit) {
+ currentRows.set(bindingCommit.agentId, persistedRow(bindingCommit.candidate) as unknown as Record<string, unknown>)
+ const displaced = bindingCommit.displaced
+ if (displaced?.candidate) currentRows.set(displaced.agentId, persistedRow(displaced.candidate) as unknown as Record<string, unknown>)
+ else if (displaced) currentRows.delete(displaced.agentId)
+ }
// A discovery batch may be awaiting a reader after acknowledging a complete binding. Exit cannot
// wait for it. Check BEFORE merge conflict resolution: an incomplete pane swap must never be
// made to look valid by evicting its other owner. Its last durable snapshot remains untouched.
@@ -2579,13 +2675,65 @@ class Registry {
if (id) latest.set(id, value as Record<string, unknown>)
}
- if (bindingCommit) {
+ if (unconfirmed && [...unconfirmed.affected].some(id => {
+ const written = unconfirmed!.image.find(row => rowId(row) === id)
+ return (latest.has(id) ? rowFingerprint(latest.get(id)) : undefined)
+ !== (written ? rowFingerprint(written) : undefined)
+ })) {
+ // A peer changed part of our unpublished ownership group. Its complete
+ // validated table wins that whole group; no fragment of the old draft may
+ // overwrite it. Recovered bindings stay held until native revalidation.
+ this.reconcileUnconfirmed(latest, unconfirmed.affected)
+ for (const id of unconfirmed.affected) {
+ const row = this.agents.get(id)
+ if (row) currentRows.set(id, persistedRow(row) as unknown as Record<string, unknown>)
+ else currentRows.delete(id)
+ }
+ const revoked = mutationAgentId !== undefined && unconfirmed.affected.has(mutationAgentId)
+ || bindingCommit?.displaced !== undefined && unconfirmed.affected.has(bindingCommit.displaced.agentId)
+ this.unconfirmedBinding = unconfirmed = null
+ confirming = false
+ if (revoked) throw new RegistryOwnershipChanged('the unconfirmed binding has a different durable owner; retry with fresh evidence')
+ }
+ // Roll back only the rows of our unpublished group for a different local
+ // operation. Unrelated peer commits remain in the merge throughout recovery.
+ if (unconfirmed && !confirming) {
+ for (const id of unconfirmed.affected) {
+ const prior = unconfirmed.prior.find(row => rowId(row) === id)
+ if (prior) latest.set(id, prior as Record<string, unknown>)
+ else latest.delete(id)
+ }
+ }
+ if (confirming) {
+ for (const id of unconfirmed!.affected) {
+ const written = unconfirmed!.image.find(row => rowId(row) === id)
+ if (written) currentRows.set(id, written as unknown as Record<string, unknown>)
+ else currentRows.delete(id)
+ }
+ }
+ if (bindingCommit && !confirming) {
if ((latest.has(bindingCommit.agentId) ? rowFingerprint(latest.get(bindingCommit.agentId)) : undefined)
!== this.persistedBaseline.get(bindingCommit.agentId)) {
throw new IdentityReadUnavailable('the saved binding changed while its evidence was being read')
}
- bindingCommit.verify()
+ const displaced = bindingCommit.displaced
+ if (displaced && (latest.has(displaced.agentId) ? rowFingerprint(latest.get(displaced.agentId)) : undefined)
+ !== this.persistedBaseline.get(displaced.agentId)) {
+ throw new IdentityReadUnavailable('the displaced binding changed while its evidence was being read')
+ }
+ const candidate = bindingCommit.candidate
+ const routes = new Set(candidate.runtimes.map(terminalRouteKey))
+ for (const [otherId, other] of new MergeIdentities(latest).sharing(candidate.agentId,
+ candidate.processIdentity?.pid, candidate.sessionId, routes)) {
+ if (otherId === displaced?.agentId) continue
+ if ((other.engine === candidate.engine && sameProcessIdentity(other.processIdentity, candidate.processIdentity))
+ || (!!candidate.sessionId && other.sessionId === candidate.sessionId)
+ || other.runtimes.some(runtime => routes.has(terminalRouteKey(runtime)))) {
+ throw new IdentityReadUnavailable('the conversation or terminal has a different durable owner')
+ }
+ }
}
+ bindingCommit?.verify()
if (externalAgentId && (latest.has(externalAgentId) ? rowFingerprint(latest.get(externalAgentId)) : undefined)
!== this.persistedBaseline.get(externalAgentId)) {
@@ -2607,26 +2755,75 @@ class Registry {
}
}
}
- const merged = mergedForSave(latest, currentRows, this.persistedBaseline, this.intended)
- const rows = validatedRows([...merged.values()])
+ // A binding may flush an already-staged discovery batch. Every changed row
+ // must still own what the observation claims, not only the hook's own row.
+ const changed = new Set([...this.persistedBaseline.keys(), ...currentRows.keys()].filter(id =>
+ this.persistedBaseline.get(id) !== (currentRows.has(id) ? rowFingerprint(currentRows.get(id)) : undefined)))
+ if (bindingCommit) {
+ const identities = new MergeIdentities(latest)
+ for (const id of changed) {
+ if (confirming && unconfirmed!.affected.has(id)) continue
+ if ((latest.has(id) ? rowFingerprint(latest.get(id)) : undefined) !== this.persistedBaseline.get(id)) {
+ throw new IdentityReadUnavailable('a staged registry observation has a different durable owner')
+ }
+ const candidate = currentRows.has(id) ? strictPersistedRow(currentRows.get(id)) : null
+ if (!candidate) continue
+ const routes = new Set(candidate.runtimes.map(terminalRouteKey))
+ for (const [otherId, other] of identities.sharing(id, candidate.processIdentity?.pid, candidate.sessionId, routes)) {
+ if (changed.has(otherId)) continue
+ if ((other.engine === candidate.engine && sameProcessIdentity(other.processIdentity, candidate.processIdentity))
+ || (!!candidate.sessionId && other.sessionId === candidate.sessionId)
+ || other.runtimes.some(runtime => routes.has(terminalRouteKey(runtime)))) {
+ throw new IdentityReadUnavailable('a staged registry observation conflicts with a newer durable owner')
+ }
+ }
+ }
+ }
+ const merged = [...mergedForSave(latest, currentRows, this.persistedBaseline, this.intended).values()]
+ const rows = validatedRows(merged)
if (!rows) throw new Error('registry transaction would violate global identity invariants')
const serialized = rows.map(persistedRow)
- atomicWriteJson(FILE, serialized)
+ try { atomicWriteJson(FILE, serialized) }
+ catch (error) {
+ if ((bindingCommit || unconfirmed) && error instanceof AtomicWriteUnconfirmed) {
+ const prior = new Map(latest)
+ if (unconfirmed) for (const id of unconfirmed.affected) {
+ const original = unconfirmed.prior.find(row => rowId(row) === id)
+ if (original) prior.set(id, original as Record<string, unknown>)
+ else prior.delete(id)
+ }
+ const image = new Map(serialized.map(row => [rowId(row), row]))
+ const affected = new Set([...prior.keys(), ...image.keys()].filter(id =>
+ (prior.has(id) ? rowFingerprint(prior.get(id)) : undefined)
+ !== (image.has(id) ? rowFingerprint(image.get(id)) : undefined)))
+ this.unconfirmedBinding = {
+ // Own the actual serialized values, never nested objects a later
+ // controller or caller can mutate through its live row/input.
+ image: JSON.parse(JSON.stringify(serialized)), prior: JSON.parse(JSON.stringify([...prior.values()])),
+ agentId: bindingCommit?.agentId ?? unconfirmed!.agentId, intent: intent ?? null,
+ before: beforeCommit, affected,
+ }
+ }
+ throw error
+ }
+ this.unconfirmedBinding = null
this.persistedContents = JSON.stringify(serialized, null, 2)
this.intended.clear()
- // Refresh external daemon-down writes into the in-memory revision without replacing object
- // identities already held by controllers.
+ // External refresh keeps controller references. Registration replaces its target only now:
+ // deferred readers must keep the former home/binding, never inherit the newly admitted one.
const previous = new Map(this.agents)
this.agents.clear()
this.sessionIndex.clear()
this.runtimeIndex.clear()
this.processIndex.clear()
for (const row of rows) {
- const entry = previous.get(row.agentId) ?? row
+ const prior = previous.get(row.agentId)
+ const entry = prior && bindingCommit?.replaceLive && bindingCommit.agentId === row.agentId ? { ...prior } : prior ?? row
if (entry !== row) {
const sameBinding = entry.engine === row.engine && entry.sessionId === row.sessionId
&& entry.transcriptPath === row.transcriptPath && entry.codexHome === row.codexHome
+ const admissionHold = entry.admissionHold
const identityHold = sameBinding ? entry.identityHold : undefined
const interpretationHold = sameBinding ? entry.interpretationHold : undefined
const evidenceRevision = sameBinding ? entry.evidenceRevision : ++this.evidenceRevision
@@ -2636,11 +2833,13 @@ class Registry {
if (!Object.hasOwn(row, key)) delete (entry as unknown as Record<string, unknown>)[key]
}
Object.assign(entry, row)
+ if (admissionHold) entry.admissionHold = admissionHold
if (identityHold) entry.identityHold = identityHold
if (interpretationHold) entry.interpretationHold = interpretationHold
if (evidenceRevision !== undefined) entry.evidenceRevision = evidenceRevision
}
- this.index(entry)
+ this.index(entry, false)
+ entered.push(entry.engine)
}
this.persistedBaseline = new Map(serialized.map((row) => [rowId(row), rowFingerprint(row)]))
})
@@ -2648,6 +2847,8 @@ class Registry {
if (strict) throw err
console.error('[registry] save failed:', err)
}
+ // Optional engine startup observes the complete durable publication, outside the write lock.
+ for (const engine of entered) this.entered(engine)
}
/**
diff --git a/cli/src/lib/registryAdmission.golden.spec.ts b/cli/src/lib/registryAdmission.golden.spec.ts
new file mode 100644
index 000000000..94ba9ad73
--- /dev/null
+++ b/cli/src/lib/registryAdmission.golden.spec.ts
@@ -0,0 +1,95 @@
+/** Former healthy registration and ownership transfers, recorded before atomic admission. */
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from './registry.js'
+
+vi.mock('node:child_process', () => {
+ const forbidden = () => { throw Error('Host binaries are forbidden in the registration golden') }
+ return { exec: forbidden, execSync: forbidden, execFile: forbidden, execFileSync: forbidden,
+ spawn: forbidden, spawnSync: forbidden, fork: forbidden }
+})
+vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => 0 } }))
+vi.mock('./loginShellEnv.js', () => ({ loginShellEnvironment: () => ({}) }))
+vi.mock('./bootId.js', async original => ({ ...await original<object>(), currentBootId: () => 'fixture-boot', bootChanged: () => false }))
+vi.mock('./processLiveness.js', async original => ({ ...await original<object>(),
+ processLockIdentity: () => ({ startMarker: 'fixture-start', generationMarker: 'fixture-generation' }), lockOwnerAlive: () => true,
+}))
+
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/registry-admission.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_REGISTRY_ADMISSION_GOLDEN === '1'
+const expected = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8'))
+const captured: Record<string, unknown> = {}
+const A = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa', B = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
+const C = 'cccccccc-3333-4333-8333-cccccccccccc', CHILD = 'dddddddd-4444-4444-8444-dddddddddddd'
+
+it.each(['linux', 'darwin'])('preserves healthy registration and transfers on %s', async platform => {
+ const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'registry-admission-golden-')))
+ const path = (...parts: string[]) => join(root, ...parts)
+ const write = (file: string, text: string) => {
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); writeFileSync(file, text, { mode: 0o600 })
+ }
+ const labels = new Map<string, string>()
+ const shape = (row: RegisteredSession) => ({ agent: labels.get(row.agentId), engine: row.engine,
+ session: row.sessionId, transcript: row.transcriptPath, cwd: row.cwd, source: row.source,
+ active: row.active, terminalHost: row.terminalHost ?? false })
+ const check = (name: string, value: unknown) => {
+ const key = `${platform}:${name}`
+ let text = JSON.stringify(value ?? null).split(root).join('<root>')
+ for (const [id, label] of labels) text = text.split(id).join(`<${label}>`)
+ captured[key] = JSON.parse(text)
+ if (!RECORD) expect({ key, value: captured[key] }).toEqual({ key, value: expected[key] })
+ }
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ try {
+ Object.defineProperty(process, 'platform', { ...descriptor, value: platform })
+ vi.useFakeTimers({ toFake: ['Date'], now: Date.parse('2026-10-10T00:00:00Z') })
+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR',
+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME']) {
+ mkdirSync(path(name), { recursive: true, mode: 0o700 }); vi.stubEnv(name, path(name))
+ }
+ vi.stubEnv('CLAUDE_PROJECTS_DIR', path('CLAUDE_CONFIG_DIR', 'projects')); vi.stubEnv('TZ', 'UTC')
+ write(path('ADAPTER_DATA_DIR', 'engine-homes.json'), '{}')
+ const codex = path('CODEX_HOME', 'sessions', `rollout-${A}.jsonl`)
+ const child = path('CODEX_HOME', 'sessions', `rollout-${CHILD}.jsonl`)
+ const claude = (id: string) => path('CLAUDE_CONFIG_DIR', 'projects', 'fixture', `${id}.jsonl`)
+ const meta = (id: string, source: unknown = 'cli') => JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, source } }) + '\n'
+ write(codex, meta(A)); write(child, meta(CHILD, { subagent: { thread_spawn: { parent_thread_id: A, depth: 1 } } }))
+ for (const id of [B, C]) write(claude(id), JSON.stringify({ type: 'user', cwd: root, sessionId: id, isSidechain: false }) + '\n')
+ vi.resetModules()
+ const { registry } = await import('./registry.js')
+ for (const [index, engine] of (['claude', 'codex', 'terminal'] as const).entries()) {
+ const { entry } = registry.openProcessAgent({ engine, tmuxPane: `%${index + 1}`, cwd: root,
+ processIdentity: { pid: 4100 + index, startMarker: 'fixture-start', executable: `<${engine}>` } })!
+ labels.set(entry.agentId, engine)
+ }
+ const register = (engine: 'claude' | 'codex', pane: string, id: string, transcriptPath: string, cwd = root) => {
+ const result = registry.register({ engine, tmuxPane: pane, sessionId: id, transcriptPath, cwd, source: 'fixture' })
+ return result && { ...result, entry: shape(result.entry) }
+ }
+ check('first', register('claude', '%1', B, claude(B)))
+ check('same-preserves-folder', register('claude', '%1', B, claude(B), path('temporary-shell-folder')))
+ check('rotation', register('claude', '%1', C, claude(C)))
+ check('terminal-promotion', register('codex', '%3', A, codex))
+ check('move-active', register('codex', '%2', A, codex))
+ check('after-active-move', registry.list().map(shape))
+ registry.setActive(registry.byPaneEngine('%2', 'codex')!.agentId, false)
+ check('move-dormant', register('codex', '%3', A, codex))
+ check('delegated-rejected', register('codex', '%3', CHILD, child))
+ check('final-live', registry.list().map(shape))
+ check('final-saved', JSON.parse(readFileSync(path('ADAPTER_DATA_DIR', 'registry.json'), 'utf8')).map(shape))
+ ;(await import('./engineHomes.js')).resetEngineHomes()
+ } finally {
+ log.mockRestore(); vi.useRealTimers(); vi.unstubAllEnvs(); vi.resetModules()
+ Object.defineProperty(process, 'platform', descriptor)
+ rmSync(root, { recursive: true, force: true })
+ }
+}, 30_000)
+
+afterAll(() => {
+ if (RECORD) writeFileSync(GOLDEN, JSON.stringify(captured, null, 2) + '\n')
+ else expect(Object.keys(captured).sort()).toEqual(Object.keys(expected).sort())
+})
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
index f223b8153..efdcf19dc 100644
--- a/cli/src/lib/stoppedAgents.spec.ts
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -22,10 +22,11 @@ afterEach(() => {
describe('saved catalog reads', () => {
it('saves a held conversation without persisting its transient identity verdict', async () => {
const { saved, store } = await fixture()
- store.save({ ...saved, identityHold: 'The session-home catalog is unavailable.', evidenceRevision: 3, interpretationHold: 'pending' })
+ store.save({ ...saved, identityHold: 'The session-home catalog is unavailable.', evidenceRevision: 3, interpretationHold: 'pending', admissionHold: 'Waiting for native source' })
const raw = JSON.parse(readFileSync(join(directory, 'stopped-agents', `${saved.agentId}.json`), 'utf8'))
expect(raw.session.sessionId).toBe(saved.sessionId)
expect(raw.session).not.toHaveProperty('identityHold')
+ expect(raw.session).not.toHaveProperty('admissionHold')
expect(raw.session).not.toHaveProperty('interpretationHold')
expect(raw.session).not.toHaveProperty('evidenceRevision')
expect(store.get(saved.agentId)).not.toHaveProperty('identityHold')
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
index 69ac73bed..682a0b1bc 100644
--- a/cli/src/lib/stoppedAgents.ts
+++ b/cli/src/lib/stoppedAgents.ts
@@ -149,6 +149,7 @@ export class StoppedAgentStore {
// A later Resume is an explicit new visit, never an instruction to close it again.
delete snapshot.closePlan
// A hold describes this daemon's current observation, never durable conversation evidence.
+ delete snapshot.admissionHold
delete snapshot.identityHold
delete snapshot.interpretationHold
delete snapshot.evidenceRevision
diff --git a/docs/research/2026-10-09-daemon-core-completion.md b/docs/research/2026-10-09-daemon-core-completion.md
index 416b3ac6a..2637693a0 100644
--- a/docs/research/2026-10-09-daemon-core-completion.md
+++ b/docs/research/2026-10-09-daemon-core-completion.md
@@ -22,10 +22,11 @@ This is the remaining completion scope as of October 9, after the six extraction
- [x] Fresh complete native home catalog evidence (#1126); durable writers and legacy consumers remain below.
- [x] Complete native descriptor/process/header ownership evidence (#1131, merged as `9eafacf3b` at October 10 00:33:06 UTC).
- [x] Durable engine-home adoption, crash recovery and core retry (#1132, merged as `c7d460b1d` at October 10 01:43:24 UTC).
+- [x] Saved-binding file/header/root evidence and ordered interpretation recovery (#1133, merged as `a2a7874f3` at October 10 05:16:31 UTC).
## Remaining blockers
-1. **Complete native identity and retry.** Exact transcript lookup and native lock/descriptor enumeration are landed. Durable home adoption and its staged registry batch are [landed](2026-10-10-durable-home-adoption.md). Saved-binding file/header/root evidence and visible retry are [under validation](2026-10-10-saved-binding-evidence.md). Hook admission, remaining saved-home consumers and pending delivery ownership still require migration. The [catalog audit](2026-10-09-native-home-catalog.md) records its fresh-evidence boundary and required remaining caller/writer migration. The native Hermes pool is landed; optional home promotion and shared handle-cache lifetime still need their authority/resource audit. An unreadable or truncated pool cannot prove absence or uniqueness. Every binding entry and transcript poll retains pending work, isolates a failed lookup, and retries without blocking sibling sessions or readiness. Surface the hold reason through the shared session state.
+1. **Complete native identity and retry.** Exact transcript lookup and native lock/descriptor enumeration are landed. Durable home adoption and its staged registry batch are [landed](2026-10-10-durable-home-adoption.md). Saved-binding file/header/root evidence and visible retry are [landed](2026-10-10-saved-binding-evidence.md). Atomic registration and live hook ownership are [under validation](2026-10-10-native-hook-admission.md); restart-persistent hook delivery, remaining saved-home consumers and legacy native-client acknowledgement/order still require migration. The [catalog audit](2026-10-09-native-home-catalog.md) records its fresh-evidence boundary and required remaining caller/writer migration. The native Hermes pool is landed; optional home promotion and shared handle-cache lifetime still need their authority/resource audit. An unreadable or truncated pool cannot prove absence or uniqueness. Every binding entry and transcript poll retains pending work, isolates a failed lookup, and retries without blocking sibling sessions or readiness. Surface the hold reason through the shared session state.
2. **Complete native launch preparation.** Probe executable/version facts asynchronously with a deadline and one confirmed executable snapshot per launch. Failed hook writes/removals hold launch, preserve foreign configuration and are checked consistently by create, fork, restart, retarget, restore and upgrades. Do not memoize an unavailable version as a permanent answer.
3. **Durable manual lifecycle intent and mutation authority.** Preserve create/fork/restart/retarget requests across unavailable services and daemon restart. Publish generated configuration atomically after dependencies are ready. Check immutable session ownership after every relevant await and before native writes, signals and publication. Reconcile unconfirmed OpenCode v2 mutations read-only; unreadable catalogs must not authorize mutation. Cover v1 missing-row/rollback cases and report a confirmed native change followed by failed respawn truthfully.
4. **Close, turns and input stay in core.** Audit OpenCode v2 Close checkpointing against its current conversation store; unavailable checkpoint/activity evidence keeps the live session with its reason. Finish per-engine Stop/turn facts, authority across asynchronous drains, Cursor pending-task persistence, agy backstop control, input verification declarations, and Pi header/argv and unwritten-conversation handling.
diff --git a/docs/research/2026-10-10-hook-admission-cost.json b/docs/research/2026-10-10-hook-admission-cost.json
new file mode 100644
index 000000000..4d967a412
--- /dev/null
+++ b/docs/research/2026-10-10-hook-admission-cost.json
@@ -0,0 +1,746 @@
+[
+ {
+ "workload": "registry",
+ "iterations": 100,
+ "latenciesMs": [
+ 62.227146000000005,
+ 60.01100199999996,
+ 61.72899400000006,
+ 58.77156400000001,
+ 59.435955000000035,
+ 61.29367500000001,
+ 61.01581199999998,
+ 58.98798199999999,
+ 58.757138000000054,
+ 56.330716999999936,
+ 58.75515199999995,
+ 58.78134,
+ 62.03055099999983,
+ 59.16058699999985,
+ 57.025875999999926,
+ 65.53222900000014,
+ 59.21973200000002,
+ 62.94617999999991,
+ 59.720947000000024,
+ 57.305368000000044,
+ 58.50589100000002,
+ 63.161157,
+ 60.33510299999989,
+ 60.997200999999905,
+ 62.48582899999997,
+ 57.67721599999982,
+ 64.67001699999992,
+ 59.933091000000104,
+ 59.36031400000002,
+ 55.720716999999695,
+ 59.772611000000325,
+ 56.30802500000027,
+ 57.56786599999987,
+ 58.73984299999984,
+ 60.39079700000002,
+ 59.676168999999845,
+ 61.10662200000024,
+ 61.918959000000086,
+ 61.72871599999962,
+ 59.879175999999916,
+ 59.690935999999965,
+ 61.37589500000013,
+ 61.05233300000009,
+ 59.85095799999999,
+ 58.863308999999845,
+ 58.60241399999995,
+ 59.42910900000015,
+ 60.4362170000004,
+ 59.30569199999991,
+ 59.845774999999776,
+ 59.615729999999985,
+ 57.13502299999982,
+ 60.021209,
+ 57.69165499999963,
+ 61.42288600000029,
+ 60.39604300000019,
+ 60.31748500000003,
+ 61.46136699999988,
+ 60.2636480000001,
+ 57.47491500000024,
+ 61.29308399999991,
+ 58.022034000000076,
+ 61.23503600000049,
+ 58.426618999999846,
+ 57.75644899999952,
+ 58.781488000000536,
+ 61.06991099999959,
+ 60.828222000000096,
+ 57.395550000000185,
+ 56.97765199999958,
+ 57.286777999999686,
+ 59.88387999999941,
+ 58.79183400000056,
+ 58.74870499999997,
+ 77.9989940000005,
+ 64.84063999999944,
+ 76.05649199999971,
+ 78.80578199999945,
+ 83.36075899999923,
+ 60.376986000000215,
+ 58.316273999999794,
+ 57.340298000000075,
+ 56.95856999999978,
+ 61.768049999999675,
+ 60.88668899999993,
+ 61.30154499999935,
+ 64.16118300000016,
+ 64.19352900000013,
+ 62.11357700000008,
+ 63.95379799999955,
+ 63.484762000000046,
+ 60.316593999999895,
+ 59.77108099999987,
+ 57.91854700000022,
+ 58.071985000000495,
+ 60.59581900000012,
+ 59.24576900000011,
+ 58.26841299999978,
+ 60.5137279999999,
+ 58.29443999999967
+ ],
+ "responseMs": [],
+ "cpuMs": 406.502,
+ "peakRssMiB": 104.65625,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "durableAdmissions": 100,
+ "notifications": 0
+ },
+ "source": "main",
+ "sha": "cc4983e1893494a653f84d861950efe5d6913590",
+ "wallSeconds": 6.477925777435303
+ },
+ {
+ "workload": "http",
+ "iterations": 100,
+ "latenciesMs": [
+ 80.38785899999999,
+ 63.38868200000002,
+ 65.28164699999996,
+ 60.6108660000001,
+ 66.05870799999991,
+ 64.54553399999998,
+ 63.10092899999995,
+ 64.22177099999999,
+ 67.97066900000004,
+ 60.50504799999999,
+ 62.57503800000006,
+ 61.33929499999999,
+ 60.36670300000014,
+ 62.14445300000011,
+ 59.64655599999992,
+ 60.82643400000006,
+ 63.32025399999998,
+ 63.39061000000015,
+ 64.96404599999983,
+ 62.220762999999806,
+ 61.33413900000005,
+ 61.056252000000086,
+ 59.77086299999996,
+ 60.806249999999864,
+ 60.86410499999988,
+ 60.30166299999996,
+ 58.31864499999983,
+ 61.16823199999976,
+ 61.23152100000016,
+ 60.628941000000395,
+ 62.712027000000035,
+ 62.03119599999991,
+ 62.59453199999962,
+ 48.56829299999981,
+ 63.95084199999974,
+ 60.47062000000005,
+ 60.6764790000002,
+ 65.08219000000008,
+ 65.09798199999977,
+ 63.35004899999967,
+ 62.70293300000003,
+ 65.80703700000004,
+ 60.513470000000325,
+ 61.959029999999984,
+ 60.58581800000002,
+ 60.835691000000224,
+ 61.71112799999992,
+ 60.82654599999978,
+ 59.2838569999999,
+ 60.36378500000001,
+ 60.48995599999989,
+ 61.17831299999989,
+ 61.50302599999986,
+ 61.29343699999981,
+ 61.04633899999999,
+ 60.59869400000025,
+ 60.18587600000001,
+ 60.52889899999991,
+ 63.37417199999982,
+ 60.043290999999954,
+ 98.86257800000021,
+ 75.73995300000024,
+ 60.58269100000052,
+ 62.75119099999938,
+ 59.573341000000255,
+ 59.48888600000009,
+ 59.89220999999998,
+ 61.61370599999918,
+ 61.88959299999988,
+ 59.53135399999974,
+ 60.47838000000047,
+ 61.0401269999993,
+ 60.64593799999966,
+ 59.87776399999984,
+ 59.905393000000004,
+ 59.869582000000264,
+ 60.90919899999972,
+ 60.39239799999996,
+ 59.35341100000005,
+ 62.698435999999674,
+ 45.07537300000058,
+ 60.90761400000065,
+ 60.6447790000002,
+ 61.83678299999974,
+ 61.37755700000071,
+ 60.94675600000028,
+ 60.254195000000436,
+ 61.302670000000035,
+ 59.97287099999994,
+ 60.747261999999864,
+ 61.18999299999996,
+ 63.409709999999905,
+ 63.71958199999972,
+ 63.01025200000004,
+ 64.29894000000058,
+ 62.14159000000018,
+ 63.24572799999987,
+ 63.756884000000355,
+ 64.17312399999992,
+ 63.55961100000059
+ ],
+ "responseMs": [
+ 80.37205499999999,
+ 63.38419700000003,
+ 65.27714999999995,
+ 60.606509000000074,
+ 66.05444399999999,
+ 64.54113399999994,
+ 63.09666600000003,
+ 64.21758299999999,
+ 67.96590100000003,
+ 60.500436000000036,
+ 62.57203100000004,
+ 61.334249999999884,
+ 60.364647000000105,
+ 62.142185000000154,
+ 59.64437799999996,
+ 60.824149000000034,
+ 63.316125000000056,
+ 63.386282000000165,
+ 64.961456,
+ 62.21862299999998,
+ 61.33106500000008,
+ 61.05405400000018,
+ 59.768450999999914,
+ 60.804079,
+ 60.86205999999993,
+ 60.29959800000006,
+ 58.316712999999936,
+ 61.166022999999996,
+ 61.229413999999906,
+ 60.62630100000024,
+ 62.70977200000016,
+ 62.02839199999971,
+ 62.59097899999961,
+ 48.56484499999988,
+ 63.94848400000001,
+ 60.46825900000022,
+ 60.67239100000006,
+ 65.07304000000022,
+ 65.09515599999986,
+ 63.34691900000007,
+ 62.69887999999992,
+ 65.80489400000033,
+ 60.51077000000032,
+ 61.9548420000001,
+ 60.58383600000025,
+ 60.833120000000235,
+ 61.70709100000022,
+ 60.82453600000008,
+ 59.2817399999999,
+ 60.36117999999988,
+ 60.4876049999998,
+ 61.1759219999999,
+ 61.500718000000234,
+ 61.29097199999978,
+ 61.04435400000011,
+ 60.5956070000002,
+ 60.18364199999996,
+ 60.52591799999982,
+ 63.37228999999979,
+ 60.04054499999984,
+ 98.85942599999998,
+ 75.73773100000017,
+ 60.58040400000027,
+ 62.7489829999995,
+ 59.57140799999979,
+ 59.486541000000216,
+ 59.889273000000685,
+ 61.60968099999991,
+ 61.88760699999966,
+ 59.52923399999963,
+ 60.47631999999976,
+ 61.03782499999943,
+ 60.643662000000404,
+ 59.87585499999932,
+ 59.90291100000013,
+ 59.86747000000014,
+ 60.906746999999996,
+ 60.39007700000002,
+ 59.35071599999992,
+ 62.696507999999994,
+ 45.07291500000065,
+ 60.905439000000115,
+ 60.640221999999994,
+ 61.83459500000026,
+ 61.37508400000024,
+ 60.94299500000034,
+ 60.25165300000026,
+ 61.300350000000435,
+ 59.970720000000256,
+ 60.74426399999993,
+ 61.187190999999984,
+ 63.405517999999574,
+ 63.71577399999933,
+ 63.006225999999515,
+ 64.2958520000002,
+ 62.13854199999969,
+ 63.24201499999981,
+ 63.7525169999999,
+ 64.1689980000001,
+ 63.55736100000013
+ ],
+ "cpuMs": 575.841,
+ "peakRssMiB": 127.05859375,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "durableAdmissions": 100,
+ "notifications": 100
+ },
+ "source": "main",
+ "sha": "cc4983e1893494a653f84d861950efe5d6913590",
+ "wallSeconds": 6.6110920906066895
+ },
+ {
+ "workload": "held",
+ "iterations": 5,
+ "latenciesMs": [
+ 580.495032,
+ 562.021465,
+ 564.0642139999998,
+ 565.3723890000001,
+ 565.86661
+ ],
+ "responseMs": [
+ 19.892968999999994,
+ 3.1590889999999945,
+ 3.4567070000000513,
+ 4.028769000000011,
+ 4.530565000000024
+ ],
+ "cpuMs": 125.619,
+ "peakRssMiB": 116.92578125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "durableAdmissions": 5,
+ "notifications": 5
+ },
+ "source": "main",
+ "sha": "cc4983e1893494a653f84d861950efe5d6913590",
+ "wallSeconds": 3.245429039001465
+ },
+ {
+ "workload": "registry",
+ "iterations": 100,
+ "latenciesMs": [
+ 66.71751500000005,
+ 60.98560200000003,
+ 59.60834899999992,
+ 67.10909200000003,
+ 61.09513400000003,
+ 59.52983300000005,
+ 61.318811000000096,
+ 63.97253999999998,
+ 63.740696999999955,
+ 60.08265099999994,
+ 61.23774300000014,
+ 60.944749,
+ 61.380775000000085,
+ 62.02612399999998,
+ 60.556467999999995,
+ 63.11309600000004,
+ 61.961693000000196,
+ 63.4380470000001,
+ 61.73517300000003,
+ 43.32680299999993,
+ 60.60576900000001,
+ 60.378195000000005,
+ 76.96750799999995,
+ 61.70967799999994,
+ 61.32290799999987,
+ 62.835489999999936,
+ 62.767972999999984,
+ 63.20650999999998,
+ 63.27283299999999,
+ 59.49965399999974,
+ 58.857942000000094,
+ 59.4076570000002,
+ 58.84505600000011,
+ 58.900286999999935,
+ 59.857294000000365,
+ 61.65599199999997,
+ 58.23200900000029,
+ 62.3589420000003,
+ 60.73036600000023,
+ 61.57096599999977,
+ 59.442323000000215,
+ 61.30495599999995,
+ 62.62505600000031,
+ 60.6734120000001,
+ 64.33108099999981,
+ 60.144002999999884,
+ 58.726298999999926,
+ 60.00127599999996,
+ 114.596904,
+ 80.42312599999968,
+ 60.47222499999998,
+ 62.388332999999875,
+ 62.568432999999914,
+ 61.643258999999944,
+ 59.448579999999765,
+ 45.21274399999993,
+ 58.561061999999765,
+ 60.558106999999836,
+ 61.89254000000028,
+ 60.84747299999981,
+ 62.49319099999957,
+ 61.42570000000069,
+ 60.4366229999996,
+ 62.520862999999736,
+ 61.58367899999939,
+ 60.5922870000004,
+ 63.46381399999973,
+ 61.33789400000023,
+ 61.296495000000505,
+ 60.4084069999999,
+ 60.3003090000002,
+ 63.37120099999993,
+ 62.8862909999998,
+ 62.7047649999995,
+ 60.41553399999975,
+ 61.05287500000031,
+ 59.70291499999985,
+ 61.46955500000058,
+ 61.44969500000025,
+ 63.558069999999134,
+ 62.47327299999961,
+ 60.81489099999999,
+ 61.71289799999977,
+ 63.76010599999972,
+ 62.328787000000375,
+ 61.38546999999926,
+ 62.62548799999968,
+ 60.962758000000576,
+ 61.377878999999666,
+ 60.281864999999925,
+ 61.312018999999964,
+ 59.194320999999945,
+ 60.609269999999924,
+ 59.05454099999952,
+ 57.8637949999993,
+ 60.44441199999983,
+ 62.844200999999885,
+ 61.36313700000028,
+ 61.06860699999925,
+ 59.88551600000028
+ ],
+ "responseMs": [],
+ "cpuMs": 558.4609999999999,
+ "peakRssMiB": 110.52734375,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "durableAdmissions": 100,
+ "notifications": 0
+ },
+ "source": "change",
+ "sha": "08afe262bfc21966a35917c59416c307f87b8e9c",
+ "wallSeconds": 6.58207106590271
+ },
+ {
+ "workload": "http",
+ "iterations": 100,
+ "latenciesMs": [
+ 85.13941799999998,
+ 66.16193600000003,
+ 74.066712,
+ 65.81210799999997,
+ 63.864341999999965,
+ 62.44590500000004,
+ 63.60655100000008,
+ 65.27582099999995,
+ 68.818671,
+ 65.329925,
+ 61.43799399999989,
+ 61.40187500000002,
+ 60.427885999999944,
+ 61.960669999999936,
+ 64.23694699999987,
+ 61.66049700000008,
+ 66.573398,
+ 67.71674199999984,
+ 67.42506600000002,
+ 66.32549399999994,
+ 67.57870900000012,
+ 65.6435039999999,
+ 60.17171899999994,
+ 62.14241700000002,
+ 62.772519999999986,
+ 61.72082299999988,
+ 61.00287299999991,
+ 63.32989499999985,
+ 61.921965,
+ 61.320190999999795,
+ 63.19334299999991,
+ 63.58189799999991,
+ 62.134897999999794,
+ 61.44411900000023,
+ 62.552020000000084,
+ 62.07730300000003,
+ 62.11451999999963,
+ 63.672659000000294,
+ 62.77239300000019,
+ 62.75873899999988,
+ 64.41096099999959,
+ 61.946496000000025,
+ 61.813740999999936,
+ 61.35491000000002,
+ 60.99325900000031,
+ 61.426212999999734,
+ 62.00598800000034,
+ 60.97267000000011,
+ 60.66827299999977,
+ 60.845986000000266,
+ 61.09220099999993,
+ 61.07160500000009,
+ 62.64037499999995,
+ 65.56079999999974,
+ 63.240408000000116,
+ 63.49509500000022,
+ 66.93058900000005,
+ 62.793048,
+ 60.96393799999987,
+ 64.45734700000048,
+ 63.8676889999997,
+ 62.49156999999923,
+ 64.83628899999985,
+ 63.403080000000045,
+ 64.46810699999969,
+ 59.27837400000044,
+ 60.80405299999984,
+ 63.028292999999394,
+ 67.46565800000008,
+ 62.681306000000404,
+ 64.37120400000003,
+ 65.82578300000023,
+ 64.75962699999945,
+ 47.87404400000014,
+ 62.86025900000004,
+ 62.985045000000355,
+ 60.88833699999941,
+ 60.23710200000005,
+ 63.318272000000434,
+ 60.87106700000004,
+ 66.4668700000002,
+ 77.30362500000047,
+ 62.42233800000031,
+ 63.16861599999993,
+ 65.76904699999977,
+ 64.47849099999985,
+ 62.1709409999994,
+ 63.46340800000053,
+ 62.430003999999826,
+ 61.22395200000028,
+ 63.11972100000003,
+ 63.65152500000022,
+ 64.5330100000001,
+ 64.64077200000065,
+ 59.04634100000021,
+ 60.02214699999968,
+ 46.02825099999973,
+ 63.07804599999963,
+ 63.78760599999987,
+ 62.39717300000029
+ ],
+ "responseMs": [
+ 85.12395499999997,
+ 66.15891000000005,
+ 74.06081699999999,
+ 65.80631699999992,
+ 63.86107800000002,
+ 62.44269899999995,
+ 63.60375900000008,
+ 65.26939200000004,
+ 68.81325800000002,
+ 65.32588499999997,
+ 61.43491199999994,
+ 61.396285000000034,
+ 60.42592600000012,
+ 61.958439,
+ 64.23467000000005,
+ 61.658157000000074,
+ 66.56960500000014,
+ 67.71386599999983,
+ 67.42204300000003,
+ 66.32132699999988,
+ 67.57564500000012,
+ 65.63974800000005,
+ 60.169639999999845,
+ 62.140452000000096,
+ 62.77004299999999,
+ 61.718610000000126,
+ 61.000846999999794,
+ 63.3279749999997,
+ 61.91987500000005,
+ 61.31795299999976,
+ 63.19125800000029,
+ 63.579919999999674,
+ 62.133038999999826,
+ 61.442083000000366,
+ 62.547141999999894,
+ 62.073687000000064,
+ 62.11070899999959,
+ 63.67021300000033,
+ 62.76830400000017,
+ 62.756409000000076,
+ 64.40859,
+ 61.94462199999998,
+ 61.81148299999995,
+ 61.352510000000166,
+ 60.9915060000003,
+ 61.424352,
+ 62.00261300000011,
+ 60.970570999999836,
+ 60.66641600000003,
+ 60.84369700000025,
+ 61.0895859999996,
+ 61.06887300000017,
+ 62.63754400000016,
+ 65.55727200000001,
+ 63.2368620000002,
+ 63.49100300000009,
+ 66.92783899999995,
+ 62.79097199999978,
+ 60.96189200000026,
+ 64.45363100000031,
+ 63.86397600000055,
+ 62.48788799999966,
+ 64.82590600000003,
+ 63.40008300000045,
+ 64.46442899999965,
+ 59.27618500000062,
+ 60.80207599999994,
+ 63.02415799999926,
+ 67.46280900000056,
+ 62.67929499999991,
+ 64.36744499999986,
+ 65.82221300000037,
+ 64.75600899999972,
+ 47.870426999999836,
+ 62.85833300000013,
+ 62.98269700000037,
+ 60.88645699999961,
+ 60.23470600000019,
+ 63.314524999999776,
+ 60.86718999999994,
+ 66.46382499999982,
+ 77.30180300000029,
+ 62.41987400000016,
+ 63.16570799999954,
+ 65.76490300000023,
+ 64.47641899999962,
+ 62.16695399999935,
+ 63.46076600000015,
+ 62.42782999999963,
+ 61.22167300000001,
+ 63.11594299999979,
+ 63.647893000000295,
+ 64.53034099999968,
+ 64.63880700000027,
+ 59.04441300000053,
+ 60.02009999999973,
+ 46.02518599999985,
+ 63.07422799999949,
+ 63.784771999999975,
+ 62.393622000000505
+ ],
+ "cpuMs": 749.063,
+ "peakRssMiB": 123.61328125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "durableAdmissions": 100,
+ "notifications": 100
+ },
+ "source": "change",
+ "sha": "08afe262bfc21966a35917c59416c307f87b8e9c",
+ "wallSeconds": 6.732025146484375
+ },
+ {
+ "workload": "held",
+ "iterations": 5,
+ "latenciesMs": [
+ 1084.454477,
+ 1073.198909,
+ 1073.0615359999997,
+ 1065.2224610000003,
+ 1068.4344350000001
+ ],
+ "responseMs": [
+ 26.369906000000015,
+ 4.8048140000000785,
+ 6.041315999999824,
+ 5.5768479999997,
+ 4.532913000000008
+ ],
+ "cpuMs": 163.626,
+ "peakRssMiB": 114.46875,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "durableAdmissions": 5,
+ "notifications": 5
+ },
+ "source": "change",
+ "sha": "08afe262bfc21966a35917c59416c307f87b8e9c",
+ "wallSeconds": 5.766082048416138
+ }
+]
diff --git a/docs/research/2026-10-10-hook-admission-cost.mts b/docs/research/2026-10-10-hook-admission-cost.mts
new file mode 100644
index 000000000..b7188413d
--- /dev/null
+++ b/docs/research/2026-10-10-hook-admission-cost.mts
@@ -0,0 +1,90 @@
+/** Matched complete registry/HTTP admissions. Private files and port; no daemon or real host binaries. */
+import childProcess from 'node:child_process'
+import { syncBuiltinESMExports } from 'node:module'
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { performance } from 'node:perf_hooks'
+import { pathToFileURL } from 'node:url'
+
+const workload = process.argv[2] ?? 'registry'
+if (!['registry', 'http', 'held'].includes(workload)) throw Error('Unknown workload')
+const cli = process.env.ADMISSION_COST_CLI ?? resolve('cli')
+const root = realpathSync(mkdtempSync(join(tmpdir(), 'hook-admission-cost-')))
+const hostPlatform = process.platform
+Object.defineProperty(process, 'platform', { value: 'linux' })
+const forbidden = () => { throw Error('Host binaries are forbidden in the admission measurement') }
+Object.assign(childProcess, { exec: forbidden, execSync: forbidden, execFile: forbidden, spawn: forbidden,
+ spawnSync: forbidden, fork: forbidden, execFileSync: (file: string, args: string[]) => {
+ if (file === 'ps' && args.join(' ') === `-p ${process.pid} -o lstart=`) return 'fixture-start'
+ return forbidden()
+ } })
+syncBuiltinESMExports()
+for (const key of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR',
+ 'HARNESS_HOOK_ROUTES_DIR', 'HARNESS_AUTH_DIR', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME',
+ 'CURSOR_HOME', 'CURSOR_CONFIG_DIR', 'CURSOR_DATA_DIR', 'HERMES_HOME', 'PI_HOME', 'MUSE_HOME', 'GROK_HOME',
+ 'COMMANDCODE_HOME', 'AGY_HOME', 'AGY_CONFIG_DIR', 'COPILOT_HOME', 'AMP_SESSIONS_DIR', 'OPENCODE_DATA_DIR',
+ 'OPENCODE_PLUGIN_DIR', 'KILO_DATA_DIR', 'KILO_PLUGIN_DIR', 'DEVIN_HOME', 'DEVIN_CONFIG_PATH']) {
+ process.env[key] = join(root, key); mkdirSync(process.env[key]!, { recursive: true, mode: 0o700 })
+}
+for (const key of ['TMUX', 'TMUX_PANE']) delete process.env[key]
+process.env.CLAUDE_PROJECTS_DIR = join(process.env.CLAUDE_CONFIG_DIR!, 'projects')
+process.env.HARNESS_CONNECTIONS_PORT = '0'; process.env.TZ = 'UTC'
+console.log = () => {}
+let server: import('node:http').Server | undefined
+try {
+ const load = (part: string) => import(pathToFileURL(join(cli, 'src', part)).href)
+ const { SYSTEM_BOOT_SOURCES } = await load('lib/bootId.ts')
+ Object.assign(SYSTEM_BOOT_SOURCES, { linuxBootId: () => 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa', bootTimeSec: () => 1 })
+ const { registry } = await load('lib/registry.ts')
+ const id = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
+ mkdirSync(join(process.env.CODEX_HOME!, 'sessions'))
+ const file = join(process.env.CODEX_HOME!, 'sessions', `rollout-${id}.jsonl`)
+ const header = JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, source: 'cli' } }) + '\n'
+ writeFileSync(file, header)
+ writeFileSync(join(process.env.ADAPTER_DATA_DIR!, 'engine-homes.json'), '{}')
+ const agent = registry.openProcessAgent({ engine: 'codex', tmuxPane: '%1', cwd: root,
+ processIdentity: { pid: 4101, startMarker: 'fixture-start', executable: '<codex>' } })!.entry
+ const body = { engine: 'codex', sessionId: id, transcriptPath: file, tmuxPane: '%1', cwd: root }
+ let registered = 0, endpoint = '', token = ''
+ if (workload !== 'registry') {
+ const { startHookServer } = await load('hookServer.ts'), { readHookCredential } = await load('lib/hookAuth.ts')
+ const started = await startHookServer(0, { onRegistered: () => { registered++ }, onSessionEnd: () => {} })
+ server = started.server; endpoint = `http://127.0.0.1:${started.port}/api/hook/session-start`
+ token = readHookCredential(process.env.ADAPTER_DATA_DIR!)
+ }
+ const iterations = workload === 'held' ? 5 : 100
+ const latenciesMs: number[] = [], responseMs: number[] = []
+ let cpuMs = 0
+ for (let i = 0; i < iterations; i++) {
+ const request = { ...body, title: `fixture ${i}`, hookEvent: 'UserPromptSubmit', prompt: `fixture ${i}` }
+ if (workload === 'held') rmSync(file)
+ const cpu = process.cpuUsage(), started = performance.now()
+ if (workload === 'registry') {
+ if (registry.register(request)?.entry.agentId !== agent.agentId) throw Error('Registration was not completed')
+ } else {
+ const response = await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json',
+ 'x-harness-hook-token': token, 'x-harness-hook-fired-at': String(Date.now()),
+ 'x-harness-hook-delivery-id': `fixture-delivery-${String(i).padStart(6, '0')}` }, body: JSON.stringify(request) })
+ const reply = await response.json() as { ok?: boolean; pending?: boolean }
+ responseMs.push(performance.now() - started)
+ if (response.status !== 200 || !(workload === 'held' ? reply.pending : reply.ok)) throw Error('Unexpected admission response')
+ if (workload === 'held') {
+ writeFileSync(file, header)
+ const deadline = performance.now() + 5_000
+ while (registered <= i && performance.now() < deadline) await new Promise(done => setTimeout(done, 10))
+ }
+ if (registered !== i + 1) throw Error('The admitted delivery was not notified exactly once')
+ }
+ latenciesMs.push(performance.now() - started)
+ const used = process.cpuUsage(cpu); cpuMs += (used.user + used.system) / 1000
+ const rows = JSON.parse(readFileSync(join(process.env.ADAPTER_DATA_DIR!, 'registry.json'), 'utf8'))
+ if (!rows.some((row: { agentId: string; sessionId: string }) => row.agentId === agent.agentId && row.sessionId === id)) throw Error('Durable binding missing')
+ }
+ process.stdout.write(JSON.stringify({ workload, iterations, latenciesMs, responseMs, cpuMs,
+ peakRssMiB: process.resourceUsage().maxRSS / 1024, node: process.version, hostPlatform, evidencePlatform: process.platform,
+ arch: process.arch, outcomes: { durableAdmissions: iterations, notifications: registered } }) + '\n')
+} finally {
+ if (server) await new Promise<void>(done => server!.close(() => done()))
+ rmSync(root, { recursive: true, force: true })
+}
diff --git a/docs/research/2026-10-10-native-hook-admission.md b/docs/research/2026-10-10-native-hook-admission.md
new file mode 100644
index 000000000..b978d523e
--- /dev/null
+++ b/docs/research/2026-10-10-native-hook-admission.md
@@ -0,0 +1,143 @@
+# Native hook admission and atomic registration
+
+This change follows saved-binding recovery (#1133). It makes registration atomic
+and gives the live core ownership of pending native admissions. It does not complete
+the restart-persistent native delivery journal or the remaining launch/control audit
+in the [completion checklist](2026-10-09-daemon-core-completion.md).
+
+## Former behavior and goldens
+
+The former core HTTP admission golden was recorded from main `c7d460b1d` in
+`d331c49a4`; #1133 already carries its unchanged artifact. The additional former
+registration golden, `dba98c53d`, records twenty Linux/macOS observations of first
+bind, repeat bind, rotation, terminal promotion, active and dormant ownership
+transfer, delegated rejection, and resulting live/durable rows. Both platform
+values are explicit, host binaries are forbidden, and runs use UTC and private
+roots under `/tmp`. Neither golden artifact changes with this implementation.
+
+Former registration could publish a terminal promotion or release an owner before
+a save whose errors were contained. Ordinary hooks credited prompts before that
+save, and missing-file admission abandoned its retry after twenty attempts. The
+Hermes queue likewise advanced accepted order before its registration callback
+committed. These paths could report success without owning the resulting work.
+
+## Transaction and live admission
+
+Registration prepares every affected row without mutating live state. Its registry
+lock compares the original durable owners, rechecks complete native evidence,
+validates the combined ownership indices, and atomically writes the full batch.
+Only a successful durable commit publishes the new rows. A rename followed by an
+uncertain directory sync retains a deep receipt of the written and prior images.
+The next strict operation confirms, reverses, or reconciles that affected ownership
+group while preserving unrelated peer writes. A peer-changed group revokes the
+stale operation, including a draft that would displace one of its owners.
+
+Every ordinary and Hermes admission uses the same core queue. A failed source or
+commit retains its original body, process incarnation, native order and delivery
+ID. Distinct prompt deliveries remain ordered; ambiguous competing conversations
+are revisited fairly. A same-process route change refreshes the inspected routing,
+while loss of the original hinted pane holds the job. Inspection and commit are
+fenced to the binding revision. Stop owns its admission fence before its first
+asynchronous operation. Prompt credit and optional registration notifications occur
+only after durable binding, and a notification failure cannot replay the commit.
+
+Admission holds are visible in session frames without changing binding authority.
+Reasons belong to individual deliveries, so completing one cannot hide another.
+They are transient and excluded from registry and stopped-session persistence.
+Native process-resolution waits and queue/receipt pressure explicitly say that
+admission is not queued; they do not claim ownership of an unretained delivery.
+
+## Linked Stop and cancellation
+
+Cursor and Command Code's catch hooks register and deliver Stop under one immutable
+native ID. Delayed, newly bound, rebuilding or missing interpretation retains the
+unmatched completion in the eager core before attachment can install a later turn.
+It stays visibly held rather than guessing which recovered turn to close. A failed
+status announcement cannot replay that retained obligation after explicit Cancel.
+
+For an already-bound conversation, a preliminary lookup captures a revocation-only
+Cancel witness before process resolution yields. It applies only if the subsequently
+proved process and conversation match. Cancel or forget revokes it before queued
+commit and before/after follow-up verification. Concurrent registration retries
+share the original witness. Completion claims are checked again after awaits; a
+duplicate acknowledgement cannot invoke Stop or clear a newer Cursor task journal.
+A native linked Stop whose registration was not retained receives an unowned retry
+response instead of bypassing admission through the legacy standalone endpoint.
+
+The private Cursor e2e exercises the actual daemon's capture/Cancel wiring, its
+native process proof and transcript watcher. The private Codex e2e places a directory
+at its own registry file path, observes the admission reason in a real session frame,
+and verifies that the exact prompt commits after that fixture failure is removed.
+
+## Bounds and remaining work
+
+The live server bounds receipt count to 65,536 and retained native payload/provenance
+to 16 MiB, with a separate bounded admission queue. Accepted receipts last for their
+process incarnation; they are not evicted to make a duplicate look like a new event.
+Each lookup retry is bounded, readiness waits on none of them, and a full queue
+returns explicit unowned backpressure. Process exit/replacement prunes receipts.
+
+This ownership is **in memory**. A daemon restart still requires a durable delivery
+journal and native-client acknowledgement/retry migration. Both currently generated
+and already-running OpenCode, Kilo, Pi and Amp plugins still need immutable callback
+IDs/native order. A timestamp-less conflicting hook currently holds with a reload
+explanation, but reloading this build does not resolve that missing client protocol.
+That client migration and the corrected recovery explanation are required before release.
+Unknown Stop-to-turn correlation remains visible until authoritative native evidence
+or explicit Cancel resolves it. Per-engine close facts, asynchronous drain authority,
+and complete Cursor task journal ordering remain in the completion checklist.
+
+## Measured cost
+
+The [matched workload](2026-10-10-hook-admission-cost.mts) ran alone under
+Node 22.23.2, UTC and `/tmp`, on the same macOS x64 host. Native-evidence platform
+is pinned to Linux and host executables are replaced with placeholders. Each tree
+runs a fresh process for each workload: 100 complete registry admissions, 100 complete
+private HTTP admissions, and five held admissions followed by recovery. Each workload
+repeats admission for the same agent and conversation; every iteration asserts durable
+admission and callback counts. Baseline is main `cc4983e18`; implementation is
+`08afe262b`. [Raw measurements](2026-10-10-hook-admission-cost.json) retain every sample.
+Medians average the two middle samples for even counts. Reported p95 uses the sorted
+sample at zero-based index `floor((n - 1) * 0.95)`; for five recovery samples, that is
+the fourth observation, not the maximum.
+
+| Workload | Tree | Median completion (ms) | p95 completion (ms) | Total CPU (ms) | Peak RSS (MiB) |
+| --- | --- | ---: | ---: | ---: | ---: |
+| registry (100) | main | 59.87 | 64.84 | 406.50 | 104.66 |
+| http (100) | main | 61.18 | 65.81 | 575.84 | 127.06 |
+| held (5) | main | 565.37 | 565.87 | 125.62 | 116.93 |
+| registry (100) | change | 61.32 | 64.33 | 558.46 | 110.53 |
+| http (100) | change | 62.83 | 67.58 | 749.06 | 123.61 |
+| held (5) | change | 1073.06 | 1073.20 | 163.63 | 114.47 |
+
+Healthy median completion increased by 1.45 ms for direct registration and 1.64 ms
+for HTTP admission. Total CPU increased by 151.96 ms and 173.22 ms across 100
+admissions respectively, with the added native evidence and strict durable commit.
+Held HTTP responses still returned immediately (median 4.03 ms before, 5.58 ms
+after). Recovery moved from the former 500 ms retry to the shared queue's 1 s
+cadence; the queue retains the delivery instead of abandoning it after twenty tries.
+Five recovery samples are descriptive, not a statistical performance threshold.
+These are private-fixture costs, not a benchmark of installed vendor engines.
+
+The before-file startup correction preserves Command Code, Grok, agy and Copilot's
+deterministic locators while their directories are still unwritten. That narrow
+exception retains the first missing component, surviving owned ancestry and alias
+proofs, and rechecks them under the registry lock. Reported paths and existing
+files still require their ordinary complete evidence.
+
+## Validation and landing
+
+Planned gates: types; architecture; per-file core/services and harnessd coverage;
+affected hook, registry, watcher, worker and native specs; unchanged goldens; composed
+resume; private hookclient, races, engine-home, machine, chaos and tmux lanes. The
+mutation runner requires a passing baseline and assertion failure for deliberately
+broken proof, commit, queue, cancellation and notification wiring. Matched complete
+registry/HTTP/held-admission costs run separately and alone. A frozen head receives
+independent review and every required CI check before the authorized merge.
+
+Validation, exact-head final attestation and merge receipts are pending. Independent
+source review approved `08afe262b` against `cc4983e18`, conditional on the gates. Record
+implementation, validation, review/CI waiting, merge and publication separately.
+The former golden was recorded at 04:33 UTC on October 10; this implementation
+continued after #1133 merged at 05:16 UTC. Publication remains zero; no release is
+authorized.