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.

Preserve transcript evidence through Stop, Resume and Close (#1139)

Deed852e1d9998e
diff --git a/cli/e2e/ends.e2e.ts b/cli/e2e/ends.e2e.ts
index a8401ca51..657588809 100644
--- a/cli/e2e/ends.e2e.ts
+++ b/cli/e2e/ends.e2e.ts
@@ -5,7 +5,7 @@
* that finds a conversation until it is purged. A close never takes a turn that is still working unless
* it was asked to; a purge leaves nothing of the conversation behind.
*/
-import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'
+import { existsSync, mkdirSync, readdirSync, readFileSync, 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'
@@ -91,6 +91,43 @@ describe('how an agent\'s life ends', () => {
client.close()
})
+ it.each(engines)('%s: unavailable transcript identity holds Close and Resume until the same conversation is restored', async engine => {
+ const d = await fresh()
+ const client = await LocalClient.connect(d)
+ const agent = await create(d, client, engine, `identity-hold-${engine}`)
+ await turn(client, agent.id, 'History that must survive')
+ const paths = transcriptsOf(d, agent.sessionId)
+ expect(paths).toHaveLength(1)
+ const file = paths[0], original = readFileSync(file, 'utf8')
+ const lines = original.split('\n'), first = JSON.parse(lines[0])
+ if (engine === 'codex') first.payload.id = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
+ else first.sessionId = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
+ lines[0] = JSON.stringify(first)
+ const foreign = lines.join('\n')
+ writeFileSync(file, foreign)
+ expect(await close(client, agent, 'now')).toMatchObject({ error: 'IDENTITY_UNAVAILABLE', detail: expect.any(String) })
+ expect(await row(client, agent.id)).toMatchObject({ status: 'active', sessionId: agent.sessionId })
+ expect(client.frames.filter(frame => frame.type === 'agent_deleted' && frame.payload?.agentId === agent.id)).toHaveLength(0)
+ expect((await d.tmux.run('list-panes', '-a', '-F', '#{pane_id}')).trim().split('\n')).toContain(agent.tmuxPane)
+ writeFileSync(file, original)
+ expect(await close(client, agent, 'now')).toMatchObject({ closed: true })
+ await stopped(client, agent.id)
+ const saved = readFileSync(file, 'utf8')
+ writeFileSync(file, foreign)
+ const refused = await client.request('agent_resume', { agentId: agent.id }, 90_000)
+ expect(refused).toMatchObject({ error: 'IDENTITY_UNAVAILABLE', detail: expect.any(String) })
+ expect(await row(client, agent.id)).toMatchObject({ status: 'stopped', sessionId: agent.sessionId })
+ expect(readFileSync(file, 'utf8')).toBe(foreign)
+ writeFileSync(file, saved)
+ expect((await client.request('agent_resume', { agentId: agent.id }, 90_000)).error).toBeUndefined()
+ await until('the held conversation to resume', async () => {
+ const latest = await row(client, agent.id)
+ return latest?.status === 'active' && latest.sessionId === agent.sessionId ? latest : null
+ }, 60_000, 500)
+ await turn(client, agent.id, 'History survives the hold')
+ client.close()
+ })
+
it.each(engines)('%s: closed only when idle, a working agent is left working and says so', async (engine) => {
const d = await fresh()
const client = await LocalClient.connect(d)
diff --git a/cli/scripts/handoff-2026-10-08/control-transcript-cost.ts b/cli/scripts/handoff-2026-10-08/control-transcript-cost.ts
new file mode 100644
index 000000000..4de42b7fc
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/control-transcript-cost.ts
@@ -0,0 +1,105 @@
+/** Matched private native-control work. Run each workload in a fresh process, alone. */
+import childProcess from 'node:child_process'
+import { syncBuiltinESMExports } from 'node:module'
+import { createHash } from 'node:crypto'
+import { closeSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, realpathSync, rmSync, statSync, 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] ?? 'capture-codex'
+if (!['capture-codex', 'capture-claude', 'checkpoint-small', 'checkpoint-large', 'checkpoint-reuse', 'stop', 'resume-held'].includes(workload)) throw Error('Unknown workload')
+const cli = process.env.CONTROL_COST_CLI ?? resolve(import.meta.dirname, '../..')
+const root = realpathSync(mkdtempSync(join(tmpdir(), 'control-transcript-cost-')))
+// The daemon normally owns live sockets. Its unref'ed zero-delay Stop wait must
+// also finish in this standalone process before its measurements are written.
+const keepAlive = setInterval(() => {}, 60_000)
+const hostPlatform = process.platform
+Object.defineProperty(process, 'platform', { value: 'linux' })
+const forbidden = () => { throw Error('Host binaries are forbidden in the control 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',
+ 'PI_HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME']) {
+ 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 = () => {}
+const hashFile = (path: string) => {
+ const hash = createHash('sha256'), buffer = Buffer.alloc(128 * 1024), fd = openSync(path, 'r')
+ try { for (;;) { const bytes = readSync(fd, buffer); if (!bytes) break; hash.update(buffer.subarray(0, bytes)) } }
+ finally { closeSync(fd) }
+ return hash.digest('hex')
+}
+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 { captureResumeIdentity } = await load('lib/captureResumeIdentity.ts')
+ const { SessionCheckpointStore } = await load('lib/sessionCheckpoint.ts')
+ const { StoppedAgentStore } = await load('lib/stoppedAgents.ts')
+ const { AgentRestartCoordinator } = await load('lib/restartAgent.ts')
+ const { createStopAgentService } = await load('lib/stopAgentService.ts')
+ const { createResumeAgentService } = await load('lib/resumeAgentService.ts')
+ const engine = workload === 'capture-claude' ? 'claude' : 'codex'
+ const id = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
+ const folder = join(process.env[engine === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME']!, engine === 'claude' ? 'projects' : 'sessions')
+ mkdirSync(folder)
+ const file = join(folder, `rollout-${id}.jsonl`)
+ const header = JSON.stringify(engine === 'codex' ? { type: 'session_meta', payload: { id, cwd: root, source: 'cli' } }
+ : { type: 'user', sessionId: id, cwd: root, isSidechain: false }) + '\n'
+ const large = workload === 'checkpoint-large' || workload === 'checkpoint-reuse'
+ const contents = header + JSON.stringify({ type: 'event_msg', text: 'x'.repeat(large ? 8 * 1024 * 1024 : 1024) }) + '\n'
+ writeFileSync(file, contents)
+ writeFileSync(join(process.env.ADAPTER_DATA_DIR!, 'engine-homes.json'), '{}')
+ const directory = join(root, 'checkpoints'), checkpoints = new SessionCheckpointStore(directory)
+ const stopped = new StoppedAgentStore(join(root, 'stopped')), restartJobs = new AgentRestartCoordinator(), stopJobs = new Map()
+ const stop = createStopAgentService({ registry, stoppedAgents: stopped, restartJobs, stopJobs,
+ tmuxBackend: { kill: async () => ({ state: 'succeeded', dispatch: 'executed' }) },
+ agentReconciler: { suppress() {}, holdRoute() {}, releaseRoute() {}, trigger: async () => {} },
+ forgetSession: (target: string) => { registry.removeAgent(target) }, markDeleted() {}, clearDeleted() {}, stopNative: async () => {} })
+ const resume = createResumeAgentService({ registry, stoppedAgents: stopped, restartJobs, stopJobs, pinnedControls: new Set(),
+ tmuxBackend: { create: forbidden, kill: forbidden }, retainExitedSession: forbidden, announceSession: forbidden,
+ relaunchOverrides: async () => ({ ok: false, error: 'SERVICE_UNAVAILABLE', detail: 'Fixture dependency is unavailable.' }),
+ prepareSessionResume: forbidden, refreshGridWebSearch: forbidden, clearDeleted() {}, attachDsh: forbidden, attachSession: forbidden })
+ const iterations = workload.startsWith('checkpoint') ? 5 : 50
+ const latenciesMs: number[] = []
+ let cpuMs = 0, agent: import('../../src/lib/registry.js').RegisteredSession | undefined
+ for (let i = 0; i < iterations; i++) {
+ if (!agent || workload === 'stop' || workload === 'resume-held') {
+ agent = registry.openPendingAgent({ engine, cwd: root, runtimes: [{ backend: 'tmux', paneId: `%${i + 1}` }] })!
+ Object.assign(agent, { sessionId: id, transcriptPath: file, processIdentity: null })
+ if (workload === 'resume-held') { registry.removeAgent(agent.agentId); stopped.save(agent) }
+ }
+ if (workload === 'checkpoint-reuse' && i === 0) await checkpoints.save(agent)
+ if (workload.startsWith('checkpoint') && workload !== 'checkpoint-reuse') writeFileSync(file, contents + JSON.stringify({ turn: i }) + '\n')
+ const cpu = process.cpuUsage(), started = performance.now()
+ if (workload.startsWith('capture')) {
+ const result = await captureResumeIdentity(agent)
+ if (result.sessionId !== id || result.transcriptPath !== file) throw Error('Capture lost native identity')
+ } else if (workload.startsWith('checkpoint')) await checkpoints.save(agent, { screen: 'Private unsent draft' })
+ else if (workload === 'stop') await stop(agent.agentId)
+ else {
+ const result = await resume(agent.agentId)
+ if (result.ok || result.error !== 'SERVICE_UNAVAILABLE' || stopped.resumeReservedAt(agent.agentId) !== null) throw Error('Resume did not retain a retryable dependency hold')
+ }
+ latenciesMs.push(performance.now() - started)
+ const used = process.cpuUsage(cpu); cpuMs += (used.user + used.system) / 1000
+ if (workload.startsWith('checkpoint')) {
+ const manifest = JSON.parse(readFileSync(join(directory, readdirSync(directory).find(name => /^[a-f0-9]{64}\.json$/.test(name))!), 'utf8'))
+ if (hashFile(join(directory, manifest.file)) !== hashFile(file)) throw Error('Checkpoint bytes differ from their source')
+ }
+ if (workload === 'stop' && (registry.byAgent(agent.agentId) || stopped.get(agent.agentId)?.sessionId !== id)) throw Error('Stop did not retain its conversation')
+ }
+ process.stdout.write(JSON.stringify({ workload, iterations, latenciesMs, cpuMs, sourceBytes: statSync(file).size,
+ peakRssMiB: process.resourceUsage().maxRSS / 1024, node: process.version, hostPlatform, evidencePlatform: process.platform,
+ arch: process.arch, outcomes: { confirmed: iterations } }) + '\n')
+} finally { clearInterval(keepAlive); rmSync(root, { recursive: true, force: true }) }
diff --git a/cli/scripts/handoff-2026-10-08/mutate-control-authority.py b/cli/scripts/handoff-2026-10-08/mutate-control-authority.py
new file mode 100644
index 000000000..b993befe4
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-control-authority.py
@@ -0,0 +1,124 @@
+"""Run only in an owned disposable worktree. Every mutant must fail an assertion."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+assert (cli.parent / '.git').is_file(), 'An owned disposable worktree is required'
+assert os.environ.get('HARNESS_CONTROL_MUTATIONS_OWNED') == '1', 'Explicit owned-worktree marker is required'
+control = 'src/lib/controlTranscript.spec.ts'
+bindings = 'src/engines/transcriptBindings.ts'
+checkpoint = 'src/lib/sessionCheckpoint.ts'
+stop = 'src/lib/stopAgentService.ts'
+resume = 'src/lib/resumeAgentService.ts'
+mutations = [
+ ('legacy capture accepts an unusable saved conversation', 'src/lib/captureResumeIdentity.ts',
+ "return nativeUnavailable('the saved conversation file is unavailable')", 'return session',
+ 'src/engines/sessionStore.golden.spec.ts', 'homes, transcripts, finders'),
+ ('capture omits eager identity', 'src/lib/captureResumeIdentity.ts',
+ 'if (proof.path) controlTranscriptEvidence(session.engine, id, proof.path, options.codexHome, session.cwd).verify()',
+ 'void proof', control, 'eagerly checks the saved claude'),
+ ('positive native claim is discarded', 'src/lib/captureResumeIdentity.ts',
+ "if (keepsFile && !transcriptPath) return nativeUnavailable('the observed conversation file is unavailable')",
+ 'if (keepsFile && !transcriptPath) return session', 'src/lib/captureResumeIdentity.spec.ts', 'announced conversation|ambiguous or unsafe'),
+ ('capture path wiring disconnected', 'src/lib/captureResumeIdentity.ts',
+ 'if (path) return path === session.transcriptPath ? session : { ...session, transcriptPath: path }',
+ 'if (path) return { ...session, transcriptPath: null }', 'src/lib/controlTranscript.golden.spec.ts', ''),
+ ('control accepts a replacement inode', bindings,
+ 'after.fileKey !== before.fileKey', 'false', control, 'physically replaced'),
+ ('copy descriptor borrows pathname authority', bindings,
+ 'openedFileKey !== undefined && openedFileKey !== before.fileKey', 'false', control, 'ancestor that moves away and back'),
+ ('Claude control header omitted', bindings,
+ "engine === 'claude' ? claudeIdentity", "engine === 'claude' ? undefined", control, 'eagerly checks the saved claude'),
+ ('opening borrows a different physical file', bindings,
+ 'head.fileKey !== proof.fileKey', 'false', control, 'lend its valid opening'),
+ ('contradictory delegation is ignored', 'src/engines/kit/controlIdentity.ts',
+ 'side !== undefined && valueSide !== undefined && valueSide !== side', 'false', 'src/engines/kit/controlIdentity.spec.ts', 'contradictory Claude'),
+ ('Pi workspace authority omitted', bindings,
+ 'if (rule.canonicalWorkspace)', 'if (false)', control, 'eagerly checks the saved pi'),
+ ('opening changes are not fenced', 'src/engines/kit/nativeFiles.ts',
+ 'record.prefix && !bytes.equals(record.prefix)', 'false', 'src/engines/kit/controlIdentity.spec.ts', 'complete opening proof'),
+ ('reusable source snapshot predates await', checkpoint,
+ "before = await input.stat({ bigint: true }).catch(() => { throw new IdentityReadUnavailable('the source transcript became unreadable') })",
+ 'void before', control, 'newly appended body'),
+ ('same-size body replacement is reused', checkpoint,
+ '&& previous.sourceCtime === String(before.ctimeNs)', '', control, 'same-sized history'),
+ ('checkpoint native hold becomes failure', checkpoint,
+ " || (error as { code?: unknown } | null)?.code === 'IDENTITY_UNAVAILABLE'", '', control, 'unavailable source'),
+ ('checkpoint draft wiring disconnected', checkpoint,
+ 'if (options.screen != null && s.sessionId)', 'if (false)', 'src/lib/controlTranscript.golden.spec.ts', ''),
+ ('Stop accepts a changed binding', stop,
+ '(binding === undefined || bindingIdentity(current!) === binding)', 'true', control, 'binding boundary'),
+ ('Stop forgets precise process birth', stop,
+ ', entry.processIdentity?.startTicks', '', control, 'process birth boundary'),
+ ('native broker hides the Stop hold', stop,
+ '.catch(error => { throw nativeIdentityError ?? error })', '', control, 'native broker contains'),
+ ('contained native errors lose their hold', stop,
+ 'if (nativeIdentityError) throw nativeIdentityError', 'void nativeIdentityError', control, 'contained grant|process signal'),
+ ('signal skips fresh transcript proof', stop,
+ 'kill: (pid, signal) => {\n verifyTranscript()', 'kill: (pid, signal) => {', control, 'process signal'),
+ ('forget drops the proven parent path', stop,
+ 'forgetSession(sessionId, { force: true, captured: s })', 'forgetSession(sessionId, { force: true })', control, 'final real forget'),
+ ('Resume configuration loses its source fence', resume,
+ 'relaunchOverrides(saved, saved, sourceCurrent)', 'relaunchOverrides(saved, saved, () => true)', control, 'during configuration'),
+ ('Resume actual dispatch fence disconnected', resume,
+ 'current: sourceCurrent,', '', control, 'during tmux dispatch'),
+ ('Resume dispatch ignores a new conversation owner', resume,
+ 'if (saved.sessionId && registry.bySession(saved.sessionId)) {', 'if (false) {', control, 'during conversation ownership'),
+ ('Resume dispatch uncertainty is forgotten', resume,
+ 'onDispatch: () => { allocationAttempted = true }', 'onDispatch: () => {}', 'src/lib/resumeAgentService.spec.ts', 'dispatch starts but loses'),
+ ('Resume repair wiring disconnected', resume,
+ 'try { prepareSessionResume(saved) }', 'try { void saved }', 'src/lib/controlResume.golden.spec.ts', ''),
+ ('Resume argv loses conversation', resume,
+ 'resumeSessionId,\n bypassPermission:', 'resumeSessionId: undefined,\n bypassPermission:', 'src/lib/controlResume.golden.spec.ts', ''),
+ ('Close accepts an unconfirmed drain', 'src/core/agents/close.ts',
+ "if (code === 'ENGINE_TRANSCRIPT_CHANGED') throw new IdentityReadUnavailable('the transcript changed while checking activity')",
+ "if (code === 'ENGINE_TRANSCRIPT_CHANGED') return", 'src/core/agents/close.spec.ts', ''),
+ ('Close activity hold becomes failed', 'src/lib/closeAgentService.ts',
+ "{ ...plan, state: 'waiting',\n detail: error", "{ ...plan, state: 'failed',\n detail: error",
+ 'src/lib/closeAgentService.spec.ts', 'queued Close visible'),
+ ('Close reason failure escapes retry', 'src/lib/closeAgentService.ts',
+ 'catch { /* The preceding durable intent survives a failed reason update. Retry next tick. */ }',
+ 'catch (error) { throw error }', 'src/lib/closeAgentService.spec.ts', 'failed Close reason'),
+]
+selected = set(sys.argv[2:])
+if selected:
+ assert selected <= {entry[0] for entry in mutations}, 'Unknown mutation'
+ 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=''):
+ return subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', *targets,
+ *(['--testNamePattern', pattern] if pattern else []), '--maxWorkers=1'],
+ cwd=cli, env=environment, text=True, capture_output=True, timeout=180)
+
+
+baseline = run(sorted({entry[4] for entry in mutations}))
+if baseline.returncode:
+ raise SystemExit('Unchanged 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 == 'contained native errors lose their hold' 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 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/core/agents/close.spec.ts b/cli/src/core/agents/close.spec.ts
index 986656a31..5be68e5c0 100644
--- a/cli/src/core/agents/close.spec.ts
+++ b/cli/src/core/agents/close.spec.ts
@@ -75,12 +75,35 @@ describe('closing agents no window shows', () => {
expect(pollSession).toHaveBeenCalledTimes(2)
})
+ it('holds changed transcript evidence before reading a screen or closing', async () => {
+ const pollSession = vi.fn().mockRejectedValue(Object.assign(new Error('changed'), { code: 'ENGINE_TRANSCRIPT_CHANGED' }))
+ const { deps, close } = setup({ watcher: { pollSession } as never })
+ await expect(close.activity(row())).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(pollSession).toHaveBeenCalledOnce()
+ expect(deps.captureTerminal).not.toHaveBeenCalled()
+ expect(deps.stopAgent).not.toHaveBeenCalled()
+ })
+
+ it.each(['ENGINE_UNAVAILABLE', 'ENGINE_TRANSCRIPT_CHANGED', 'DISK_UNREADABLE', undefined])(
+ 'retains a failed second activity read with its correct reason: %s', async code => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ const failure = code ? Object.assign(new Error(code), { code }) : null
+ const pollSession = vi.fn().mockRejectedValueOnce(Object.assign(new Error('reconnect'), { code: 'ENGINE_UNAVAILABLE' }))
+ .mockRejectedValueOnce(failure)
+ const { close } = setup({ watcher: { pollSession } as never })
+ const result = expect(close.activity(row()))
+ if (code === 'ENGINE_UNAVAILABLE' || code === 'ENGINE_TRANSCRIPT_CHANGED') {
+ await result.rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ } else await result.rejects.toBe(failure)
+ expect(pollSession).toHaveBeenCalledTimes(2)
+ })
+
it('reads only once more, and never retries a failure that is not a worker\'s restart', async () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
const stale = Object.assign(new Error('stale'), { code: 'ENGINE_STALE_REPLY' })
const twice = vi.fn().mockRejectedValue(stale)
const again = setup({ watcher: { pollSession: twice } as unknown as ClosingDeps['watcher'] })
- await expect(again.close.activity(row())).rejects.toBe(stale)
+ await expect(again.close.activity(row())).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
expect(twice).toHaveBeenCalledTimes(2)
for (const error of [new Error('disk gone'), null]) {
const other = vi.fn().mockRejectedValue(error)
diff --git a/cli/src/core/agents/close.ts b/cli/src/core/agents/close.ts
index d4abd3afa..56596a67e 100644
--- a/cli/src/core/agents/close.ts
+++ b/cli/src/core/agents/close.ts
@@ -1,4 +1,5 @@
import type { ScreenReader } from '../../lib/screenReader.js'
+import { IdentityReadUnavailable } from '../../engines/kit/identityScan.js'
/**
* Closing agents that no window shows: the close service (now, once idle, after the task) and the
* cleanup preview that lists what a close would take, each with what it is doing right now.
@@ -46,10 +47,17 @@ export function createAgentClosing({
try { await watcher.pollSession(s.sessionId) }
catch (error) {
const code = (error as { code?: unknown } | null)?.code
+ if (code === 'ENGINE_TRANSCRIPT_CHANGED') throw new IdentityReadUnavailable('the transcript changed while checking activity')
if (code !== 'ENGINE_STALE_REPLY' && code !== 'ENGINE_UNAVAILABLE') throw error
console.log(`[close] ${sid(s.sessionId)} its ${s.engine} worker was replaced under the read (${code}); reading again once it is back`)
await engineReady(s.engine, CLOSE_READ_RECONNECT_MS)
- await watcher.pollSession(s.sessionId)
+ try { await watcher.pollSession(s.sessionId) } catch (error) {
+ const code = (error as { code?: unknown } | null)?.code
+ if (code === 'ENGINE_STALE_REPLY' || code === 'ENGINE_UNAVAILABLE' || code === 'ENGINE_TRANSCRIPT_CHANGED') {
+ throw new IdentityReadUnavailable('the current conversation could not be read completely')
+ }
+ throw error
+ }
}
}
const closeAgentService = new CloseAgentService({
diff --git a/cli/src/core/agents/forget.spec.ts b/cli/src/core/agents/forget.spec.ts
index 389c0f0a6..b9b1cd267 100644
--- a/cli/src/core/agents/forget.spec.ts
+++ b/cli/src/core/agents/forget.spec.ts
@@ -64,6 +64,35 @@ function expectLetGo(deps: ForgetDeps, sessionId: string, agentId: string) {
describe('forgetting a session', () => {
afterEach(() => { vi.restoreAllMocks(); vi.mocked(removePendingCursorTasks).mockClear() })
+ it.each(['bound', 'unbound', 'process'] as const)('archives the proven capture of an unchanged %s agent', mode => {
+ const { deps, forgetSession } = setup()
+ const live = deps.registry.resolve(mode === 'unbound' ? 'fresh' : 'a1')!
+ if (mode === 'process') live.processIdentity = { pid: 41, startMarker: 'birth', executable: '<engine>' }
+ const captured = { ...live, sessionId: 's1', transcriptPath: '/fixture/parent.jsonl', boundAt: 23, source: 'stop-repair' }
+ forgetSession(live.agentId, { captured })
+ expect(deps.stoppedAgents.save).toHaveBeenCalledWith(expect.objectContaining(captured))
+ expect(deps.registry.removeAgent).toHaveBeenCalledWith(live.agentId)
+ })
+
+ it.each(['agent', 'engine', 'registered', 'conversation', 'process', 'executable', 'missing process'] as const)(
+ 'refuses a captured conversation after the %s identity changes', changed => {
+ const { deps, forgetSession } = setup()
+ const live = deps.registry.resolve('a1')!
+ live.processIdentity = { pid: 41, startMarker: 'birth', executable: '<engine>' }
+ const captured = { ...live, processIdentity: { ...live.processIdentity }, transcriptPath: '/fixture/parent.jsonl' }
+ if (changed === 'agent') captured.agentId = 'other'
+ if (changed === 'engine') captured.engine = 'codex'
+ if (changed === 'registered') captured.registeredAt = 2
+ if (changed === 'conversation') captured.sessionId = 'other'
+ if (changed === 'process') captured.processIdentity.pid++
+ if (changed === 'executable') live.processIdentity.executable = '<replacement>'
+ if (changed === 'missing process') live.processIdentity = null
+ expect(() => forgetSession('a1', { captured })).toThrow('changed before')
+ expect(deps.stoppedAgents.save).not.toHaveBeenCalled()
+ expect(deps.registry.removeAgent).not.toHaveBeenCalled()
+ expect(deps.clients.send).not.toHaveBeenCalled()
+ })
+
it('drops a crash-resume boundary when the conversation is stopped or unbound', () => {
const { deps } = setup()
const marks = createRelaunchMarks()
diff --git a/cli/src/core/agents/forget.ts b/cli/src/core/agents/forget.ts
index 9d3feb359..fff022a9b 100644
--- a/cli/src/core/agents/forget.ts
+++ b/cli/src/core/agents/forget.ts
@@ -11,7 +11,8 @@ import type { CursorSubagentManager } from '../../engines/cursor/subagent.js'
import type { AutonomousDeviceInput } from '../deviceInput.js'
import type { TurnRecaps } from '../turns/recaps.js'
import { sid } from '../../lib/log.js'
-import type { registry } from '../../lib/registry.js'
+import { sameProcessIdentity } from '../../lib/terminalRuntime.js'
+import type { RegisteredSession, registry } from '../../lib/registry.js'
import type { RuntimeProfileManager } from '../../lib/runtimeProfile.js'
import type { SessionInputController } from '../../lib/sessionInput.js'
import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'
@@ -58,7 +59,7 @@ export function createForgetSession({
/** Release a mutable session binding, or remove the process-owned agent everywhere. */
const forgetSession = (
id: string,
- opts: { force?: boolean; keepAgent?: boolean; agentId?: string } = {},
+ opts: { force?: boolean; keepAgent?: boolean; agentId?: string; captured?: RegisteredSession } = {},
): void => {
const doomed = registry.resolve(id)
const sessionId = doomed?.sessionId || id
@@ -73,7 +74,19 @@ export function createForgetSession({
? `[agent] ${sid(announceId)} released session ${sid(sessionId)}`
: `[agent] ${sid(announceId)} forgotten`)
- if (!opts.keepAgent && doomed) stoppedAgents.save(doomed)
+ if (!opts.keepAgent && doomed) {
+ const captured = opts.captured
+ if (captured && (captured.agentId !== doomed.agentId || captured.engine !== doomed.engine
+ || captured.registeredAt !== doomed.registeredAt || doomed.sessionId && captured.sessionId !== doomed.sessionId
+ || captured.processIdentity && (!sameProcessIdentity(captured.processIdentity, doomed.processIdentity)
+ || captured.processIdentity.executable !== doomed.processIdentity?.executable))) {
+ throw new Error('The harness changed before its captured conversation could be retained.')
+ }
+ // Stop may prove a parent path while the live row still names an overwritten child.
+ // Preserve that capture through this last archive, including intervening hook saves.
+ stoppedAgents.save(captured ? { ...doomed, sessionId: captured.sessionId, transcriptPath: captured.transcriptPath,
+ hermesHome: captured.hermesHome, boundAt: captured.boundAt, source: captured.source } : doomed)
+ }
if (opts.keepAgent) registry.unbindSession(sessionId)
else if (doomed) registry.removeAgent(doomed.agentId)
else registry.remove(sessionId)
diff --git a/cli/src/engines/claude/sessionStore.ts b/cli/src/engines/claude/sessionStore.ts
index 0cfaa6ebe..b2d6dbca3 100644
--- a/cli/src/engines/claude/sessionStore.ts
+++ b/cli/src/engines/claude/sessionStore.ts
@@ -45,3 +45,8 @@ export const sessionStore: SessionStoreContract = {
],
},
}
+
+/** Control reads the first identity-bearing opening, after Claude's bookkeeping. */
+export const controlIdentity = {
+ maxBytes: 1024 * 1024, maxRecords: 20, id: ['sessionId'], cwd: ['cwd'], sidechain: 'isSidechain',
+} as const satisfies import('../kit/controlIdentity.js').ControlIdentityRule
diff --git a/cli/src/engines/kit/controlIdentity.spec.ts b/cli/src/engines/kit/controlIdentity.spec.ts
new file mode 100644
index 000000000..b5fc855be
--- /dev/null
+++ b/cli/src/engines/kit/controlIdentity.spec.ts
@@ -0,0 +1,59 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it } from 'vitest'
+import { controlIdentity as claude } from '../claude/sessionStore.js'
+import { PI_CONTROL_IDENTITY as pi } from '../pi/contract.js'
+import { controlIdentity } from './controlIdentity.js'
+import { NativeFiles } from './nativeFiles.js'
+
+const line = (value: unknown) => JSON.stringify(value) + '\n'
+const opening = { type: 'user', sessionId: 'native-conversation', cwd: '/fixture/work', isSidechain: false }
+const roots: string[] = []
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+
+it('reads identity after bookkeeping and ignores sidechain body records after the parent opening', () => {
+ const prefix = line({ type: 'queue-operation' }) + '\n' + line(opening)
+ const text = prefix + line({ ...opening, isSidechain: true })
+ expect(controlIdentity(Buffer.from(text), claude)).toEqual({ id: opening.sessionId, cwd: opening.cwd,
+ delegated: false, bytes: Buffer.byteLength(prefix) })
+ expect(controlIdentity(Buffer.from(line({ ...opening, isSidechain: true })), claude).delegated).toBe(true)
+})
+
+it.each([
+ '', '{partial', line(null), line([]), line({ ...opening, sessionId: 8 }), line({ ...opening, sessionId: '' }),
+ line({ ...opening, cwd: 'relative' }), line({ ...opening, cwd: 9 }), line({ ...opening, isSidechain: 'false' }),
+ line({ type: 'bookkeeping' }).repeat(20) + line(opening),
+ line({ sessionId: 'first' }) + line(opening), line({ cwd: '/other' }) + line(opening),
+ line({ sessionId: 'native-conversation', isSidechain: false }) + line({ cwd: '/fixture/work', isSidechain: true }),
+ line({ sessionId: 'native-conversation', isSidechain: false }) + line({ cwd: '/fixture/work', isSidechain: 'false' }),
+ line({ ...opening, padding: 'x'.repeat(1024 * 1024) }),
+].map((text, index) => ({ text, index })))('holds incomplete or contradictory Claude opening $index', ({ text }) => {
+ expect(() => controlIdentity(Buffer.from(text), claude)).toThrow(expect.objectContaining({ code: 'IDENTITY_UNAVAILABLE' }))
+})
+
+it('rejects invalid UTF-8 rather than manufacturing an identity from replacement characters', () => {
+ const bytes = Buffer.concat([Buffer.from('{"sessionId":"'), Buffer.from([0xff]), Buffer.from('","cwd":"/fixture"}\n')])
+ expect(() => controlIdentity(bytes, claude)).toThrow('complete UTF-8')
+})
+
+it.each(['wrong type', 'path id', 'incomplete', 'missing workspace'])('holds a Pi opening with %s', state => {
+ const value = { type: 'session', id: 'native-id', cwd: '/fixture/work' }
+ if (state === 'wrong type') value.type = 'message'
+ if (state === 'path id') value.id = 'conversation.jsonl'
+ if (state === 'missing workspace') delete (value as Partial<typeof value>).cwd
+ const text = line(value)
+ expect(() => controlIdentity(Buffer.from(state === 'incomplete' ? text.trimEnd() : text), pi))
+ .toThrow(expect.objectContaining({ code: 'IDENTITY_UNAVAILABLE' }))
+})
+
+it('keeps a complete opening proof through appends and rejects its replacement before publication', () => {
+ const root = mkdtempSync(join(tmpdir(), 'native-control-opening-')); roots.push(root)
+ const path = join(root, 'conversation.jsonl'), files = new NativeFiles()
+ writeFileSync(path, line(opening))
+ expect(files.opening(path, claude).id).toBe(opening.sessionId)
+ writeFileSync(path, line(opening) + line({ type: 'assistant', text: 'appended body' }))
+ expect(() => files.verify(path)).not.toThrow()
+ writeFileSync(path, line({ ...opening, sessionId: 'other-conversation' }))
+ expect(() => files.verify(path)).toThrow('opening changed')
+})
diff --git a/cli/src/engines/kit/controlIdentity.ts b/cli/src/engines/kit/controlIdentity.ts
new file mode 100644
index 000000000..39ce9864b
--- /dev/null
+++ b/cli/src/engines/kit/controlIdentity.ts
@@ -0,0 +1,51 @@
+/** Engine-declared opening records needed for eager session control. */
+import { isAbsolute } from 'node:path'
+import { nativeText, nativeUnavailable } from './nativeEvidence.js'
+
+export interface ControlIdentityRule {
+ maxBytes: number
+ maxRecords: number
+ type?: string
+ id: readonly string[]
+ cwd: readonly string[]
+ idPattern?: RegExp
+ sidechain?: string
+ canonicalWorkspace?: boolean
+}
+const field = (record: unknown, path: readonly string[]): unknown => path.reduce<unknown>((value, key) =>
+ value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>)[key] : undefined, record)
+
+/** Bookkeeping may precede identity. A partial or invalid opening never proves a match. */
+export function controlIdentity(bytes: Buffer, rule: ControlIdentityRule) {
+ let id: string | undefined, cwd: string | undefined, side: boolean | undefined, start = 0
+ for (let record = 0; record < rule.maxRecords; record++) {
+ const end = bytes.indexOf(10, start)
+ if (end < 0 || end >= rule.maxBytes) break
+ const line = nativeText(bytes.subarray(start, end)); start = end + 1
+ if (!line.trim()) continue
+ let value: unknown
+ try { value = JSON.parse(line) } catch { return nativeUnavailable('the conversation opening is incomplete or invalid') }
+ if (!value || typeof value !== 'object' || Array.isArray(value)
+ || rule.type && field(value, ['type']) !== rule.type) return nativeUnavailable('the conversation opening has an unexpected record')
+ const nextId = field(value, rule.id), nextCwd = field(value, rule.cwd)
+ if (nextId !== undefined && (typeof nextId !== 'string' || !nextId || rule.idPattern && !rule.idPattern.test(nextId))) {
+ return nativeUnavailable('the conversation opening has an invalid identity')
+ }
+ if (nextCwd !== undefined && (typeof nextCwd !== 'string' || !isAbsolute(nextCwd))) {
+ return nativeUnavailable('the conversation opening has an invalid workspace')
+ }
+ if (id && nextId !== undefined && nextId !== id || cwd && nextCwd !== undefined && nextCwd !== cwd) {
+ return nativeUnavailable('the conversation opening has conflicting identities')
+ }
+ id ??= nextId as string | undefined
+ cwd ??= nextCwd as string | undefined
+ if (rule.sidechain) {
+ const valueSide = field(value, [rule.sidechain])
+ if (valueSide !== undefined && typeof valueSide !== 'boolean') return nativeUnavailable('the conversation delegation is unconfirmed')
+ if (side !== undefined && valueSide !== undefined && valueSide !== side) return nativeUnavailable('the conversation opening has conflicting delegation')
+ side ??= valueSide as boolean | undefined
+ }
+ if (id && cwd) return { id, cwd, delegated: side === true, bytes: start }
+ }
+ return nativeUnavailable('the conversation opening is incomplete or exceeds its read limit')
+}
diff --git a/cli/src/engines/kit/nativeFiles.ts b/cli/src/engines/kit/nativeFiles.ts
index 28219db2c..7ab730d45 100644
--- a/cli/src/engines/kit/nativeFiles.ts
+++ b/cli/src/engines/kit/nativeFiles.ts
@@ -5,10 +5,11 @@ import { IdentityReadUnavailable } from './identityScan.js'
import { NativeEvidenceBudget, nativeUnavailable } from './nativeEvidence.js'
import { nativeFileKey, NativePaths } from './nativePaths.js'
import { firstLine, nativeSessionMeta, type NativeFirstRecord } from './nativeHeader.js'
+import { controlIdentity, type ControlIdentityRule } from './controlIdentity.js'
const stamp = (info: BigIntStats) => `${nativeFileKey(info)}:${info.mode}:${info.uid}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`
type Location = { path: string; info: BigIntStats }
-type Read = { location: Location; limit: number; line?: string }
+type Read = { location: Location; limit: number; line?: string; prefix?: Buffer }
export class NativeFiles {
readonly paths: NativePaths
@@ -45,6 +46,15 @@ export class NativeFiles {
}
}
+ opening(path: string, rule: ControlIdentityRule) {
+ const location = this.locate(path)!
+ const bytes = this.read(location, rule.maxBytes + 1)
+ const meta = controlIdentity(bytes, rule)
+ const prefix = Buffer.from(bytes.subarray(0, meta.bytes))
+ this.reads.set(location.path, { location, limit: prefix.length, prefix })
+ return { ...meta, fileKey: nativeFileKey(location.info) }
+ }
+
private read(location: Location, limit: number): Buffer {
this.budget.step()
let fd: number | undefined
@@ -142,6 +152,7 @@ export class NativeFiles {
const records = [...this.reads.values()]
for (const record of [...records.filter(read => read.location.path !== last), ...records.filter(read => read.location.path === last)]) {
const bytes = this.read(record.location, record.limit)
+ if (record.prefix && !bytes.equals(record.prefix)) return nativeUnavailable('the conversation opening changed during inspection')
if (record.line !== undefined && firstLine(bytes, record.limit - 1) !== record.line) {
return nativeUnavailable('the binding header changed during inspection')
}
diff --git a/cli/src/engines/pi/contract.ts b/cli/src/engines/pi/contract.ts
index bf3245827..7b564ed17 100644
--- a/cli/src/engines/pi/contract.ts
+++ b/cli/src/engines/pi/contract.ts
@@ -9,6 +9,11 @@ export const PI_HEADER: SessionHeader = {
bytes: [16 * 1024, 1024 * 1024], type: 'session',
id: { field: ['id'], pattern: PI_SESSION_ID }, cwd: ['cwd'],
}
+/** Bound control checks the same native header and canonical workspace as exact discovery. */
+export const PI_CONTROL_IDENTITY = {
+ maxBytes: PI_HEADER.bytes.at(-1)!, maxRecords: 1, type: PI_HEADER.type,
+ id: PI_HEADER.id.field, idPattern: PI_HEADER.id.pattern, cwd: PI_HEADER.cwd, canonicalWorkspace: true,
+} as const satisfies import('../kit/controlIdentity.js').ControlIdentityRule
export const PI_FOLDER: SessionFolder = {
prefix: '--', suffix: '--', trim: /^[/\\]/, mangle: /[/\\:]/g, replacement: '-',
}
diff --git a/cli/src/engines/sessionStore.golden.spec.ts b/cli/src/engines/sessionStore.golden.spec.ts
index 97aebda3d..8a4e55d34 100644
--- a/cli/src/engines/sessionStore.golden.spec.ts
+++ b/cli/src/engines/sessionStore.golden.spec.ts
@@ -569,8 +569,17 @@ async function captureCases(): Promise<Record<string, unknown>> {
'claude, unbound, no process': { sessionId: '' },
}
for (const [name, over] of Object.entries(shapes)) {
- const out = await m.capture.captureResumeIdentity(session(over))
- cases[`capture · ${name}`] = norm({ sessionId: out.sessionId, transcriptPath: out.transcriptPath, source: out.source ?? null })
+ const input = session(over), before = structuredClone(input)
+ try {
+ const out = await m.capture.captureResumeIdentity(input)
+ cases[`capture · ${name}`] = norm({ sessionId: out.sessionId, transcriptPath: out.transcriptPath, source: out.source ?? null })
+ } catch (error) {
+ if (name !== 'claude, unknown' && name !== 'codex, a sub-agent id') throw error
+ expect(error).toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(input).toEqual(before)
+ cases[`capture · ${name}`] = norm({ held: (error as Error).message,
+ retained: { sessionId: input.sessionId, transcriptPath: input.transcriptPath, source: input.source ?? null } })
+ }
}
forgetMoved()
// Which finder the handoff asks, per engine, and with what.
@@ -623,6 +632,24 @@ describe('core finds sessions where it did before Claude Code and Codex declared
for (const [section, cases] of Object.entries(golden)) {
expect(Object.keys(actual[section]!).sort(), `${platform} · ${section}`).toEqual(Object.keys(cases).sort())
for (const [key, value] of Object.entries(cases)) {
+ // These former successful answers are unsafe for Stop: no usable native
+ // file, or a delegated rollout. Keep the historical artifact unchanged,
+ // assert its exact former answer, and require the typed hold plus unchanged
+ // input now. In particular, do not synthesize the child's former path.
+ const captureCorrections = new Map<string, { before: unknown; retained: unknown }>([
+ ['capture · claude, unknown', { before: { sessionId: OTHER, transcriptPath: null, source: null },
+ retained: { sessionId: OTHER, transcriptPath: null, source: null } }],
+ ['capture · codex, a sub-agent id', { before: { sessionId: CHILD, transcriptPath: norm(paths.codexChild), source: null },
+ retained: { sessionId: CHILD, transcriptPath: null, source: null } }],
+ ])
+ const captureCorrection = section === 'capture' ? captureCorrections.get(key) : undefined
+ if (captureCorrection) {
+ expect(value, `${platform} · ${key} · former unsafe success`).toEqual(captureCorrection.before)
+ expect(actual[section]![key], `${platform} · ${key} · retained hold`).toEqual({
+ held: 'Conversation identity is held: the saved conversation file is unavailable.', retained: captureCorrection.retained,
+ })
+ continue
+ }
// Safety correction: an existing unusable process record is not proof of absence. Keep
// the former artifact intact, assert its exact old answer, and name every changed case.
const held = new Map<string, string>(['default homes', 'moved homes'].flatMap(home => [
diff --git a/cli/src/engines/transcriptBindings.ts b/cli/src/engines/transcriptBindings.ts
index b31cb5666..70d5f373e 100644
--- a/cli/src/engines/transcriptBindings.ts
+++ b/cli/src/engines/transcriptBindings.ts
@@ -2,8 +2,11 @@
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 { controlIdentity as claudeIdentity } from './claude/sessionStore.js'
+import { PI_CONTROL_IDENTITY } from './pi/contract.js'
import { cursorDataDir } from './cursor/contract.js'
import { NativeFiles } from './kit/nativeFiles.js'
+import type { ControlIdentityRule } from './kit/controlIdentity.js'
import { nativeFileKey } from './kit/nativePaths.js'
import { nativeUnavailable } from './kit/nativeEvidence.js'
import { sessionStoreOf } from './sessionStoreContracts.js'
@@ -161,5 +164,39 @@ export function savedTranscriptEvidence(engine: AgentEngine, sessionId: string,
return nativeUnavailable('the saved transcript names a different conversation')
}
}
- return { path: selected, verify: () => proof.verify(selected ?? path) }
+ const fileKey = selected ? nativeFileKey(proof.files.file(selected)!.info) : null
+ return { path: selected, fileKey, verify: () => proof.verify(selected ?? path) }
+}
+
+/** Keep immutable identity across awaits, not a lookup's expiring work budget.
+ * Each control boundary earns fresh header, root and catalog evidence before acting. */
+export function controlTranscriptEvidence(engine: AgentEngine, sessionId: string, path: string, profile?: string, cwd?: string | null) {
+ const read = () => {
+ const proof = savedTranscriptEvidence(engine, sessionId, path, profile)
+ if (!proof.path) return nativeUnavailable('the saved conversation file is unavailable')
+ const rule: ControlIdentityRule | undefined = engine === 'claude' ? claudeIdentity : engine === 'pi' ? PI_CONTROL_IDENTITY : undefined
+ if (rule) {
+ const files = new NativeFiles()
+ const head = files.opening(proof.path, rule)
+ if (head.fileKey !== proof.fileKey) return nativeUnavailable('the conversation opening belongs to a replaced file')
+ if (head.id !== sessionId || head.delegated) return nativeUnavailable('the saved transcript names a different or delegated conversation')
+ if (rule.canonicalWorkspace) {
+ if (!cwd) return nativeUnavailable('the saved conversation workspace is unavailable')
+ const expected = files.locate(cwd), actual = files.locate(head.cwd)
+ if (!expected?.info.isDirectory() || !actual?.info.isDirectory()
+ || nativeFileKey(expected.info) !== nativeFileKey(actual.info)) return nativeUnavailable('the saved conversation workspace does not match')
+ }
+ files.verify(proof.path)
+ }
+ proof.verify()
+ return { path: proof.path, fileKey: proof.fileKey }
+ }
+ const before = read()
+ return { path: before.path, verify(openedFileKey?: string): void {
+ const after = read()
+ if (after.path !== before.path || after.fileKey !== before.fileKey
+ || openedFileKey !== undefined && openedFileKey !== before.fileKey) {
+ nativeUnavailable('the saved conversation file was replaced during the operation')
+ }
+ } }
}
diff --git a/cli/src/lib/__fixtures__/control-resume.golden.json b/cli/src/lib/__fixtures__/control-resume.golden.json
new file mode 100644
index 000000000..77d8e3a14
--- /dev/null
+++ b/cli/src/lib/__fixtures__/control-resume.golden.json
@@ -0,0 +1,294 @@
+{
+ "linux:claude": {
+ "events": [
+ [
+ "launch-prepare",
+ "claude",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ],
+ [
+ "history-prepare",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ],
+ [
+ "create",
+ [
+ "<engine>",
+ "claude",
+ "--resume",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ]
+ ],
+ [
+ "grid"
+ ],
+ [
+ "announce",
+ "claude",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "starting"
+ ],
+ [
+ "announce",
+ "claude",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "ready"
+ ],
+ [
+ "attach",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ]
+ ],
+ "result": {
+ "ok": true,
+ "resumed": true,
+ "engine": "claude",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": null,
+ "launch": {
+ "state": "ready"
+ }
+ },
+ "reserved": false
+ },
+ "linux:codex": {
+ "events": [
+ [
+ "launch-prepare",
+ "codex",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ],
+ [
+ "history-prepare",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ],
+ [
+ "create",
+ [
+ "<engine>",
+ "codex",
+ "--resume",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ]
+ ],
+ [
+ "grid"
+ ],
+ [
+ "announce",
+ "codex",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "starting"
+ ],
+ [
+ "announce",
+ "codex",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "ready"
+ ],
+ [
+ "attach",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ]
+ ],
+ "result": {
+ "ok": true,
+ "resumed": true,
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": null,
+ "launch": {
+ "state": "ready"
+ }
+ },
+ "reserved": false
+ },
+ "linux:terminal": {
+ "events": [
+ [
+ "launch-prepare",
+ "terminal",
+ ""
+ ],
+ [
+ "create",
+ [
+ "<engine>",
+ "terminal"
+ ]
+ ],
+ [
+ "grid"
+ ],
+ [
+ "announce",
+ "terminal",
+ "",
+ "starting"
+ ],
+ [
+ "announce",
+ "terminal",
+ "",
+ "ready"
+ ]
+ ],
+ "result": {
+ "ok": true,
+ "resumed": true,
+ "engine": "terminal",
+ "sessionId": "",
+ "source": null,
+ "launch": {
+ "state": "ready"
+ }
+ },
+ "reserved": false
+ },
+ "darwin:claude": {
+ "events": [
+ [
+ "launch-prepare",
+ "claude",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ],
+ [
+ "history-prepare",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ],
+ [
+ "create",
+ [
+ "<engine>",
+ "claude",
+ "--resume",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ]
+ ],
+ [
+ "grid"
+ ],
+ [
+ "announce",
+ "claude",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "starting"
+ ],
+ [
+ "announce",
+ "claude",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "ready"
+ ],
+ [
+ "attach",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ]
+ ],
+ "result": {
+ "ok": true,
+ "resumed": true,
+ "engine": "claude",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": null,
+ "launch": {
+ "state": "ready"
+ }
+ },
+ "reserved": false
+ },
+ "darwin:codex": {
+ "events": [
+ [
+ "launch-prepare",
+ "codex",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ],
+ [
+ "history-prepare",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ],
+ [
+ "create",
+ [
+ "<engine>",
+ "codex",
+ "--resume",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ]
+ ],
+ [
+ "grid"
+ ],
+ [
+ "announce",
+ "codex",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "starting"
+ ],
+ [
+ "announce",
+ "codex",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "ready"
+ ],
+ [
+ "attach",
+ "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"
+ ]
+ ],
+ "result": {
+ "ok": true,
+ "resumed": true,
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": null,
+ "launch": {
+ "state": "ready"
+ }
+ },
+ "reserved": false
+ },
+ "darwin:terminal": {
+ "events": [
+ [
+ "launch-prepare",
+ "terminal",
+ ""
+ ],
+ [
+ "create",
+ [
+ "<engine>",
+ "terminal"
+ ]
+ ],
+ [
+ "grid"
+ ],
+ [
+ "announce",
+ "terminal",
+ "",
+ "starting"
+ ],
+ [
+ "announce",
+ "terminal",
+ "",
+ "ready"
+ ]
+ ],
+ "result": {
+ "ok": true,
+ "resumed": true,
+ "engine": "terminal",
+ "sessionId": "",
+ "source": null,
+ "launch": {
+ "state": "ready"
+ }
+ },
+ "reserved": false
+ }
+}
diff --git a/cli/src/lib/__fixtures__/control-transcript.golden.json b/cli/src/lib/__fixtures__/control-transcript.golden.json
new file mode 100644
index 000000000..11ba2d498
--- /dev/null
+++ b/cli/src/lib/__fixtures__/control-transcript.golden.json
@@ -0,0 +1,380 @@
+{
+ "linux:claude:capture": {
+ "engine": "claude",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/CLAUDE_CONFIG_DIR/projects/project/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "linux:claude:checkpoint": {
+ "engine": "claude",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/CLAUDE_CONFIG_DIR/projects/project/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"user\",\"cwd\":\"<root>\",\"sessionId\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"isSidechain\":false}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "linux:codex:capture": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "linux:codex:checkpoint": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"session_meta\",\"payload\":{\"id\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"cwd\":\"<root>\",\"source\":\"cli\"}}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "linux:moved-codex:capture": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/moved-codex/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "linux:moved-codex:checkpoint": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/moved-codex/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"session_meta\",\"payload\":{\"id\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"cwd\":\"<root>\",\"source\":\"cli\"}}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "linux:profile-codex:capture": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/profile/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "profile": "<root>/profile",
+ "source": "fixture"
+ },
+ "linux:profile-codex:checkpoint": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/profile/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": "<root>/profile",
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"session_meta\",\"payload\":{\"id\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"cwd\":\"<root>\",\"source\":\"cli\"}}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "linux:alias-codex:capture": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/alias.jsonl",
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "linux:alias-codex:checkpoint": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/alias.jsonl",
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"session_meta\",\"payload\":{\"id\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"cwd\":\"<root>\",\"source\":\"cli\"}}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "linux:pi:capture": {
+ "engine": "pi",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/PI_HOME/agent/sessions/workspace/2026-10-10T08-00-00-000Z_aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "linux:pi:checkpoint": {
+ "engine": "pi",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/PI_HOME/agent/sessions/workspace/2026-10-10T08-00-00-000Z_aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"session\",\"version\":3,\"id\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"cwd\":\"<root>\"}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "linux:unwritten-pi:capture": {
+ "engine": "pi",
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcriptPath": null,
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "linux:unwritten-pi:checkpoint": {
+ "engine": "pi",
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "source": null,
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": {
+ "version": 1,
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "engine": "pi",
+ "cwd": "<root>",
+ "savedAt": 1791619200000,
+ "screen": "Unsent fixture draft"
+ },
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "linux:terminal:capture": {
+ "engine": "terminal",
+ "sessionId": "",
+ "transcriptPath": null,
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "linux:terminal:checkpoint": {
+ "engine": "terminal",
+ "sessionId": "",
+ "source": null,
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": {
+ "version": 1,
+ "sessionId": "",
+ "engine": "terminal",
+ "cwd": "<root>",
+ "savedAt": 1791619200000,
+ "screen": "Unsent fixture draft"
+ },
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest"
+ ]
+ },
+ "darwin:claude:capture": {
+ "engine": "claude",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/CLAUDE_CONFIG_DIR/projects/project/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "darwin:claude:checkpoint": {
+ "engine": "claude",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/CLAUDE_CONFIG_DIR/projects/project/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"user\",\"cwd\":\"<root>\",\"sessionId\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"isSidechain\":false}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "darwin:codex:capture": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "darwin:codex:checkpoint": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/CODEX_HOME/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"session_meta\",\"payload\":{\"id\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"cwd\":\"<root>\",\"source\":\"cli\"}}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "darwin:moved-codex:capture": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/moved-codex/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "darwin:moved-codex:checkpoint": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/moved-codex/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"session_meta\",\"payload\":{\"id\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"cwd\":\"<root>\",\"source\":\"cli\"}}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "darwin:profile-codex:capture": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/profile/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "profile": "<root>/profile",
+ "source": "fixture"
+ },
+ "darwin:profile-codex:checkpoint": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/profile/sessions/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": "<root>/profile",
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"session_meta\",\"payload\":{\"id\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"cwd\":\"<root>\",\"source\":\"cli\"}}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "darwin:alias-codex:capture": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/alias.jsonl",
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "darwin:alias-codex:checkpoint": {
+ "engine": "codex",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/alias.jsonl",
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"session_meta\",\"payload\":{\"id\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"cwd\":\"<root>\",\"source\":\"cli\"}}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "darwin:pi:capture": {
+ "engine": "pi",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcriptPath": "<root>/PI_HOME/agent/sessions/workspace/2026-10-10T08-00-00-000Z_aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "darwin:pi:checkpoint": {
+ "engine": "pi",
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "source": "<root>/PI_HOME/agent/sessions/workspace/2026-10-10T08-00-00-000Z_aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": "{\"type\":\"session\",\"version\":3,\"id\":\"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa\",\"cwd\":\"<root>\"}\n",
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "darwin:unwritten-pi:capture": {
+ "engine": "pi",
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcriptPath": null,
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "darwin:unwritten-pi:checkpoint": {
+ "engine": "pi",
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "source": null,
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": {
+ "version": 1,
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "engine": "pi",
+ "cwd": "<root>",
+ "savedAt": 1791619200000,
+ "screen": "Unsent fixture draft"
+ },
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest",
+ "screen"
+ ]
+ },
+ "darwin:terminal:capture": {
+ "engine": "terminal",
+ "sessionId": "",
+ "transcriptPath": null,
+ "cwd": "<root>",
+ "profile": null,
+ "source": "fixture"
+ },
+ "darwin:terminal:checkpoint": {
+ "engine": "terminal",
+ "sessionId": "",
+ "source": null,
+ "profile": null,
+ "savedAt": 1791619200000,
+ "contents": {
+ "version": 1,
+ "sessionId": "",
+ "engine": "terminal",
+ "cwd": "<root>",
+ "savedAt": 1791619200000,
+ "screen": "Unsent fixture draft"
+ },
+ "unchanged": true,
+ "files": [
+ "history",
+ "manifest"
+ ]
+ }
+}
diff --git a/cli/src/lib/captureResumeIdentity.spec.ts b/cli/src/lib/captureResumeIdentity.spec.ts
index 701dc3ad8..071bc9748 100644
--- a/cli/src/lib/captureResumeIdentity.spec.ts
+++ b/cli/src/lib/captureResumeIdentity.spec.ts
@@ -1,9 +1,11 @@
import { beforeEach, expect, it, vi } from 'vitest'
import { captureResumeIdentity } from './captureResumeIdentity.js'
-import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'
+import { engineKeepsTranscriptFile, type RegisteredSession } from './registry.js'
+import { controlTranscriptEvidence, savedTranscriptEvidence } from '../engines/transcriptBindings.js'
import { findLiveSession, findResumedTranscript, processSessionEvidence } from './sessionRepair.js'
import { processRows, resumeSessionId } from './tmux.js'
-vi.mock('./registry.js', () => ({ validTranscriptPath: vi.fn(() => true), engineKeepsTranscriptFile: vi.fn(() => true) }))
+vi.mock('./registry.js', () => ({ engineKeepsTranscriptFile: vi.fn(() => true) }))
+vi.mock('../engines/transcriptBindings.js', () => ({ savedTranscriptEvidence: vi.fn(), controlTranscriptEvidence: vi.fn() }))
vi.mock('./sessionRepair.js', () => ({ processSessionEvidence: vi.fn(), findLiveSession: vi.fn(), findResumedTranscript: vi.fn() }))
vi.mock('./tmux.js', () => ({ processRows: vi.fn(), resumeSessionId: vi.fn() }))
vi.mock('./processEvidence.js', async () => {
@@ -18,7 +20,8 @@ beforeEach(() => {
row = { engine: 'claude', sessionId: '', cwd: '/work', codexHome: null,
processIdentity: { pid: 77, executable: '/bin/claude', startMarker: 'Mon Sep 21 01:00:00 2026' } } as RegisteredSession
vi.mocked(processRows).mockResolvedValue([{ ...row.processIdentity!, args: 'claude', parentPid: 1 }])
- vi.mocked(validTranscriptPath).mockReturnValue(true)
+ vi.mocked(savedTranscriptEvidence).mockImplementation((_engine, _id, path) => ({ path, fileKey: 'fixture', verify: vi.fn() }))
+ vi.mocked(controlTranscriptEvidence).mockImplementation((_engine, _id, path) => ({ path, verify: vi.fn() }))
vi.mocked(engineKeepsTranscriptFile).mockReturnValue(true)
vi.mocked(resumeSessionId).mockReturnValue(null)
vi.mocked(processSessionEvidence).mockResolvedValue({ session: null, verify: vi.fn() })
@@ -31,6 +34,14 @@ it('leaves a shell and a complete binding unchanged', async () => {
expect(await captureResumeIdentity(row)).toBe(row); expect(processRows).not.toHaveBeenCalled()
})
+it('uses a completely proven parent transcript without changing the saved conversation', async () => {
+ Object.assign(row, { sessionId: 'parent', transcriptPath: '/child' })
+ vi.mocked(savedTranscriptEvidence).mockReturnValue({ path: '/parent', fileKey: 'parent-file', verify: vi.fn() })
+ expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'parent', transcriptPath: '/parent' })
+ expect(row.transcriptPath).toBe('/child')
+ expect(findResumedTranscript).not.toHaveBeenCalled()
+})
+
it('takes a database-backed engine on its recorded id, with no transcript to check', async () => {
// opencode/kilo/hermes/devin keep the conversation in SQLite: there is no file, and demanding one
// is what used to leave their resume with nothing to reopen.
@@ -55,14 +66,16 @@ it('captures and preserves the exact Hermes home before stopping its process', a
})
it.each([null, '/stale'])('repairs a known id with missing or invalid path %s', async transcriptPath => {
Object.assign(row, { sessionId: 'known', transcriptPath, codexHome: '/profile' })
- vi.mocked(validTranscriptPath).mockImplementation((_, path) => path === '/found')
+ vi.mocked(savedTranscriptEvidence).mockImplementation((_engine, _id, path) => ({ path: path === '/found' ? path : null, fileKey: 'fixture', verify: vi.fn() }))
vi.mocked(findResumedTranscript).mockResolvedValue('/found')
expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'known', transcriptPath: '/found' })
expect(findResumedTranscript).toHaveBeenCalledWith('claude', 'known', { codexHome: '/profile' })
})
-it.each([null, '/unsafe'])('retains the known id when its file is unavailable: %s', async path => {
+it.each([null, '/unsafe'])('holds the known id when its file is unavailable: %s', async path => {
row.sessionId = 'known'; vi.mocked(findResumedTranscript).mockResolvedValue(path)
- vi.mocked(validTranscriptPath).mockReturnValue(false); expect(await captureResumeIdentity(row)).toBe(row)
+ vi.mocked(savedTranscriptEvidence).mockReturnValue({ path: null, fileKey: null, verify: vi.fn() })
+ await expect(captureResumeIdentity(row)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(row.sessionId).toBe('known')
})
it('looks up a preallocated Pi session ID in its own project before stopping', async () => {
Object.assign(row, { engine: 'pi', sessionId: 'preallocated', transcriptPath: null })
@@ -99,10 +112,10 @@ it.each(['claude', 'codex'] as const)('captures an explicit %s resume without gu
expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'exact', transcriptPath: '/exact', source: 'stop-repair' })
expect(findLiveSession).not.toHaveBeenCalled()
})
-it('keeps an explicit file-backed resume unbound while its transcript is still unwritten', async () => {
+it('holds an explicit file-backed resume whose announced conversation is unavailable', async () => {
vi.mocked(resumeSessionId).mockReturnValue('exact')
vi.mocked(findResumedTranscript).mockResolvedValue(null)
- expect(await captureResumeIdentity(row)).toBe(row)
+ await expect(captureResumeIdentity(row)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
expect(findLiveSession).not.toHaveBeenCalled()
})
it('prefers current Claude native metadata to old resume argv', async () => {
@@ -118,6 +131,8 @@ it('captures a unique fresh session before its first hook arrives', async () =>
expect(findLiveSession).toHaveBeenCalledWith('claude', '/work', Date.parse(row.processIdentity!.startMarker), expect.objectContaining({ pid: 77, bornOnly: true, codexHome: undefined, expectedProcess: row.processIdentity }))
})
it.each([null, { sessionId: 'missing' }, { sessionId: 'unsafe', transcriptPath: '/unsafe' }])('does not bind ambiguous or unsafe history: %s', async found => {
- vi.mocked(findLiveSession).mockResolvedValue(found); vi.mocked(validTranscriptPath).mockReturnValue(false)
- expect(await captureResumeIdentity(row)).toBe(row)
+ vi.mocked(findLiveSession).mockResolvedValue(found)
+ vi.mocked(savedTranscriptEvidence).mockReturnValue({ path: null, fileKey: null, verify: vi.fn() })
+ if (found) await expect(captureResumeIdentity(row)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ else expect(await captureResumeIdentity(row)).toBe(row)
})
diff --git a/cli/src/lib/captureResumeIdentity.ts b/cli/src/lib/captureResumeIdentity.ts
index 815943072..8aa1191a4 100644
--- a/cli/src/lib/captureResumeIdentity.ts
+++ b/cli/src/lib/captureResumeIdentity.ts
@@ -7,11 +7,12 @@
* had nothing to reopen. `findLiveSession` already knows how to find a live session for all of them,
* including the four that keep theirs in a database rather than a file.
*/
-import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'
+import { engineKeepsTranscriptFile, type RegisteredSession } from './registry.js'
+import { controlTranscriptEvidence, savedTranscriptEvidence } from '../engines/transcriptBindings.js'
import { findLiveSession, findResumedTranscript, processSessionEvidence, type RepairedSession } from './sessionRepair.js'
import { resumeSessionId } from './tmux.js'
import { readProcessEvidence } from './processEvidence.js'
-import { NativeEvidenceBudget } from '../engines/kit/nativeEvidence.js'
+import { NativeEvidenceBudget, nativeUnavailable } from '../engines/kit/nativeEvidence.js'
import { isTerminalEngine } from '../engines/types.js'
export async function captureResumeIdentity(session: RegisteredSession): Promise<RegisteredSession> {
@@ -20,13 +21,24 @@ export async function captureResumeIdentity(session: RegisteredSession): Promise
const options = { codexHome: session.codexHome ?? undefined,
...(session.engine === 'pi' ? { cwd: session.cwd ?? undefined } : {}) }
const keepsFile = engineKeepsTranscriptFile(session.engine)
+ const verifiedPath = (id: string, path: string) => {
+ const proof = savedTranscriptEvidence(session.engine, id, path, options.codexHome)
+ proof.verify()
+ if (proof.path) controlTranscriptEvidence(session.engine, id, proof.path, options.codexHome, session.cwd).verify()
+ return proof.path
+ }
if (session.sessionId) {
// A database-backed engine has the whole record already: the id IS the conversation.
if (!keepsFile) return session
- if (session.transcriptPath && validTranscriptPath(session.engine, session.transcriptPath, options.codexHome)) return session
+ if (session.transcriptPath) {
+ const path = verifiedPath(session.sessionId, session.transcriptPath)
+ if (path) return path === session.transcriptPath ? session : { ...session, transcriptPath: path }
+ }
const transcriptPath = await findResumedTranscript(session.engine, session.sessionId, options)
- return transcriptPath && validTranscriptPath(session.engine, transcriptPath, options.codexHome)
- ? { ...session, transcriptPath } : session
+ const path = transcriptPath && verifiedPath(session.sessionId, transcriptPath)
+ if (path) return { ...session, transcriptPath: path }
+ if (session.engine === 'pi' && !session.transcriptPath) return session
+ return nativeUnavailable('the saved conversation file is unavailable')
}
const expected = session.processIdentity
if (!expected || !session.cwd) return session
@@ -51,11 +63,12 @@ export async function captureResumeIdentity(session: RegisteredSession): Promise
if (!found?.sessionId) return session
// A file-backed engine still has to produce a transcript this daemon can point a resume at; a
// database-backed one has nothing to check and is taken on its id alone.
- if (keepsFile && (!found.transcriptPath || !validTranscriptPath(session.engine, found.transcriptPath, options.codexHome))) return session
+ const transcriptPath = found.transcriptPath && keepsFile ? verifiedPath(found.sessionId, found.transcriptPath) : found.transcriptPath
+ if (keepsFile && !transcriptPath) return nativeUnavailable('the observed conversation file is unavailable')
return {
...session,
sessionId: found.sessionId,
- ...(found.transcriptPath ? { transcriptPath: found.transcriptPath } : {}),
+ ...(transcriptPath ? { transcriptPath } : {}),
...(found.hermesHome ? { hermesHome: found.hermesHome } : {}),
source: 'stop-repair',
boundAt: Date.now(),
diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.ts
index e3d8a1f53..48ab26525 100644
--- a/cli/src/lib/closeAgentService.spec.ts
+++ b/cli/src/lib/closeAgentService.spec.ts
@@ -379,6 +379,27 @@ it('automatically stops only after two timer observations of sustained idle', as
service.dispose()
await service.tick()
})
+it.each(['unavailable', 'untyped', 'cancelled', 'disposed'] as const)('keeps a queued Close visible through an activity read that is %s', async phase => {
+ await service.request(request('after_task'))
+ const plan = row.closePlan!
+ vi.mocked(deps.activity).mockImplementationOnce(async () => {
+ if (phase === 'cancelled') service.cancel(row.agentId)
+ if (phase === 'disposed') service.dispose()
+ throw phase === 'untyped' ? null : new Error('The conversation reader is unavailable.')
+ })
+ await service.tick()
+ expect(deps.stop).not.toHaveBeenCalled()
+ if (phase === 'cancelled') expect(row.closePlan).toBeUndefined()
+ else if (phase === 'disposed') expect(row.closePlan).toEqual(plan)
+ else {
+ expect(row.closePlan).toMatchObject({ id: plan.id, state: 'waiting', detail: expect.any(String) })
+ expect(deps.changed).toHaveBeenLastCalledWith(row)
+ await service.tick()
+ time += 5_000
+ await service.tick()
+ expect(deps.stop).toHaveBeenCalledOnce()
+ }
+})
it('resets a deferred idle observation after a failed read instead of stopping on stale evidence', async () => {
await service.request(request('after_task'))
await service.tick()
@@ -394,6 +415,20 @@ it('resets a deferred idle observation after a failed read instead of stopping o
await service.tick()
expect(deps.stop).toHaveBeenCalledOnce()
})
+it.each(['persist', 'notify'] as const)('contains a failed Close reason %s and retries the existing intent', async stage => {
+ await service.request(request('after_task'))
+ const id = row.closePlan!.id
+ vi.mocked(deps.activity).mockRejectedValueOnce(new Error('Reader unavailable'))
+ if (stage === 'persist') vi.spyOn(registry, 'setClosePlan').mockImplementationOnce(() => { throw Error('Disk full') })
+ else vi.mocked(deps.changed).mockImplementationOnce(() => { throw Error('Client disconnected') })
+ await expect(service.tick()).resolves.toBeUndefined()
+ expect(row.closePlan).toMatchObject({ id, state: 'waiting' })
+ expect(deps.stop).not.toHaveBeenCalled()
+ await service.tick()
+ time += 5_000
+ await service.tick()
+ expect(deps.stop).toHaveBeenCalledOnce()
+})
it('rejects a disposed service and a target replaced while reading activity', async () => {
service.dispose()
expect(await service.request(request('inspect'))).toEqual({ error: 'AGENT_CHANGED' })
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index 017a83524..046d98abe 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -224,9 +224,18 @@ export class CloseAgentService {
if (changed) this.deps.changed(changed)
}
}
- } catch {
- // A read failure is unknown activity, never proof that the task finished.
+ } catch (error) {
+ // A missing reader is unknown activity. Keep the durable intent and expose
+ // its reason while retrying, without changing a cancelled or replaced plan.
this.idleSince.delete(s.agentId)
+ const latest = this.deps.registry.byAgent(s.agentId)
+ if (!this.disposed && latest?.closePlan?.id === plan.id) {
+ try {
+ const changed = this.deps.registry.setClosePlan(s.agentId, { ...plan, state: 'waiting',
+ detail: error instanceof Error ? error.message : 'The conversation activity could not be confirmed.' })
+ if (changed) this.deps.changed(changed)
+ } catch { /* The preceding durable intent survives a failed reason update. Retry next tick. */ }
+ }
}
}
}
diff --git a/cli/src/lib/controlResume.golden.spec.ts b/cli/src/lib/controlResume.golden.spec.ts
new file mode 100644
index 000000000..43bf65743
--- /dev/null
+++ b/cli/src/lib/controlResume.golden.spec.ts
@@ -0,0 +1,106 @@
+/** Healthy resume composition recorded from the former code, with no host engine or terminal. */
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { fileURLToPath } from 'node:url'
+import { afterAll, expect, it, vi } from 'vitest'
+
+vi.mock('node:child_process', () => {
+ const forbidden = () => { throw Error('Host binaries are forbidden in the resume 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,
+}))
+vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: async () => ({ state: 'gone', reason: 'fixture' }) }))
+vi.mock('./tmuxAgentDiscovery.js', () => ({ listTmuxPanes: async () => ({ ok: true, panes: [] }) }))
+vi.mock('./tmux.js', () => ({ checkSessionRuntime: async () => ({ state: 'alive' }),
+ clearPaneRemainOnExit: async () => {}, tmuxPaneState: async () => ({ dead: false }),
+ resolvePaneEngineProcess: async () => ({ pid: 7001, executable: '<engine>', startMarker: 'fixture-start' }),
+}))
+vi.mock('./engineLaunch.js', async original => ({ ...await original<object>(),
+ buildEngineLaunchArgv: (engine: string, options: { resumeSessionId?: string }) => [
+ '<engine>', engine, ...(options.resumeSessionId ? ['--resume', options.resumeSessionId] : []),
+ ],
+ dropPermissionFlagIfUnsupported: async (_engine: unknown, choice: unknown) => ({ choice, droppedFlag: null }),
+ refusePermissionFlagIfUnsupported: async () => null,
+}))
+vi.mock('./engineBin.js', async original => ({ ...await original<object>(), enginePathOverride: () => '<engine>' }))
+
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/control-resume.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_CONTROL_RESUME_GOLDEN === '1'
+const expected = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8'))
+const captured: Record<string, unknown> = {}
+const ID = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa'
+
+it.each(['linux', 'darwin'])('keeps healthy native resume composition on %s', async platform => {
+ const descriptor = Object.getOwnPropertyDescriptor(process, 'platform')!
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'control-resume-golden-')))
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ try {
+ Object.defineProperty(process, 'platform', { ...descriptor, value: platform })
+ vi.useFakeTimers({ toFake: ['Date'], now: Date.parse('2026-10-10T08:00:00Z') })
+ for (const key of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR',
+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME']) {
+ const path = join(root, key); mkdirSync(path, { recursive: true, mode: 0o700 }); vi.stubEnv(key, path)
+ }
+ vi.stubEnv('CLAUDE_PROJECTS_DIR', join(root, 'CLAUDE_CONFIG_DIR', 'projects'))
+ vi.stubEnv('TZ', 'UTC')
+ writeFileSync(join(root, 'ADAPTER_DATA_DIR', 'engine-homes.json'), '{}')
+ vi.resetModules()
+ const { registry } = await import('./registry.js')
+ const { StoppedAgentStore } = await import('./stoppedAgents.js')
+ const { AgentRestartCoordinator } = await import('./restartAgent.js')
+ const { createResumeAgentService } = await import('./resumeAgentService.js')
+ let pane = 0
+ for (const engine of ['claude', 'codex', 'terminal'] as const) {
+ const directory = join(root, engine === 'codex' ? 'CODEX_HOME' : 'CLAUDE_CONFIG_DIR', engine === 'codex' ? 'sessions' : 'projects')
+ mkdirSync(directory, { recursive: true, mode: 0o700 })
+ const file = join(directory, `${ID}.jsonl`)
+ writeFileSync(file, JSON.stringify(engine === 'codex'
+ ? { type: 'session_meta', payload: { id: ID, cwd: root, source: 'cli' } }
+ : { type: 'user', sessionId: ID, cwd: root, isSidechain: false }) + '\n')
+ const original = registry.openPendingAgent({ engine, cwd: root, runtimes: [{ backend: 'tmux', paneId: `%${++pane}` }] })!
+ const saved = { ...original, sessionId: engine === 'terminal' ? '' : ID, transcriptPath: engine === 'terminal' ? null : file,
+ processIdentity: { pid: 7000, executable: '<engine>', startMarker: 'prior-process' } }
+ registry.removeAgent(saved.agentId)
+ const stopped = new StoppedAgentStore(join(root, 'saved', engine)); stopped.save(saved)
+ const events: unknown[] = []
+ const resume = createResumeAgentService({ registry, stoppedAgents: stopped, restartJobs: new AgentRestartCoordinator(),
+ stopJobs: new Map(), pinnedControls: new Set(), tmuxBackend: {
+ create: async request => { events.push(['create', request.command]); return { state: 'succeeded', dispatch: 'executed',
+ runtime: { backend: 'tmux', paneId: `%${++pane}` } } },
+ kill: async () => { throw Error('A healthy resume must not kill a pane') },
+ }, retainExitedSession: () => { throw Error('No live session exists in this fixture') },
+ announceSession: session => { events.push(['announce', session.engine, session.sessionId, session.launch?.state]) },
+ relaunchOverrides: async session => { events.push(['launch-prepare', session.engine, session.sessionId]);
+ return { ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } } },
+ prepareSessionResume: session => { events.push(['history-prepare', session.sessionId]) },
+ refreshGridWebSearch: () => { events.push(['grid']) }, clearDeleted: () => {}, attachDsh: () => {},
+ attachSession: async session => { events.push(['attach', session.sessionId]); return true },
+ })
+ const result = await resume(saved.agentId)
+ expect(result.ok).toBe(true)
+ if (!result.ok) throw Error('Resume did not produce an observation')
+ const key = `${platform}:${engine}`
+ captured[key] = { events, result: { ok: result.ok, resumed: result.resumed, engine: result.session.engine,
+ sessionId: result.session.sessionId, source: result.session.source, launch: result.session.launch },
+ reserved: stopped.resumeReservedAt(saved.agentId) !== null }
+ if (!RECORD) expect({ key, value: captured[key] }).toEqual({ key, value: expected[key] })
+ registry.removeAgent(saved.agentId)
+ }
+ } 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/controlTranscript.golden.spec.ts b/cli/src/lib/controlTranscript.golden.spec.ts
new file mode 100644
index 000000000..14be4dec5
--- /dev/null
+++ b/cli/src/lib/controlTranscript.golden.spec.ts
@@ -0,0 +1,105 @@
+/** Healthy capture and Close checkpoints recorded on main before the legacy path checks move. */
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, symlinkSync, 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 { AgentEngine } from '../engines/types.js'
+
+vi.mock('node:child_process', () => {
+ const forbidden = () => { throw Error('Host binaries are forbidden in the control transcript 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__/control-transcript.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_CONTROL_TRANSCRIPT_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'
+
+it.each(['linux', 'darwin'])('keeps complete native capture and checkpoint behavior on %s', async platform => {
+ const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'control-transcript-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 check = (name: string, value: unknown) => {
+ const key = `${platform}:${name}`
+ captured[key] = JSON.parse(JSON.stringify(value).split(root).join('<root>'))
+ if (!RECORD) expect({ key, value: captured[key] }).toEqual({ key, value: expected[key] })
+ }
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ try {
+ Object.defineProperty(process, 'platform', { ...originalPlatform, value: platform })
+ vi.useFakeTimers({ toFake: ['Date'], now: Date.parse('2026-10-10T08:00:00Z') })
+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR',
+ 'PI_HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_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')
+ const moved = path('moved-codex'), profile = path('profile')
+ write(path('ADAPTER_DATA_DIR', 'engine-homes.json'), JSON.stringify({ claude: [], codex: [moved] }))
+ const codex = JSON.stringify({ type: 'session_meta', payload: { id: A, cwd: root, source: 'cli' } }) + '\n'
+ const claude = JSON.stringify({ type: 'user', cwd: root, sessionId: A, isSidechain: false }) + '\n'
+ const pi = JSON.stringify({ type: 'session', version: 3, id: A, cwd: root }) + '\n'
+ const cases: Array<{ name: string; engine: AgentEngine; file?: string; text?: string; profile?: string; id?: string }> = [
+ { name: 'claude', engine: 'claude', file: path('CLAUDE_CONFIG_DIR', 'projects', 'project', `${A}.jsonl`), text: claude },
+ { name: 'codex', engine: 'codex', file: path('CODEX_HOME', 'sessions', `rollout-${A}.jsonl`), text: codex },
+ { name: 'moved-codex', engine: 'codex', file: join(moved, 'sessions', `rollout-${A}.jsonl`), text: codex },
+ { name: 'profile-codex', engine: 'codex', file: join(profile, 'sessions', `rollout-${A}.jsonl`), text: codex, profile },
+ { name: 'alias-codex', engine: 'codex', file: path('alias.jsonl') },
+ { name: 'pi', engine: 'pi', file: path('PI_HOME', 'agent', 'sessions', 'workspace', `2026-10-10T08-00-00-000Z_${A}.jsonl`), text: pi },
+ { name: 'unwritten-pi', engine: 'pi', id: B },
+ { name: 'terminal', engine: 'terminal', id: '' },
+ ]
+ for (const fixture of cases) if (fixture.file && fixture.text) write(fixture.file, fixture.text)
+ symlinkSync(cases[1].file!, path('alias.jsonl'))
+ vi.resetModules()
+ const { registry } = await import('./registry.js')
+ const { captureResumeIdentity } = await import('./captureResumeIdentity.js')
+ const { SessionCheckpointStore } = await import('./sessionCheckpoint.js')
+ let pane = 0
+ for (const fixture of cases) {
+ const entry = registry.openPendingAgent({ engine: fixture.engine, cwd: root,
+ codexHome: fixture.profile, runtimes: [{ backend: 'tmux', paneId: `%${++pane}` }] })!
+ Object.assign(entry, { sessionId: fixture.id ?? A, transcriptPath: fixture.file ?? null, source: 'fixture' })
+ const found = await captureResumeIdentity(entry)
+ check(`${fixture.name}:capture`, { engine: found.engine, sessionId: found.sessionId,
+ transcriptPath: found.transcriptPath, cwd: found.cwd, profile: found.codexHome, source: found.source })
+ const directory = path('checkpoints', fixture.name), store = new SessionCheckpointStore(directory)
+ await store.save(found, { screen: 'Unsent fixture draft' })
+ const manifestFile = () => readdirSync(directory).find(name => /^[a-f0-9]{64}\.json$/.test(name))!
+ const first = JSON.parse(readFileSync(join(directory, manifestFile()), 'utf8'))
+ await store.save(found, { screen: null })
+ const again = JSON.parse(readFileSync(join(directory, manifestFile()), 'utf8'))
+ const saved = readFileSync(join(directory, first.file), 'utf8')
+ const contents = fixture.file ? saved : (() => {
+ const snapshot = JSON.parse(saved); delete snapshot.agentId; return snapshot
+ })()
+ check(`${fixture.name}:checkpoint`, { engine: first.engine, sessionId: first.sessionId,
+ source: first.source, profile: first.codexHome, savedAt: first.savedAt, contents,
+ unchanged: JSON.stringify(first) === JSON.stringify(again),
+ files: readdirSync(directory).map(name => name.endsWith('.screen.json') ? 'screen' : name.endsWith('.history') ? 'history' : 'manifest').sort() })
+ }
+ ;(await import('./engineHomes.js')).resetEngineHomes()
+ } finally {
+ log.mockRestore(); vi.useRealTimers(); vi.unstubAllEnvs(); vi.resetModules()
+ Object.defineProperty(process, 'platform', originalPlatform)
+ 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/controlTranscript.spec.ts b/cli/src/lib/controlTranscript.spec.ts
new file mode 100644
index 000000000..cce1046bc
--- /dev/null
+++ b/cli/src/lib/controlTranscript.spec.ts
@@ -0,0 +1,459 @@
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { basename, dirname, join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+const faults = vi.hoisted(() => ({
+ copied: undefined as (() => void | Promise<void>) | undefined,
+ inspectedCheckpoint: undefined as (() => void) | undefined,
+ openingSource: undefined as (() => () => void) | undefined,
+ sourceFailure: undefined as 'open' | 'stat' | 'read' | 'close' | undefined,
+}))
+vi.mock('node:fs/promises', async original => {
+ const actual = await original<typeof import('node:fs/promises')>()
+ return { ...actual, copyFile: async (...args: Parameters<typeof actual.copyFile>) => {
+ const restore = faults.openingSource?.()
+ try { await actual.copyFile(...args) } finally { restore?.() }
+ await faults.copied?.()
+ }, open: async (...args: Parameters<typeof actual.open>) => {
+ const source = String(args[0]).endsWith('.jsonl')
+ if (source && faults.sourceFailure === 'open') throw Error('Source open unavailable')
+ const restore = source ? faults.openingSource?.() : undefined
+ const handle = await actual.open(...args).finally(() => restore?.())
+ if (source) {
+ const stat = handle.stat.bind(handle), read = handle.read.bind(handle), close = handle.close.bind(handle)
+ handle.close = async () => {
+ await close()
+ if (faults.sourceFailure === 'close') throw Error('Source close unavailable')
+ }
+ handle.stat = (async (...values: Parameters<typeof stat>) => {
+ if (faults.sourceFailure === 'stat') throw Error('Source stat unavailable')
+ return stat(...values)
+ }) as typeof handle.stat
+ handle.read = (async (...values: Parameters<typeof read>) => {
+ if (faults.sourceFailure === 'read') throw Error('Source read unavailable')
+ return read(...values)
+ }) as typeof handle.read
+ }
+ if (String(args[0]).endsWith('.history.tmp')) {
+ const write = handle.write.bind(handle)
+ handle.write = (async (...values: Parameters<typeof write>) => {
+ const result = await write(...values)
+ await faults.copied?.()
+ return result
+ }) as typeof handle.write
+ }
+ return handle
+ }, lstat: async (...args: Parameters<typeof actual.lstat>) => {
+ const result = await actual.lstat(...args)
+ if (String(args[0]).endsWith('.history')) faults.inspectedCheckpoint?.()
+ return result
+ } }
+})
+vi.mock('node:child_process', () => {
+ const forbidden = () => { throw Error('Host binaries are forbidden in the transcript authority fixture') }
+ return { exec: forbidden, execSync: forbidden, execFile: forbidden, execFileSync: forbidden,
+ spawn: forbidden, spawnSync: forbidden, fork: forbidden }
+})
+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,
+}))
+vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn(async () => 'gone') }))
+vi.mock('./engineLaunch.js', async original => ({ ...await original<object>(),
+ buildEngineLaunchArgv: () => ['<engine>'], dropPermissionFlagIfUnsupported: vi.fn(),
+}))
+vi.mock('./engineBin.js', async original => ({ ...await original<object>(), enginePathOverride: () => '<engine>' }))
+vi.mock('../core/engines/cursorTasks.js', () => ({ removePendingCursorTasks: vi.fn(async () => {}) }))
+
+const A = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa', B = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
+let root: string, transcript: string, directory: string
+let registry: typeof import('./registry.js')['registry']
+let row: import('./registry.js').RegisteredSession
+let capture: typeof import('./captureResumeIdentity.js')['captureResumeIdentity']
+let checkpoints: import('./sessionCheckpoint.js').SessionCheckpointStore
+const header = (id = A) => JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, source: 'cli' } }) + '\n'
+const files = () => Object.fromEntries(readdirSync(directory).map(name => [name, readFileSync(join(directory, name), 'utf8')]))
+
+beforeEach(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'control-transcript-')))
+ faults.copied = undefined; faults.inspectedCheckpoint = undefined; faults.openingSource = undefined; faults.sourceFailure = undefined
+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR',
+ 'PI_HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME']) {
+ const path = join(root, name); mkdirSync(path, { recursive: true, mode: 0o700 }); vi.stubEnv(name, path)
+ }
+ vi.stubEnv('CLAUDE_PROJECTS_DIR', join(root, 'CLAUDE_CONFIG_DIR', 'projects'))
+ mkdirSync(join(root, 'CODEX_HOME', 'sessions'))
+ writeFileSync(join(root, 'ADAPTER_DATA_DIR', 'engine-homes.json'), '{}')
+ transcript = join(root, 'CODEX_HOME', 'sessions', `rollout-${A}.jsonl`)
+ writeFileSync(transcript, header())
+ directory = join(root, 'checkpoints')
+ vi.resetModules()
+ vi.mocked((await import('./deleteAgentFallback.js')).terminateDeletedAgent).mockReset().mockResolvedValue('gone')
+ ;({ registry } = await import('./registry.js'))
+ capture = (await import('./captureResumeIdentity.js')).captureResumeIdentity
+ checkpoints = new (await import('./sessionCheckpoint.js')).SessionCheckpointStore(directory)
+ row = registry.openPendingAgent({ engine: 'codex', cwd: root, runtimes: [{ backend: 'tmux', paneId: '%1' }] })!
+ Object.assign(row, { sessionId: A, transcriptPath: transcript,
+ processIdentity: { pid: 7001, executable: '<codex>', startMarker: 'fixture-start' } })
+ registry.flush()
+})
+afterEach(() => {
+ faults.copied = undefined; faults.inspectedCheckpoint = undefined; faults.openingSource = undefined; faults.sourceFailure = undefined
+ vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.resetModules()
+ rmSync(root, { recursive: true, force: true })
+})
+
+it.each(['different conversation', 'partial header'])('holds capture of a saved %s before Stop can archive it', async state => {
+ writeFileSync(transcript, state === 'partial header' ? '{partial' : header(B))
+ await expect(capture(row)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(registry.byAgent(row.agentId)?.sessionId).toBe(A)
+})
+
+it.each(['different conversation', 'partial header', 'unreadable catalog'])('keeps the prior checkpoint and draft when its source has %s', async state => {
+ await checkpoints.save(row, { screen: 'Original unsent draft' })
+ const before = files()
+ if (state === 'unreadable catalog') writeFileSync(join(root, 'ADAPTER_DATA_DIR', 'engine-homes.json'), '{partial')
+ else writeFileSync(transcript, state === 'partial header' ? '{partial' : header(B))
+ await expect(checkpoints.save(row, { screen: 'Must not replace the prior draft' })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(files()).toEqual(before)
+})
+
+it.each(['header', 'catalog'])('rechecks the native %s after asynchronous copying before publishing a checkpoint', async changed => {
+ utimesSync(transcript, 1, 1)
+ await checkpoints.save(row, { screen: 'Original draft' })
+ const before = files()
+ // Force another checkpoint without changing its native header or identity.
+ writeFileSync(transcript, header() + '{"type":"event_msg"}\n')
+ utimesSync(transcript, 2, 2)
+ faults.copied = () => {
+ if (changed === 'catalog') writeFileSync(join(root, 'ADAPTER_DATA_DIR', 'engine-homes.json'), '{partial')
+ else {
+ writeFileSync(transcript, header(B) + '{"type":"event_msg"}\n')
+ // Same inode, byte count and timestamp do not prove the same native conversation.
+ utimesSync(transcript, 2, 2)
+ }
+ }
+ await expect(checkpoints.save(row, { screen: 'New draft' })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(files()).toEqual(before)
+})
+
+it('rechecks native identity after inspecting an otherwise reusable checkpoint', async () => {
+ await checkpoints.save(row, { screen: 'Original draft' })
+ const before = files()
+ faults.inspectedCheckpoint = () => writeFileSync(transcript, header(B))
+ await expect(checkpoints.save(row, { screen: 'New draft' })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(files()).toEqual(before)
+})
+
+it('holds a source descriptor opened through an ancestor that moves away and back', async () => {
+ await checkpoints.save(row, { screen: 'Original draft' })
+ const before = files()
+ writeFileSync(transcript, header() + '{"turn":"new content"}\n')
+ const sourceDirectory = dirname(transcript), parked = sourceDirectory + '-parked', other = sourceDirectory + '-other'
+ mkdirSync(other)
+ writeFileSync(join(other, basename(transcript)), header() + '{"turn":"wrong file!"}\n')
+ faults.openingSource = () => {
+ faults.openingSource = undefined
+ renameSync(sourceDirectory, parked); renameSync(other, sourceDirectory)
+ return () => { renameSync(sourceDirectory, other); renameSync(parked, sourceDirectory) }
+ }
+ await expect(checkpoints.save(row, { screen: 'New draft' })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(files()).toEqual(before)
+ expect(readFileSync(transcript, 'utf8')).toContain('new content')
+})
+
+it('copies a newly appended body rather than reusing history inspected before an await', async () => {
+ await checkpoints.save(row)
+ faults.inspectedCheckpoint = () => {
+ faults.inspectedCheckpoint = undefined
+ writeFileSync(transcript, header() + '{"turn":"flushed during checkpoint lookup"}\n')
+ }
+ await checkpoints.save(row)
+ expect(Object.values(files()).some(contents => contents === readFileSync(transcript, 'utf8'))).toBe(true)
+})
+
+it('does not reuse same-sized history rewritten in place with a restored modification time', async () => {
+ writeFileSync(transcript, header() + '{"turn":"first"}\n')
+ utimesSync(transcript, 1, 1)
+ await checkpoints.save(row)
+ writeFileSync(transcript, header() + '{"turn":"later"}\n')
+ utimesSync(transcript, 1, 1)
+ await checkpoints.save(row)
+ expect(Object.values(files()).some(contents => contents === readFileSync(transcript, 'utf8'))).toBe(true)
+})
+
+it.each(['open', 'stat', 'read', 'close'] as const)('holds an unavailable source %s without replacing saved history or draft', async stage => {
+ await checkpoints.save(row, { screen: 'Original draft' })
+ const before = files()
+ writeFileSync(transcript, header() + '{"turn":"new content"}\n')
+ faults.sourceFailure = stage
+ await expect(checkpoints.save(row, { screen: 'New draft' })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(files()).toEqual(before)
+})
+
+it('keeps the prior draft if closing an otherwise reusable source descriptor fails', async () => {
+ await checkpoints.save(row, { screen: 'Original draft' })
+ const before = files()
+ faults.sourceFailure = 'close'
+ await expect(checkpoints.save(row, { screen: 'New draft' })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(files()).toEqual(before)
+})
+
+it('keeps a fresh lookup budget after a slow copy instead of expiring otherwise valid history', async () => {
+ faults.copied = async () => { await new Promise(resolve => setTimeout(resolve, 350)) }
+ await expect(checkpoints.save(row, { screen: 'The unsent draft' })).resolves.toBeUndefined()
+ expect(Object.values(files()).some(contents => contents === header())).toBe(true)
+})
+
+it('refuses a physically replaced transcript even when its new header names the same conversation', async () => {
+ const { controlTranscriptEvidence } = await import('../engines/transcriptBindings.js')
+ const proof = controlTranscriptEvidence('codex', A, transcript)
+ const replacement = transcript + '.replacement'
+ writeFileSync(replacement, header()); renameSync(replacement, transcript)
+ expect(() => proof.verify()).toThrow('replaced during the operation')
+})
+
+it('accepts an appended body with a fresh complete header after a long wait', async () => {
+ const { controlTranscriptEvidence } = await import('../engines/transcriptBindings.js')
+ const proof = controlTranscriptEvidence('codex', A, transcript)
+ await new Promise(resolve => setTimeout(resolve, 350))
+ writeFileSync(transcript, header() + '{"type":"event_msg"}\n')
+ expect(() => proof.verify()).not.toThrow()
+})
+
+it.each(['claude', 'pi'] as const)('eagerly checks the saved %s opening without a worker', async engine => {
+ const folder = engine === 'claude' ? join(root, 'CLAUDE_CONFIG_DIR', 'projects', 'fixture')
+ : join(root, 'PI_HOME', 'agent', 'sessions', 'fixture')
+ mkdirSync(folder, { recursive: true })
+ transcript = join(folder, `${A}.jsonl`)
+ const opening = (id: string, extra: object = {}) => JSON.stringify(engine === 'claude'
+ ? { type: 'user', sessionId: id, cwd: root, isSidechain: false, ...extra }
+ : { type: 'session', id, cwd: root, ...extra }) + '\n'
+ Object.assign(row, { engine, transcriptPath: transcript })
+ writeFileSync(transcript, opening(A))
+ await checkpoints.save(row, { screen: 'Original draft' })
+ const before = files()
+ for (const contents of [opening(B), '{partial', opening(A, engine === 'claude' ? { isSidechain: true } : { cwd: dirname(root) })]) {
+ writeFileSync(transcript, contents)
+ await expect(capture(row)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ await expect(checkpoints.save(row, { screen: 'New draft' })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(files()).toEqual(before)
+ }
+ writeFileSync(transcript, (engine === 'claude' ? '{"type":"queue-operation"}\n' : '') + opening(A))
+ await expect(capture(row)).resolves.toMatchObject({ sessionId: A, transcriptPath: transcript })
+})
+
+it.each(['claude', 'pi'] as const)('does not let a different physical %s file lend its valid opening to a saved path', async engine => {
+ const { NativeFiles } = await import('../engines/kit/nativeFiles.js')
+ const { controlTranscriptEvidence } = await import('../engines/transcriptBindings.js')
+ const parent = engine === 'claude' ? join(root, 'CLAUDE_CONFIG_DIR', 'projects') : join(root, 'PI_HOME', 'agent', 'sessions')
+ const folder = join(parent, 'source'), parked = join(parent, 'parked'), other = join(parent, 'other')
+ mkdirSync(folder, { recursive: true }); mkdirSync(other)
+ const opening = (id: string) => JSON.stringify(engine === 'claude'
+ ? { type: 'user', sessionId: id, cwd: root, isSidechain: false } : { type: 'session', id, cwd: root }) + '\n'
+ const path = join(folder, `${A}.jsonl`)
+ writeFileSync(path, opening(B)); writeFileSync(join(other, `${A}.jsonl`), opening(A))
+ const readOpening = NativeFiles.prototype.opening, verify = NativeFiles.prototype.verify
+ const swapped = new Set<import('../engines/kit/nativeFiles.js').NativeFiles>()
+ let moved = false
+ const restore = () => { if (moved) { renameSync(folder, other); renameSync(parked, folder); moved = false } }
+ vi.spyOn(NativeFiles.prototype, 'opening').mockImplementation(function (this: import('../engines/kit/nativeFiles.js').NativeFiles, selected, rule) {
+ renameSync(folder, parked); renameSync(other, folder); moved = true; swapped.add(this)
+ return readOpening.call(this, selected, rule)
+ })
+ vi.spyOn(NativeFiles.prototype, 'verify').mockImplementation(function (this: import('../engines/kit/nativeFiles.js').NativeFiles, selected) {
+ verify.call(this, selected)
+ if (swapped.has(this)) restore()
+ })
+ try { expect(() => controlTranscriptEvidence(engine, A, path, undefined, root)).toThrow(expect.objectContaining({ code: 'IDENTITY_UNAVAILABLE' })) }
+ finally { restore() }
+ expect(readFileSync(path, 'utf8')).toBe(opening(B))
+})
+
+it('preserves a repaired parent through Stop and the final real forget archive', async () => {
+ const { createStopAgentService } = await import('./stopAgentService.js')
+ const { createForgetSession } = await import('../core/agents/forget.js')
+ const { StoppedAgentStore } = await import('./stoppedAgents.js')
+ const { AgentRestartCoordinator } = await import('./restartAgent.js')
+ const parent = transcript, child = join(dirname(parent), `rollout-${B}.jsonl`)
+ writeFileSync(child, JSON.stringify({ type: 'session_meta', payload: { id: B, cwd: root,
+ source: { subagent: { thread_spawn: { parent_thread_id: A } } } } }) + '\n')
+ row.transcriptPath = child
+ const stopped = new StoppedAgentStore(join(root, 'stopped'))
+ const forget = createForgetSession({ registry, stoppedAgents: stopped, syncRecapPool: vi.fn(), normalizers: { forget: vi.fn() },
+ forgetAttach: vi.fn(), turnStartedAt: new Map(), neverFoldedHistory: new Set(), replayedFirstTurn: new Set(),
+ clearAgyIdleWatch: vi.fn(), cursorDiscovery: { remove: vi.fn() }, cursorSubagents: { forget: vi.fn() },
+ runtimeProfiles: { forget: vi.fn() }, watcher: { removeSession: vi.fn(async () => {}) },
+ stopHeartbeat: vi.fn(), teams: { forget: vi.fn() }, input: { forget: vi.fn() }, deviceInput: { forget: vi.fn() },
+ detachDsh: vi.fn(), mirror: { forget: vi.fn() }, clients: { send: vi.fn(), sendCommander: vi.fn() },
+ dataDir: join(root, 'ADAPTER_DATA_DIR') })
+ const stop = createStopAgentService({ registry, stoppedAgents: stopped, restartJobs: new AgentRestartCoordinator(),
+ stopJobs: new Map(), tmuxBackend: { kill: vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })) },
+ agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn(async () => {}) },
+ forgetSession: forget, markDeleted: vi.fn(), clearDeleted: vi.fn(), stopNative: async () => {} })
+ await stop(row.agentId, { checkpoint: async session => {
+ expect(session.transcriptPath).toBe(parent)
+ stopped.save({ ...row, title: 'A hook saved the stale child path' })
+ } })
+ expect(registry.byAgent(row.agentId)).toBeUndefined()
+ expect(stopped.get(row.agentId)).toMatchObject({ active: false, sessionId: A, transcriptPath: parent })
+})
+
+it('retains a typed Stop hold when the native broker contains a failed grant check', async () => {
+ const { createNativeControls } = await import('../core/engines/nativeControls.js')
+ const { engineNativeControlRequests } = await import('../engines/worker/nativeControlRequests.js')
+ const { launch } = await import('../engines/codex/launch.js')
+ const { argvTokens } = await import('./tmux.js')
+ const { createStopAgentService } = await import('./stopAgentService.js')
+ const { StoppedAgentStore } = await import('./stoppedAgents.js')
+ const { AgentRestartCoordinator } = await import('./restartAgent.js')
+ const { terminateDeletedAgent } = await import('./deleteAgentFallback.js')
+ const mutation = vi.fn()
+ let core!: ReturnType<typeof createNativeControls>
+ const requests = engineNativeControlRequests('codex', { load: async () => ({ activity: async () => 'working',
+ stop: async (_conversation, host) => { writeFileSync(transcript, header(B)); if (await host.current()) mutation() },
+ recover: async () => {}, close: () => {} }), recycle: vi.fn(),
+ query: async (query, payload) => core.answer('engine-codex', query, payload) ?? { error: 'DENIED' } })
+ core = createNativeControls({ call: async (_service, method, payload) =>
+ requests[method]({ ...payload, requestId: 'fixture-request' }, { owner: true, local: true }) as Promise<Record<string, unknown>>,
+ handles: () => true, inline: () => undefined, servers: { codex: launch.sharedServer! }, home: () => join(root, 'CODEX_HOME'),
+ rows: async () => [{ ...row.processIdentity!, parentPid: 1, args: `codex resume ${A}` },
+ { pid: 90, parentPid: 1, executable: 'codex', startMarker: 'server-birth', args: 'codex app-server' }],
+ argv: argvTokens, readFile: async () => JSON.stringify({ pid: 90, processStartTime: 'server-birth' }), log: vi.fn() })
+ core.connected('engine-codex')
+ const kill = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const })), forget = vi.fn()
+ const stop = createStopAgentService({ registry, stoppedAgents: new StoppedAgentStore(join(root, 'stopped')),
+ restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(), tmuxBackend: { kill },
+ agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn(async () => {}) },
+ forgetSession: forget, markDeleted: vi.fn(), clearDeleted: vi.fn(), stopNative: core.stop })
+ await expect(stop(row.agentId)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(mutation).not.toHaveBeenCalled(); expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ expect(kill).not.toHaveBeenCalled(); expect(forget).not.toHaveBeenCalled()
+})
+
+it.each(['checkpoint', 'native drain'])('holds Stop when its transcript changes during the %s await', async phase => {
+ const { createStopAgentService } = await import('./stopAgentService.js')
+ const { StoppedAgentStore } = await import('./stoppedAgents.js')
+ const { AgentRestartCoordinator } = await import('./restartAgent.js')
+ const { terminateDeletedAgent } = await import('./deleteAgentFallback.js')
+ vi.mocked(terminateDeletedAgent).mockClear()
+ const kill = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))
+ const forget = vi.fn()
+ const stopNative = vi.fn(async () => { if (phase === 'native drain') writeFileSync(transcript, header(B)) })
+ const stop = createStopAgentService({ registry, stoppedAgents: new StoppedAgentStore(join(root, 'stopped')),
+ restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(), tmuxBackend: { kill },
+ agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn(async () => {}) },
+ forgetSession: forget, markDeleted: vi.fn(), clearDeleted: vi.fn(), stopNative })
+ await expect(stop(row.agentId, { checkpoint: async () => {
+ if (phase === 'checkpoint') writeFileSync(transcript, header(B))
+ } })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ expect(kill).not.toHaveBeenCalled()
+ expect(forget).not.toHaveBeenCalled()
+ expect(registry.byAgent(row.agentId)?.sessionId).toBe(A)
+ if (phase === 'checkpoint') expect(stopNative).not.toHaveBeenCalled()
+})
+
+it.each(['binding', 'process birth', 'native grant', 'contained grant', 'process signal', 'pane completion'] as const)(
+ 'keeps Stop authority at the %s boundary', async phase => {
+ const { createStopAgentService } = await import('./stopAgentService.js')
+ const { StoppedAgentStore } = await import('./stoppedAgents.js')
+ const { AgentRestartCoordinator } = await import('./restartAgent.js')
+ const { terminateDeletedAgent } = await import('./deleteAgentFallback.js')
+ if (phase === 'process birth') row.processIdentity!.startTicks = 1
+ const signal = vi.spyOn(process, 'kill').mockReturnValue(true)
+ const realTermination = (await vi.importActual<typeof import('./deleteAgentFallback.js')>('./deleteAgentFallback.js')).terminateDeletedAgent
+ vi.mocked(terminateDeletedAgent).mockImplementationOnce(async (session, dependencies) => {
+ if (phase === 'process signal') return realTermination(session, { ...dependencies,
+ sleep: async () => {}, checkRuntime: async () => { writeFileSync(transcript, header(B)); return { state: 'alive' } },
+ })
+ return 'gone'
+ })
+ const kill = vi.fn(async () => {
+ if (phase === 'pane completion') writeFileSync(transcript, header(B))
+ return { state: 'succeeded' as const, dispatch: 'executed' as const }
+ })
+ const forget = vi.fn(), nativeMutation = vi.fn()
+ const stop = createStopAgentService({ registry, stoppedAgents: new StoppedAgentStore(join(root, 'stopped')),
+ restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(), tmuxBackend: { kill },
+ agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn(async () => {}) },
+ forgetSession: forget, markDeleted: vi.fn(), clearDeleted: vi.fn(), stopNative: async (_session, current) => {
+ if (phase === 'native grant' || phase === 'contained grant') writeFileSync(transcript, header(B))
+ if (phase === 'contained grant') { try { current() } catch {} return }
+ if (current()) nativeMutation()
+ } })
+ await expect(stop(row.agentId, { checkpoint: async (_session, when) => {
+ if (phase === 'binding' && when === 'before') registry.byAgent(row.agentId)!.boundAt = 2
+ if (phase === 'process birth' && when === 'before') registry.byAgent(row.agentId)!.processIdentity!.startTicks = 2
+ } })).rejects.toMatchObject({ code: phase === 'binding' || phase === 'process birth' ? 'STOP_UNCONFIRMED' : 'IDENTITY_UNAVAILABLE' })
+ expect(signal).not.toHaveBeenCalled()
+ expect(forget).not.toHaveBeenCalled()
+ if (phase !== 'pane completion') expect(kill).not.toHaveBeenCalled()
+ if (phase === 'native grant' || phase === 'contained grant' || phase === 'binding' || phase === 'process birth') expect(nativeMutation).not.toHaveBeenCalled()
+ })
+
+it.each(['before', 'configuration', 'history repair', 'permission', 'tmux dispatch', 'conversation ownership', 'allocation'] as const)(
+ 'holds Resume when its native conversation changes during %s', async phase => {
+ const { createResumeAgentService } = await import('./resumeAgentService.js')
+ const { StoppedAgentStore } = await import('./stoppedAgents.js')
+ const { AgentRestartCoordinator } = await import('./restartAgent.js')
+ const { checkPidRuntime } = await import('./deleteAgentFallback.js')
+ const { dropPermissionFlagIfUnsupported } = await import('./engineLaunch.js')
+ const { TmuxBackend } = await import('./tmuxBackend.js')
+ const { tmuxFeaturesOf } = await import('./tmuxVersion.js')
+ vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'gone', reason: 'fixture process ended' })
+ vi.mocked(dropPermissionFlagIfUnsupported).mockImplementation(async (_engine, choice) => {
+ if (phase === 'permission') writeFileSync(transcript, header(B))
+ return { choice, droppedFlag: null }
+ })
+ registry.removeAgent(row.agentId)
+ const stopped = new StoppedAgentStore(join(root, 'stopped')); stopped.save(row)
+ const writeConfiguration = vi.fn()
+ const prepare = vi.fn(() => { if (phase === 'history repair') writeFileSync(transcript, header(B)) })
+ const create = vi.fn(async () => {
+ writeFileSync(transcript, header(B))
+ return { state: 'succeeded' as const, dispatch: 'executed' as const, runtime: { backend: 'tmux' as const, paneId: '%99' } }
+ })
+ const kill = vi.fn(async () => ({ state: 'succeeded' as const, dispatch: 'executed' as const }))
+ const announce = vi.fn()
+ let newOwner: string | undefined
+ const backend = phase === 'tmux dispatch' || phase === 'conversation ownership' ? new TmuxBackend(undefined, () => 'fixture-owner', () => {}, async () => {
+ // The backend has accepted the request, but has not crossed its actual process-dispatch gate.
+ if (phase === 'conversation ownership') {
+ const other = registry.openPendingAgent({ engine: 'codex', cwd: root, runtimes: [{ backend: 'tmux', paneId: '%88' }] })!
+ const admitted = registry.register({ engine: 'codex', cwd: root, tmuxPane: '%88', sessionId: A, transcriptPath: transcript })!
+ expect(admitted.entry.agentId).toBe(other.agentId)
+ newOwner = other.agentId
+ } else writeFileSync(transcript, header(B))
+ return tmuxFeaturesOf({ major: 3, minor: 7 })
+ }) : { create, kill }
+ const resume = createResumeAgentService({ registry, stoppedAgents: stopped, restartJobs: new AgentRestartCoordinator(),
+ stopJobs: new Map(), pinnedControls: new Set(), tmuxBackend: backend,
+ retainExitedSession: vi.fn(), announceSession: announce,
+ relaunchOverrides: async (_session, _source, current) => {
+ await Promise.resolve()
+ if (phase === 'configuration') writeFileSync(transcript, header(B))
+ if (current()) writeConfiguration()
+ return { ok: true, overrides: { env: {}, extraArgs: [], clearEnv: [] } }
+ },
+ prepareSessionResume: prepare, refreshGridWebSearch: vi.fn(), clearDeleted: vi.fn(), attachDsh: vi.fn(),
+ attachSession: vi.fn(async () => true),
+ })
+ if (phase === 'before') writeFileSync(transcript, header(B))
+ await expect(resume(row.agentId)).resolves.toMatchObject({ ok: false,
+ error: phase === 'allocation' ? 'RESUME_UNCONFIRMED' : 'IDENTITY_UNAVAILABLE',
+ detail: expect.stringContaining(phase === 'conversation ownership' ? 'another live harness' : 'different conversation') })
+ expect(registry.byAgent(row.agentId)).toBeUndefined()
+ expect(announce).not.toHaveBeenCalled()
+ expect(stopped.get(row.agentId)?.sessionId).toBe(A)
+ if (newOwner) expect(registry.bySession(A)?.agentId).toBe(newOwner)
+ if (phase === 'before' || phase === 'configuration') {
+ expect(writeConfiguration).not.toHaveBeenCalled()
+ expect(prepare).not.toHaveBeenCalled()
+ }
+ if (phase === 'allocation') expect(kill).toHaveBeenCalledExactlyOnceWith({ backend: 'tmux', paneId: '%99' })
+ else { expect(create).not.toHaveBeenCalled(); expect(stopped.resumeReservedAt(row.agentId)).toBeNull() }
+ },
+)
diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.ts
index ac610aa2b..582e9d9ba 100644
--- a/cli/src/lib/createAgentPane.ts
+++ b/cli/src/lib/createAgentPane.ts
@@ -77,6 +77,9 @@ export interface CreateAgentPaneDeps {
/** The agent this pane is a fork of (`agent_fork`), recorded on the row; null otherwise. */
forkedFrom?: ForkOrigin | null
externalResume?: ExternalResumeIntent
+ /** Rechecked by the backend after its gates and immediately before process dispatch. */
+ current?: () => boolean
+ onDispatch?: () => void
maxAttempts?: number
}
@@ -95,6 +98,8 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<
cwd: deps.spawnCwd ?? homedir(),
label,
command: deps.argv,
+ ...(deps.current ? { current: deps.current } : {}),
+ ...(deps.onDispatch ? { onDispatch: deps.onDispatch } : {}),
...(deps.env ? { env: deps.env } : {}),
})
if (spawned.state !== 'succeeded') {
diff --git a/cli/src/lib/purgeAgentService.spec.ts b/cli/src/lib/purgeAgentService.spec.ts
index 96468d8d6..94586917b 100644
--- a/cli/src/lib/purgeAgentService.spec.ts
+++ b/cli/src/lib/purgeAgentService.spec.ts
@@ -21,7 +21,9 @@ beforeEach(() => {
mkdirSync(join(codexHome, 'sessions'), { recursive: true }); mkdirSync(cwd)
session = registry.openPendingAgent({ engine: 'codex', cwd, codexHome, runtimes: [{ backend: 'tmux', paneId: '%77' }] })!
Object.assign(session, { sessionId: 'selected-session', launch: { state: 'ready' }, transcriptPath: join(codexHome, 'sessions', 'selected-session.jsonl') })
- writeFileSync(session.transcriptPath!, 'selected conversation')
+ writeFileSync(session.transcriptPath!, JSON.stringify({ type: 'session_meta', payload: {
+ id: session.sessionId, cwd, source: 'cli',
+ } }) + '\n')
writeFileSync(join(codexHome, 'sessions', 'other.jsonl'), 'another conversation')
writeFileSync(join(cwd, 'project.txt'), 'project files stay')
stopped = new StoppedAgentStore(join(root, 'stopped'))
diff --git a/cli/src/lib/resumeAgentService.spec.ts b/cli/src/lib/resumeAgentService.spec.ts
index 748276712..b1dbef636 100644
--- a/cli/src/lib/resumeAgentService.spec.ts
+++ b/cli/src/lib/resumeAgentService.spec.ts
@@ -4,7 +4,9 @@ import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { createResumeAgentService, type ResumeAgentServiceDeps } from './resumeAgentService.js'
import { RESUME_READINESS_BUDGET_MS } from './resumeStoppedAgent.js'
-import { registry, validTranscriptPath, type RegisteredSession } from './registry.js'
+import { registry, type RegisteredSession } from './registry.js'
+import { controlTranscriptEvidence } from '../engines/transcriptBindings.js'
+import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'
import { env } from '../config/env.js'
import { StoppedAgentStore } from './stoppedAgents.js'
import { AgentRestartCoordinator } from './restartAgent.js'
@@ -33,7 +35,7 @@ vi.mock('./engineLaunch.js', async importOriginal => ({
vi.mock('./engineBin.js', () => ({ enginePathOverride: vi.fn(() => undefined) }))
vi.mock('./engineInstall.js', async original => ({ ...await original<object>(), engineInstallRecipe: () => ({ command: 'fixture-install' }) }))
vi.mock('../dsh/installed.js', () => ({ installedDsh: vi.fn() }))
-vi.mock('./registry.js', async original => ({ ...await original<object>(), validTranscriptPath: vi.fn(() => true) }))
+vi.mock('../engines/transcriptBindings.js', async original => ({ ...await original<object>(), controlTranscriptEvidence: vi.fn() }))
let dir: string
let saved: RegisteredSession
@@ -50,6 +52,14 @@ function rewrite(extra: Partial<RegisteredSession>) { saved = { ...saved, ...ext
function start() { return createResumeAgentService(deps)(saved.agentId) }
function deferred<T>() { let resolve!: (v: T) => void; const promise = new Promise<T>(r => { resolve = r }); return { promise, resolve } }
+it('retains the reservation if terminal dispatch starts but loses its reply', async () => {
+ create.mockImplementationOnce(async request => { request.onDispatch(); throw Error('Terminal transport disconnected') })
+ await expect(start()).rejects.toThrow('Terminal transport disconnected')
+ expect(deps.stoppedAgents.resumeReservedAt(saved.agentId)).not.toBeNull()
+ expect(registry.byAgent(saved.agentId)).toBeUndefined()
+ expect(deps.announceSession).not.toHaveBeenCalled()
+})
+
beforeEach(() => {
vi.clearAllMocks()
for (const row of registry.list()) registry.removeAgent(row.agentId)
@@ -61,7 +71,7 @@ beforeEach(() => {
store.save(saved)
create.mockReset().mockResolvedValue({ state: 'succeeded', runtime: { backend: 'tmux', paneId: pane } })
kill.mockReset().mockResolvedValue({ state: 'succeeded' })
- vi.mocked(validTranscriptPath).mockReturnValue(true)
+ vi.mocked(controlTranscriptEvidence).mockImplementation((_engine, _id, path) => ({ path, verify: vi.fn() }))
vi.mocked(enginePathOverride).mockReturnValue(undefined)
vi.mocked(refusePermissionFlagIfUnsupported).mockReset().mockResolvedValue(null)
vi.mocked(installedDsh).mockReturnValue(undefined)
@@ -279,7 +289,7 @@ describe('production resume handler', () => {
['removed cwd', () => rewrite({ cwd: join(dir, 'gone') }), 'CWD_NOT_FOUND'],
['file cwd', () => { const file = join(dir, 'file'); writeFileSync(file, 'file'); rewrite({ cwd: file }) }, 'CWD_NOT_FOUND'],
['missing transcript', () => rewrite({ transcriptPath: '' }), 'RESUME_UNAVAILABLE'],
- ['invalid transcript', () => vi.mocked(validTranscriptPath).mockReturnValue(false), 'RESUME_UNAVAILABLE'],
+ ['invalid transcript', () => vi.mocked(controlTranscriptEvidence).mockImplementation(() => { throw new IdentityReadUnavailable('fixture source unavailable') }), 'IDENTITY_UNAVAILABLE'],
['old process alive', () => vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'alive' }), 'AGENT_BUSY'],
['old process unknown', () => vi.mocked(checkPidRuntime).mockResolvedValue({ state: 'unknown', reason: 'fixture' }), 'AGENT_BUSY'],
] as const)('refuses %s without allocating or losing history', async (_label, setup, error) => {
@@ -317,6 +327,34 @@ describe('production resume handler', () => {
expect(deps.stoppedAgents.beginResume(saved.agentId) === null).toBe(reason !== 'tmux is unavailable')
expect(registry.byAgent(saved.agentId)).toBeUndefined()
})
+ it('retains a typed native hold from synchronous history repair and releases its reservation', async () => {
+ vi.mocked(deps.prepareSessionResume).mockImplementationOnce(() => { throw new IdentityReadUnavailable('the native store is incomplete') })
+ expect(await start()).toMatchObject({ ok: false, error: 'IDENTITY_UNAVAILABLE' })
+ expect(create).not.toHaveBeenCalled()
+ expect(deps.stoppedAgents.resumeReservedAt(saved.agentId)).toBeNull()
+ expect(deps.stoppedAgents.get(saved.agentId)?.sessionId).toBe(saved.sessionId)
+ })
+
+ it.each(['permission', 'argv'] as const)('checks cancellation after %s preparation before allocating a pane', async phase => {
+ if (phase === 'permission') vi.mocked(dropPermissionFlagIfUnsupported).mockImplementationOnce(async (_engine, choice) => {
+ deps.restartJobs.cancel(saved.agentId)
+ return { choice, droppedFlag: null }
+ })
+ else vi.mocked(buildEngineLaunchArgv).mockImplementationOnce(() => { deps.restartJobs.cancel(saved.agentId); return ['fixture-engine'] })
+ expect(await start()).toMatchObject({ ok: false, error: 'AGENT_CHANGED' })
+ expect(create).not.toHaveBeenCalled()
+ expect(deps.stoppedAgents.resumeReservedAt(saved.agentId)).toBeNull()
+ })
+
+ it('releases the reservation and preserves an unexpected launch preparation failure', async () => {
+ const failure = new Error('private configuration write refused')
+ vi.mocked(deps.relaunchOverrides).mockRejectedValueOnce(failure)
+ await expect(start()).rejects.toBe(failure)
+ expect(create).not.toHaveBeenCalled()
+ expect(deps.stoppedAgents.resumeReservedAt(saved.agentId)).toBeNull()
+ expect(deps.stoppedAgents.get(saved.agentId)?.sessionId).toBe(saved.sessionId)
+ })
+
it('cancels a tmux allocation without registering or reusing its pane', async () => {
create.mockImplementation(async () => { deps.restartJobs.cancel(saved.agentId); return { state: 'succeeded', runtime: { backend: 'tmux', paneId: pane } } })
expect(await start()).toMatchObject({ error: 'AGENT_CHANGED' }); expect(kill).toHaveBeenCalledTimes(1)
diff --git a/cli/src/lib/resumeAgentService.ts b/cli/src/lib/resumeAgentService.ts
index da4567d2e..0c0323449 100644
--- a/cli/src/lib/resumeAgentService.ts
+++ b/cli/src/lib/resumeAgentService.ts
@@ -2,7 +2,9 @@
import { transcriptSize, type RelaunchMarks } from '../core/transcripts/relaunch.js'
import { isTerminalEngine } from '../engines/types.js'
import { installedDsh } from '../dsh/installed.js'
-import { engineKeepsTranscriptFile, registry as liveRegistry, validTranscriptPath, type RegisteredSession } from './registry.js'
+import { engineKeepsTranscriptFile, registry as liveRegistry, type RegisteredSession } from './registry.js'
+import { controlTranscriptEvidence } from '../engines/transcriptBindings.js'
+import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'
import type { StoppedAgentStore } from './stoppedAgents.js'
import { resumeStoppedAgent, waitForResumedAgent, resumeChanged, resumeUnconfirmed, RESUME_READINESS_BUDGET_MS } from './resumeStoppedAgent.js'
import { checkPidRuntime } from './deleteAgentFallback.js'
@@ -190,15 +192,17 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
if (saved.grid && !saved.gridLaunch) return { ok: false, error: 'GRID_CREDENTIAL_REQUIRED', detail: 'The saved provider configuration is unavailable.' }
if (saved.dsh && !installedDsh(saved.dsh)) return { ok: false, error: 'INVALID_DSH', detail: 'Install this harness from the Harness Store before resuming it.' }
if (!saved.cwd) return { ok: false, error: 'CWD_NOT_FOUND', detail: 'The saved project folder is no longer available.' }
- const missing = workspaceMissing(saved.cwd)
+ const cwd = saved.cwd
+ const missing = workspaceMissing(cwd)
if (missing) return missing
// Only for an engine whose conversation IS a file. opencode, kilo, hermes and devin keep
// theirs in a database, so they have no transcript to point at and demanding one here refused
// a resume that works — after the harness had already been paused.
- if (resumeSessionId && engineKeepsTranscriptFile(saved.engine)
- && (!saved.transcriptPath || !validTranscriptPath(saved.engine, saved.transcriptPath, saved.codexHome ?? undefined))) {
+ if (resumeSessionId && engineKeepsTranscriptFile(saved.engine) && !saved.transcriptPath) {
return { ok: false, error: 'RESUME_UNAVAILABLE', detail: 'The saved conversation file is unavailable. Start a new conversation separately.' }
}
+ const sourceEvidence = () => resumeSessionId && engineKeepsTranscriptFile(saved.engine)
+ ? controlTranscriptEvidence(saved.engine, resumeSessionId, saved.transcriptPath!, saved.codexHome ?? undefined, saved.cwd) : undefined
// Match the registry's globally unique conversation index, including aliases/profiles.
const key = saved.sessionId || saved.agentId
if (resumeConversations.has(key)) return { ok: false, error: 'AGENT_BUSY' }
@@ -206,18 +210,36 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
let token: string | null = null
let allocationAttempted = false
try {
+ let transcript = sourceEvidence()
+ if (transcript) saved = { ...saved, transcriptPath: transcript.path }
+ let sourceError: unknown
+ const sourceCurrent = () => {
+ if (!current() || sourceError) return false
+ if (saved.sessionId && registry.bySession(saved.sessionId)) {
+ sourceError = new IdentityReadUnavailable('another live harness owns this conversation')
+ return false
+ }
+ try { transcript?.verify(); return true }
+ catch (error) { sourceError = error; return false }
+ }
// Reserve before preparing history or rewriting launch configuration: an unknown previous
// allocation may still have a writer using those files.
token = stoppedAgents.beginResume(agentId)
if (!token) token = retakeStaleReservation(agentId)
if (!token) return resumeUnconfirmed
- const built = await relaunchOverrides(saved, saved, current)
+ const built = await relaunchOverrides(saved, saved, sourceCurrent)
+ if (sourceError) throw sourceError
+ transcript?.verify()
if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
if (!current()) return resumeChanged
if (resumeSessionId) {
- try { prepareSessionResume(saved) } catch {
+ try { prepareSessionResume(saved) } catch (error) {
+ if (error instanceof IdentityReadUnavailable) throw error
return { ok: false, error: 'RESUME_PREPARATION_FAILED', detail: 'Could not prepare the saved conversation. Its history has been retained.' }
}
+ // The confirmed synchronous repair may atomically replace this file.
+ // Earn a new proof of the same conversation before the next await.
+ transcript = sourceEvidence()
}
if (saved.sessionId && registry.bySession(saved.sessionId)) return { ok: false, error: 'AGENT_BUSY' }
// Everything the engine writes from here on is its own, and live: the attach after it folds the
@@ -240,6 +262,8 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
const { choice: permission, droppedFlag } = permissionMode === undefined
? await dropPermissionFlagIfUnsupported(saved.engine, savedPermission)
: { choice: savedPermission, droppedFlag: null }
+ transcript?.verify()
+ if (!current()) return resumeChanged
if (droppedFlag) {
console.warn(`[resume] ${sid(saved.agentId)} · ${saved.engine} does not take ${droppedFlag}`
+ ` · resuming in Ask · update ${saved.engine} to get ${saved.permissionMode ?? 'Auto'} back`)
@@ -248,24 +272,35 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
resumeSessionId,
bypassPermission: permission.bypassPermission === true,
...(permission.permissionMode ? { permissionMode: permission.permissionMode } : {}),
- cwd: saved.cwd,
+ cwd,
...(extraArgs.length ? { extraArgs } : {}),
...(clearEnv.length ? { clearEnv } : {}),
...(launchEnv.HARNESS_DSH ? { harnessNode: true } : {}),
installIfMissing: enginePathOverride(saved.engine) ? undefined : engineInstallRecipe(saved.engine),
}
+ const argv = buildEngineLaunchArgv(saved.engine, options)
+ transcript?.verify()
+ if (!current()) return resumeChanged
clearDeleted(agentId)
if (saved.sessionId) clearDeleted(saved.sessionId)
- allocationAttempted = true
+ // Only actual dispatch can leave an unknown allocation. A held backend
+ // gate releases the reservation so recovery may retry without spawning twice.
const result = await createAndRegisterPane({
- tmuxBackend,
- registry: { openPendingAgent: input => current() ? registry.resumePendingAgent(saved, input.runtimes) : null },
+ current: sourceCurrent,
+ onDispatch: () => { allocationAttempted = true },
+ tmuxBackend: { ...tmuxBackend, create: async request => {
+ const result = await tmuxBackend.create(request)
+ if (result.dispatch !== 'not_started') allocationAttempted = true
+ return result
+ }, kill: runtime => tmuxBackend.kill(runtime) },
+ registry: { openPendingAgent: input => sourceCurrent() ? registry.resumePendingAgent(saved, input.runtimes) : null },
maxAttempts: 1,
engine: saved.engine,
sessionLabel: buildHarnessSessionLabel(saved.engine),
- argv: buildEngineLaunchArgv(saved.engine, options),
+ argv,
...(Object.keys(launchEnv).length ? { env: launchEnv } : {}),
})
+ if (sourceError) throw sourceError
if (!result.ok) {
if (result.error === 'TMUX_UNAVAILABLE') {
stoppedAgents.finishResume(agentId, token)
@@ -296,6 +331,10 @@ export function createResumeAgentService(deps: ResumeAgentServiceDeps) {
}
if (pending.dsh) attachDsh(pending)
return await waitForResume(pending, current)
+ } catch (error) {
+ if (error instanceof IdentityReadUnavailable) return { ok: false,
+ error: allocationAttempted ? 'RESUME_UNCONFIRMED' : error.code, detail: error.message }
+ throw error
} finally {
if (token && !allocationAttempted) stoppedAgents.finishResume(agentId, token)
resumeConversations.delete(key)
diff --git a/cli/src/lib/sessionCheckpoint.spec.ts b/cli/src/lib/sessionCheckpoint.spec.ts
index 8d429ae6b..010de6545 100644
--- a/cli/src/lib/sessionCheckpoint.spec.ts
+++ b/cli/src/lib/sessionCheckpoint.spec.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
-import { copyFile, link, mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
+import { link, mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { SessionCheckpointStore } from './sessionCheckpoint.js'
@@ -7,9 +7,22 @@ import { registry, type RegisteredSession } from './registry.js'
import { sqliteReadAll } from './sqliteRead.js'
import { env } from '../config/env.js'
import { piSessionFolder } from './sessionSearch/externals/pi.js'
+const faults = vi.hoisted(() => ({ wrote: undefined as ((path: string) => Promise<void>) | undefined }))
vi.mock('node:fs/promises', async importOriginal => {
const real = await importOriginal<typeof import('node:fs/promises')>()
- return { ...real, copyFile: vi.fn(real.copyFile), rm: vi.fn(real.rm) }
+ return { ...real, rm: vi.fn(real.rm), open: async (...args: Parameters<typeof real.open>) => {
+ const handle = await real.open(...args)
+ if (String(args[0]).endsWith('.history.tmp')) {
+ const write = handle.write.bind(handle)
+ handle.write = (async (...values: Parameters<typeof write>) => {
+ const result = await write(...values)
+ const fault = faults.wrote; faults.wrote = undefined
+ await fault?.(String(args[0]))
+ return result
+ }) as typeof handle.write
+ }
+ return handle
+ } }
})
vi.mock('./sqliteRead.js', () => ({ sqliteReadAll: vi.fn() }))
let root: string
@@ -17,12 +30,14 @@ let history: string
let directory: string
let row: RegisteredSession
let store: SessionCheckpointStore
+const transcript = (body: string) => JSON.stringify({ type: 'session_meta', payload: { id: 'conversation', cwd: '/tmp', source: 'cli' } }) + '\n' + body
beforeEach(async () => {
+ faults.wrote = undefined
root = await mkdtemp(join(tmpdir(), 'harness-close-checkpoint-'))
const home = join(root, 'profile')
await mkdir(join(home, 'sessions'), { recursive: true, mode: 0o700 })
history = join(home, 'sessions', 'conversation.jsonl')
- await writeFile(history, '{"history":"retained conversation"}\n', { mode: 0o600 })
+ await writeFile(history, transcript('{"history":"retained conversation"}\n'), { mode: 0o600 })
row = registry.openPendingAgent({ engine: 'codex', cwd: '/tmp', codexHome: home, runtimes: [{ backend: 'tmux', paneId: '%777' }] })!
Object.assign(row, { sessionId: 'conversation', transcriptPath: history })
directory = join(root, 'checkpoints')
@@ -184,12 +199,20 @@ it('retains the full native transcript with private permissions, independently o
await rm(history)
expect(await readFile(backup, 'utf8')).toContain('retained conversation')
})
+it('retains a conversation larger than a copy chunk with exact bytes', async () => {
+ const contents = transcript('long conversation\n'.repeat(25000))
+ await writeFile(history, contents)
+ await store.save(row)
+ const saved = await manifest()
+ expect(await readFile(join(directory, saved.file), 'utf8')).toBe(contents)
+ expect(saved.bytes).toBe(Buffer.byteLength(contents))
+})
it('reuses an unchanged checkpoint and replaces it only after a complete new save', async () => {
await store.save(row)
const first = await manifest()
await store.save(row)
expect(await manifest()).toEqual(first)
- await writeFile(history, '{"history":"last flushed response"}\n')
+ await writeFile(history, transcript('{"history":"last flushed response"}\n'))
await store.save(row)
const last = await manifest()
expect(last.file).not.toBe(first.file)
@@ -251,29 +274,25 @@ it('refuses an unset conversation path instead of inventing an empty checkpoint'
it('rejects a transcript changed during copy and retains the last committed backup', async () => {
await store.save(row)
const previous = await manifest()
- await writeFile(history, 'new turn\n')
- const real = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
- vi.mocked(copyFile).mockImplementationOnce(async (source, target, flags) => {
- await real.copyFile(source, target, flags)
- await writeFile(history, 'a response arrived while copying\n')
- })
+ await writeFile(history, transcript('new turn\n'))
+ faults.wrote = async () => {
+ await writeFile(history, transcript('a response arrived while copying\n'))
+ }
await expect(store.save(row)).rejects.toThrow('changed while saving')
expect(await manifest()).toEqual(previous)
expect(await readFile(join(directory, previous.file), 'utf8')).toContain('retained conversation')
})
it('rejects a checkpoint that gained an unexpected hard link before commit', async () => {
- const real = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
- vi.mocked(copyFile).mockImplementationOnce(async (source, target, flags) => {
- await real.copyFile(source, target, flags)
+ faults.wrote = async target => {
await link(target, join(root, 'unexpected-link'))
- })
+ }
await expect(store.save(row)).rejects.toThrow('Could not back up')
expect((await readdir(directory)).some(file => file.endsWith('.json'))).toBe(false)
})
it('keeps a successful new checkpoint when cleanup of the older copy fails', async () => {
await store.save(row)
const before = await manifest()
- await writeFile(history, 'new conversation state\n')
+ await writeFile(history, transcript('new conversation state\n'))
vi.mocked(rm).mockRejectedValueOnce(new Error('file busy'))
await store.save(row)
const after = await manifest()
diff --git a/cli/src/lib/sessionCheckpoint.ts b/cli/src/lib/sessionCheckpoint.ts
index 7b82044df..83975d7b7 100644
--- a/cli/src/lib/sessionCheckpoint.ts
+++ b/cli/src/lib/sessionCheckpoint.ts
@@ -1,10 +1,13 @@
/** Disk checkpoints made only when closing a session, never by a resource sampler. */
import { constants, existsSync } from 'node:fs'
-import { chmod, copyFile, lstat, open, rename, rm, stat } from 'node:fs/promises'
+import { lstat, open, rename, rm, type FileHandle } from 'node:fs/promises'
import { createHash, randomUUID } from 'node:crypto'
import { dirname, join } from 'node:path'
import { env } from '../config/env.js'
-import { atomicWriteJson, engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'
+import { atomicWriteJson, engineKeepsTranscriptFile, type RegisteredSession } from './registry.js'
+import { controlTranscriptEvidence } from '../engines/transcriptBindings.js'
+import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'
+import { nativeFileKey } from '../engines/kit/nativePaths.js'
import { readPrivateStateFile, secureStateDirectory } from './secureState.js'
import { sqliteReadAll } from './sqliteRead.js'
import { hermesDbPath } from '../engines/hermes/contract.js'
@@ -57,6 +60,8 @@ type Checkpoint = {
sourceSize?: number
sourceMtime?: number
sourceInode?: number
+ sourceKey?: string
+ sourceCtime?: string
file: string
bytes: number
}
@@ -98,14 +103,17 @@ export class SessionCheckpointStore {
try { previous = JSON.parse(readPrivateStateFile(manifest, 16384)) as Checkpoint } catch (e) {
if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e
}
- const source = s.transcriptPath ?? (s.engine === 'pi' && s.sessionId
+ let source = s.transcriptPath ?? (s.engine === 'pi' && s.sessionId
? await findResumedTranscript('pi', s.sessionId, { cwd: s.cwd ?? undefined }) : null)
- if (options.screen != null && s.sessionId) {
+ const authority = s.sessionId && source && engineKeepsTranscriptFile(s.engine)
+ ? controlTranscriptEvidence(s.engine, s.sessionId, source, s.codexHome ?? undefined, s.cwd) : undefined
+ if (authority) source = authority.path
+ const saveScreen = () => { if (options.screen != null && s.sessionId) {
// Save even when the native transcript is unchanged: a newly typed draft
// belongs to the terminal, not to that transcript. Never submit it.
atomicWriteJson(join(this.directory, `${key}.screen.json`), { version: 1, agentId: s.agentId,
sessionId: s.sessionId, savedAt: Date.now(), screen: options.screen })
- }
+ } }
const checkpoint: Checkpoint = { version: 1, agentId: s.agentId, sessionId: s.sessionId,
engine: s.engine, codexHome: s.codexHome ?? null, savedAt: Date.now(), source: null, file, bytes: 0 }
// Pi announces a session ID before it writes any history. In particular,
@@ -125,26 +133,46 @@ export class SessionCheckpointStore {
atomicWriteJson(temporary, { version: 1, agentId: s.agentId, sessionId: s.sessionId, engine: s.engine, cwd: s.cwd,
savedAt: checkpoint.savedAt, screen: options.screen })
} else if (engineKeepsTranscriptFile(s.engine)) {
- if (!source || !validTranscriptPath(s.engine, source, s.codexHome ?? undefined)) {
+ if (!source) {
throw new SessionCheckpointError('The conversation file is unavailable. The session has not been closed.')
}
- const before = await stat(source)
- if (before.size === 0) throw new SessionCheckpointError('This conversation is still being saved. Keep it open and try again shortly.')
- const previousFile = previous?.file && previousFileSafe(previous.file)
- ? await lstat(join(this.directory, previous.file)).catch(() => null) : null
- // A second checkpoint after a quiet exit need not copy the same history twice.
- if (previous?.version === 1 && previous.source === source && previous.sourceInode === before.ino
- && previous.sourceSize === before.size && previous.sourceMtime === before.mtimeMs
- && previousFile?.isFile() && previousFile.nlink === 1 && (previousFile.mode & 0o777) === 0o600
- && previousFile.size === before.size) return
- // APFS/reflink when available, ordinary file copy otherwise. No transcript-sized JS buffer.
- await copyFile(source, temporary, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE)
- await chmod(temporary, 0o600)
- const after = await stat(source)
- if (before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs) {
- throw new SessionCheckpointError('The conversation changed while saving. Please try closing it again.')
- }
- Object.assign(checkpoint, { source, sourceSize: after.size, sourceMtime: after.mtimeMs, sourceInode: after.ino })
+ // copyFile reopens a pathname in another thread. An ancestor could briefly
+ // point elsewhere, copying B while both surrounding path checks still see A.
+ // Read from the exact descriptor our native evidence confirms, with bounded memory.
+ // A saved path may be a legitimate alias. The opened descriptor must match
+ // the proven physical file before we copy a byte, including after ancestor swaps.
+ const input = await open(source, constants.O_RDONLY | constants.O_NONBLOCK)
+ .catch(() => { throw new IdentityReadUnavailable('the source transcript could not be opened') })
+ let reuseCheckpoint = false
+ try {
+ let before = await input.stat({ bigint: true }).catch(() => { throw new IdentityReadUnavailable('the source transcript could not be inspected') })
+ authority!.verify(nativeFileKey(before))
+ if (!before.isFile() || !Number.isSafeInteger(Number(before.size))) throw new IdentityReadUnavailable('the source transcript has an unconfirmed type or size')
+ if (before.size === 0n) throw new SessionCheckpointError('This conversation is still being saved. Keep it open and try again shortly.')
+ const previousFile = previous?.file && previousFileSafe(previous.file)
+ ? await lstat(join(this.directory, previous.file)).catch(() => null) : null
+ before = await input.stat({ bigint: true }).catch(() => { throw new IdentityReadUnavailable('the source transcript became unreadable') })
+ authority!.verify(nativeFileKey(before))
+ // Older manifests did not bind a copied descriptor. Rebuild those once;
+ // subsequent quiet exits can reuse this exact, completely saved incarnation.
+ if (previous?.version === 1 && previous.source === source && previous.sourceKey === nativeFileKey(before)
+ && previous.sourceSize === Number(before.size) && previous.sourceCtime === String(before.ctimeNs)
+ && previousFile?.isFile() && previousFile.nlink === 1 && (previousFile.mode & 0o777) === 0o600
+ && previousFile.size === Number(before.size)) {
+ authority!.verify(nativeFileKey(before))
+ reuseCheckpoint = true
+ } else {
+ await copyCheckpointDescriptor(input, temporary, Number(before.size))
+ const after = await input.stat({ bigint: true }).catch(() => { throw new IdentityReadUnavailable('the source transcript became unreadable') })
+ authority!.verify(nativeFileKey(after))
+ if (before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs) {
+ throw new IdentityReadUnavailable('the conversation changed while saving; waiting for a stable copy')
+ }
+ Object.assign(checkpoint, { source, sourceSize: Number(after.size), sourceMtime: Number(after.mtimeMs),
+ sourceInode: Number(after.ino), sourceKey: nativeFileKey(after), sourceCtime: String(after.ctimeNs) })
+ }
+ } finally { await input.close().catch(() => { throw new IdentityReadUnavailable('the source transcript could not be closed') }) }
+ if (reuseCheckpoint) { authority!.verify(); saveScreen(); return }
} else {
const history = await databaseHistory(s)
const handle = await open(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
@@ -159,6 +187,8 @@ export class SessionCheckpointStore {
await handle.sync()
} finally { await handle.close() }
await rename(temporary, destination)
+ authority?.verify()
+ saveScreen()
// Publish only after data is durable. A failed save keeps the preceding checkpoint intact.
atomicWriteJson(manifest, checkpoint)
committed = true
@@ -175,6 +205,27 @@ export class SessionCheckpointStore {
}
}
+/** A finite snapshot length and one reusable chunk; no transcript-sized JS buffer. */
+async function copyCheckpointDescriptor(input: FileHandle, path: string, size: number): Promise<void> {
+ const output = await open(path, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
+ try {
+ const buffer = Buffer.alloc(Math.min(size, 128 * 1024))
+ let position = 0
+ while (position < size) {
+ const { bytesRead } = await input.read(buffer, 0, Math.min(buffer.length, size - position), position)
+ .catch(() => { throw new IdentityReadUnavailable('the source transcript became unreadable') })
+ if (!bytesRead) throw new IdentityReadUnavailable('the conversation changed while saving; waiting for a stable copy')
+ let written = 0
+ while (written < bytesRead) {
+ const { bytesWritten } = await output.write(buffer, written, bytesRead - written, position + written)
+ if (!bytesWritten) throw new Error('checkpoint write made no progress')
+ written += bytesWritten
+ }
+ position += bytesRead
+ }
+ } finally { await output.close() }
+}
+
const previousFileSafe = (file: string): boolean => /^[a-f0-9]{64}-[a-f0-9-]{36}\.history$/.test(file)
export const sessionCheckpoints = new SessionCheckpointStore()
diff --git a/cli/src/lib/stopAgentService.spec.ts b/cli/src/lib/stopAgentService.spec.ts
index 827d26465..80c7e3104 100644
--- a/cli/src/lib/stopAgentService.spec.ts
+++ b/cli/src/lib/stopAgentService.spec.ts
@@ -7,13 +7,18 @@ import { AgentRestartCoordinator } from './restartAgent.js'
import { checkPidRuntime, terminateDeletedAgent } from './deleteAgentFallback.js'
import { createForgetSession } from '../core/agents/forget.js'
import { env } from '../config/env.js'
+import { controlTranscriptEvidence } from '../engines/transcriptBindings.js'
vi.mock('./captureResumeIdentity.js', () => ({ captureResumeIdentity: vi.fn(async session => session) }))
+vi.mock('../engines/transcriptBindings.js', async original => ({ ...await original<object>(),
+ controlTranscriptEvidence: vi.fn(),
+}))
vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn() }))
vi.mock('../core/engines/cursorTasks.js', () => ({ removePendingCursorTasks: vi.fn(async () => {}) }))
let row: RegisteredSession
let deps: StopAgentServiceDeps
beforeEach(() => {
vi.clearAllMocks()
+ vi.mocked(controlTranscriptEvidence).mockReset().mockImplementation((_engine, _id, path) => ({ path, verify: vi.fn() }))
vi.mocked(captureResumeIdentity).mockReset().mockImplementation(async session => session)
row = registry.openPendingAgent({ engine: 'codex', runtimes: [{ backend: 'tmux', paneId: '%44' }], cwd: '/tmp' })!
Object.assign(row, { sessionId: 'saved', processIdentity: { pid: 77, executable: 'codex', startMarker: 'fixture' } })
@@ -82,6 +87,14 @@ it('storage failure leaves the live process and registry untouched', async () =>
await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('disk full')
expect(registry.byAgent(row.agentId)).toBe(row); expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled(); expect(deps.markDeleted).not.toHaveBeenCalled()
})
+it('preserves an unexpected evidence failure without signalling or hiding its cause', async () => {
+ row.transcriptPath = '/fixture/history.jsonl'
+ vi.mocked(controlTranscriptEvidence).mockReturnValue({ path: row.transcriptPath,
+ verify: () => { throw new Error('Evidence implementation unavailable') } })
+ await expect(createStopAgentService(deps)(row.agentId)).rejects.toThrow('Evidence implementation unavailable')
+ expect(terminateDeletedAgent).not.toHaveBeenCalled()
+ expect(deps.forgetSession).not.toHaveBeenCalled()
+})
it.each(['before', 'after'] as const)('honors cancellation at the %s checkpoint before retiring the terminal', async phase => {
let current = true
await expect(createStopAgentService(deps)(row.agentId, {
@@ -198,7 +211,7 @@ it.each(['capture', 'termination'] as const)('accepts a hook rebuilding the same
if (stage === 'capture') vi.mocked(captureResumeIdentity).mockImplementation(async session => { rebuild(); return session })
else vi.mocked(terminateDeletedAgent).mockImplementation(async () => { rebuild(); return 'terminated' })
await createStopAgentService(deps)(row.agentId)
- expect(deps.forgetSession).toHaveBeenCalledExactlyOnceWith(row.agentId, { force: true })
+ expect(deps.forgetSession).toHaveBeenCalledExactlyOnceWith(row.agentId, { force: true, captured: expect.objectContaining({ sessionId: 'saved' }) })
expect(registry.byAgent(row.agentId)).toBeUndefined()
expect(stoppedAgents.get(row.agentId)?.sessionId).toBe('saved')
})
diff --git a/cli/src/lib/stopAgentService.ts b/cli/src/lib/stopAgentService.ts
index c8fe93986..cd92ab521 100644
--- a/cli/src/lib/stopAgentService.ts
+++ b/cli/src/lib/stopAgentService.ts
@@ -2,6 +2,8 @@
import { externalResumePending } from './externalResume.js'
import { captureResumeIdentity } from './captureResumeIdentity.js'
import { isTerminalEngine } from '../engines/types.js'
+import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'
+import { controlTranscriptEvidence, engineKeepsTranscriptFile } from '../engines/transcriptBindings.js'
import type { registry as liveRegistry, RegisteredSession } from './registry.js'
import type { StoppedAgentStore } from './stoppedAgents.js'
import type { AgentRestartCoordinator } from './restartAgent.js'
@@ -24,7 +26,7 @@ export interface StopAgentServiceDeps {
releaseRoute(route: string): void
trigger(): Promise<unknown>
}
- forgetSession(agentId: string, options: { force: true }): void
+ forgetSession(agentId: string, options: { force: true; captured?: RegisteredSession }): void
markDeleted(agentId: string): void
clearDeleted(agentId: string): void
/**
@@ -51,11 +53,14 @@ export interface StopAgentOptions {
// Hooks rebuild registry objects. Compare stable values, never JavaScript object
// identity or property ordering, while retaining the exact PID-reuse guard.
const runtimeIdentity = (entry: RegisteredSession | undefined, withProcess = true) => entry ? JSON.stringify([
- entry.engine, entry.registeredAt,
+ entry.engine, entry.registeredAt, entry.cwd,
entry.codexHome ?? null, entry.hermesHome ?? null,
- ...(withProcess ? [entry.processIdentity?.pid, entry.processIdentity?.executable, entry.processIdentity?.startMarker] : []),
+ ...(withProcess ? [entry.processIdentity?.pid, entry.processIdentity?.executable, entry.processIdentity?.startMarker, entry.processIdentity?.startTicks] : []),
entry.runtimes.map(terminalRouteKey).sort(),
]) : null
+const bindingIdentity = (entry: RegisteredSession) => JSON.stringify([
+ entry.sessionId, entry.transcriptPath, entry.boundAt, entry.evidenceRevision,
+])
export function createStopAgentService(deps: StopAgentServiceDeps) {
const { registry, stoppedAgents, restartJobs, stopJobs, tmuxBackend, agentReconciler,
@@ -82,9 +87,11 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
const starting = !live.processIdentity
const identity = runtimeIdentity(live, !starting)
const conversation = live.sessionId
+ let binding = conversation ? bindingIdentity(live) : undefined
const sameTarget = () => {
const current = registry.resolve(sessionId)
return runtimeIdentity(current, !starting) === identity && (!conversation || current!.sessionId === conversation)
+ && (binding === undefined || bindingIdentity(current!) === binding)
}
const captured = await captureResumeIdentity({ ...live })
// Discovery or a hook may have updated this row while reading the native store.
@@ -95,10 +102,22 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
const current = registry.resolve(sessionId)!
const s = current.sessionId && current.sessionId !== captured.sessionId ? { ...current } : { ...current, sessionId: captured.sessionId,
transcriptPath: captured.transcriptPath, hermesHome: captured.hermesHome, boundAt: captured.boundAt, source: captured.source }
+ binding = bindingIdentity(current)
+ const transcript = s.sessionId && s.transcriptPath && engineKeepsTranscriptFile(s.engine)
+ ? controlTranscriptEvidence(s.engine, s.sessionId, s.transcriptPath, s.codexHome ?? undefined, s.cwd) : undefined
+ let nativeIdentityError: IdentityReadUnavailable | undefined
+ const verifyTranscript = () => {
+ try { transcript?.verify() } catch (error) {
+ if (error instanceof IdentityReadUnavailable) nativeIdentityError = error
+ throw error
+ }
+ }
// Saving precedes every mutation. A storage failure leaves the live agent alone.
stoppedAgents.save(s)
await options.checkpoint?.(s, 'before')
+ verifyTranscript()
await options.beforeStop?.(s)
+ verifyTranscript()
if (!sameTarget() || options.current?.() === false) {
throw new AgentStopError('Harness changed while saving its conversation. Try stopping again.')
}
@@ -107,19 +126,28 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
try {
markDeleted(sessionId)
if (s.sessionId) markDeleted(s.sessionId)
- await stopNative(s, () => sameTarget() && options.current?.() !== false, options.confirmUnusedConversation)
+ await stopNative(s, () => {
+ verifyTranscript()
+ return sameTarget() && options.current?.() !== false
+ }, options.confirmUnusedConversation).catch(error => { throw nativeIdentityError ?? error })
+ if (nativeIdentityError) throw nativeIdentityError
+ verifyTranscript()
// Keep the terminal alive while the engine handles SIGTERM and flushes
// its native store. Killing tmux in parallel can deliver SIGHUP first.
const termination = await (isTerminalEngine(s.engine) ? Promise.resolve('gone' as const)
: terminateDeletedAgent(s, {
checkRuntime: checkPidRuntime,
kill: (pid, signal) => {
+ verifyTranscript()
if (!sameTarget() || options.current?.() === false) throw new AgentStopError('The close request was cancelled or changed.')
process.kill(pid, signal)
},
sleep: ms => new Promise(resolve => { const timer = setTimeout(resolve, ms); timer.unref?.() }),
log: message => console.log(message),
}, 0)).catch(() => 'failed' as const)
+ // The process helper catches signal failures. Preserve native evidence holds
+ // so a queued Close retries instead of becoming a permanently failed plan.
+ if (nativeIdentityError) throw nativeIdentityError
if (termination === 'failed' || termination === 'not-ours') {
throw new AgentStopError('Could not confirm that the harness stopped. Its saved conversation is safe. Try stopping again.')
}
@@ -127,7 +155,9 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
if (!sameTarget() || options.current?.() === false) {
throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')
}
+ verifyTranscript()
await options.checkpoint?.(s, 'after')
+ verifyTranscript()
if (!sameTarget() || options.current?.() === false) {
throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')
}
@@ -141,11 +171,12 @@ export function createStopAgentService(deps: StopAgentServiceDeps) {
if (!sameTarget()) {
throw new AgentStopError('The harness changed while pausing. Check its current state before trying again.')
}
+ verifyTranscript()
stoppedAgents.finishResume(sessionId)
if (s.processIdentity) agentReconciler.suppress(s)
// This publishes agent_deleted. It must follow confirmed termination, or a
// desktop can display Paused and allow Resume while the old process runs.
- forgetSession(sessionId, { force: true })
+ forgetSession(sessionId, { force: true, captured: s })
} finally {
clearDeleted(sessionId)
if (s.sessionId) clearDeleted(s.sessionId)
diff --git a/docs/research/2026-10-09-daemon-core-completion.md b/docs/research/2026-10-09-daemon-core-completion.md
index 2637693a0..a460af242 100644
--- a/docs/research/2026-10-09-daemon-core-completion.md
+++ b/docs/research/2026-10-09-daemon-core-completion.md
@@ -23,10 +23,11 @@ This is the remaining completion scope as of October 9, after the six extraction
- [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).
+- [x] Atomic native hook admission and live Stop ownership (#1137, merged as `9618c2e2c` at October 10 08:36:54 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 [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.
+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 [landed](2026-10-10-native-hook-admission.md). Stop/Resume/Close transcript authority is [under final validation](2026-10-10-control-transcript-authority.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-09-daemon-separation-progress.md b/docs/research/2026-10-09-daemon-separation-progress.md
index 351a724c7..b83974c38 100644
--- a/docs/research/2026-10-09-daemon-separation-progress.md
+++ b/docs/research/2026-10-09-daemon-separation-progress.md
@@ -221,3 +221,19 @@ and the final unavailable-service/readiness audit. Line counts do not establish
The owner resumed the paused task on October 9 at 22:25:51 UTC. [Durable home adoption](2026-10-10-durable-home-adoption.md) landed in [#1132](https://github.com/autonomous-ai/openharness/pull/1132) as `c7d460b1d8018ed56126c662702fd44db886d07d` at October 10 01:43:24 UTC. Independent review approved exact head `7ae6c83921b76733e96db70a0948c73ff1b55e70` against base `9eafacf3b512a0b1ffd23e0d446115896b01f7ed`. Automatic run `38013783062` passed every applicable check including `ci/required`. Final local validation ran 01:35:58–01:38:38; composed resume and large-transcript checks ran alone 01:40:42–01:41:56. Merge verification ran 01:43:11–01:43:24. Publication remains zero.
Work continues on [saved-binding evidence and recovery](2026-10-10-saved-binding-evidence.md). This is not a claim that the native-identity group or complete refactor is finished.
+
+## Saved binding and atomic hook admission
+
+[PR #1133](https://github.com/autonomous-ai/openharness/pull/1133) landed saved-binding
+evidence and visible recovery as `a2a7874f3` at October 10 05:16:31 UTC.
+[PR #1137](https://github.com/autonomous-ai/openharness/pull/1137) then landed atomic
+native hook admission and live Stop ownership as `9618c2e2c` at 08:36:54 UTC. The
+[hook admission report](2026-10-10-native-hook-admission.md) records exact-head review,
+unchanged goldens, mutation proofs, costs, acceptance and automatic CI. The guarded
+merge occupied 08:36:40–08:36:54; publication remains zero.
+
+The next [Stop/Resume/Close authority change](2026-10-10-control-transcript-authority.md)
+has independent source approval and passing unit, core, harnessd and Resume gates;
+private lifecycle acceptance, mutation checks, costs and final CI remain under way.
+The [completion checklist](2026-10-09-daemon-core-completion.md) still tracks durable
+delivery/lifecycle intent and the other concrete architecture gaps.
diff --git a/docs/research/2026-10-10-control-transcript-authority.md b/docs/research/2026-10-10-control-transcript-authority.md
new file mode 100644
index 000000000..306d66fd4
--- /dev/null
+++ b/docs/research/2026-10-10-control-transcript-authority.md
@@ -0,0 +1,165 @@
+# Native transcript authority through Stop, Resume and Close
+
+This step of the [completion checklist](2026-10-09-daemon-core-completion.md)
+extends eager native evidence from binding to the lifecycle consumers. An unreadable,
+incomplete, replaced or differently owned conversation holds the operation with its
+reason. It cannot authorize a signal, launch, archive or partially published checkpoint.
+No service or lazily loaded interpreter owns these decisions.
+
+## Former-code goldens
+
+Commit `340ab59ad9ca60fd36f2fb26645885b278941f4a` records the capture/checkpoint golden
+from main `cc4983e1893494a653f84d861950efe5d6913590`, before implementation. Its 32
+observations cover Claude, default/moved/profile/aliased Codex, written/unwritten Pi
+and terminal sessions. Commit `6c06b697` separately records six healthy Resume
+observations from main `0b2dd18f8`, before the Resume move. Both explicitly pin Linux
+and macOS, the clock, private paths and placeholder binaries under `TZ=UTC TMPDIR=/tmp`.
+Neither artifact changes in this implementation.
+
+## Authority and publication
+
+`controlTranscriptEvidence` retains the original physical file key and earns fresh,
+bounded path, catalog and native-header evidence at each boundary. A long asynchronous
+operation does not borrow an expired proof; an ordinary body append can still be valid.
+Claude and Pi opening declarations run eagerly. The opening is tied to the descriptor
+that supplied its bytes and compared with the saved proof's file key. Every consumed
+identity, workspace and delegation field must agree. Pi also proves its canonical
+workspace. An incomplete opening or an incomplete native-home catalog holds control.
+
+Checkpoints open and retain their source descriptor, compare its key with the native
+proof before reading, and copy in bounded chunks. The source snapshot is taken again
+after asynchronous backup inspection. Reuse requires the physical key, exact size and
+nanosecond change time as well as a private regular backup. Same-size body rewrites
+cannot reuse stale history. Open, read, stat and close failures retain the previous
+checkpoint and draft. Draft publication follows successful source closure and fresh
+authority; manifest publication follows the completed private copy. Ordinary output
+storage failures remain distinct from unavailable native identity.
+
+Stop fences both the binding revision and the precise process birth across its awaits.
+Native brokers and process helpers may contain callback errors, so the typed hold is
+retained separately and checked before any next effect. The final archive receives the
+proven parent conversation path, even if a delayed hook saved the prior child path.
+
+Resume proves the saved source before preparation and carries a current-ownership
+callback through configuration and the actual tmux dispatch boundary. A conversation
+claimed by another live agent during permission or backend checks cannot acquire a
+second writer. A reservation is released when dispatch is known not to have started;
+once dispatch may have occurred, its uncertainty remains reserved for reconciliation.
+The proven synchronous history repair can replace a file, so Resume earns new evidence
+after that repair before its next await.
+
+Close treats changed or unavailable activity drains as a hold. A failed activity read
+clears obsolete idle evidence and preserves the waiting plan and its reason. Even a
+secondary reason-publication failure keeps the preceding intent for the next tick.
+
+## Regression and review evidence
+
+Private composed tests exercise the real Registry, stopped store, checkpoint store,
+native broker and tmux backend. They cover physical file substitution, ancestor
+replacement and restoration, conflicting opening records, body rewrites, failures at
+each source descriptor operation, contained grant/signal errors, competing conversation
+ownership and uncertainty after dispatch. A regression run on former implementation
+`ef13de889` fails by assertion when an ancestor moves away and back around opening the
+checkpoint source: that code copied from the wrong descriptor while pathname checks
+matched. The corrected implementation holds before writing history.
+
+Independent review found and verified corrections for descriptor-bound copy authority,
+contained native holds, final archive identity, opening-file substitution, contradictory
+delegation and a new conversation owner before dispatch. The reviewer approved runtime
+head `7ce86bc1558ff59fe44ce5cb8732ef2f60904f92` against base
+`526d6bb9d081a5e8afbefd21ddefb28586570adc`, conditional on final gates and CI. Review was
+read-only and independent of implementation. Both golden artifacts were checked byte
+for byte, and the incoming router wiring was reviewed for interaction.
+
+## Matched runtime cost
+
+The [workload](../../cli/scripts/handoff-2026-10-08/control-transcript-cost.ts) compared
+main `526d6bb9d081a5e8afbefd21ddefb28586570adc` with runtime head
+`7ce86bc1558ff59fe44ce5cb8732ef2f60904f92`, using Node 22.23.2 on the same macOS x64
+host, pinned Linux evidence, UTC and private `/tmp` homes. Forty-two fresh processes
+ran alone, interleaving three samples per revision and workload. Each revision confirmed
+645 operations. The [raw measurements](2026-10-10-control-transcript-cost.json) retain
+every latency, CPU total, source byte count and outcome.
+
+Numbers below are former → candidate. Latency is the median of the operation samples;
+CPU is median per-operation CPU across the three processes; memory is median peak RSS
+of those processes, including setup/imports. Setup, fixture writes and post-operation
+byte-hash verification are outside operation timing. Checkpoint-large and reuse use
+8 MiB bodies. Stop uses a confirmed absent process and private placeholder pane deletion;
+Resume measures a dependency-held preparation, not a full vendor startup.
+
+| Workload | Latency (ms) | CPU per operation (ms) | Peak RSS (MiB) |
+| --- | ---: | ---: | ---: |
+| capture-codex | 0.32 → 2.25 | 0.37 → 3.32 | 101.05 → 112.52 |
+| capture-claude | 0.29 → 2.31 | 0.37 → 3.40 | 103.20 → 113.20 |
+| checkpoint-small | 98.31 → 103.00 | 4.67 → 11.47 | 103.11 → 107.00 |
+| checkpoint-large | 181.16 → 153.84 | 67.90 → 43.58 | 166.52 → 169.77 |
+| checkpoint-reuse | 38.99 → 45.39 | 2.51 → 8.09 | 159.84 → 166.95 |
+| stop | 98.33 → 107.63 | 4.69 → 15.20 | 105.58 → 116.95 |
+| resume-held | 39.93 → 42.32 | 2.19 → 5.03 | 116.99 → 114.92 |
+
+Fresh capture proof adds about 2 ms median latency; the complete Stop path adds about
+9 ms on this workload. Checkpoint source verification and reuse incur more CPU. The
+large copy was faster in these samples, which is not a claim about other filesystems
+or larger histories. This is a same-host cost comparison, not a new performance gate;
+the bounded-read and failure-isolation tests remain mandatory.
+
+The standalone benchmark now retains an event-loop handle until its awaited work
+finishes. Its first attempt exited at the daemon's unreferenced Stop timer and supplied
+no complete measurement set. The final run completed 09:37:47–09:40:10 UTC. No other
+validation ran concurrently.
+
+## Validation and timing
+
+On the frozen runtime head, receipt `20261010T092933.619874Z-98787` passed typecheck,
+architecture and 274 affected tests in ten files, core/services at 100% in every file
+(2,148 tests in 167 files), and harnessd at 100% in every file (265 passed, one existing
+skip). Receipt `20261010T093105.734148Z-8974` passed all 602 Resume and composed native
+tests in fourteen files, including both unchanged goldens, with 100% Resume coverage.
+Resume ran alone to avoid contention. The deterministic input scopes exclude research
+writeups and the standalone handoff measurement/mutation scripts, which these checks
+do not load; they include runtime, tests, build/configuration, dependency and toolchain
+inputs.
+
+Earlier receipts were mixed, not full passes: three missing Resume coverage branches
+needed meaningful regression cases, and the 512 MiB repair fixture exceeded its 30-second
+deadline while competing with coverage. Its unchanged case passed alone in 19.8 seconds;
+the other 288 cases in that earlier affected run passed. A focused run initially hit
+sandbox uptime restrictions and a real alias-opening regression, both diagnosed before
+the subsequent authorized green runs.
+
+All 29 initial deliberately broken wiring variants failed by assertion after their unchanged
+baseline passed, using `cli/scripts/handoff-2026-10-08/mutate-control-authority.py` in
+an owned disposable worktree. The runner restores each changed file and requires a
+behavioral assertion, not a compile failure. This includes the former-code golden
+connections as well as physical identity, opening records, draft/checkpoint publication,
+Stop grants and signals, Resume ownership/dispatch and Close retry.
+
+The first ready-PR Linux run found three fixture failures. Two checkpoint tests used
+non-JSON text in place of a native Codex header; their fixture now contains a matching
+`session_meta` record. The older session-store golden also recorded successful capture
+for an unknown Claude conversation and a delegated Codex rollout. These are named safety
+corrections, not healthy compatibility cases. Its artifact stays byte-identical: the
+test first asserts each exact former answer, then requires `IDENTITY_UNAVAILABLE` and
+the unchanged original input. The child case retains its original null path; it does
+not synthesize the formerly discovered delegated path after catching an error. All 18
+tests in the two affected files pass. Removing this older golden's saved-conversation
+hold also failed by assertion after its unchanged baseline passed, bringing the total
+to 30 proven mutations. No product code changed for these fixture corrections.
+
+Private acceptance covers the complete `ends`, `machine`, `races`, `enginehomes`,
+`chaos` and `tmuxsocket` lanes, including the original mid-turn tmux crash and new
+Claude/Codex unavailable-identity recovery cases. These use isolated daemon ports,
+homes and explicit private tmux servers; the owner's daemon, homes and tmux server
+are never targets. [PR #1139](https://github.com/autonomous-ai/openharness/pull/1139)
+records their final exact-source receipt, automatic CI, review attestation and guarded
+merge result. They remain required before landing.
+
+Capture/checkpoint golden recording began at 07:45 UTC on October 10; the Resume golden
+was recorded at 08:22. Implementation and independent review continued through the
+09:24 corrections and clean integration of main. The successful unit gate occupied
+09:29:33–09:30:54; the successful Resume gate took 90.7 seconds from 09:31:05. These
+intervals overlap other work and are not added to estimate elapsed request time. The
+original request began October 8 at 23:26:41; this continuation resumed October 9 at
+22:25:51. CI/review waiting, merge and publication are tracked separately in the PR.
+Publication remains zero. No release is authorized.
diff --git a/docs/research/2026-10-10-control-transcript-cost.json b/docs/research/2026-10-10-control-transcript-cost.json
new file mode 100644
index 000000000..66f47365c
--- /dev/null
+++ b/docs/research/2026-10-10-control-transcript-cost.json
@@ -0,0 +1,2056 @@
+{
+ "schema": 1,
+ "startedAt": "2026-10-10T09:37:47Z",
+ "baseline": "526d6bb9d081a5e8afbefd21ddefb28586570adc",
+ "candidate": "7ce86bc1558ff59fe44ce5cb8732ef2f60904f92",
+ "method": "Three interleaved fresh processes per revision/workload; no competing validation; explicit linux evidence platform, private homes, host binaries forbidden. Setup and post-run byte checks are outside operation timing. Peak RSS includes setup/imports.",
+ "samples": [
+ {
+ "workload": "capture-codex",
+ "iterations": 50,
+ "latenciesMs": [
+ 1.7381919999999695,
+ 0.4165519999999674,
+ 0.42674699999997756,
+ 0.4000970000000166,
+ 0.3055180000000064,
+ 0.2878130000000283,
+ 0.3338459999999941,
+ 0.3100130000000263,
+ 0.4404969999999935,
+ 0.33525500000001784,
+ 0.28080600000004097,
+ 0.2806760000000281,
+ 0.30550700000003417,
+ 0.284227000000044,
+ 0.2776309999999853,
+ 0.28405099999997674,
+ 0.2733210000000099,
+ 0.3377399999999966,
+ 0.27943799999997054,
+ 0.2738490000000411,
+ 0.27092999999996437,
+ 0.2775930000000244,
+ 0.2718269999999734,
+ 0.2674849999999651,
+ 0.26756000000000313,
+ 0.2652209999999968,
+ 0.28040099999998347,
+ 0.28259400000001733,
+ 0.26774299999999585,
+ 0.2656830000000241,
+ 0.2698410000000422,
+ 0.2655849999999873,
+ 0.3173180000000002,
+ 0.2727729999999724,
+ 0.2797060000000329,
+ 0.2679689999999937,
+ 0.2670630000000074,
+ 0.26750800000002073,
+ 0.33879000000001724,
+ 0.2876019999999926,
+ 0.27107599999999366,
+ 0.2667350000000397,
+ 0.2642969999999991,
+ 0.263779999999997,
+ 0.31251499999996213,
+ 0.28230300000001307,
+ 0.2795679999999834,
+ 0.26418800000004694,
+ 0.26007400000003145,
+ 0.23278299999998353
+ ],
+ "cpuMs": 16.539,
+ "sourceBytes": 1202,
+ "peakRssMiB": 107.63671875,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "capture-codex",
+ "iterations": 50,
+ "latenciesMs": [
+ 7.666185999999982,
+ 3.3231380000000286,
+ 3.3606490000000235,
+ 3.5852709999999774,
+ 2.5043609999999603,
+ 2.801170999999954,
+ 2.8625320000000443,
+ 2.736417000000017,
+ 2.6906420000000253,
+ 2.9007500000000164,
+ 2.889081000000033,
+ 2.8426840000000198,
+ 2.8820500000000493,
+ 2.9387420000000475,
+ 3.2381039999999643,
+ 3.6282390000000078,
+ 2.3903229999999667,
+ 2.3282069999999635,
+ 2.3594269999999824,
+ 2.2706379999999626,
+ 2.284357,
+ 2.2598090000000184,
+ 2.3307910000000334,
+ 2.2873969999999986,
+ 2.3384869999999864,
+ 2.344841000000031,
+ 2.517702999999983,
+ 2.1722070000000144,
+ 2.2169399999999655,
+ 2.075872000000004,
+ 2.034108999999944,
+ 2.344848000000013,
+ 2.0182929999999715,
+ 2.016373999999985,
+ 2.004795999999999,
+ 2.0280030000000124,
+ 2.123463000000015,
+ 2.054497000000026,
+ 2.0651600000000485,
+ 2.049775000000011,
+ 2.0438819999999964,
+ 2.032334999999989,
+ 2.021501999999998,
+ 2.0761509999999817,
+ 2.0116590000000087,
+ 2.008168000000012,
+ 1.9982860000000073,
+ 1.9899729999999636,
+ 2.296959999999899,
+ 1.9784449999999651
+ ],
+ "cpuMs": 166.139,
+ "sourceBytes": 1202,
+ "peakRssMiB": 112.51953125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "capture-codex",
+ "iterations": 50,
+ "latenciesMs": [
+ 2.5110959999999523,
+ 0.5089629999999943,
+ 0.54549099999997,
+ 0.4496869999999831,
+ 0.32413300000001755,
+ 0.30910700000004,
+ 0.3609690000000114,
+ 0.33792000000005373,
+ 0.44938499999994974,
+ 0.3488060000000246,
+ 0.30925499999995054,
+ 0.2997729999999592,
+ 0.3206440000000157,
+ 0.31814900000000534,
+ 0.2947149999999965,
+ 0.2905089999999859,
+ 0.3134410000000116,
+ 0.35161099999999124,
+ 0.29989899999998215,
+ 0.29024799999996276,
+ 0.2848889999999642,
+ 0.29463299999997616,
+ 0.2854419999999891,
+ 0.28469599999999673,
+ 0.28670099999999366,
+ 0.2978090000000293,
+ 0.2869159999999624,
+ 0.2863709999999742,
+ 0.2866489999999544,
+ 0.2863140000000044,
+ 0.2841319999999996,
+ 0.28449000000000524,
+ 0.3343959999999697,
+ 0.30003399999998237,
+ 0.2860350000000267,
+ 0.2854600000000005,
+ 0.2823940000000107,
+ 0.2836120000000051,
+ 0.37109600000002274,
+ 0.30312400000002526,
+ 0.2911579999999958,
+ 0.29696100000001024,
+ 0.2811500000000251,
+ 0.2817670000000021,
+ 0.32762000000002445,
+ 0.29650200000003224,
+ 0.2838300000000231,
+ 0.2767820000000256,
+ 0.27659599999998363,
+ 0.2622069999999894
+ ],
+ "cpuMs": 18.456999999999997,
+ "sourceBytes": 1202,
+ "peakRssMiB": 101.05078125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "capture-codex",
+ "iterations": 50,
+ "latenciesMs": [
+ 7.829317000000003,
+ 3.323712999999998,
+ 3.3838969999999904,
+ 3.8488849999999957,
+ 2.648916999999983,
+ 2.797317000000021,
+ 3.081237999999985,
+ 2.895216000000005,
+ 2.871144999999956,
+ 2.9402769999999805,
+ 2.8290250000000015,
+ 2.8958149999999705,
+ 2.9121489999999994,
+ 2.810495000000003,
+ 4.004559000000029,
+ 2.536541999999997,
+ 2.2990029999999706,
+ 2.2511369999999715,
+ 2.385852,
+ 2.2043150000000082,
+ 2.162323000000015,
+ 2.17452099999997,
+ 2.1994980000000055,
+ 2.212740999999994,
+ 2.271792000000005,
+ 2.2640420000000177,
+ 2.162091999999973,
+ 2.154205999999988,
+ 2.2483290000000125,
+ 2.0945859999999925,
+ 2.023134999999968,
+ 2.2292549999999665,
+ 2.0297580000000153,
+ 2.0207489999999666,
+ 2.0152929999999856,
+ 2.0442299999999705,
+ 2.110773999999992,
+ 2.0370790000000056,
+ 2.0714020000000346,
+ 2.046147000000019,
+ 2.0226900000000114,
+ 2.204609000000005,
+ 2.154337999999939,
+ 2.2067160000000285,
+ 2.138877999999977,
+ 2.111703000000034,
+ 2.1008509999999205,
+ 2.113270000000057,
+ 2.4297000000000253,
+ 1.981049999999982
+ ],
+ "cpuMs": 168.20999999999998,
+ "sourceBytes": 1202,
+ "peakRssMiB": 114.078125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "capture-codex",
+ "iterations": 50,
+ "latenciesMs": [
+ 2.0368100000000027,
+ 0.5913830000000075,
+ 0.5556520000000091,
+ 0.48743100000001505,
+ 0.4076500000000465,
+ 0.3967810000000327,
+ 0.44007800000002817,
+ 0.42700600000000577,
+ 0.5256889999999999,
+ 0.4287970000000314,
+ 0.3823650000000498,
+ 0.387155000000007,
+ 0.3996659999999679,
+ 0.3859040000000391,
+ 0.37657100000001265,
+ 0.3608590000000049,
+ 0.3864260000000286,
+ 0.43815100000000484,
+ 0.4785049999999842,
+ 0.4147389999999973,
+ 0.39702299999999013,
+ 0.3903020000000197,
+ 0.3834679999999935,
+ 0.3946990000000028,
+ 0.4149550000000204,
+ 0.3717730000000188,
+ 0.39148700000004055,
+ 0.3831360000000359,
+ 0.3837639999999851,
+ 0.4114469999999528,
+ 0.3780809999999519,
+ 0.3850280000000339,
+ 0.4538109999999733,
+ 0.39303200000000516,
+ 0.38116600000000744,
+ 0.3722359999999867,
+ 0.3966260000000261,
+ 0.376829999999984,
+ 0.4717719999999872,
+ 0.4091799999999921,
+ 0.3822340000000395,
+ 0.385832999999991,
+ 0.3774700000000166,
+ 0.37293099999999413,
+ 0.41729200000003175,
+ 0.38651699999996936,
+ 0.37322000000000344,
+ 0.3686569999999847,
+ 0.3825560000000223,
+ 0.363330000000019
+ ],
+ "cpuMs": 22.536,
+ "sourceBytes": 1202,
+ "peakRssMiB": 100.66015625,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "capture-codex",
+ "iterations": 50,
+ "latenciesMs": [
+ 7.025823000000003,
+ 3.3377079999999637,
+ 3.369336999999973,
+ 3.715759999999989,
+ 2.5296069999999986,
+ 3.161303999999973,
+ 2.9783690000000433,
+ 2.8126120000000014,
+ 2.8058399999999892,
+ 2.8887080000000083,
+ 2.773603000000037,
+ 2.7671770000000038,
+ 2.784323000000029,
+ 2.7558010000000195,
+ 2.8508300000000304,
+ 3.465169000000003,
+ 2.367580000000032,
+ 2.3144399999999905,
+ 2.35413699999998,
+ 2.246672999999987,
+ 2.226350000000025,
+ 2.2256780000000163,
+ 2.251383999999973,
+ 2.2516239999999925,
+ 2.2896499999999946,
+ 2.30545699999999,
+ 2.213146999999992,
+ 2.1963069999999902,
+ 2.2265479999999798,
+ 2.072011000000032,
+ 2.067190000000039,
+ 2.3357429999999795,
+ 2.038792000000001,
+ 2.0382830000000354,
+ 2.1796879999999987,
+ 2.1760909999999853,
+ 2.235726999999997,
+ 2.140465000000006,
+ 2.1664959999999382,
+ 2.2204779999999573,
+ 2.2191310000000612,
+ 2.1339910000000373,
+ 2.1486609999999473,
+ 2.1804670000000215,
+ 2.1105119999999715,
+ 2.0906780000000253,
+ 2.2079109999999673,
+ 2.000644999999963,
+ 2.212362999999982,
+ 2.000987000000009
+ ],
+ "cpuMs": 163.993,
+ "sourceBytes": 1202,
+ "peakRssMiB": 107.4296875,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 3
+ },
+ {
+ "workload": "capture-claude",
+ "iterations": 50,
+ "latenciesMs": [
+ 2.545839000000001,
+ 0.4946939999999813,
+ 0.5010159999999928,
+ 0.4349369999999908,
+ 0.35304800000000114,
+ 0.29188400000003867,
+ 0.33492999999998574,
+ 0.3357040000000211,
+ 0.4752560000000017,
+ 0.3851120000000492,
+ 0.32236599999998816,
+ 0.29795899999999165,
+ 0.32286499999997886,
+ 0.303641999999968,
+ 0.2940070000000219,
+ 0.2913250000000289,
+ 0.2885840000000144,
+ 0.3638740000000098,
+ 0.3273269999999684,
+ 0.28858900000000176,
+ 0.2908779999999638,
+ 0.28557999999998174,
+ 0.28123499999998103,
+ 0.2801769999999806,
+ 0.28329800000000205,
+ 0.2886710000000221,
+ 0.2827429999999822,
+ 0.2824679999999944,
+ 0.2834750000000099,
+ 0.2793490000000247,
+ 0.2814730000000054,
+ 0.2916200000000231,
+ 0.3432980000000043,
+ 0.2898169999999709,
+ 0.2847679999999855,
+ 0.2858770000000277,
+ 0.28290900000001784,
+ 0.2837729999999965,
+ 0.3568209999999681,
+ 0.31227899999998954,
+ 0.2850410000000352,
+ 0.27963700000003655,
+ 0.27798799999999346,
+ 0.30930499999999483,
+ 0.3305689999999686,
+ 0.3024029999999698,
+ 0.28256000000004633,
+ 0.2764359999999897,
+ 0.2783709999999928,
+ 0.2727660000000469
+ ],
+ "cpuMs": 18.462000000000003,
+ "sourceBytes": 1194,
+ "peakRssMiB": 103.19921875,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "capture-claude",
+ "iterations": 50,
+ "latenciesMs": [
+ 8.26020200000005,
+ 3.638670999999988,
+ 3.5312040000000025,
+ 3.6776419999999916,
+ 2.9331700000000183,
+ 3.1201829999999973,
+ 3.1176929999999743,
+ 2.968018000000029,
+ 3.0599209999999744,
+ 2.9679759999999646,
+ 3.177630000000022,
+ 3.165590000000009,
+ 3.219481999999971,
+ 3.486105000000009,
+ 2.6207899999999995,
+ 2.512450000000001,
+ 2.377010000000041,
+ 2.3601319999999646,
+ 2.3609050000000025,
+ 2.437821999999983,
+ 2.3278140000000462,
+ 2.386528999999996,
+ 2.3360699999999497,
+ 2.289863999999966,
+ 2.3057269999999903,
+ 2.1639190000000212,
+ 2.151440999999977,
+ 2.3914629999999875,
+ 2.1579909999999813,
+ 2.1592210000000023,
+ 2.15310199999999,
+ 2.146429000000012,
+ 2.1713940000000207,
+ 2.1528820000000337,
+ 2.17079700000005,
+ 2.2409619999999677,
+ 2.2545559999999796,
+ 2.158865999999989,
+ 2.192028999999991,
+ 2.1260089999999536,
+ 2.11721,
+ 2.1382730000000265,
+ 2.0809379999999464,
+ 2.318431999999916,
+ 2.0842780000000403,
+ 2.20737900000006,
+ 2.1412129999999934,
+ 2.11048100000005,
+ 2.0706650000000764,
+ 2.063635999999974
+ ],
+ "cpuMs": 169.29999999999998,
+ "sourceBytes": 1194,
+ "peakRssMiB": 113.48046875,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "capture-claude",
+ "iterations": 50,
+ "latenciesMs": [
+ 2.561661000000015,
+ 0.5113089999999829,
+ 0.5263559999999643,
+ 0.47610899999995127,
+ 0.33157399999998916,
+ 0.30777100000000246,
+ 0.3521870000000149,
+ 0.3056219999999712,
+ 0.45714699999996355,
+ 0.37174599999997326,
+ 0.31793399999997973,
+ 0.30000899999998865,
+ 0.3234429999999975,
+ 0.31479799999999614,
+ 0.29582199999998693,
+ 0.36522999999999683,
+ 0.30242700000002287,
+ 0.3613819999999919,
+ 0.29540900000000647,
+ 0.2913070000000175,
+ 0.29154499999998507,
+ 0.29449799999997595,
+ 0.29128000000002885,
+ 0.28100500000005013,
+ 0.2800739999999564,
+ 0.29296700000003284,
+ 0.28209800000001906,
+ 0.28227599999996755,
+ 0.28457400000002053,
+ 0.2814119999999889,
+ 0.2831130000000144,
+ 0.27992499999999154,
+ 0.3343800000000101,
+ 0.28865500000000566,
+ 0.28387499999996635,
+ 0.28289499999999634,
+ 0.30297899999999345,
+ 0.2820159999999987,
+ 0.36524000000002843,
+ 0.3067060000000197,
+ 0.2856760000000236,
+ 0.2812070000000517,
+ 0.27943799999997054,
+ 0.27702799999997296,
+ 0.32372200000003204,
+ 0.29411299999998164,
+ 0.2794499999999971,
+ 0.27543100000002596,
+ 0.3069380000000024,
+ 0.27161499999999705
+ ],
+ "cpuMs": 18.555999999999997,
+ "sourceBytes": 1194,
+ "peakRssMiB": 107.25,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "capture-claude",
+ "iterations": 50,
+ "latenciesMs": [
+ 7.9221430000000055,
+ 3.5710060000000112,
+ 3.586083999999971,
+ 4.029594999999972,
+ 3.161153000000013,
+ 3.0726999999999975,
+ 3.1621850000000222,
+ 3.164264000000003,
+ 3.131057999999996,
+ 3.0064010000000394,
+ 2.979311999999993,
+ 2.957582000000002,
+ 3.2845350000000053,
+ 3.6900929999999903,
+ 2.5836340000000177,
+ 2.4985810000000015,
+ 2.361622000000011,
+ 2.3707489999999893,
+ 2.378247999999985,
+ 2.438918000000001,
+ 2.3193430000000035,
+ 2.340377999999987,
+ 2.3819760000000088,
+ 2.304990000000032,
+ 2.305692000000022,
+ 2.175504999999987,
+ 2.1897260000000074,
+ 2.3946070000000077,
+ 2.1839330000000245,
+ 2.1710390000000075,
+ 2.188742999999988,
+ 2.1852140000000304,
+ 2.2071960000000104,
+ 2.173673000000008,
+ 2.1759519999999952,
+ 2.2595420000000104,
+ 2.2546520000000214,
+ 2.149447000000009,
+ 2.1967089999999416,
+ 2.128825000000006,
+ 2.125046999999995,
+ 2.161053000000038,
+ 2.068061999999941,
+ 2.3878160000000435,
+ 2.1908979999999474,
+ 2.2238230000000385,
+ 2.0723749999999654,
+ 2.0657580000000735,
+ 2.067888999999923,
+ 2.11425399999996
+ ],
+ "cpuMs": 170.0639999999999,
+ "sourceBytes": 1194,
+ "peakRssMiB": 113.1953125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "capture-claude",
+ "iterations": 50,
+ "latenciesMs": [
+ 2.161455999999987,
+ 0.4869289999999751,
+ 0.44831400000003896,
+ 0.38414600000004384,
+ 0.3183530000000019,
+ 0.3016319999999837,
+ 0.3464129999999841,
+ 0.29906299999998964,
+ 0.43629900000001953,
+ 0.36902199999997265,
+ 0.3120219999999563,
+ 0.2948539999999866,
+ 0.3325500000000261,
+ 0.2981290000000172,
+ 0.2877300000000105,
+ 0.28491000000002487,
+ 0.28483099999999695,
+ 0.3460569999999734,
+ 0.292951999999957,
+ 0.2846190000000206,
+ 0.2866559999999936,
+ 0.2890780000000177,
+ 0.2783900000000017,
+ 0.2769190000000208,
+ 0.2776410000000169,
+ 0.29017399999997906,
+ 0.2817719999999895,
+ 0.27881700000000365,
+ 0.27664299999997866,
+ 0.2753099999999904,
+ 0.28354699999999866,
+ 0.2740699999999947,
+ 0.3287809999999922,
+ 0.283266000000026,
+ 0.2809469999999692,
+ 0.2754770000000235,
+ 0.2750270000000228,
+ 0.29045500000000857,
+ 0.35812299999997776,
+ 0.2968759999999975,
+ 0.28303799999997636,
+ 0.279213000000027,
+ 0.2754719999999793,
+ 0.2749939999999924,
+ 0.3216000000000463,
+ 0.29782000000000153,
+ 0.2790319999999724,
+ 0.2723010000000272,
+ 0.2713899999999967,
+ 0.2684520000000248
+ ],
+ "cpuMs": 17.595,
+ "sourceBytes": 1194,
+ "peakRssMiB": 101.5078125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "capture-claude",
+ "iterations": 50,
+ "latenciesMs": [
+ 8.030516000000034,
+ 3.4608010000000036,
+ 3.5089849999999956,
+ 3.75987200000003,
+ 2.939653000000021,
+ 3.0777080000000296,
+ 3.094348000000025,
+ 3.1444359999999847,
+ 3.067579999999964,
+ 2.9539199999999823,
+ 2.9177310000000034,
+ 2.900121000000013,
+ 3.2388010000000236,
+ 3.804540999999972,
+ 2.6836769999999888,
+ 2.598948000000007,
+ 2.4835809999999583,
+ 2.4701319999999782,
+ 2.481540999999993,
+ 2.558337999999992,
+ 2.4096139999999764,
+ 2.429168000000004,
+ 2.4964180000000056,
+ 2.2966279999999983,
+ 2.298784000000012,
+ 2.1428110000000515,
+ 2.2038650000000075,
+ 2.9039280000000076,
+ 2.196680000000015,
+ 2.174182999999971,
+ 2.171428999999989,
+ 2.161624999999958,
+ 2.2003400000000397,
+ 2.179312999999979,
+ 2.170963000000029,
+ 2.247240999999974,
+ 2.2886480000000233,
+ 2.1660780000000273,
+ 2.2165049999999837,
+ 2.131264999999985,
+ 2.145130999999992,
+ 2.1871740000000273,
+ 2.0841609999999946,
+ 2.338211000000001,
+ 2.088376999999923,
+ 2.082087999999999,
+ 2.08778499999994,
+ 2.081519999999955,
+ 2.1250519999999824,
+ 2.0851729999999407
+ ],
+ "cpuMs": 170.65100000000004,
+ "sourceBytes": 1194,
+ "peakRssMiB": 111.1328125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 3
+ },
+ {
+ "workload": "checkpoint-small",
+ "iterations": 5,
+ "latenciesMs": [
+ 98.454858,
+ 98.33565899999996,
+ 95.66925700000002,
+ 95.96632299999999,
+ 95.98863099999994
+ ],
+ "cpuMs": 22.221,
+ "sourceBytes": 1213,
+ "peakRssMiB": 103.10546875,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "checkpoint-small",
+ "iterations": 5,
+ "latenciesMs": [
+ 109.59409900000003,
+ 101.71375400000005,
+ 99.52347699999996,
+ 99.44003199999997,
+ 100.51650599999994
+ ],
+ "cpuMs": 52.343,
+ "sourceBytes": 1213,
+ "peakRssMiB": 107.00390625,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "checkpoint-small",
+ "iterations": 5,
+ "latenciesMs": [
+ 99.05669600000004,
+ 96.355774,
+ 97.34124099999997,
+ 98.45333699999992,
+ 96.40748099999996
+ ],
+ "cpuMs": 23.369999999999997,
+ "sourceBytes": 1213,
+ "peakRssMiB": 103.75,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "checkpoint-small",
+ "iterations": 5,
+ "latenciesMs": [
+ 108.33492999999999,
+ 107.98458700000003,
+ 103.573938,
+ 119.349152,
+ 100.60154
+ ],
+ "cpuMs": 57.372,
+ "sourceBytes": 1213,
+ "peakRssMiB": 109.359375,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "checkpoint-small",
+ "iterations": 5,
+ "latenciesMs": [
+ 98.305519,
+ 99.53313899999995,
+ 97.625588,
+ 100.20518000000004,
+ 99.27867600000002
+ ],
+ "cpuMs": 30.093000000000004,
+ "sourceBytes": 1213,
+ "peakRssMiB": 99.98828125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "checkpoint-small",
+ "iterations": 5,
+ "latenciesMs": [
+ 105.54789899999997,
+ 102.52619899999996,
+ 102.99697199999991,
+ 104.8776160000001,
+ 101.69512899999995
+ ],
+ "cpuMs": 59.324,
+ "sourceBytes": 1213,
+ "peakRssMiB": 102.96875,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "candidate",
+ "sample": 3
+ },
+ {
+ "workload": "checkpoint-large",
+ "iterations": 5,
+ "latenciesMs": [
+ 167.57471899999996,
+ 171.12226999999996,
+ 177.138694,
+ 222.80504700000006,
+ 187.43860999999993
+ ],
+ "cpuMs": 339.505,
+ "sourceBytes": 8388797,
+ "peakRssMiB": 166.51953125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "checkpoint-large",
+ "iterations": 5,
+ "latenciesMs": [
+ 161.19978500000002,
+ 192.17306900000005,
+ 184.01415099999997,
+ 153.8417320000001,
+ 144.54230400000006
+ ],
+ "cpuMs": 217.89,
+ "sourceBytes": 8388797,
+ "peakRssMiB": 169.7734375,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "checkpoint-large",
+ "iterations": 5,
+ "latenciesMs": [
+ 161.95752099999993,
+ 178.42947600000002,
+ 191.10924699999998,
+ 187.440472,
+ 188.790346
+ ],
+ "cpuMs": 342.183,
+ "sourceBytes": 8388797,
+ "peakRssMiB": 169.42578125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "checkpoint-large",
+ "iterations": 5,
+ "latenciesMs": [
+ 180.49137399999995,
+ 169.93359799999996,
+ 205.51447199999996,
+ 148.41981799999985,
+ 165.04299800000013
+ ],
+ "cpuMs": 230.60399999999998,
+ "sourceBytes": 8388797,
+ "peakRssMiB": 169.55859375,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "checkpoint-large",
+ "iterations": 5,
+ "latenciesMs": [
+ 145.06555199999997,
+ 181.15579300000002,
+ 175.46919100000002,
+ 191.60128899999995,
+ 194.97920399999998
+ ],
+ "cpuMs": 337.448,
+ "sourceBytes": 8388797,
+ "peakRssMiB": 166.02734375,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "checkpoint-large",
+ "iterations": 5,
+ "latenciesMs": [
+ 151.68243900000004,
+ 150.5803420000001,
+ 150.9046689999999,
+ 140.69385599999987,
+ 148.01391000000012
+ ],
+ "cpuMs": 214.69099999999997,
+ "sourceBytes": 8388797,
+ "peakRssMiB": 172.05078125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "candidate",
+ "sample": 3
+ },
+ {
+ "workload": "checkpoint-reuse",
+ "iterations": 5,
+ "latenciesMs": [
+ 41.595128000000045,
+ 38.69319900000005,
+ 39.23817900000006,
+ 38.344104000000016,
+ 39.80381399999999
+ ],
+ "cpuMs": 12.543,
+ "sourceBytes": 8388786,
+ "peakRssMiB": 160.08984375,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "checkpoint-reuse",
+ "iterations": 5,
+ "latenciesMs": [
+ 45.427768000000015,
+ 46.81931199999997,
+ 45.14391699999999,
+ 45.3899990000001,
+ 46.761837000000014
+ ],
+ "cpuMs": 61.688,
+ "sourceBytes": 8388786,
+ "peakRssMiB": 164.515625,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "checkpoint-reuse",
+ "iterations": 5,
+ "latenciesMs": [
+ 39.58060499999999,
+ 40.414826999999946,
+ 38.903715000000034,
+ 38.994641,
+ 38.70756199999994
+ ],
+ "cpuMs": 10.128,
+ "sourceBytes": 8388786,
+ "peakRssMiB": 159.83984375,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "checkpoint-reuse",
+ "iterations": 5,
+ "latenciesMs": [
+ 47.925749999999994,
+ 46.708087999999975,
+ 44.820955000000026,
+ 44.95655499999998,
+ 44.55211099999997
+ ],
+ "cpuMs": 40.464000000000006,
+ "sourceBytes": 8388786,
+ "peakRssMiB": 168.69140625,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "checkpoint-reuse",
+ "iterations": 5,
+ "latenciesMs": [
+ 43.0143579999999,
+ 41.863696000000004,
+ 38.921704999999974,
+ 38.87633000000005,
+ 37.533383999999955
+ ],
+ "cpuMs": 12.602,
+ "sourceBytes": 8388786,
+ "peakRssMiB": 152.53125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "checkpoint-reuse",
+ "iterations": 5,
+ "latenciesMs": [
+ 43.64644600000008,
+ 45.27237200000002,
+ 43.8047949999999,
+ 45.472267999999985,
+ 45.39868100000001
+ ],
+ "cpuMs": 37.928,
+ "sourceBytes": 8388786,
+ "peakRssMiB": 166.9453125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 5
+ },
+ "revision": "candidate",
+ "sample": 3
+ },
+ {
+ "workload": "stop",
+ "iterations": 50,
+ "latenciesMs": [
+ 103.902218,
+ 104.24017500000002,
+ 101.17978499999992,
+ 99.57269000000008,
+ 84.56795499999998,
+ 99.71533799999997,
+ 100.33694300000002,
+ 97.04752599999983,
+ 100.35569400000008,
+ 97.57931800000006,
+ 101.61892100000023,
+ 99.5392509999997,
+ 80.77203399999962,
+ 100.87595400000009,
+ 97.79997599999979,
+ 98.69606599999997,
+ 96.97850100000005,
+ 98.90492199999971,
+ 99.33689299999969,
+ 95.67726799999991,
+ 96.86508599999979,
+ 97.61935300000005,
+ 95.78506000000016,
+ 98.76677299999983,
+ 78.69447299999956,
+ 96.11906199999976,
+ 98.09790500000054,
+ 82.05295100000058,
+ 97.88419299999987,
+ 98.27459799999997,
+ 133.96182700000008,
+ 96.80369700000028,
+ 94.9807009999995,
+ 97.78243800000018,
+ 96.72639499999968,
+ 97.08485800000017,
+ 97.48075999999946,
+ 97.00830499999938,
+ 97.0270730000002,
+ 96.59483600000021,
+ 94.01484100000016,
+ 94.92439399999967,
+ 96.90040700000009,
+ 98.51942700000018,
+ 97.86309600000004,
+ 94.78726999999981,
+ 98.8305820000005,
+ 99.9045959999994,
+ 97.37838199999987,
+ 99.59280299999955
+ ],
+ "cpuMs": 223.38199999999992,
+ "sourceBytes": 1202,
+ "peakRssMiB": 105.2890625,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "stop",
+ "iterations": 50,
+ "latenciesMs": [
+ 115.06904099999997,
+ 110.67937999999992,
+ 111.92400899999996,
+ 111.60953000000006,
+ 107.337714,
+ 108.80276700000013,
+ 110.07583699999986,
+ 122.99198899999988,
+ 106.71612700000014,
+ 111.34667799999988,
+ 105.47991900000034,
+ 107.14565100000027,
+ 107.2022109999998,
+ 104.23915399999987,
+ 90.79958799999986,
+ 110.42796199999975,
+ 106.80744000000004,
+ 92.77496700000029,
+ 110.75825200000008,
+ 104.14225699999997,
+ 106.79251699999986,
+ 109.22544799999969,
+ 104.78705500000024,
+ 108.8150740000001,
+ 107.92261600000074,
+ 108.63035800000034,
+ 106.26315900000009,
+ 105.96216900000036,
+ 103.9627760000003,
+ 108.37286700000004,
+ 91.65911799999958,
+ 108.70964499999991,
+ 111.6669579999998,
+ 106.68810699999995,
+ 120.11326199999985,
+ 110.12229399999978,
+ 108.9407970000002,
+ 111.40361200000007,
+ 109.20955000000049,
+ 109.73817099999997,
+ 104.97665999999936,
+ 87.55412100000012,
+ 106.08669000000009,
+ 109.42145100000016,
+ 107.54212700000062,
+ 106.57605500000045,
+ 107.15230800000063,
+ 103.58673999999883,
+ 107.77635699999882,
+ 105.87427199999911
+ ],
+ "cpuMs": 778.2419999999998,
+ "sourceBytes": 1202,
+ "peakRssMiB": 113.859375,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "stop",
+ "iterations": 50,
+ "latenciesMs": [
+ 105.043588,
+ 99.41243499999996,
+ 100.33394600000008,
+ 99.79365399999995,
+ 100.0022449999999,
+ 102.08139000000006,
+ 98.64303599999994,
+ 101.22937999999999,
+ 98.98989400000005,
+ 98.26792299999988,
+ 94.86671799999976,
+ 101.11842699999988,
+ 95.2190099999998,
+ 101.18855599999961,
+ 98.32337999999982,
+ 100.77592000000004,
+ 96.4026689999996,
+ 101.399899,
+ 100.02747899999986,
+ 101.30677699999978,
+ 99.3986219999997,
+ 100.94734900000003,
+ 96.41896700000007,
+ 98.44147399999974,
+ 149.73884999999973,
+ 118.26367399999981,
+ 98.21008600000005,
+ 97.51744299999973,
+ 99.74224000000049,
+ 97.59939799999938,
+ 97.12047200000052,
+ 94.55834700000014,
+ 98.44510199999968,
+ 102.08321400000023,
+ 100.14127800000006,
+ 97.92711000000054,
+ 99.23176599999988,
+ 100.25698700000066,
+ 101.53585899999962,
+ 100.62522600000011,
+ 103.32578399999966,
+ 96.818311,
+ 98.18151099999977,
+ 101.16940599999998,
+ 98.73616599999968,
+ 94.53083100000003,
+ 97.56713499999933,
+ 99.56209599999966,
+ 96.0886929999997,
+ 97.92772900000091
+ ],
+ "cpuMs": 265.74399999999997,
+ "sourceBytes": 1202,
+ "peakRssMiB": 110.12109375,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "stop",
+ "iterations": 50,
+ "latenciesMs": [
+ 116.72800800000005,
+ 109.48307199999999,
+ 111.87151700000004,
+ 109.43046700000002,
+ 107.07302400000003,
+ 105.25672400000008,
+ 105.99938399999996,
+ 107.95715400000017,
+ 109.34790899999985,
+ 106.89142399999992,
+ 105.663141,
+ 109.41870000000017,
+ 106.19461899999988,
+ 103.24663899999996,
+ 111.20083999999997,
+ 109.98969000000034,
+ 107.6667779999998,
+ 111.42286799999965,
+ 110.87948200000028,
+ 106.44609300000002,
+ 105.08510299999989,
+ 111.17930700000034,
+ 107.59158500000012,
+ 92.26591000000008,
+ 125.63998600000014,
+ 107.72398599999997,
+ 108.98576299999968,
+ 109.78856799999994,
+ 108.74831400000039,
+ 102.19547499999953,
+ 105.03417300000001,
+ 108.35869100000036,
+ 111.60292699999991,
+ 103.92406299999948,
+ 109.03046499999982,
+ 108.55876799999987,
+ 107.32949199999985,
+ 105.8132169999999,
+ 104.95281599999998,
+ 108.28150800000003,
+ 107.9193239999995,
+ 107.00365299999976,
+ 111.5061110000006,
+ 109.51007700000082,
+ 109.04713100000026,
+ 108.20645400000012,
+ 104.72545600000012,
+ 104.85245299999951,
+ 109.36069700000007,
+ 104.69877400000041
+ ],
+ "cpuMs": 760.1239999999998,
+ "sourceBytes": 1202,
+ "peakRssMiB": 116.94921875,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "stop",
+ "iterations": 50,
+ "latenciesMs": [
+ 103.61275999999998,
+ 101.70926000000009,
+ 96.44394999999997,
+ 107.17077899999992,
+ 100.07671700000014,
+ 103.00867900000003,
+ 103.53929799999992,
+ 97.77955900000006,
+ 100.58955600000013,
+ 99.979196,
+ 99.52485200000001,
+ 105.43423900000016,
+ 96.95511699999997,
+ 118.38351299999977,
+ 100.91344900000013,
+ 100.31662500000039,
+ 97.47899400000006,
+ 83.74007400000028,
+ 100.78908599999977,
+ 97.43811400000004,
+ 95.28249300000016,
+ 98.58228699999972,
+ 99.80450000000019,
+ 96.94873199999938,
+ 96.69430000000011,
+ 100.28807700000016,
+ 96.7233239999996,
+ 84.88192999999956,
+ 96.39779700000054,
+ 101.91277600000012,
+ 97.67806800000017,
+ 96.84814700000061,
+ 98.81066699999974,
+ 100.24972700000035,
+ 98.34294499999942,
+ 97.96982399999979,
+ 95.83350000000064,
+ 97.31328899999971,
+ 97.44688700000006,
+ 97.9205380000003,
+ 83.18042499999956,
+ 96.89769100000012,
+ 96.22939600000063,
+ 97.0185220000003,
+ 102.84038200000032,
+ 96.93139000000065,
+ 99.96336500000052,
+ 100.22573999999986,
+ 97.86891500000002,
+ 97.57173000000057
+ ],
+ "cpuMs": 234.45399999999995,
+ "sourceBytes": 1202,
+ "peakRssMiB": 105.58203125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "stop",
+ "iterations": 50,
+ "latenciesMs": [
+ 113.60176799999999,
+ 106.878871,
+ 107.93192299999998,
+ 105.20798000000002,
+ 108.14956299999994,
+ 105.10640199999989,
+ 105.90644900000007,
+ 121.93954399999984,
+ 124.54954999999995,
+ 107.62924900000007,
+ 111.23318500000005,
+ 109.51652000000013,
+ 110.83282199999985,
+ 108.01994999999988,
+ 123.76604999999972,
+ 106.27897900000016,
+ 108.3947989999997,
+ 108.39222400000017,
+ 109.9454609999998,
+ 107.47945200000004,
+ 107.63374900000008,
+ 104.2889839999998,
+ 107.80514200000016,
+ 108.55919600000016,
+ 107.96024200000011,
+ 104.72457500000019,
+ 107.15520799999922,
+ 105.61773700000049,
+ 106.18149000000085,
+ 111.41138899999987,
+ 94.85477300000002,
+ 110.78177200000027,
+ 110.56977000000006,
+ 106.31428499999947,
+ 106.78728199999932,
+ 105.39555499999915,
+ 103.7722389999999,
+ 105.70159899999999,
+ 103.20857199999955,
+ 102.5054970000001,
+ 105.46352900000056,
+ 103.721587,
+ 103.31825899999967,
+ 104.01593500000035,
+ 106.6644039999992,
+ 108.33432300000004,
+ 102.92701399999987,
+ 103.61358599999949,
+ 102.80118599999878,
+ 105.53026999999929
+ ],
+ "cpuMs": 752.551,
+ "sourceBytes": 1202,
+ "peakRssMiB": 117.58203125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 3
+ },
+ {
+ "workload": "resume-held",
+ "iterations": 50,
+ "latenciesMs": [
+ 42.876288999999986,
+ 40.15352900000005,
+ 39.380987000000005,
+ 57.50665600000002,
+ 41.41008800000009,
+ 39.7785879999999,
+ 40.6222150000001,
+ 40.33495199999993,
+ 41.854513000000225,
+ 40.55897099999993,
+ 39.024139000000105,
+ 39.98457299999973,
+ 39.13254800000004,
+ 40.11517499999991,
+ 40.21562700000004,
+ 40.70990100000017,
+ 37.32342599999993,
+ 58.55485899999985,
+ 40.22508800000014,
+ 40.567243999999846,
+ 39.90107999999964,
+ 40.6565870000004,
+ 39.394766000000345,
+ 55.48282399999971,
+ 40.37856600000032,
+ 39.46464399999968,
+ 39.50996200000009,
+ 39.43123800000012,
+ 40.29913000000033,
+ 40.63509400000021,
+ 39.31870500000059,
+ 41.04853700000058,
+ 38.0589200000004,
+ 39.220815000000584,
+ 38.541708000000654,
+ 57.46876799999973,
+ 38.599089000000276,
+ 38.921800000000076,
+ 38.51036599999952,
+ 57.680309000001216,
+ 57.799465000000055,
+ 57.989102999999886,
+ 39.91116099999999,
+ 57.0137109999996,
+ 38.12059699999918,
+ 40.05321200000071,
+ 41.63701799999944,
+ 39.72352200000023,
+ 37.90358800000104,
+ 60.54349099999854
+ ],
+ "cpuMs": 116.05299999999998,
+ "sourceBytes": 1202,
+ "peakRssMiB": 117.25,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "resume-held",
+ "iterations": 50,
+ "latenciesMs": [
+ 45.45271500000001,
+ 44.75338399999998,
+ 40.79284000000007,
+ 42.914378999999826,
+ 44.04486100000008,
+ 44.11550299999999,
+ 42.95079499999997,
+ 40.12248100000011,
+ 59.04338400000006,
+ 42.16779399999996,
+ 40.9417169999997,
+ 57.71706200000017,
+ 74.7918279999999,
+ 40.523347000000285,
+ 77.51973799999996,
+ 56.88884199999984,
+ 43.16601300000002,
+ 59.686469000000216,
+ 42.31317399999989,
+ 41.56449299999986,
+ 62.95617200000015,
+ 41.560419999999795,
+ 41.08387700000003,
+ 42.71362399999998,
+ 43.05279100000007,
+ 25.64519399999972,
+ 61.37528900000052,
+ 41.983705999999984,
+ 41.104199999999764,
+ 59.82532899999933,
+ 39.88548199999968,
+ 42.973839999999655,
+ 40.41132099999959,
+ 42.944297000000006,
+ 40.1299199999994,
+ 40.590870999999424,
+ 41.09205800000018,
+ 39.98872499999925,
+ 40.78996400000051,
+ 77.97037799999998,
+ 41.663596000000325,
+ 41.54248199999893,
+ 41.10517699999946,
+ 42.121995999999854,
+ 41.54768199999853,
+ 42.04580700000042,
+ 39.61110899999949,
+ 56.522195000001375,
+ 43.24301000000014,
+ 42.88956899999903
+ ],
+ "cpuMs": 288.788,
+ "sourceBytes": 1202,
+ "peakRssMiB": 111.89453125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "resume-held",
+ "iterations": 50,
+ "latenciesMs": [
+ 40.16654499999993,
+ 55.80594700000006,
+ 40.32169799999997,
+ 41.6021639999999,
+ 40.103672999999844,
+ 39.38883900000019,
+ 39.55183000000011,
+ 37.89265099999989,
+ 57.98679100000027,
+ 38.778335000000425,
+ 59.97431800000004,
+ 60.50478199999998,
+ 40.237971000000016,
+ 38.33019800000011,
+ 40.319980000000214,
+ 59.011303000000225,
+ 38.94587499999989,
+ 60.420144000000164,
+ 58.57592999999997,
+ 37.63246600000002,
+ 39.51063200000044,
+ 40.31100500000048,
+ 38.45624100000077,
+ 36.71465100000023,
+ 38.07585399999971,
+ 39.588981000000786,
+ 40.82421499999964,
+ 39.77836699999989,
+ 39.53008500000033,
+ 37.72793900000033,
+ 38.79291699999976,
+ 39.08682099999987,
+ 38.67549500000041,
+ 56.1913169999998,
+ 39.546621000000414,
+ 71.09632200000033,
+ 63.493257000000085,
+ 39.45052200000009,
+ 88.5900700000002,
+ 89.69630000000143,
+ 115.6213029999999,
+ 65.65259100000003,
+ 120.67485300000044,
+ 79.36983300000065,
+ 59.390166999999565,
+ 77.42476499999975,
+ 74.28712099999939,
+ 58.41186000000016,
+ 61.507239999999,
+ 42.2497170000006
+ ],
+ "cpuMs": 109.45200000000001,
+ "sourceBytes": 1202,
+ "peakRssMiB": 109.6328125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "resume-held",
+ "iterations": 50,
+ "latenciesMs": [
+ 65.45309799999995,
+ 40.08895899999993,
+ 40.006595999999945,
+ 42.399979999999914,
+ 44.473964000000024,
+ 41.06640399999992,
+ 57.654059999999845,
+ 43.0360619999999,
+ 60.21552100000008,
+ 61.78787399999965,
+ 42.016581999999744,
+ 41.44266599999992,
+ 79.49906400000009,
+ 61.14910299999974,
+ 43.56473799999958,
+ 40.22576600000002,
+ 60.190729000000374,
+ 40.08459599999969,
+ 42.166212999999516,
+ 60.95606599999974,
+ 41.18190499999946,
+ 60.35049699999945,
+ 40.194054999999935,
+ 42.42967399999998,
+ 43.103587999999945,
+ 41.84442299999955,
+ 64.99362399999973,
+ 41.62541500000043,
+ 39.4445740000001,
+ 58.486008999999285,
+ 38.695831,
+ 38.90313200000037,
+ 40.41041700000005,
+ 42.32918100000006,
+ 40.60287299999982,
+ 42.87626199999977,
+ 61.60767300000043,
+ 57.71015499999976,
+ 42.06031199999961,
+ 65.23667199999909,
+ 40.22993100000167,
+ 39.066617000000406,
+ 42.11505399999987,
+ 43.0318329999991,
+ 43.15864099999999,
+ 60.76939599999969,
+ 41.62194900000031,
+ 40.46730000000025,
+ 40.633951000001616,
+ 76.66603100000066
+ ],
+ "cpuMs": 247.982,
+ "sourceBytes": 1202,
+ "peakRssMiB": 114.921875,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "resume-held",
+ "iterations": 50,
+ "latenciesMs": [
+ 39.076211,
+ 38.617331000000036,
+ 41.39609500000006,
+ 38.88655199999994,
+ 38.488444999999956,
+ 39.955658000000085,
+ 39.602701000000025,
+ 38.518246999999974,
+ 39.97711699999991,
+ 38.76130199999989,
+ 39.11741600000005,
+ 41.027857999999924,
+ 38.84621300000026,
+ 39.723587999999836,
+ 40.094522999999754,
+ 38.446624000000156,
+ 41.09661899999992,
+ 40.6984809999999,
+ 40.102034,
+ 39.15348499999982,
+ 39.83173799999986,
+ 41.06684899999982,
+ 22.996742000000268,
+ 38.65602899999976,
+ 38.91822200000024,
+ 39.251907000000756,
+ 37.60982899999999,
+ 38.93413199999941,
+ 39.10108299999956,
+ 38.730501000000004,
+ 38.06421499999942,
+ 21.164840999999797,
+ 37.11946699999953,
+ 37.62373900000057,
+ 40.04923099999996,
+ 40.2642620000006,
+ 58.31854800000019,
+ 39.51050799999939,
+ 37.59674199999972,
+ 40.61963300000025,
+ 37.837657999998555,
+ 38.00216100000034,
+ 38.02450999999928,
+ 57.49105100000088,
+ 36.66113899999982,
+ 38.2465370000009,
+ 37.15480600000046,
+ 57.07066600000144,
+ 57.08546899999965,
+ 39.56836800000019
+ ],
+ "cpuMs": 100.98999999999998,
+ "sourceBytes": 1202,
+ "peakRssMiB": 116.9921875,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "resume-held",
+ "iterations": 50,
+ "latenciesMs": [
+ 46.144604999999956,
+ 59.490261999999916,
+ 43.84102299999995,
+ 41.630919000000176,
+ 41.206995000000006,
+ 40.68048999999996,
+ 43.66366100000005,
+ 42.48920399999997,
+ 42.48573299999998,
+ 39.714668000000074,
+ 57.80603400000018,
+ 40.14778899999965,
+ 43.38395400000036,
+ 43.3791040000001,
+ 42.212422999999944,
+ 41.97302600000012,
+ 39.69175000000041,
+ 42.226938000000246,
+ 43.8661060000004,
+ 42.44679999999971,
+ 40.457932999999684,
+ 56.995991000000686,
+ 40.18611199999941,
+ 57.10327600000073,
+ 39.21204200000011,
+ 40.4502080000002,
+ 39.621549000000414,
+ 41.28505899999982,
+ 62.22131099999933,
+ 69.2958179999996,
+ 39.95238299999983,
+ 44.0874789999998,
+ 42.03221200000007,
+ 44.11381999999958,
+ 42.4870719999999,
+ 42.954782000000705,
+ 41.14189699999952,
+ 39.60766500000045,
+ 39.913408999998865,
+ 42.32852400000047,
+ 59.49109700000008,
+ 63.07748999999967,
+ 42.43077500000072,
+ 40.06159999999909,
+ 39.172717999999804,
+ 57.269367000000784,
+ 42.87862200000018,
+ 41.83141699999942,
+ 41.13173199999983,
+ 41.840800999998464
+ ],
+ "cpuMs": 251.49699999999999,
+ "sourceBytes": 1202,
+ "peakRssMiB": 117.86328125,
+ "node": "v22.23.2",
+ "hostPlatform": "darwin",
+ "evidencePlatform": "linux",
+ "arch": "x64",
+ "outcomes": {
+ "confirmed": 50
+ },
+ "revision": "candidate",
+ "sample": 3
+ }
+ ],
+ "finishedAt": "2026-10-10T09:40:10Z"
+}
diff --git a/docs/research/2026-10-10-native-hook-admission.md b/docs/research/2026-10-10-native-hook-admission.md
index b978d523e..2a08aa1fe 100644
--- a/docs/research/2026-10-10-native-hook-admission.md
+++ b/docs/research/2026-10-10-native-hook-admission.md
@@ -135,9 +135,21 @@ broken proof, commit, queue, cancellation and notification wiring. Matched compl
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.
+[PR #1137](https://github.com/autonomous-ai/openharness/pull/1137) merged as
+`9618c2e2c09c078a27a0d76b94f62365bd7a2c89` at October 10 08:36:54 UTC. Independent
+review approved final head `5af2d4bd25fd4d82ca1061c6b8ffb686f80ddfb8` against base
+`294548e`, following review corrections. Receipt `20261010T083045` passed core/services
+(2,114 tests in 165 files, 100%), harnessd (265 passed and one existing skip, 100%),
+162 native cases, 22 admission-golden/architecture cases and private hook-client
+acceptance (ten passed, one older-release compatibility opt-in skip). Source comparison
+and review retained unchanged serial Resume, 63 private lifecycle e2e cases, all 32
+assertion-failing mutations and the matched cost evidence above.
+
+Automatic [CI run 38038140466](https://github.com/autonomous-ai/openharness/actions/runs/38038140466)
+passed every head check, including `ci/required`. Merge verification occupied
+08:36:40–08:36:54; receipt `20261010T083640.654250Z-merge-1137` records the reviewed
+trees. The former golden was recorded at 04:33; implementation continued after #1133
+merged at 05:16, with review and validation interleaved through the final gate at
+08:30:45. Those overlapping intervals are not added to estimate elapsed request time.
+Publication remains zero; no release is authorized. Restart-persistent delivery and
+legacy native-client acknowledgement/order remain in the completion checklist.