Skip to content

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

Keep saved bindings through incomplete native evidence (#1133)

Deea2a7874f35b4
diff --git a/cli/e2e/enginehomes.e2e.ts b/cli/e2e/enginehomes.e2e.ts
index 457bd27b6..2e56623aa 100644
--- a/cli/e2e/enginehomes.e2e.ts
+++ b/cli/e2e/enginehomes.e2e.ts
@@ -9,7 +9,7 @@
import { createHash } from 'node:crypto'
import { tmpdir } from 'node:os'
import { execFileSync } from 'node:child_process'
-import { existsSync, mkdtempSync, rmSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs'
+import { appendFileSync, existsSync, mkdtempSync, rmSync, mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
@@ -245,6 +245,60 @@ describe('the person\'s engines keeping their data elsewhere', () => {
again.close()
})
+ it.each([false, true])('retains a saved binding with an incomplete header while readiness and a sibling work, then recovers in place: inline=%s', async inline => {
+ const d = await IsolatedDaemon.create(inline ? { env: { HARNESSD_SERVICES: 'none' } } : {}); daemon = d
+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`))
+ await d.start()
+ let client = await LocalClient.connect(d)
+ const agents: Row[] = []
+ for (const engine of ['codex', 'claude']) {
+ const created = await client.request('agent_create', { engine, cwd: d.projectsDir, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ agents.push(await until('the private conversation to bind', async () => {
+ const value = await row(client, created.agent.id); return value?.sessionId ? value : null
+ }, 45_000))
+ }
+ const [bound, sibling] = agents
+ await turn(client, bound!.id, 'before the incomplete header')
+ client.close(); await d.stop()
+ const original = (JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8')) as Row[])
+ .find(value => value.agentId === bound!.id)!
+ const file = original.transcriptPath as string
+ expect(file.startsWith(d.root + '/')).toBe(true)
+ const complete = readFileSync(file)
+ writeFileSync(file, complete.subarray(0, 12))
+ await d.start(); client = await LocalClient.connect(d)
+ const held = await until('the saved conversation to expose its hold', async () => {
+ const value = await row(client, bound!.id); return value?.identityHold ? value : null
+ }, 45_000)
+ expect(held).toMatchObject({ sessionId: bound!.sessionId, status: 'active' })
+ // A mistakenly installed tail would parse this valid turn record despite its invalid header.
+ // Only this fixture's file is written; no synthetic input goes to the held pane.
+ appendFileSync(file, '\n' + JSON.stringify({ type: 'event_msg', payload: { type: 'user_message', message: 'unconfirmed held record' } }) + '\n')
+ await turn(client, sibling!.id, 'a sibling works during the hold')
+ expect(client.frames.filter(frame => frame.agentId === bound!.id && ['turn_started', 'turn_ended'].includes(frame.type))).toEqual([])
+ const cancelled = client.next(isTurn('agent_activity', bound!.id), 15_000, 'held cancellation acknowledged by core')
+ client.send('cancel', { agentId: bound!.id })
+ await cancelled
+ const saved = JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8')) as Row[]
+ expect(saved.find(value => value.agentId === bound!.id)).toMatchObject({ sessionId: bound!.sessionId, transcriptPath: file })
+ writeFileSync(file, complete)
+ await expect.poll(async () => (await row(client, bound!.id))?.identityHold, { timeout: 45_000, interval: 200 })
+ .toEqual(expect.stringMatching(/^Waiting for transcript interpretation:/))
+ const recovery = await row(client, bound!.id)
+ expect(recovery?.identityHold).toEqual(expect.stringMatching(/control boundary|replaced or truncated|boundary is an incomplete record/))
+ const confirmed = client.next(isTurn('agent_activity', bound!.id), 15_000, 'current cancellation acknowledged by core')
+ client.send('cancel', { agentId: bound!.id })
+ await confirmed
+ await until('the same live binding to recover without another restart', async () => {
+ const value = await row(client, bound!.id)
+ return value?.sessionId === bound!.sessionId && !value.identityHold ? value : null
+ }, 45_000)
+ await turn(client, bound!.id, 'after the header recovered')
+ expect(d.coresStarted()).toBe(2)
+ client.close()
+ }, 240_000)
+
it.each(['claude', 'codex'] as const)('search finds external %s conversations in the moved home after startup', async engine => {
const d = await IsolatedDaemon.create(); daemon = d
onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`))
diff --git a/cli/scripts/handoff-2026-10-08/binding-evidence-cost.ts b/cli/scripts/handoff-2026-10-08/binding-evidence-cost.ts
new file mode 100644
index 000000000..a30f8d4e4
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/binding-evidence-cost.ts
@@ -0,0 +1,48 @@
+/** Whole registry load cost, including fresh catalog, root and final file proofs. Run alone. */
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { performance } from 'node:perf_hooks'
+import { pathToFileURL } from 'node:url'
+
+const workload = process.argv[2] ?? 'single'
+if (!['single', 'batch', 'many-homes'].includes(workload)) throw Error('Unknown workload')
+const cli = process.env.BINDING_COST_CLI ?? resolve(import.meta.dirname, '../..')
+const root = realpathSync(mkdtempSync(join(tmpdir(), 'binding-evidence-cost-')))
+for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR']) process.env[name] = join(root, name)
+process.env.CLAUDE_PROJECTS_DIR = join(process.env.CLAUDE_CONFIG_DIR!, 'projects')
+process.env.HARNESS_CONNECTIONS_PORT = '0'
+const count = workload === 'single' ? 1 : 200, homeCount = workload === 'many-homes' ? 63 : 1
+const data = process.env.ADAPTER_DATA_DIR!
+mkdirSync(data, { mode: 0o700 })
+try {
+ const homes = Array.from({ length: homeCount }, (_, i) => join(root, `home-${i}`))
+ for (const home of homes) mkdirSync(join(home, 'sessions'), { recursive: true })
+ writeFileSync(join(data, 'engine-homes.json'), JSON.stringify({ codex: homes }), { mode: 0o600 })
+ const rows = Array.from({ length: count }, (_, i) => {
+ const id = `aaaaaaaa-1111-4222-8333-${String(i).padStart(12, '0')}`, home = homes[i % homeCount]!
+ const transcriptPath = join(home, 'sessions', `rollout-${id}.jsonl`)
+ writeFileSync(transcriptPath, JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, source: 'cli' } }) + '\n', { mode: 0o600 })
+ return { launcherId: `fixture-${i}`, engine: 'codex', sessionId: id, transcriptPath, tmuxPane: `%${i + 1}`,
+ projectDir: 'fixture', cwd: root, processIdentity: null, registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1 }
+ })
+ writeFileSync(join(data, 'registry.json'), JSON.stringify(rows), { mode: 0o600 })
+ const { registry } = await import(pathToFileURL(join(cli, 'src/lib/registry.ts')).href)
+ // Normalize the same legacy fixture before measuring unchanged complete v2 loads.
+ registry.load()
+ const expected = new Set(rows.map(row => row.sessionId))
+ const outcomes: Record<string, number> = {}, latenciesMs: number[] = []
+ const cpu = process.cpuUsage(), started = performance.now()
+ for (let i = 0; i < 5; i++) {
+ const before = performance.now(); registry.load(); latenciesMs.push(performance.now() - before)
+ for (const row of registry.list()) {
+ const result = row.identityHold ? 'held' : expected.has(row.sessionId) && row.transcriptPath ? 'complete' : 'wrong'
+ outcomes[result] = (outcomes[result] ?? 0) + 1
+ }
+ if (registry.list().length !== count) throw Error('The measured load lost rows')
+ }
+ const elapsedMs = performance.now() - started, used = process.cpuUsage(cpu)
+ console.log(JSON.stringify({ workload, rows: count, homes: homeCount, iterations: 5, outcomes, latenciesMs, elapsedMs,
+ cpuMs: (used.user + used.system) / 1000, peakRssMiB: process.resourceUsage().maxRSS / 1024,
+ node: process.version, platform: process.platform, arch: process.arch }))
+} finally { rmSync(root, { recursive: true, force: true }) }
diff --git a/cli/scripts/handoff-2026-10-08/mutate-binding-evidence.py b/cli/scripts/handoff-2026-10-08/mutate-binding-evidence.py
new file mode 100644
index 000000000..63682ed2b
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-binding-evidence.py
@@ -0,0 +1,102 @@
+"""Run only in an owned disposable worktree: every broken binding fence must fail an assertion."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+registry = 'src/lib/registry.ts'
+binding = 'src/engines/transcriptBindings.ts'
+files = 'src/engines/kit/nativeFiles.ts'
+paths = 'src/engines/kit/nativePaths.ts'
+primitive = 'src/engines/transcriptBindings.spec.ts'
+loaded = 'src/lib/registry.binding.spec.ts'
+core = 'src/core/agents/bind.ts'
+core_spec = 'src/core/agents/bind.spec.ts'
+controls = 'src/core/transcripts/attach.control.spec.ts'
+mutations = [
+ ('parent repair disconnected', binding, 'selected = store.repairsOverwrittenParent && meta.parentThreadId === sessionId', 'selected = false', 'src/lib/bindingEvidence.golden.spec.ts'),
+ ('saved binding file fence omitted', registry, 'try { proof.verify() }', 'try { void 0 }', loaded),
+ ('root batch fence omitted', registry, 'try { proof?.verify() }', 'try { void 0 }', loaded),
+ ('held retry disconnected', core, 'const retried = registry.revalidateBinding(agent.agentId)', 'const retried = agent', core_spec),
+ ('held reason not exposed', core, 'if (registry.setIdentityHold(agent.agentId, reason)) announceSession(agent)', 'if (false) announceSession(agent)', core_spec),
+ ('saved header id ignored', binding, 'meta.id !== sessionId', 'false', loaded),
+ ('saved header read omitted', binding, 'const meta = proof.files.header(selected, store.first)', "const meta = { id: sessionId, isSubagent: false, parentThreadId: undefined }", loaded),
+ ('opened file identity ignored', files, '!before.isFile() || nativeFileKey(before) !== nativeFileKey(location.info)', '!before.isFile() || false', primitive),
+ ('final header change ignored', files, 'firstLine(bytes, record.limit - 1) !== record.line', 'false', primitive),
+ ('repeated header evidence replaced', files, 'earlier.line !== line', 'false', primitive),
+ ('final ancestry ignored', paths, 'identity(now) !== identity(before.info)', 'false', primitive),
+ ('announced parent owner ignored', binding, 'parent.info.uid !== BigInt(process.getuid())', 'false', primitive),
+ ('dangling leaf accepted', binding, '!files.paths.absentLeaf(join(parent.path, basename(path)))', 'false', primitive),
+ ('repaired file root ignored', binding, '!files.paths.within(file.path, roots.map(root => root.info))', 'false', primitive),
+ ('repaired directory root ignored', binding, '!files.paths.within(location.path, roots.map(root => root.info))', 'false', primitive),
+ ('ambiguous parent accepted', binding, 'selected.size > 1', 'false', primitive),
+ ('parent pool final stamp ignored', files, 'stamp(lstatSync(path, { bigint: true })) !== before', 'false', primitive),
+ ('ancestor round trip ignored', files, 'route.size !== after.size || [...route].some(([part, version]) => after.get(part) !== version)', 'false', primitive),
+ ('recovery does not reset parser', core, 'const reset = meta.isNew || !!meta.recovered', 'const reset = meta.isNew', 'src/core/transcripts/attach.spec.ts'),
+ ('recovery replays saved first turn', core, '!meta.recovered && !resumedConversation', '!resumedConversation', 'src/core/transcripts/attach.spec.ts'),
+ ('released input loses agent key', 'src/core/agents/forget.ts', 'input.forget(announceId)', 'input.forget(sessionId)', 'src/core/agents/forget.spec.ts'),
+ ('durable binding comparison omitted', registry, '!== this.persistedBaseline.get(bindingCommit.agentId)', '!== this.persistedBaseline.get(bindingCommit.agentId) && false', loaded),
+ ('native commit fence omitted', registry, 'bindingCommit.verify()', 'void 0', loaded),
+ ('held attachment admitted', 'src/core/transcripts/attach.ts', 'if (session.identityHold) return Promise.resolve(true)', 'if (false) return Promise.resolve(true)', 'src/core/transcripts/attach.spec.ts'),
+ ('held replies retain authority', 'src/core/transcripts/readIdentity.ts', "...(session.identityHold ? ['identity-held'] : [])", '...[]', 'src/core/transcripts/attach.spec.ts'),
+ ('held line is interpreted', 'src/core/transcripts/ingest.ts', 'session.identityHold || ', '', 'src/core/transcripts/ingest.spec.ts'),
+ ('Cancel admission disconnected', 'src/core/turns/cancel.ts', 'if (record) beforeCancel?.(record)', 'if (false) beforeCancel?.(record!)', controls),
+ ('first ordinary Cancel is forgotten', 'src/core/transcripts/attach.ts', 'session.transcriptPath || turnReplacements.retains(session)', 'turnReplacements.retains(session)', controls),
+ ('Stop retention disconnected', 'src/core/turns/turnHooks.ts', 'retained = holdStop(latest, changed)', 'retained = true', controls),
+ ('ordinary successful Stop is forgotten', 'src/core/turns/turnHooks.ts', 'afterStop?.(resolve(sessionId)!)', 'void 0', controls),
+ ('retained cancellation discarded after recovery', 'src/core/transcripts/turnReplacement.ts', 'if (!boundaries.length && !stopRevision) pending.delete(id)', 'pending.delete(id)', controls),
+ ('cancellation follows old path spelling', 'src/core/transcripts/turnReplacement.ts', 'JSON.stringify([session.agentId, id, session.engine])', 'JSON.stringify([session.agentId, id, session.engine, session.transcriptPath])', controls),
+ ('inline cancellation replay disconnected', 'src/core/transcripts/attach.ts', 'parser!.closeTurn(reason); historyExplicitlyClosed = true', 'historyExplicitlyClosed = true', controls),
+ ('worker request drops cancellation boundaries', 'src/engines/worker/liveRequests.ts', '...(payload.closes === undefined ? {} : { closes: payload.closes })', '...{}', controls),
+ ('worker cancellation replay disconnected', 'src/engines/worker/liveStreams.ts', 'closeThrough: replayCloses(ask.closes ?? [], reason => {', 'closeThrough: replayCloses([], reason => {', controls),
+ ('worker boundary failure loses its reason', 'src/engines/worker/liveRequests.ts', "'ENGINE_TRANSCRIPT_CHANGED', 'ENGINE_CONTROL_BOUNDARY_CHANGED'", "'ENGINE_TRANSCRIPT_CHANGED'", controls),
+ ('replay descriptor fence omitted', 'src/lib/transcriptBoundary.ts', '!actual.isFile() || actual.dev !== expected.device || actual.ino !== expected.inode', 'false', controls),
+ ('ordinary database Cancel starts a file hold', 'src/core/transcripts/attach.ts', 'if (reason && session.transcriptPath)', 'if (reason)', 'src/core/transcripts/attach.spec.ts'),
+ ('legacy open-turn snapshot ignored', 'src/core/transcripts/turnReplacement.ts', 'turnOpen: normalizers.sessionTurnState(id) ?? false', 'turnOpen: false', controls),
+ ('retained legacy open turn ignored', 'src/core/transcripts/turnReplacement.ts', 'normalizers.sessionTurnState(id) ?? state.turnOpen', 'state.turnOpen', controls),
+ ('core Cancel wiring disconnected', 'src/core/main.ts', 'beforeCancel: attach.beforeCancel,', '', 'e2e/enginehomes.e2e.ts'),
+]
+# A receipt can reuse unaffected mutants while a changed composed assertion runs again.
+selected = set(sys.argv[2:])
+if selected:
+ assert selected <= {label for label, *_ in mutations}, 'Unknown mutation label'
+ mutations = [entry for entry in mutations if entry[0] in selected]
+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}
+for key in list(env):
+ if key in ['TMUX', 'TMUX_PANE'] or key.startswith('RECORD_'):
+ env.pop(key)
+if not Path(env.get('TMUX_TMPDIR', '/missing-private-tmux')).is_dir():
+ raise SystemExit('An existing private TMUX_TMPDIR is required')
+
+
+def run(specs):
+ e2e = any(spec.startswith('e2e/') for spec in specs)
+ lane = ['--config', 'vitest.e2e.config.ts', '--testNamePattern', 'retains a saved binding with an incomplete header'] if e2e else []
+ return subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', *lane, *specs, '--maxWorkers=1'],
+ cwd=cli, env=env, capture_output=True, text=True, timeout=300 if e2e else 180)
+
+
+for e2e in [False, True]:
+ specs = sorted({target for _, _, _, _, target in mutations if target.startswith('e2e/') == e2e})
+ if not specs:
+ continue
+ baseline = run(specs)
+ if baseline.returncode:
+ print(baseline.stdout + baseline.stderr)
+ raise SystemExit('baseline failed; no mutants ran')
+print('unchanged baseline passed', flush=True)
+for label, relative, before, after, target in mutations:
+ path = cli / relative
+ original = path.read_text()
+ assert original.count(before) == (2 if label == 'held reason not exposed' else 1), (label, original.count(before))
+ try:
+ path.write_text(original.replace(before, after))
+ result = run([target])
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError' not in output:
+ print(output)
+ raise SystemExit(f'{label}: not caught by an assertion')
+ print(f'{label}: caught by assertion', flush=True)
+ finally:
+ path.write_text(original)
diff --git a/cli/src/__fixtures__/hook-admission.golden.json b/cli/src/__fixtures__/hook-admission.golden.json
new file mode 100644
index 000000000..66861144f
--- /dev/null
+++ b/cli/src/__fixtures__/hook-admission.golden.json
@@ -0,0 +1,394 @@
+{
+ "linux:authentication": {
+ "status": 401,
+ "body": {
+ "error": "UNAUTHORIZED"
+ }
+ },
+ "linux:claude-start": {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ "linux:claude-prompt": {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ "linux:codex-start": {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ "linux:codex-prompt": {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ "linux:delegated": {
+ "status": 200,
+ "body": {
+ "ignored": true,
+ "reason": "codex_subagent"
+ }
+ },
+ "linux:bound-controls": [
+ {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ }
+ ],
+ "linux:unbound-control": {
+ "status": 403,
+ "body": {
+ "error": "UNBOUND_HOOK"
+ }
+ },
+ "linux:callbacks": {
+ "registered": [
+ {
+ "row": {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "source": "fixture"
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null,
+ "hookEvent": "SessionStart"
+ },
+ {
+ "row": {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "source": "fixture"
+ },
+ "isNew": false,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null,
+ "hookEvent": "UserPromptSubmit"
+ },
+ {
+ "row": {
+ "agent": "codex",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "source": "fixture"
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null,
+ "hookEvent": "SessionStart"
+ },
+ {
+ "row": {
+ "agent": "codex",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "source": "fixture"
+ },
+ "isNew": false,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null,
+ "hookEvent": "UserPromptSubmit"
+ }
+ ],
+ "prompts": [
+ {
+ "agent": "claude",
+ "prompt": "healthy Claude prompt"
+ },
+ {
+ "agent": "codex",
+ "prompt": "healthy Codex prompt"
+ }
+ ],
+ "promptHooks": [
+ {
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "firedAt": 1791590400123
+ },
+ {
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "firedAt": 1791590400123
+ }
+ ],
+ "turns": [
+ {
+ "start": {
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb"
+ }
+ },
+ {
+ "tool": {
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "toolUseId": "tool-1",
+ "toolName": "Read",
+ "input": {
+ "file": "<file>"
+ }
+ }
+ },
+ {
+ "stop": {
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "status": "completed",
+ "transcriptPath": "<root>/CODEX_HOME/sessions/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "firedAt": 1791590400123
+ }
+ }
+ ],
+ "ends": [
+ {
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "reason": "exit"
+ }
+ ]
+ },
+ "linux:bindings": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "source": "fixture"
+ },
+ {
+ "agent": "codex",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "source": "fixture"
+ }
+ ],
+ "darwin:authentication": {
+ "status": 401,
+ "body": {
+ "error": "UNAUTHORIZED"
+ }
+ },
+ "darwin:claude-start": {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ "darwin:claude-prompt": {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ "darwin:codex-start": {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ "darwin:codex-prompt": {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ "darwin:delegated": {
+ "status": 200,
+ "body": {
+ "ignored": true,
+ "reason": "codex_subagent"
+ }
+ },
+ "darwin:bound-controls": [
+ {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ },
+ {
+ "status": 200,
+ "body": {
+ "ok": true
+ }
+ }
+ ],
+ "darwin:unbound-control": {
+ "status": 403,
+ "body": {
+ "error": "UNBOUND_HOOK"
+ }
+ },
+ "darwin:callbacks": {
+ "registered": [
+ {
+ "row": {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "source": "fixture"
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null,
+ "hookEvent": "SessionStart"
+ },
+ {
+ "row": {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "source": "fixture"
+ },
+ "isNew": false,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null,
+ "hookEvent": "UserPromptSubmit"
+ },
+ {
+ "row": {
+ "agent": "codex",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "source": "fixture"
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null,
+ "hookEvent": "SessionStart"
+ },
+ {
+ "row": {
+ "agent": "codex",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "source": "fixture"
+ },
+ "isNew": false,
+ "evicted": null,
+ "rebound": null,
+ "orphaned": null,
+ "hookEvent": "UserPromptSubmit"
+ }
+ ],
+ "prompts": [
+ {
+ "agent": "claude",
+ "prompt": "healthy Claude prompt"
+ },
+ {
+ "agent": "codex",
+ "prompt": "healthy Codex prompt"
+ }
+ ],
+ "promptHooks": [
+ {
+ "sessionId": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "firedAt": 1791590400123
+ },
+ {
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "firedAt": 1791590400123
+ }
+ ],
+ "turns": [
+ {
+ "start": {
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb"
+ }
+ },
+ {
+ "tool": {
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "toolUseId": "tool-1",
+ "toolName": "Read",
+ "input": {
+ "file": "<file>"
+ }
+ }
+ },
+ {
+ "stop": {
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "status": "completed",
+ "transcriptPath": "<root>/CODEX_HOME/sessions/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "firedAt": 1791590400123
+ }
+ }
+ ],
+ "ends": [
+ {
+ "sessionId": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "reason": "exit"
+ }
+ ]
+ },
+ "darwin:bindings": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/fixture/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "source": "fixture"
+ },
+ {
+ "agent": "codex",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/CODEX_HOME/sessions/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "source": "fixture"
+ }
+ ]
+}
diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.ts
index 9b87e2860..594f51d7b 100644
--- a/cli/src/core/agents/bind.spec.ts
+++ b/cli/src/core/agents/bind.spec.ts
@@ -54,6 +54,18 @@ function setup(over: Partial<BindDeps> = {}) {
byAgent: vi.fn((agentId: string) => byAgent.get(agentId) ?? vi.mocked(deps.registry.register).mock.results.at(-1)?.value?.entry),
byProcess: vi.fn(() => undefined),
register: vi.fn(() => null),
+ setIdentityHold: vi.fn((id: string, reason?: string) => {
+ const row = byAgent.get(id) ?? vi.mocked(deps.registry.byProcess).mock.results.at(-1)?.value
+ if (!row || row.identityHold === reason) return false
+ if (reason) row.identityHold = reason
+ else delete row.identityHold
+ return true
+ }),
+ revalidateBinding: vi.fn((id: string) => {
+ const row = byAgent.get(id) ?? vi.mocked(deps.registry.byProcess).mock.results.at(-1)?.value
+ if (row) delete row.identityHold
+ return row ?? null
+ }),
has: vi.fn(() => false),
bySession: vi.fn((sessionId: string) => bySession.get(sessionId)),
} as unknown as BindDeps['registry'],
@@ -319,6 +331,77 @@ describe('binding a running process to its session', () => {
expect(run.deps.attachSession).toHaveBeenCalledOnce()
})
+ it.each([new Error('saved header is incomplete'), 'saved header is incomplete'])(
+ 'keeps a saved binding visibly held until its own evidence recovers: %s', async error => {
+ const run = setup(), row = agent({ transcriptPath: '/t/s1.jsonl', identityHold: 'previous hold' })
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(row)
+ vi.mocked(run.deps.registry.revalidateBinding).mockImplementationOnce(() => { throw error })
+ .mockImplementationOnce(() => { throw error })
+ await run.binding.bindObservedAgent(observed())
+ await run.binding.bindObservedAgent(observed())
+ expect(row).toMatchObject({ sessionId: 's1', transcriptPath: '/t/s1.jsonl', identityHold: 'saved header is incomplete' })
+ expect(run.deps.announceSession).toHaveBeenCalledOnce()
+ expect(continuationOf).not.toHaveBeenCalled()
+ expect(run.deps.registry.unbindSession).not.toHaveBeenCalled()
+ expect(run.deps.stoppedAgents.save).not.toHaveBeenCalled()
+ await run.binding.bindObservedAgent(observed())
+ expect(row).not.toHaveProperty('identityHold')
+ expect(run.deps.announceSession).toHaveBeenCalledTimes(2)
+ expect(continuationOf).toHaveBeenCalledOnce()
+ })
+
+ it('does not follow a saved binding removed while its retry commits', async () => {
+ const run = setup(), row = agent({ transcriptPath: '/t/s1.jsonl', identityHold: 'unavailable' })
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(row)
+ vi.mocked(run.deps.registry.revalidateBinding).mockReturnValue(null)
+ await run.binding.bindObservedAgent(observed())
+ expect(run.deps.announceSession).not.toHaveBeenCalled()
+ expect(continuationOf).not.toHaveBeenCalled()
+ })
+
+ it.each(['repaired', 'same', 'absent'] as const)('updates transcript attachment after a held binding is conclusively %s', async outcome => {
+ const run = setup(), row = agent({ transcriptPath: '/t/child.jsonl', identityHold: 'unavailable' })
+ run.byAgent.set(row.agentId, row)
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(row)
+ vi.mocked(run.deps.registry.revalidateBinding).mockImplementation(() => {
+ Object.assign(row, { sessionId: outcome === 'absent' ? '' : 's1', transcriptPath: outcome === 'absent' ? null : outcome === 'same' ? row.transcriptPath : '/t/parent.jsonl' })
+ delete row.identityHold
+ return row
+ })
+ await run.binding.bindObservedAgent(observed())
+ if (outcome === 'absent') {
+ expect(run.deps.forgetSession).toHaveBeenCalledWith('s1', { force: true, keepAgent: true, agentId: 'a1' })
+ expect(run.deps.stoppedAgents.save).not.toHaveBeenCalled()
+ } else {
+ await vi.waitFor(() => expect(run.deps.attachSession).toHaveBeenCalledWith(row, true, false, false))
+ expect(run.deps.forgetSession).not.toHaveBeenCalled()
+ }
+ expect(run.deps.announceSession).toHaveBeenCalledWith(row)
+ })
+
+ it.each(['changing', 'deleted'] as const)('does not retry a binding whose process is %s', async state => {
+ const run = setup(), row = agent({ transcriptPath: '/t/s1.jsonl', identityHold: 'unavailable' })
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(row)
+ if (state === 'changing') run.binding.whileChanging(() => true)
+ else vi.mocked(isRecentlyDeleted).mockReturnValue(true)
+ await run.binding.bindObservedAgent(observed())
+ expect(run.deps.registry.revalidateBinding).not.toHaveBeenCalled()
+ expect(continuationOf).not.toHaveBeenCalled()
+ })
+
+ it('contains a registration failure, keeps the reason, and retries an unbound process', async () => {
+ const run = setup(), row = agent({ sessionId: '', identityHold: 'waiting for first transcript' })
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(row)
+ vi.mocked(run.deps.registry.register).mockImplementationOnce(() => { throw new Error('binding evidence changed') })
+ await run.binding.bindObservedAgent(observed({ resumeSessionId: 'resumed' }))
+ expect(row).toMatchObject({ sessionId: '', identityHold: 'binding evidence changed' })
+ expect(run.deps.registry.revalidateBinding).not.toHaveBeenCalled()
+ expect(run.deps.stoppedAgents.save).not.toHaveBeenCalled()
+ vi.mocked(run.deps.registry.register).mockReturnValue({ entry: agent(), ...meta({ isNew: true }) } as never)
+ await run.binding.bindObservedAgent(observed({ resumeSessionId: 'resumed' }))
+ expect(run.deps.attachSession).toHaveBeenCalledOnce()
+ })
+
it.each([new Error('identity read limit'), 'identity read limit'])('holds only the unreadable native identity and finishes the discovery/readiness pass: %s', async error => {
const run = setup()
const rows = [agent({ engine: 'muse', agentId: 'held', sessionId: '', runtimes: [], active: true,
@@ -496,7 +579,7 @@ describe('binding a running process to its session', () => {
vi.mocked(processSessionOf).mockResolvedValueOnce('s1')
await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))
vi.mocked(processSessionOf).mockResolvedValueOnce('deleted')
- vi.mocked(isRecentlyDeleted).mockReturnValueOnce(true)
+ vi.mocked(isRecentlyDeleted).mockImplementation(id => id === 'deleted')
await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))
expect(run.deps.registry.register).not.toHaveBeenCalled()
vi.mocked(processSessionOf).mockResolvedValue('s2')
diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.ts
index c695a8326..78c87cdff 100644
--- a/cli/src/core/agents/bind.ts
+++ b/cli/src/core/agents/bind.ts
@@ -50,10 +50,12 @@ export type RegisteredMeta = {
rebound: string | null
orphaned?: { agentId: string; sessionId: string } | null
hookEvent?: string
+ /** A saved binding's evidence recovered; rebuild even an inline parser of the old file. */
+ recovered?: boolean
}
export interface BindDeps {
- registry: Pick<typeof registry, 'inheritName' | 'unbindSession' | 'byAgent' | 'byProcess' | 'register' | 'has' | 'bySession'>
+ registry: Pick<typeof registry, 'inheritName' | 'unbindSession' | 'byAgent' | 'byProcess' | 'register' | 'has' | 'bySession' | 'setIdentityHold' | 'revalidateBinding'>
mirror: Pick<TurnRecaps, 'inheritSummary'>
forgetSession: (id: string, opts?: { force?: boolean; keepAgent?: boolean; agentId?: string }) => void
/** The app. */
@@ -86,7 +88,7 @@ export function createBinding({
const handleRegistered = async (entry: RegisteredSession, meta: RegisteredMeta): Promise<void> => {
const authority = paneReadIdentity(entry)
const current = () => paneReadIdentity(registry.byAgent(entry.agentId)) === authority
- if (!current()) return
+ if (!current() || entry.identityHold) return
const forkSource = pendingForkInherit.get(entry.agentId)
if (forkSource && entry.sessionId) {
pendingForkInherit.delete(entry.agentId)
@@ -151,7 +153,7 @@ export function createBinding({
// `userPromptSubmitted` and `sessionStart` hooks both register (measured 2.5s apart, and in that
// order — sessionStart fires AFTER the first prompt), so treating the second as a reset re-folded
// the transcript and emitted a second `turn_started` for one exchange.
- const reset = meta.isNew
+ const reset = meta.isNew || !!meta.recovered
|| (entry.engine !== 'cursor' && entry.engine !== 'agy' && entry.engine !== 'copilot'
&& meta.hookEvent === 'SessionStart')
// Deliberately NOT gated on `meta.isNew`. `isNew` is false in exactly the case this is meant to catch:
@@ -180,16 +182,16 @@ export function createBinding({
// announced as running with nothing left to end it (found end to end: stop in the middle of a first
// turn, resume, and the agent read as working for good). A new session started in the agent after
// the resume is not this conversation, and is judged like any other.
- const bornAfterAgent = !resumedConversation && transcriptIsFirstTurn(
+ const bornAfterAgent = !meta.recovered && !resumedConversation && transcriptIsFirstTurn(
entry,
entry.transcriptPath ? await statBirthMs(entry.transcriptPath) : 0,
{ rebound: !!meta.rebound, now: Date.now() },
)
- if (!current()) return
+ if (!current() || entry.identityHold) return
const attached = await attachSession(entry, reset, entry.engine === 'cursor', bornAfterAgent)
// The registry mutates rows in place. This completion cannot unbind or re-announce a later
// conversation, nor an agent that Stop has already retired.
- if (!current()) return
+ if (!current() || entry.identityHold) return
if (!attached) {
// A terminal reads as gone while a stop or a restart ends its engine. A registration that comes in
// then, such as the old engine's own SessionStart arriving late on a loaded machine, is still the
@@ -218,17 +220,43 @@ export function createBinding({
const ownTranscript = (engine: 'cursor' | 'grok' | 'agy' | 'copilot', sessionId: string, cwd: string): Promise<string | null> =>
transcriptOf(engine, engine === 'cursor' ? cursorDataDir() : homes[engine], sessionId, cwd)
const bindObservedAgent = async (observed: DiscoveredTerminalAgent): Promise<void> => {
- const agent = registry.byProcess(observed.engine, observed.processIdentity)
- if (!agent) return
+ const found = registry.byProcess(observed.engine, observed.processIdentity)
+ if (!found || changing(found.agentId) || isRecentlyDeleted(found.agentId)) return
+ let agent: RegisteredSession = found
+ if (agent.identityHold && agent.sessionId && agent.transcriptPath) {
+ try {
+ const previous = agent.sessionId
+ const retried = registry.revalidateBinding(agent.agentId)
+ if (!retried) return
+ agent = retried
+ if (!agent.sessionId) forgetSession(previous, { force: true, keepAgent: true, agentId: agent.agentId })
+ else followRegistered(agent, { isNew: false, evicted: null, rebound: null, recovered: true })
+ announceSession(agent)
+ } catch (error) {
+ const reason = error instanceof Error ? error.message : String(error)
+ if (registry.setIdentityHold(agent.agentId, reason)) announceSession(agent)
+ return
+ }
+ }
const authority = paneReadIdentity(agent)
const current = () => !changing(agent.agentId) && !isRecentlyDeleted(agent.agentId)
&& paneReadIdentity(registry.byProcess(observed.engine, observed.processIdentity)) === authority
+ const hold = (error: unknown) => {
+ if (!current()) return
+ const reason = error instanceof Error ? error.message : String(error)
+ if (registry.setIdentityHold(agent.agentId, reason)) announceSession(agent)
+ console.log(`[discovery] ${sid(agent.agentId)} binding held · ${reason}`)
+ }
+ const commit = (input: Parameters<typeof registry.register>[0]) => {
+ try { return registry.register(input) }
+ catch (error) { hold(error); return null }
+ }
// Only native reads are contained here. A rejected lookup cannot end the serial
// discovery/readiness pass or bind an unwritten session as if evidence were absent.
const read = async <T>(work: () => Promise<T>): Promise<{ value: T } | null> => {
try { return { value: await work() } }
catch (error) {
- if (current()) console.log(`[discovery] ${sid(agent.agentId)} binding held · ${error instanceof Error ? error.message : error}`)
+ hold(error)
return null
}
}
@@ -265,7 +293,7 @@ export function createBinding({
const transcript = located.value
if (!current() || !mayClaim(next)) return
console.log(`[discovery] ${sid(agent.agentId)} switched copilot session ${sid(agent.sessionId)} → ${sid(next)} (/resume)`)
- const rotated = registry.register({
+ const rotated = commit({
engine: 'copilot',
sessionId: next,
transcriptPath: transcript ?? undefined,
@@ -295,7 +323,7 @@ export function createBinding({
|| registry.has(continuation.sessionId) || isRecentlyDeleted(continuation.sessionId)) return
if (!current()) return
console.log(`[discovery] ${sid(agent.agentId)} ${observed.engine} session continued ${sid(agent.sessionId)} → ${sid(continuation.sessionId)}`)
- const rotated = registry.register({
+ const rotated = commit({
engine: observed.engine,
sessionId: continuation.sessionId,
transcriptPath: continuation.transcriptPath,
@@ -359,7 +387,7 @@ export function createBinding({
if (!current() || !mayClaim(sessionId)) return
const previousOwner = registry.bySession(sessionId)
- const result = registry.register({
+ const result = commit({
engine: observed.engine,
sessionId,
transcriptPath,
diff --git a/cli/src/core/agents/discovery.spec.ts b/cli/src/core/agents/discovery.spec.ts
index f3eb11ee0..110faab0d 100644
--- a/cli/src/core/agents/discovery.spec.ts
+++ b/cli/src/core/agents/discovery.spec.ts
@@ -182,6 +182,21 @@ describe('discovery', () => {
expect(run.deps.registry.setLaunch).toHaveBeenCalledTimes(1)
})
+ it.each(['held', 'removed', 'rebound'] as const)('cannot retire or announce an attachment whose binding became %s', async state => {
+ const run = setup(), awake = row()
+ run.rows.set('a1', awake)
+ vi.mocked(run.deps.attachSession).mockImplementationOnce(async () => {
+ if (state === 'held') awake.identityHold = 'waiting for native evidence'
+ if (state === 'removed') run.rows.clear()
+ if (state === 'rebound') awake.sessionId = 'replacement'
+ return false
+ })
+ await run.handlers.onObserved(seen(), row({ active: false }))
+ await settle()
+ expect(run.deps.registry.setActive).not.toHaveBeenCalled()
+ expect(run.deps.announceSession).not.toHaveBeenCalled()
+ })
+
it('announces an awake agent whose grid moved, and nothing when it did not or could not be read', async () => {
const run = setup()
run.rows.set('a1', row())
diff --git a/cli/src/core/agents/discovery.ts b/cli/src/core/agents/discovery.ts
index d495279b5..736265e07 100644
--- a/cli/src/core/agents/discovery.ts
+++ b/cli/src/core/agents/discovery.ts
@@ -8,6 +8,7 @@
* docs/design/2026-10-03-harnessd.md). The reconciler itself, with what it scans, stays there.
*/
import { externalResumePending } from '../../lib/externalResume.js'
+import { paneReadIdentity } from '../transcripts/readIdentity.js'
import { isTerminalEngine } from '../../engines/types.js'
import type { AutonomousDeviceInput } from '../deviceInput.js'
import type { QuestionWatcher } from '../../lib/questionController.js'
@@ -146,7 +147,7 @@ export function createDiscoveryHandlers({
if (wasDormant || wasLaunching || adopted) {
const active = registry.byAgent(current.agentId)
if (!active) return
- if (!active.sessionId) {
+ if (!active.sessionId || active.identityHold) {
syncRecapPool()
announceSession(active)
return
@@ -154,7 +155,10 @@ export function createDiscoveryHandlers({
// Not awaited: the attach reads this agent's whole history, and this callback runs inside the
// reconcile pass whose completion is what publishes `discoveryReady`. One agent's slow store
// must not hold the pass — or, at boot, the app. The tracker runs a few of these at a time.
+ const authority = paneReadIdentity(active)
void attachSession(active).then((attached) => {
+ const latest = registry.byAgent(active.agentId)
+ if (paneReadIdentity(latest) !== authority || latest?.identityHold) return
if (!attached) {
registry.setActive(active.agentId, false)
return
diff --git a/cli/src/core/agents/forget.spec.ts b/cli/src/core/agents/forget.spec.ts
index 7d95434f2..389c0f0a6 100644
--- a/cli/src/core/agents/forget.spec.ts
+++ b/cli/src/core/agents/forget.spec.ts
@@ -118,13 +118,27 @@ describe('forgetting a session', () => {
expect(named.deps.stoppedAgents.save).not.toHaveBeenCalled()
expect(named.deps.detachDsh).toHaveBeenCalledWith('a9')
expect(named.deps.clients.send).toHaveBeenCalledWith({ type: 'agent_deleted', payload: { agentId: 'a9', retained: false } })
- expect(named.deps.input.forget).toHaveBeenCalledWith('s9')
+ expect(named.deps.input.forget).toHaveBeenCalledWith('a9')
// With no agent id at all, the session id is all there is to announce.
const bare = setup()
bare.forgetSession('s9')
expect(bare.deps.clients.sendCommander).toHaveBeenCalledWith({ type: 'agent_deleted', payload: { agentId: 's9' } })
})
+ it('clears agent-keyed input after binding revalidation has already released the session index', () => {
+ const { deps } = setup()
+ vi.mocked(deps.registry.resolve).mockReturnValue(undefined)
+ const pending = ['teams', 'input', 'deviceInput'].map(() => new Map([['a1', 'queued'], ['other', 'keep']]))
+ for (const [index, key] of (['teams', 'input', 'deviceInput'] as const).entries()) {
+ deps[key].forget = id => { pending[index]!.delete(id) }
+ }
+ createForgetSession(deps)('s1', { force: true, keepAgent: true, agentId: 'a1' })
+ for (const queue of pending) expect([...queue]).toEqual([['other', 'keep']])
+ expect(deps.stoppedAgents.save).not.toHaveBeenCalled()
+ expect(deps.registry.removeAgent).not.toHaveBeenCalled()
+ expect(deps.normalizers.forget).toHaveBeenCalledWith('s1')
+ })
+
it('forgets an agent that has no session yet under the id it was asked by', () => {
vi.spyOn(console, 'log').mockImplementation(() => {})
const { deps, forgetSession } = setup()
diff --git a/cli/src/core/agents/forget.ts b/cli/src/core/agents/forget.ts
index 2ff165f6c..9d3feb359 100644
--- a/cli/src/core/agents/forget.ts
+++ b/cli/src/core/agents/forget.ts
@@ -94,9 +94,9 @@ export function createForgetSession({
runtimeProfiles.forget(sessionId)
void watcher.removeSession(sessionId)
stopHeartbeat(sessionId)
- teams.forget(doomed?.agentId ?? sessionId)
- input.forget(doomed?.agentId ?? sessionId)
- deviceInput.forget(doomed?.agentId ?? sessionId)
+ teams.forget(announceId)
+ input.forget(announceId)
+ deviceInput.forget(announceId)
if (!opts.keepAgent) { detachDsh(announceId); onRemoved?.(announceId) }
mirror.forget(sessionId) // aborts any in-flight recap + clears busy; KEEPS the persisted summary
if (opts.keepAgent) return
diff --git a/cli/src/core/engines/liveSessions.spec.ts b/cli/src/core/engines/liveSessions.spec.ts
index 838799f9c..d002effd2 100644
--- a/cli/src/core/engines/liveSessions.spec.ts
+++ b/cli/src/core/engines/liveSessions.spec.ts
@@ -278,3 +278,32 @@ describe('core engine stream authority', () => {
expect(t.frames.at(-1)).toMatchObject({ replay: false, events: [{ type: 'turn_started', payload: { userMessage: 'fresh' } }] })
})
})
+
+it('does not accept a worker page from before a same-path evidence hold/recovery', async () => {
+ const t = await setup(''), prepared = await t.attach()
+ const cursor = prepared.state.ask.cursor
+ const entered = deferred<void>(), release = deferred<void>()
+ t.intercept(async (method, reply) => { if (method === LIVE_READ) { entered.resolve(); await release.promise }; return reply })
+ await appendFile(t.file, prompt('unconfirmed'))
+ const pending = t.live.pollSession(t.session.sessionId)
+ await entered.promise
+ t.session.identityHold = 'incomplete'; t.session.evidenceRevision = 1
+ delete t.session.identityHold; t.session.evidenceRevision = 2
+ release.resolve(); await pending
+ expect(t.events()).toEqual([])
+ expect(prepared.state.ask.cursor).toBe(cursor)
+})
+
+it('leaves newly followed worker bytes unread until interpretation recovery commits', async () => {
+ const t = await setup('')
+ t.session.evidenceRevision = 2; t.session.interpretationHold = 'replacement pending'
+ const prepared = await t.prepare()
+ expect(t.live.install(prepared)).toBe(true)
+ await appendFile(t.file, prompt('arrived during installation'))
+ await t.live.follow(t.session)
+ expect(t.events()).toEqual([])
+ expect(prepared.state.ask.cursor?.offset).toBe(0)
+ delete t.session.interpretationHold
+ await t.live.pollSession(t.session.sessionId)
+ expect(t.events().filter(event => event.type === 'turn_started')).toHaveLength(1)
+})
diff --git a/cli/src/core/engines/liveSessions.ts b/cli/src/core/engines/liveSessions.ts
index 74e74e417..595582d3b 100644
--- a/cli/src/core/engines/liveSessions.ts
+++ b/cli/src/core/engines/liveSessions.ts
@@ -5,6 +5,7 @@ import type { RegisteredSession } from '../../lib/registry.js'
import { HOLD_TIMEOUT_MS, type TailHold } from '../../watcher/watcher.js'
import { transcriptReadIdentity } from '../transcripts/readIdentity.js'
import { EngineLiveError, type LiveTransport } from './liveTransport.js'
+import type { TranscriptClose } from '../../lib/transcriptControls.js'
interface SessionState {
ask: LivePull
@@ -41,6 +42,7 @@ export interface LiveSessionDeps {
/** Reduce side evidence before acknowledging the page; the returned commit must be synchronous. */
prepareFrames?(session: RegisteredSession, frames: readonly LiveFrame[]): Promise<() => boolean>
reattach(session: RegisteredSession): Promise<unknown>
+ hold?(session: RegisteredSession, reason: string): void
watch(path: string): void
unwatch(path: string): void
log?(message: string): void
@@ -85,12 +87,12 @@ export function createLiveSessions(deps: LiveSessionDeps) {
const forget = (engine: string, token: string): void => {
void slot(engine, () => deps.transport.forget(engine, token)).catch(() => {})
}
- const makeState = (session: RegisteredSession, live: boolean, end?: number): SessionState => {
+ const makeState = (session: RegisteredSession, live: boolean, end?: number, closes?: readonly TranscriptClose[]): SessionState => {
const state: SessionState = { identity: transcriptReadIdentity(session), epoch: 0,
ask: { token: randomUUID(), session: { agentId: session.agentId, sessionId: session.sessionId,
engine: session.engine, transcriptPath: session.transcriptPath, cwd: session.cwd, model: session.model,
cliVersion: session.cliVersion, codexHome: session.codexHome }, cursor: null, fromStart: live,
- replay: false, liveStart: live, ...(end === undefined ? {} : { end }),
+ replay: false, liveStart: live, ...(end === undefined ? {} : { end }), ...(closes?.length ? { closes } : {}),
// The stream still installed is the one whose read found the rewrite: its worker knows where.
...(tails.get(session.sessionId)?.rewritten ? { rewritten: true, rewrittenFrom: states.get(session.sessionId)?.ask.token } : {}) },
handle: {
@@ -131,7 +133,7 @@ export function createLiveSessions(deps: LiveSessionDeps) {
}
async function pollSession(id: string): Promise<void> {
const tail = tails.get(id)
- if (!tail || stopped) return
+ if (!tail || stopped || deps.bySession(id)?.interpretationHold) return
if (tail.unheld) await tail.unheld
if (tail.running) return tail.running
if (tail.offset !== null || tails.get(id) !== tail) return
@@ -145,6 +147,10 @@ export function createLiveSessions(deps: LiveSessionDeps) {
let page: LivePage
try { page = await pull({ ...state.ask }) }
catch (error) {
+ if (error instanceof EngineLiveError && error.code === 'ENGINE_CONTROL_BOUNDARY_CHANGED'
+ && valid(state) && states.get(id) === state && state.epoch === epoch) {
+ deps.hold?.(deps.bySession(id)!, 'The transcript no longer matches its cancellation boundary; interpretation is held.')
+ }
if (error instanceof EngineLiveError && error.code === 'ENGINE_TRANSCRIPT_CHANGED') {
// No cursor from the changed file is accepted. Re-attach under a hold and a new identity.
// Said once per rewrite, as the legacy tailer says it (core/transcripts/ingest.ts).
@@ -193,12 +199,12 @@ export function createLiveSessions(deps: LiveSessionDeps) {
return {
handles: deps.handles,
current(session: RegisteredSession): boolean { return states.get(session.sessionId)?.identity === transcriptReadIdentity(session) },
- async prepare(session: RegisteredSession, options: { live: boolean; end?: number }, observe: (frame: LiveFrame) => void,
+ async prepare(session: RegisteredSession, options: { live: boolean; end?: number; closes?: readonly TranscriptClose[] }, observe: (frame: LiveFrame) => void,
observePage?: (frames: readonly LiveFrame[]) => Promise<void>): Promise<PreparedLive> {
// A retry has no original attach flags. Keep first-turn delivery intent until activation;
// otherwise a failed first prepare turns the user's completed first response into silent history.
if (options.live) firstLive.set(session.sessionId, transcriptReadIdentity(session))
- const state = makeState(session, firstLive.get(session.sessionId) === transcriptReadIdentity(session), options.end)
+ const state = makeState(session, firstLive.get(session.sessionId) === transcriptReadIdentity(session), options.end, options.closes)
const parent = states.get(session.sessionId), parentEpoch = parent?.epoch
const moves = tails.get(session.sessionId)?.moves ?? 0
let records = 0, content = false
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 81e18f8dc..993572d2d 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1011,6 +1011,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
prepareFrames: (session, frames) => runtimeProfiles.prepareFrames(session, frames),
frame: (session, frame) => ingest.acceptFrame(session.sessionId, session.engine, frame, runtimeProfiles.handles(session.engine)),
reattach: (session) => attachSession(session, true),
+ hold: (session, reason) => attach.holdInterpretation(session, reason),
})
// Whether a turn is really working, beyond its transcript (core/turns/activity.ts).
const activity = createTurnActivity({
@@ -1067,6 +1068,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Following a session: its history read into its engine's normalizer, then its tail
// (core/transcripts/attach.ts).
const attach = createAttach({
+ setInterpretationHold: registry.setInterpretationHold.bind(registry),
+ announceSession,
liveFor,
resolve: id => registry.resolve(id),
remoteLive: engineLive,
@@ -1679,6 +1682,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
const turnHooks = createTurnHooks({
+ holdStop: attach.holdStop,
+ afterStop: attach.afterStop,
resolve: (id) => registry.resolve(id),
normalizers,
emit: (sessionId, events) => emitSessionEvents(sessionId, events),
@@ -2207,6 +2212,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Cancelling a turn (core/turns/cancel.ts).
const cancelAgent = createCancel({
+ beforeCancel: attach.beforeCancel,
resolve: (id) => registry.resolve(id),
normalizers,
cursorSubagents,
diff --git a/cli/src/core/transcripts/attach.control.spec.ts b/cli/src/core/transcripts/attach.control.spec.ts
new file mode 100644
index 000000000..25663ae68
--- /dev/null
+++ b/cli/src/core/transcripts/attach.control.spec.ts
@@ -0,0 +1,311 @@
+import { appendFileSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import * as nativeReads from 'node:fs/promises'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import { liveFor } from '../../engines/live.js'
+import { CopilotNormalizer } from '../../engines/copilot/normalizer.js'
+import { engineLiveRequests } from '../../engines/worker/liveRequests.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { Watcher } from '../../watcher/watcher.js'
+import { createLiveTransport } from '../engines/liveTransport.js'
+import { createLiveWatcher } from '../engines/liveWatcher.js'
+import { createCancel } from '../turns/cancel.js'
+import { createTurnHooks } from '../turns/turnHooks.js'
+import { createAttach } from './attach.js'
+import { createIngest } from './ingest.js'
+import { createSessionNormalizers } from './normalizers.js'
+
+vi.mock('node:fs/promises', async original => {
+ const actual = await original<typeof import('node:fs/promises')>()
+ return { ...actual, open: vi.fn(actual.open) }
+})
+
+const prompt = (text: string) => JSON.stringify({ type: 'user', uuid: text, message: { role: 'user', content: text } }) + '\n'
+const continuation = JSON.stringify({ type: 'attachment', attachment: { type: 'goal_status', met: false, condition: 'finish' } }) + '\n'
+const done = JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: [], stop_reason: 'end_turn' } }) + '\n'
+const cleanups: Array<() => Promise<void>> = []
+afterEach(async () => {
+ for (const clean of cleanups.splice(0)) await clean()
+ vi.restoreAllMocks()
+ vi.mocked(nativeReads.open).mockReset()
+})
+function setup(mode: 'inline' | 'worker', content = prompt('T1')) {
+ const root = mkdtempSync(join(tmpdir(), 'attach-control-')), file = join(root, 'session.jsonl')
+ writeFileSync(file, content)
+ const row = { agentId: 'agent', sessionId: 'session', engine: 'claude', transcriptPath: file,
+ cwd: root, model: null, cliVersion: null, evidenceRevision: 0 } as RegisteredSession
+ const normalizers = createSessionNormalizers(), emit = vi.fn(), settled = vi.fn()
+ let worker = engineLiveRequests('claude')
+ const transport = createLiveTransport({ call: async (_service, type, payload) =>
+ await worker[type](payload, { owner: true, local: true }) as Record<string, unknown> })
+ transport.connected('engine-claude')
+ const local = new Watcher()
+ const { watcher, live } = createLiveWatcher(local, { handles: () => mode === 'worker', transport,
+ bySession: () => row, frame: (session, frame) => ingest.acceptFrame(session.sessionId, session.engine, frame),
+ reattach: session => attach.attachSession(session, true), hold: (session, reason) => attach.holdInterpretation(session, reason) })
+ const profile = { ingest: vi.fn(), commit: vi.fn(), config: vi.fn(async () => {}) }
+ const attach = createAttach({ liveFor, normalizers, remoteLive: live, watcher, resolve: () => row,
+ setInterpretationHold: (_id, revision, reason, create) => {
+ if (row.identityHold || row.evidenceRevision !== revision || (!row.interpretationHold && !(create && reason))) return false
+ if (!row.interpretationHold) row.evidenceRevision = (row.evidenceRevision ?? 0) + 1
+ if (reason) row.interpretationHold = reason; else delete row.interpretationHold
+ return true
+ }, announceSession: vi.fn(), terminalGone: async () => false,
+ runtimeProfiles: { transcriptFields: () => [], beginHydrate: () => profile, hydrate: vi.fn(),
+ ingestConfig: async () => false, ingestPane: () => false, capturePane: async () => null },
+ cursorDiscovery: { add: async () => {} }, device: () => undefined, captureTerminal: async () => null,
+ emit, settled, announceTurnAborted: vi.fn(), questionWatcher: { start: vi.fn() }, terminalLabel: () => 'private fixture',
+ dbs: { opencode: join(root, 'o.db'), kilo: join(root, 'k.db'), devin: join(root, 'd.db') },
+ devinHome: root, hermesDb: async () => join(root, 'h.db'), concurrency: 1 })
+ const ingest = createIngest({ liveFor, has: () => true, bySession: () => row, normalizers,
+ tokenUsage: { changed: vi.fn() }, device: () => undefined, runtimeProfiles: { ingest: () => false },
+ announceTurnAborted: vi.fn(), emit, attachSession: attach.attachSession })
+ ingest.wireWatcher(watcher)
+ const cancel = createCancel({ resolve: () => row, beforeCancel: attach.beforeCancel, normalizers,
+ cursorSubagents: { forget: vi.fn() }, input: { cancel: vi.fn(), cancelConfirmed: vi.fn(async () => true) },
+ device: () => undefined, stopHeartbeat: vi.fn(), questionWatcher: { stop: vi.fn() }, mirror: { cancel: vi.fn() },
+ turnActivity: { observe: vi.fn(), snapshot: vi.fn() }, turnStartedAt: new Map(), agentIdFor: () => row.agentId, clients: { send: vi.fn() } })
+ const hooks = createTurnHooks({ resolve: () => row, normalizers, holdStop: attach.holdStop, afterStop: attach.afterStop,
+ emit, drain: async () => watcher.pollSession(row.sessionId), onCursorTaskStart: vi.fn(),
+ cursorTaskHooks: { wait: async () => {} }, cursorSubagents: { closeParent: vi.fn() }, announceTurnAborted: vi.fn(),
+ armAgyIdleWatch: vi.fn(), clearAgyIdleWatch: vi.fn(), mirror: { noteEngineStopped: vi.fn() }, dataDir: root })
+ const hold = () => { row.identityHold = 'native evidence unavailable'; row.evidenceRevision = (row.evidenceRevision ?? 0) + 1 }
+ const recover = () => { delete row.identityHold; row.evidenceRevision = (row.evidenceRevision ?? 0) + 1; row.interpretationHold = 'recovering' }
+ cleanups.push(async () => { attach.forget(row.sessionId); await watcher.stop(); rmSync(root, { recursive: true, force: true }) })
+ return { row, file, normalizers, emit, settled, attach, cancel, hooks, profile, watcher, hold, recover,
+ restartWorker: () => { worker = engineLiveRequests('claude') } }
+}
+
+it.each(['inline', 'worker'] as const)('%s preserves Cancel → failed recovery → later prompt ordering', async mode => {
+ const t = setup(mode)
+ await t.attach.attachSession(t.row)
+ t.hold(); await t.cancel(t.row.agentId); t.recover()
+ t.profile.config.mockRejectedValueOnce(new Error('configuration unavailable'))
+ await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeTruthy()
+ appendFileSync(t.file, prompt('T2'))
+ await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(true)
+ t.restartWorker(); await t.watcher.pollSession(t.row.sessionId)
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(true)
+})
+it.each(['inline', 'worker'] as const)('%s applies repeated cancellation before each goal continuation, including worker reconstruction', async mode => {
+ const t = setup(mode)
+ await t.attach.attachSession(t.row)
+ t.hold(); await t.cancel(t.row.agentId)
+ appendFileSync(t.file, continuation)
+ await t.cancel(t.row.agentId)
+ appendFileSync(t.file, continuation)
+ t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.liveParsers.get(t.row.sessionId)?.snapshot()).toMatchObject({ turnOpen: true, continued: true })
+ t.restartWorker(); await t.watcher.pollSession(t.row.sessionId)
+ appendFileSync(t.file, done); await t.watcher.pollSession(t.row.sessionId)
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+})
+it.each(['inline', 'worker'] as const)('%s keeps delayed and cold Stop intent held even with empty or older closed history', async mode => {
+ const t = setup(mode, '')
+ t.hold(); t.hooks.onTurnStop({ sessionId: t.row.sessionId, firedAt: 100 })
+ t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toContain('Stop could not be matched')
+ appendFileSync(t.file, prompt('T1') + done + prompt('T2'))
+ t.hooks.onPromptHook(t.row.sessionId, 200) // Its delayed arrival cannot authorize the old Stop.
+ await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toContain('Stop could not be matched')
+ expect(t.emit).not.toHaveBeenCalled()
+ await t.cancel(t.row.agentId) // Explicit current control safely supersedes the unknown completion.
+ await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+})
+it.each(['inline', 'worker'] as const)('%s holds a replaced file rather than moving its cancellation cutoff', async mode => {
+ const t = setup(mode)
+ t.hold(); await t.cancel(t.row.agentId)
+ renameSync(t.file, t.file + '.old'); writeFileSync(t.file, prompt('T2'))
+ t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toContain('control boundary')
+ expect(t.emit).not.toHaveBeenCalled()
+})
+
+it.each(['inline', 'worker'] as const)('%s retains cancellation across repeated recovery and never settles cancelled history', async mode => {
+ const t = setup(mode)
+ await t.attach.attachSession(t.row)
+ t.hold(); await t.cancel(t.row.agentId); t.recover()
+ await t.attach.attachSession(t.row)
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+ t.hold(); t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+ expect(t.settled).not.toHaveBeenCalled()
+ await t.attach.attachSession(t.row, true) // Ordinary compact/reset must also keep the cancellation.
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+ expect(t.settled).not.toHaveBeenCalled()
+ appendFileSync(t.file, prompt('T2') + done)
+ t.hold(); t.recover(); await t.attach.attachSession(t.row)
+ expect(t.settled).toHaveBeenCalledOnce()
+})
+it.each(['inline', 'worker'] as const)('%s preserves Stop and Cancel obligations across a repaired path', async mode => {
+ const t = setup(mode)
+ t.hold(); t.hooks.onTurnStop({ sessionId: t.row.sessionId })
+ const repaired = t.file + '.repaired'; writeFileSync(repaired, prompt('T2'))
+ t.row.transcriptPath = repaired
+ t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toContain('Stop could not be matched')
+ await t.cancel(t.row.agentId)
+ const again = t.file + '.again'; writeFileSync(again, prompt('T3'))
+ t.row.transcriptPath = again
+ await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toContain('control boundary')
+ expect(t.emit).not.toHaveBeenCalled()
+})
+it.each(['inline', 'worker'] as const)('%s retains a Stop whose drain outlasts a complete hold and recovery cycle', async mode => {
+ const t = setup(mode)
+ await t.attach.attachSession(t.row)
+ let finish!: () => void
+ vi.spyOn(t.watcher, 'pollSession').mockImplementationOnce(() => new Promise<void>(resolve => { finish = resolve }))
+ t.hooks.onTurnStop({ sessionId: t.row.sessionId })
+ t.hold(); t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ finish()
+ await vi.waitFor(() => expect(t.row.interpretationHold).toContain('Stop could not be matched'))
+})
+it('holds rewritten worker evidence visibly and accepts a later explicit cancellation of the new incarnation', async () => {
+ const t = setup('worker')
+ t.hold(); await t.cancel(t.row.agentId); t.recover(); await t.attach.attachSession(t.row)
+ // Recovery starts a detached tail read. Finish it before replacing the file so the assertion
+ // below observes the restarted worker's request, not that earlier read during the rename.
+ await t.watcher.pollSession(t.row.sessionId)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+ renameSync(t.file, t.file + '.old'); writeFileSync(t.file, prompt('T2'))
+ t.restartWorker()
+ await expect(t.watcher.pollSession(t.row.sessionId)).rejects.toThrow('ENGINE_CONTROL_BOUNDARY_CHANGED')
+ await vi.waitFor(() => expect(t.row.interpretationHold).toBeTruthy())
+ await t.cancel(t.row.agentId)
+ appendFileSync(t.file, prompt('T3'))
+ await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(true)
+})
+it.each(['inline', 'worker'] as const)('%s refuses a different replay descriptor even when the path verifies before and after', async mode => {
+ const t = setup(mode)
+ t.hold(); await t.cancel(t.row.agentId); t.recover()
+ const other = t.file + '.other'; writeFileSync(other, prompt('T2'))
+ const { open } = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
+ const verifyFile = vi.spyOn(await import('../../lib/transcriptBoundary.js'), 'verifyTranscriptHandle')
+ vi.spyOn(nativeReads, 'open').mockImplementation((path, flags, access) => open(path === t.file ? other : path, flags, access))
+ await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeTruthy()
+ expect(t.emit).not.toHaveBeenCalled()
+ expect(t.settled).not.toHaveBeenCalled()
+ expect(verifyFile).toHaveBeenCalled()
+ await expect(verifyFile.mock.results[0]?.value).rejects.toThrow('ENGINE_CONTROL_BOUNDARY_CHANGED')
+})
+
+it.each(['inline', 'worker'] as const)('%s retains a later ordinary Cancel without replacing its live parser', async mode => {
+ const t = setup(mode)
+ t.hold(); await t.cancel(t.row.agentId); t.recover(); await t.attach.attachSession(t.row)
+ appendFileSync(t.file, prompt('T2')); await t.watcher.pollSession(t.row.sessionId)
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(true)
+ const live = t.normalizers.liveParsers.get(t.row.sessionId)
+ await t.cancel(t.row.agentId)
+ expect(t.normalizers.liveParsers.get(t.row.sessionId)).toBe(live)
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+ t.hold(); t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+ expect(t.settled).not.toHaveBeenCalled()
+})
+it.each(['inline', 'worker'] as const)('%s preserves positive stale Stop evidence while held', async mode => {
+ const t = setup(mode)
+ t.hold()
+ t.hooks.onPromptHook(t.row.sessionId, 200)
+ t.hooks.onTurnStop({ sessionId: t.row.sessionId, firedAt: 100 })
+ t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(true)
+})
+
+it.each(['inline', 'worker'] as const)('%s holds a later ordinary cancellation whose file boundary is incomplete', async mode => {
+ const t = setup(mode)
+ t.hold(); await t.cancel(t.row.agentId); t.recover(); await t.attach.attachSession(t.row)
+ appendFileSync(t.file, '{')
+ await t.cancel(t.row.agentId)
+ expect(t.row.interpretationHold).toBeTruthy()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+ writeFileSync(t.file, prompt('T2'))
+ await t.cancel(t.row.agentId)
+ await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+})
+
+it.each(['inline', 'worker'] as const)('%s preserves an ordinary Cancel through the first later binding recovery', async mode => {
+ const t = setup(mode)
+ await t.attach.attachSession(t.row)
+ const live = t.normalizers.liveParsers.get(t.row.sessionId)
+ await t.cancel(t.row.agentId)
+ expect(t.normalizers.liveParsers.get(t.row.sessionId)).toBe(live)
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+ t.hold(); t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false)
+ expect(t.settled).not.toHaveBeenCalled()
+})
+
+it.each([
+ ['inline', false], ['worker', false], ['inline', true], ['worker', true],
+] as const)('%s retains an ordinary successful Stop through first recovery (later turn=%s)', async (mode, later) => {
+ const t = setup(mode)
+ await t.attach.attachSession(t.row)
+ const live = t.normalizers.liveParsers.get(t.row.sessionId)
+ t.hooks.onTurnStop({ sessionId: t.row.sessionId })
+ await vi.waitFor(() => expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(false), { timeout: 3_000 })
+ expect(t.normalizers.liveParsers.get(t.row.sessionId)).toBe(live)
+ expect(t.row.interpretationHold).toBeUndefined()
+ if (later) {
+ appendFileSync(t.file, prompt('T2'))
+ await t.watcher.pollSession(t.row.sessionId)
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(true)
+ }
+ const sent = t.emit.mock.calls.length
+ t.hold(); t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toContain('Stop could not be matched')
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(later)
+ expect(t.emit).toHaveBeenCalledTimes(sent)
+ await t.cancel(t.row.agentId)
+ appendFileSync(t.file, prompt('T3'))
+ await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toBeUndefined()
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(true)
+})
+
+
+it.each([false, true])('preserves the known legacy open turn through a held Stop and recovery (retained=%s)', async retained => {
+ const record = (text: string) => JSON.stringify({ type: 'user.message', data: { content: text }, id: text, parentId: '' })
+ const t = setup('inline', record('T1') + '\n')
+ t.row.engine = 'copilot'
+ const normalizer = new CopilotNormalizer()
+ normalizer.ingest(record('T1'))
+ t.normalizers.copilotNormalizers.set(t.row.sessionId, normalizer)
+ if (retained) {
+ t.hooks.onTurnStop({ sessionId: t.row.sessionId })
+ await vi.waitFor(() => expect(normalizer.turnOpen).toBe(false), { timeout: 3_000 })
+ appendFileSync(t.file, record('T2') + '\n')
+ normalizer.ingest(record('T2'))
+ }
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(true)
+ const sent = t.emit.mock.calls.length
+ t.hold(); t.hooks.onTurnStop({ sessionId: t.row.sessionId })
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(true)
+ expect(normalizer.turnOpen).toBe(true)
+ t.recover(); await t.attach.attachSession(t.row)
+ expect(t.row.interpretationHold).toContain('Stop could not be matched')
+ expect(t.normalizers.sessionTurnOpen(t.row.sessionId)).toBe(true)
+ expect(normalizer.turnOpen).toBe(true)
+ expect(t.emit).toHaveBeenCalledTimes(sent)
+ expect(t.settled).not.toHaveBeenCalled()
+})
diff --git a/cli/src/core/transcripts/attach.runtime.spec.ts b/cli/src/core/transcripts/attach.runtime.spec.ts
index ba78b4920..183810fda 100644
--- a/cli/src/core/transcripts/attach.runtime.spec.ts
+++ b/cli/src/core/transcripts/attach.runtime.spec.ts
@@ -34,8 +34,8 @@ function setup() {
normalizers.liveParsers.set(session.sessionId, oldParser)
const hold = { offset: statSync(path).size, expired: false, release: vi.fn() }
const emit = vi.fn(), addSession = vi.fn(async () => {})
- const attach = createAttach({ liveFor, normalizers, runtimeProfiles: profiles, resolve: () => session,
- terminalGone: async () => false, watcher: { hold: async () => hold, tails: () => true, addSession },
+ const attach = createAttach({ setInterpretationHold: () => false, announceSession: vi.fn(), liveFor, normalizers, runtimeProfiles: profiles, resolve: () => session,
+ terminalGone: async () => false, watcher: { removeSession: async () => {}, pollSession: async () => {}, hold: async () => hold, tails: () => true, addSession },
cursorDiscovery: { add: async () => {} }, device: () => undefined,
captureTerminal: async () => null, emit, announceTurnAborted: vi.fn(),
questionWatcher: { start: vi.fn() }, terminalLabel: () => 'private fixture',
diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.ts
index 2cad5fba2..a377e3530 100644
--- a/cli/src/core/transcripts/attach.spec.ts
+++ b/cli/src/core/transcripts/attach.spec.ts
@@ -1,10 +1,12 @@
import { liveFor } from '../../engines/live.js'
-import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { appendFileSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { RegisteredSession } from '../../lib/registry.js'
-import type { TailHold } from '../../watcher/watcher.js'
+import { Watcher, type TailHold } from '../../watcher/watcher.js'
+import { createIngest } from './ingest.js'
+import { createCancel } from '../turns/cancel.js'
import { createAttach, type AttachDeps } from './attach.js'
import { loadEngine } from '../../engines/inProcess.js'
import { createSessionNormalizers } from './normalizers.js'
@@ -12,6 +14,11 @@ import { createRelaunchMarks, type RelaunchMark } from './relaunch.js'
import type { PreparedLive } from '../engines/liveSessions.js'
import type { LiveFrame } from '../../engines/worker/liveProtocol.js'
import { TranscriptDiscovery } from '../../engines/kit/transcriptDiscovery.js'
+import { createBinding, type BindDeps } from '../agents/bind.js'
+import { createDiscoveryHandlers, type DiscoveryDeps } from '../agents/discovery.js'
+import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'
+
+vi.mock('../../lib/deletedSessions.js', () => ({ isRecentlyDeleted: () => false }))
/**
* The engines' own normalizers and readers are tested with each engine. Here each is a fake that
@@ -92,10 +99,19 @@ function setup(over: Partial<AttachDeps> = {}) {
const profile = { ingest: vi.fn(), commit: vi.fn() }
const deps: AttachDeps = {
liveFor,
+ announceSession: vi.fn(),
+ setInterpretationHold: (id, revision, reason, create) => {
+ const row = bindings.get(id)
+ if (!row || row.evidenceRevision !== revision || row.identityHold || (!row.interpretationHold && !(create && reason))) return false
+ if (!row.interpretationHold) row.evidenceRevision = (row.evidenceRevision ?? 0) + 1
+ if (reason) row.interpretationHold = reason
+ else delete row.interpretationHold
+ return true
+ },
resolve: id => bindings.get(id),
terminalGone: vi.fn(async () => false),
normalizers,
- watcher: { addSession: vi.fn(async () => {}), hold: vi.fn(async () => null), tails: vi.fn(() => false) },
+ watcher: { addSession: vi.fn(async () => {}), removeSession: vi.fn(async () => {}), pollSession: vi.fn(async () => {}), hold: vi.fn(async () => null), tails: vi.fn(() => false) },
cursorDiscovery: { add: vi.fn(async () => {}) },
device: () => service,
runtimeProfiles: {
@@ -154,6 +170,120 @@ afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
+it.each(['same', 'repaired'] as const)('composes discovery, retry and inline attachment after %s binding recovery', async outcome => {
+ const run = setup({ settled: vi.fn() })
+ const savedPath = transcript([{ events: [started('unconfirmed')], open: true }])
+ const verifiedPath = outcome === 'same' ? savedPath : transcript([{ events: [started('verified')], open: true }, { close: true }])
+ const row = session('codex', savedPath, { active: false, registeredAt: 1, boundAt: 2, permissionMode: 'default' })
+ let previous: unknown
+ if (outcome === 'repaired') {
+ await run.attach.attachSession(row)
+ previous = run.normalizers.liveParsers.get(row.sessionId)
+ expect(run.normalizers.sessionTurnOpen(row.sessionId)).toBe(true)
+ }
+ row.identityHold = 'header incomplete'
+ let available = false
+ const registry = {
+ byAgent: (id: string) => bindings.get(id), byProcess: () => row,
+ updateRuntimes: vi.fn(), updateProcessIdentity: () => { row.active = true },
+ setBypassPermission: vi.fn(), setLaunch: vi.fn(),
+ revalidateBinding: () => {
+ if (!available) throw new Error('header incomplete')
+ row.transcriptPath = verifiedPath; delete row.identityHold; return row
+ },
+ setIdentityHold: (_id: string, reason: string) => { row.identityHold = reason; return false },
+ bySession: () => row,
+ }
+ const bind = createBinding({ registry, attachSession: run.attach.attachSession,
+ announceSession: vi.fn(), stoppedAgents: { save: vi.fn() }, syncRecapPool: vi.fn(),
+ } as unknown as BindDeps)
+ const discover = createDiscoveryHandlers({ registry, bindObservedAgent: bind.bindObservedAgent,
+ attachSession: run.attach.attachSession, announceSession: vi.fn(), syncRecapPool: vi.fn(),
+ } as unknown as DiscoveryDeps)
+ const seen = { engine: 'codex', processIdentity: { pid: 42, startMarker: 'fixture' }, args: 'codex', runtimes: [] } as unknown as DiscoveredTerminalAgent
+ vi.clearAllMocks()
+ await discover.onObserved(seen, row)
+ await new Promise(resolve => setTimeout(resolve, 20))
+ expect(run.deps.terminalGone).not.toHaveBeenCalled()
+ expect(run.deps.runtimeProfiles.beginHydrate).not.toHaveBeenCalled()
+ expect(run.profile.commit).not.toHaveBeenCalled()
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ expect(run.deps.watcher.addSession).not.toHaveBeenCalled()
+ expect(row).toMatchObject({ active: true, identityHold: 'header incomplete', transcriptPath: savedPath })
+ if (outcome === 'same') writeFileSync(savedPath, JSON.stringify({ events: [started('verified')], open: true }) + '\n' + JSON.stringify({ close: true }) + '\n')
+ available = true
+ await discover.onObserved(seen, row)
+ await vi.waitFor(() => expect(run.deps.watcher.addSession).toHaveBeenCalledOnce())
+ expect(row).not.toHaveProperty('identityHold')
+ expect(run.normalizers.liveParsers.get(row.sessionId)).not.toBe(previous)
+ expect(run.normalizers.sessionTurnOpen(row.sessionId)).toBe(false)
+ expect(run.profile.commit).toHaveBeenCalledOnce()
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ expect(run.deps.settled).toHaveBeenCalledWith(row.sessionId)
+})
+
+it('keeps an already held binding without starting a terminal probe or reader', async () => {
+ const run = setup()
+ expect(await run.attach.attachSession(session('codex', transcript([]), { identityHold: 'waiting' }))).toBe(true)
+ expect(run.deps.terminalGone).not.toHaveBeenCalled()
+ expect(run.deps.runtimeProfiles.beginHydrate).not.toHaveBeenCalled()
+})
+
+it.each(['terminal', 'config', 'watcher'] as const)('revokes inline attachment when identity becomes held during %s', async phase => {
+ const run = setup(), row = session('codex', transcript([{ events: [started()], open: true }]))
+ const hold = () => { row.identityHold = 'identity unavailable' }
+ if (phase === 'terminal') vi.mocked(run.deps.terminalGone).mockImplementationOnce(async () => { hold(); return false })
+ if (phase === 'config') vi.mocked(run.deps.runtimeProfiles.ingestConfig).mockImplementationOnce(async () => { hold(); return false })
+ if (phase === 'watcher') vi.mocked(run.deps.watcher.addSession).mockImplementationOnce(async () => { hold() })
+ expect(await run.attach.attachSession(row)).toBe(true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ if (phase !== 'watcher') {
+ expect(run.profile.commit).not.toHaveBeenCalled()
+ expect(run.normalizers.hasState(row.sessionId)).toBe(false)
+ }
+})
+
+it.each(['prepare', 'config'] as const)('discards worker history when identity becomes held during %s', async phase => {
+ const run = remoteSetup(true), row = session('claude', '/fixture/transcript')
+ if (phase === 'prepare') vi.mocked(run.remote.prepare).mockImplementationOnce(async () => { row.identityHold = 'waiting'; return run.candidate })
+ else vi.mocked(run.deps.runtimeProfiles.ingestConfig).mockImplementationOnce(async () => { row.identityHold = 'waiting'; return false })
+ expect(await run.attach.attachSession(row)).toBe(true)
+ expect(run.remote.discard).toHaveBeenCalledWith(run.candidate)
+ expect(run.remote.install).not.toHaveBeenCalled()
+ expect(run.profile.commit).not.toHaveBeenCalled()
+ expect(run.deps.emit).not.toHaveBeenCalled()
+})
+
+it('discards an inline fold held during its file read, without observing it on a device', async () => {
+ const run = setup(), row = session('codex', transcript([{ events: [started()], open: true }]))
+ run.service.needsTranscript.mockReturnValue(true)
+ run.profile.ingest.mockImplementation(() => { row.identityHold = 'header changed' })
+ expect(await run.attach.attachSession(row)).toBe(true)
+ expect(run.service.observeTranscript).not.toHaveBeenCalled()
+ expect(run.profile.commit).not.toHaveBeenCalled()
+ expect(run.normalizers.hasState(row.sessionId)).toBe(false)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+})
+
+it('discards a whole-file read when identity becomes held before hydration', async () => {
+ const row = session('terminal', transcript([{}]))
+ const run = setup({ liveFor: engine => {
+ queueMicrotask(() => { row.identityHold = 'path changed' })
+ return liveFor(engine)
+ } })
+ expect(await run.attach.attachSession(row)).toBe(true)
+ expect(run.deps.runtimeProfiles.hydrate).not.toHaveBeenCalled()
+ expect(run.normalizers.hasState(row.sessionId)).toBe(false)
+})
+
+it('defers history publication if identity becomes held during pane hydration', async () => {
+ const row = session('cursor', transcript([{ events: [started()], open: true }]))
+ const run = setup({ captureTerminal: async () => { row.identityHold = 'path changed'; return null } })
+ expect(await run.attach.attachSession(row)).toBe(true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ expect(run.deps.watcher.addSession).not.toHaveBeenCalled()
+})
+
describe('the order of an attach of another engine\'s session', () => {
it('loads the engine\'s code, then folds, then starts the tail: no line can come before its normalizer', async () => {
let loaded!: () => void
@@ -977,3 +1107,344 @@ describe('attaching a session', () => {
expect(run.attach.attaches.attaching()).toHaveLength(1)
})
})
+
+
+it.each(['terminal', 'config', 'worker'] as const)('discards a deferred %s result across a full same-path native hold/recovery', async phase => {
+ const run = phase === 'worker' ? remoteSetup(true) : setup()
+ const row = session('claude', transcript([CLAUDE_PROMPT]))
+ let finish!: () => void
+ const wait = new Promise<void>(resolve => { finish = resolve })
+ const entered = vi.fn()
+ if (phase === 'terminal') vi.mocked(run.deps.terminalGone).mockImplementationOnce(async () => { entered(); await wait; return false })
+ else if (phase === 'config') vi.mocked(run.deps.runtimeProfiles.ingestConfig).mockImplementationOnce(async () => { entered(); await wait; return false })
+ else {
+ const remote = (run as ReturnType<typeof remoteSetup>).remote
+ const prepare = vi.mocked(remote.prepare).getMockImplementation()!
+ vi.mocked(remote.prepare).mockImplementationOnce(async (...args) => { const value = await prepare(...args); entered(); await wait; return value })
+ }
+ const pending = run.attach.attachSession(row)
+ await vi.waitFor(() => expect(entered).toHaveBeenCalled())
+ row.identityHold = 'incomplete'; row.evidenceRevision = 1
+ delete row.identityHold; row.evidenceRevision = 2; row.interpretationHold = 'replacement pending'
+ finish(); expect(await pending).toBe(true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ expect(run.profile.commit).not.toHaveBeenCalled()
+ expect(run.normalizers.hasState(row.sessionId)).toBe(false)
+ run.attach.forget(row.sessionId)
+})
+
+it.each(['config', 'watcher'] as const)('holds real watcher ingestion through deferred and failed replacement %s, then retries without another event', async phase => {
+ const watcher = new Watcher()
+ const run = setup({ watcher })
+ const file = transcript([]), row = session('claude', file)
+ const emit = vi.fn(), ingestProfile = vi.fn(), token = vi.fn()
+ const ingest = createIngest({ liveFor, has: () => true, bySession: () => row, device: () => undefined,
+ runtimeProfiles: { ingest: ingestProfile }, tokenUsage: { changed: token }, normalizers: run.normalizers,
+ announceTurnAborted: vi.fn(), emit, attachSession: run.attach.attachSession })
+ ingest.wireWatcher(watcher)
+ try {
+ await run.attach.attachSession(row)
+ const old = run.normalizers.liveParsers.get(row.sessionId)
+ row.identityHold = 'header incomplete'; row.evidenceRevision = 1
+ appendFileSync(file, JSON.stringify(CLAUDE_PROMPT) + '\n')
+ await watcher.pollSession(row.sessionId)
+ expect(emit).not.toHaveBeenCalled(); expect(ingestProfile).not.toHaveBeenCalled()
+ delete row.identityHold; row.evidenceRevision = 2; row.interpretationHold = 'replacement pending'
+ const entered = vi.fn()
+ let fail!: (error: Error) => void
+ const pending = new Promise<void>((_resolve, reject) => { fail = reject })
+ run.profile.commit.mockClear()
+ if (phase === 'config') {
+ vi.mocked(run.deps.runtimeProfiles.beginHydrate).mockReturnValue({ ...run.profile, config: async () => { entered(); await pending } })
+ } else {
+ const add = watcher.addSession.bind(watcher)
+ vi.spyOn(watcher, 'addSession').mockImplementationOnce(async (...args) => { await add(...args); entered(); await pending })
+ }
+ const attached = run.attach.attachSession(row) // ordinary caller must see the recovery obligation
+ await vi.waitFor(() => expect(entered).toHaveBeenCalled())
+ appendFileSync(file, JSON.stringify({ ...CLAUDE_PROMPT, uuid: 'u2', message: { role: 'user', content: 'while installation waits' } }) + '\n')
+ await watcher.pollSession(row.sessionId)
+ expect(emit).not.toHaveBeenCalled(); expect(ingestProfile).not.toHaveBeenCalled(); expect(token).not.toHaveBeenCalled()
+ expect(run.profile.commit).not.toHaveBeenCalled()
+ expect(run.normalizers.liveParsers.get(row.sessionId)).not.toBe(old)
+ fail(new Error('replacement unavailable')); expect(await attached).toBe(true)
+ expect(row.interpretationHold).toContain(phase === 'config' ? 'runtime profile' : 'replacement unavailable')
+ expect(run.profile.commit).not.toHaveBeenCalled()
+ // On the next timer attempt the actual file is read again; stale held lines are history.
+ vi.mocked(run.deps.runtimeProfiles.beginHydrate).mockReturnValue(run.profile)
+ await vi.waitFor(() => expect(row.interpretationHold).toBeUndefined(), { timeout: 3_000 })
+ expect(run.normalizers.liveParsers.get(row.sessionId)).not.toBe(old)
+ expect(emit).not.toHaveBeenCalled()
+ appendFileSync(file, JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'done' }], stop_reason: 'end_turn' } }) + '\n')
+ await watcher.pollSession(row.sessionId)
+ expect(ingestProfile).toHaveBeenCalledTimes(1)
+ expect(emit).toHaveBeenCalledTimes(1)
+ // A completed installation gate is temporary. A later legitimate same-path restart must
+ // hand the existing tail to its next parser without retaining the recovery's pane identity.
+ row.tmuxPane = '%new'; row.boundAt = 99
+ await run.attach.attachSession(row, true)
+ appendFileSync(file, JSON.stringify({ ...CLAUDE_PROMPT, uuid: 'after-reset' }) + '\n')
+ await watcher.pollSession(row.sessionId)
+ expect(ingestProfile).toHaveBeenCalledTimes(2)
+ expect(emit).toHaveBeenCalledTimes(2)
+ } finally { run.attach.forget(row.sessionId); await watcher.stop() }
+})
+
+
+it.each(['inline', 'worker'] as const)('retains the crash boundary across failed recovery installation and closes the staged %s turn', async mode => {
+ const marks = createRelaunchMarks()
+ const run = mode === 'worker' ? remoteSetup(true, { relaunchMarks: marks }) : setup({ relaunchMarks: marks })
+ const file = transcript([CLAUDE_PROMPT]), row = session('claude', file, { evidenceRevision: 2, interpretationHold: 'replacement pending' })
+ marks.note(row.sessionId, statSync(file).size, true)
+ const mark = marks.read(row.sessionId)
+ const commitWith = vi.fn((install: () => boolean) => install())
+ vi.mocked(run.deps.runtimeProfiles.beginHydrate).mockReturnValue({ ...run.profile, commitWith })
+ vi.mocked(run.deps.watcher.addSession).mockRejectedValueOnce(new Error('tail unavailable'))
+ await run.attach.attachSession(row)
+ expect(marks.read(row.sessionId)).toBe(mark)
+ expect(row.interpretationHold).toContain('tail unavailable')
+ expect(commitWith).not.toHaveBeenCalled()
+ expect(run.normalizers.liveParsers.get(row.sessionId)?.snapshot().identity).toMatch(/^held:/)
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toBeUndefined()
+ expect(marks.read(row.sessionId)).toBeUndefined()
+ if (mode === 'inline') expect(run.normalizers.sessionTurnOpen(row.sessionId)).toBe(false)
+ else expect((run as ReturnType<typeof remoteSetup>).handle.closeTurn).toHaveBeenCalledWith('abandoned')
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
+
+it('keeps a replacement obligation when the profile commit loses authority during watcher installation', async () => {
+ const run = setup(), row = session('claude', transcript([CLAUDE_PROMPT]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ const commitWith = vi.fn(() => false)
+ vi.mocked(run.deps.runtimeProfiles.beginHydrate).mockReturnValue({ ...run.profile, commitWith })
+ expect(await run.attach.attachSession(row)).toBe(true)
+ expect(row.interpretationHold).toContain('superseded during watcher installation')
+ expect(run.normalizers.liveParsers.get(row.sessionId)?.snapshot().identity).toMatch(/^held:/)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
+
+it.each([new Error('tail read failed'), 'tail read failed'])('contains a failed post-recovery drain: %s', async error => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const run = setup(), row = session('claude', transcript([]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ vi.mocked(run.deps.watcher.pollSession).mockRejectedValueOnce(error)
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toBeUndefined()
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('recovered tail read failed'))
+ run.attach.forget(row.sessionId)
+})
+
+it.each(['queued', 'detaching', 'rejected', 'non-error', 'retry-stale'] as const)('fences recovery while %s and does not retire its binding', async phase => {
+ const run = setup(), row = session('claude', transcript([]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ let finish!: () => void
+ const waiting = new Promise<void>(resolve => { finish = resolve })
+ let first: Promise<boolean> | undefined
+ if (phase === 'queued') {
+ const other = session('claude', row.transcriptPath!, { agentId: row.agentId, sessionId: row.sessionId, evidenceRevision: 2 })
+ bindings.set(row.agentId, row)
+ delete row.interpretationHold
+ vi.mocked(run.deps.terminalGone).mockImplementationOnce(async () => { await waiting; return false })
+ first = run.attach.attachSession(other)
+ row.interpretationHold = 'pending'
+ } else if (phase === 'detaching') vi.mocked(run.deps.watcher.removeSession).mockImplementationOnce(async () => { await waiting })
+ else vi.mocked(run.deps.watcher.removeSession).mockImplementationOnce(async () => {
+ if (phase === 'rejected') row.evidenceRevision = row.evidenceRevision! + 1
+ throw phase === 'non-error' ? 'detachment failed' : new Error('detachment failed')
+ })
+ const pending = run.attach.attachSession(row)
+ if (phase === 'queued' || phase === 'detaching') { row.evidenceRevision = row.evidenceRevision! + 1; finish() }
+ await first; await pending
+ expect(run.profile.commit).not.toHaveBeenCalled()
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ if (phase === 'retry-stale') {
+ row.evidenceRevision = row.evidenceRevision! + 1
+ await new Promise(resolve => setTimeout(resolve, 1_100))
+ expect(run.deps.watcher.removeSession).toHaveBeenCalledOnce()
+ }
+ run.attach.forget(row.sessionId)
+})
+
+
+it.each(['inline', 'worker'] as const)('preserves eager cancel while the %s recovery parser is staged', async mode => {
+ const run = mode === 'worker' ? remoteSetup(true) : setup()
+ const row = session('claude', transcript([CLAUDE_PROMPT]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ if (mode === 'worker') (run as ReturnType<typeof remoteSetup>).candidate.page.cursor.offset = statSync(row.transcriptPath!).size
+ let finish!: () => void
+ const waiting = new Promise<void>(resolve => { finish = resolve })
+ vi.mocked(run.deps.watcher.addSession).mockImplementationOnce(async () => { await waiting })
+ const pending = run.attach.attachSession(row)
+ await vi.waitFor(() => expect(run.deps.watcher.addSession).toHaveBeenCalledOnce())
+ const cancel = createCancel({ resolve: () => row, normalizers: run.normalizers,
+ cursorSubagents: { forget: vi.fn() }, input: { cancel: vi.fn(), cancelConfirmed: vi.fn(async () => true) },
+ device: () => undefined, stopHeartbeat: vi.fn(), questionWatcher: { stop: vi.fn() }, mirror: { cancel: vi.fn() },
+ turnActivity: { observe: vi.fn(), snapshot: vi.fn() }, turnStartedAt: new Map(), agentIdFor: () => row.agentId, clients: { send: vi.fn() },
+ })
+ await cancel(row.agentId)
+ finish(); await pending
+ expect(row.interpretationHold).toContain('turn control changed')
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toBeUndefined()
+ if (mode === 'inline') expect(run.normalizers.sessionTurnOpen(row.sessionId)).toBe(false)
+ else expect((run as ReturnType<typeof remoteSetup>).remote.prepare).toHaveBeenLastCalledWith(
+ expect.anything(), expect.objectContaining({ closes: [expect.objectContaining({ reason: 'cancel' })] }), expect.anything(), undefined)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
+
+it('coalesces a queued recovery after the first replacement completes', async () => {
+ const run = setup(), row = session('claude', transcript([]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ let finish!: () => void
+ const waiting = new Promise<void>(resolve => { finish = resolve })
+ vi.mocked(run.deps.terminalGone).mockImplementationOnce(async () => { await waiting; return false }).mockRejectedValueOnce(new Error('must not run a second read'))
+ const first = run.attach.attachSession(row), second = run.attach.attachSession(row)
+ finish(); expect(await first).toBe(true); expect(await second).toBe(true)
+ expect(run.deps.terminalGone).toHaveBeenCalledOnce()
+ expect(run.deps.watcher.removeSession).toHaveBeenCalledOnce()
+ expect(row.interpretationHold).toBeUndefined()
+ expect(run.normalizers.hasState(row.sessionId)).toBe(true)
+ run.attach.forget(row.sessionId)
+})
+
+it('retries a still-current recovery after its pane route moves without another hook', async () => {
+ const run = setup(), row = session('claude', transcript([]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ vi.mocked(run.deps.watcher.addSession).mockImplementationOnce(async () => { row.tmuxPane = '%moved' })
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toBeTruthy()
+ await vi.waitFor(() => expect(row.interpretationHold).toBeUndefined(), { timeout: 3_000 })
+ expect(run.deps.watcher.addSession).toHaveBeenCalledTimes(2)
+ run.attach.forget(row.sessionId)
+})
+
+it('revokes a recovery still detaching when its session is forgotten', async () => {
+ const run = setup(), row = session('claude', transcript([]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ let finish!: () => void
+ vi.mocked(run.deps.watcher.removeSession).mockImplementationOnce(() => new Promise<void>(resolve => { finish = resolve }))
+ const pending = run.attach.attachSession(row)
+ run.attach.forget(row.sessionId); finish(); await pending
+ expect(run.deps.terminalGone).not.toHaveBeenCalled()
+ expect(run.profile.commit).not.toHaveBeenCalled()
+ expect(run.deps.watcher.addSession).not.toHaveBeenCalled()
+})
+
+it('keeps a recovered tail paused if clearing its obligation loses registry authority', async () => {
+ const setInterpretationHold = vi.fn(() => false), run = setup({ setInterpretationHold })
+ const row = session('claude', transcript([CLAUDE_PROMPT]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toBe('pending')
+ expect(vi.mocked(run.deps.watcher.addSession).mock.calls[0][1]?.deliveryAllowed?.()).toBe(false)
+ expect(run.deps.watcher.pollSession).not.toHaveBeenCalled()
+ expect(run.deps.announceSession).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
+it('does not reconstruct a retained cancellation when the new recovery obligation cannot be claimed', async () => {
+ let claim = true
+ const run = setup({ setInterpretationHold: (_id, _revision, reason) => {
+ if (!claim) return false
+ row.interpretationHold = reason
+ return true
+ } })
+ const row = session('claude', transcript([CLAUDE_PROMPT]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ run.attach.beforeCancel(row); run.normalizers.closeTurns(row.sessionId)
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toBeUndefined()
+ claim = false
+ vi.mocked(run.deps.watcher.addSession).mockClear()
+ await run.attach.attachSession(row, true)
+ expect(run.deps.watcher.addSession).not.toHaveBeenCalled()
+ expect(run.normalizers.sessionTurnOpen(row.sessionId)).toBe(false)
+ run.attach.forget(row.sessionId)
+})
+it('keeps normal Stop on its existing path and contains a rejected recovery scheduler', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const run = setup(), row = session('claude', transcript([]))
+ run.attach.beforeCancel(row)
+ expect(run.attach.holdStop(row)).toBe(false)
+ vi.spyOn(run.attach.attaches, 'attach').mockRejectedValueOnce(new Error('scheduler unavailable'))
+ run.attach.holdInterpretation(row, 'waiting for evidence')
+ await vi.waitFor(() => expect(warn).toHaveBeenCalledWith(expect.stringContaining('scheduler unavailable')))
+ expect(row.interpretationHold).toBe('waiting for evidence')
+ run.attach.forget(row.sessionId)
+})
+it('recovers a legacy reader without control cuts and holds one that cannot replay them', async () => {
+ const run = setup(), row = session('muse', transcript([]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toBeUndefined()
+ expect(run.normalizers.museNormalizers.has(row.sessionId)).toBe(true)
+ row.interpretationHold = 'pending'
+ run.attach.beforeCancel(row); run.normalizers.closeTurns(row.sessionId)
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toContain('cannot yet replay ordered cancellation')
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
+it('abandons a legacy open turn at the relaunch boundary', async () => {
+ const marks = createRelaunchMarks(), run = setup({ relaunchMarks: marks })
+ const file = transcript([{ open: true, events: [started()] }]), row = session('muse', file)
+ marks.note(row.sessionId, statSync(file).size, true)
+ await run.attach.attachSession(row)
+ expect(run.normalizers.museNormalizers.get(row.sessionId)?.turnOpen).toBe(false)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ expect(marks.read(row.sessionId)).toBeUndefined()
+})
+it('holds a worker candidate that stops before its cancellation cutoff', async () => {
+ const run = remoteSetup(), row = session('claude', transcript([CLAUDE_PROMPT]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ run.attach.beforeCancel(row); run.normalizers.closeTurns(row.sessionId)
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toContain('did not reach its cancellation boundary')
+ expect(run.deps.watcher.pollSession).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
+it('holds a recovery whose control proxy was replaced during watcher installation', async () => {
+ const run = setup(), row = session('claude', transcript([CLAUDE_PROMPT]), { evidenceRevision: 2, interpretationHold: 'pending' })
+ vi.mocked(run.deps.watcher.addSession).mockImplementationOnce(async () => { run.normalizers.liveParsers.delete(row.sessionId) })
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toContain('superseded during watcher installation')
+ expect(run.profile.commit).not.toHaveBeenCalled()
+ expect(run.deps.watcher.pollSession).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
+it('replays a crash boundary in order with a retained cancellation', async () => {
+ const marks = createRelaunchMarks(), run = setup({ relaunchMarks: marks })
+ const file = transcript([CLAUDE_PROMPT]), row = session('claude', file, { evidenceRevision: 2, interpretationHold: 'pending' })
+ run.attach.beforeCancel(row); run.normalizers.closeTurns(row.sessionId)
+ appendFileSync(file, JSON.stringify({ ...CLAUDE_PROMPT, uuid: 'second' }) + '\n')
+ marks.note(row.sessionId, statSync(file).size, true)
+ appendFileSync(file, JSON.stringify({ ...CLAUDE_PROMPT, uuid: 'third' }) + '\n')
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toBeUndefined()
+ expect(run.normalizers.sessionTurnOpen(row.sessionId)).toBe(true)
+ expect(marks.read(row.sessionId)).toBeUndefined()
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
+
+it('leaves an ordinary database cancellation on its eager native control path', () => {
+ const run = setup(), row = session('opencode')
+ run.attach.beforeCancel(row)
+ expect(row.interpretationHold).toBeUndefined()
+ expect(run.normalizers.liveParsers.has(row.sessionId)).toBe(false)
+ expect(run.deps.terminalGone).not.toHaveBeenCalled()
+ expect(run.deps.watcher.addSession).not.toHaveBeenCalled()
+})
+
+it.each(['opencode', 'kilo', 'hermes', 'devin'])('keeps %s Cancel eager after retaining a previous Stop without a file boundary', async engine => {
+ const run = setup(), row = session(engine)
+ const reader = { turnOpen: false, closeTurn() { this.turnOpen = false } }
+ const maps = { opencode: run.normalizers.opencodeReaders, kilo: run.normalizers.kiloReaders,
+ hermes: run.normalizers.hermesReaders, devin: run.normalizers.devinReaders }
+ ;(maps[engine as keyof typeof maps] as Map<string, unknown>).set(row.sessionId, reader)
+ run.attach.afterStop(row)
+ reader.turnOpen = true
+ run.attach.beforeCancel(row)
+ run.normalizers.closeTurns(row.sessionId)
+ expect(reader.turnOpen).toBe(false)
+ expect(row.interpretationHold).toBeUndefined()
+ expect(run.normalizers.liveParsers.has(row.sessionId)).toBe(false)
+ expect(run.deps.watcher.removeSession).not.toHaveBeenCalled()
+ row.evidenceRevision = 1; row.interpretationHold = 'pending'
+ await run.attach.attachSession(row)
+ expect(row.interpretationHold).toContain('no file cancellation boundary')
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ run.attach.forget(row.sessionId)
+})
diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.ts
index 07df35312..9138b70ce 100644
--- a/cli/src/core/transcripts/attach.ts
+++ b/cli/src/core/transcripts/attach.ts
@@ -29,6 +29,7 @@ import { createSideReads } from './sideReads.js'
import { paneReadIdentity } from './readIdentity.js'
import type { LiveSessions, PreparedLive } from '../engines/liveSessions.js'
import { createReaderLoads } from './readerLoads.js'
+import { createTurnReplacements } from './turnReplacement.js'
export interface AttachDeps {
liveFor: LiveFor
@@ -37,7 +38,9 @@ export interface AttachDeps {
/** Whether the session's terminal is known to be gone (core/terminals/control.ts `terminalGone`). */
terminalGone: (session: RegisteredSession) => Promise<boolean>
normalizers: SessionNormalizers
- watcher: Pick<Watcher, 'addSession' | 'hold' | 'tails'>
+ watcher: Pick<Watcher, 'addSession' | 'removeSession' | 'pollSession' | 'hold' | 'tails'>
+ setInterpretationHold: (agentId: string, revision: number | undefined, reason?: string, create?: boolean) => boolean
+ announceSession: (session: RegisteredSession) => void
cursorDiscovery: Pick<CursorTranscriptDiscovery, 'add'>
/** The Wi-Fi device's service, wherever it runs (core/wifi.ts): it proves its turns by the raw transcript. */
device: () => Pick<WifiFeed, 'needsTranscript' | 'observeTranscript'> | undefined
@@ -71,7 +74,7 @@ export interface AttachDeps {
export function createAttach({
liveFor, resolve, remoteLive, terminalGone, normalizers, watcher, cursorDiscovery, device, runtimeProfiles, captureTerminal, emit,
announceTurnAborted, questionWatcher, terminalLabel, dbs, devinHome, hermesDb, concurrency, relaunchMarks,
- wholeReadCapBytes = WHOLE_READ_CAP_BYTES, settled, readerLoadWaitMs,
+ wholeReadCapBytes = WHOLE_READ_CAP_BYTES, settled, readerLoadWaitMs, setInterpretationHold, announceSession,
}: AttachDeps) {
const {
liveParsers, cursorNormalizers, opencodeReaders, kiloReaders, museNormalizers, ampNormalizers,
@@ -79,6 +82,43 @@ export function createAttach({
} = normalizers
const sideRead = createSideReads()
const readerLoads = createReaderLoads(readerLoadWaitMs)
+ const turnReplacements = createTurnReplacements(normalizers)
+ const recoveryRetries = new Map<string, ReturnType<typeof setTimeout>>()
+ const lifetimes = new Map<string, object>()
+ const forget = (sessionId: string): void => {
+ readerLoads.forget(sessionId)
+ lifetimes.delete(sessionId)
+ turnReplacements.forget(sessionId)
+ clearTimeout(recoveryRetries.get(sessionId))
+ recoveryRetries.delete(sessionId)
+ }
+ const explainRecovery = (session: RegisteredSession, reason?: string): boolean => {
+ if (!setInterpretationHold(session.agentId, session.evidenceRevision, reason)) return false
+ announceSession(resolve(session.agentId)!)
+ return true
+ }
+ const beforeCancel = (session: RegisteredSession): void => {
+ if (session.identityHold || session.interpretationHold) turnReplacements.stage(session)
+ else if (session.transcriptPath || turnReplacements.retains(session)) {
+ const reason = turnReplacements.cancel(session)
+ if (reason && session.transcriptPath) holdInterpretation(session, `Waiting for transcript interpretation: ${reason}.`)
+ }
+ }
+ const holdInterpretation = (session: RegisteredSession, reason: string): void => {
+ turnReplacements.stage(session)
+ if (setInterpretationHold(session.agentId, session.evidenceRevision, reason, true)) {
+ const latest = resolve(session.agentId)!
+ announceSession(latest)
+ void attachSession(latest, true).catch(error => console.warn(`[agent] recovery held: ${String(error)}`))
+ }
+ }
+ const holdStop = (session: RegisteredSession, force = false): boolean => {
+ if (!session.identityHold && !session.interpretationHold && !force) return false
+ turnReplacements.stage(session).stop()
+ holdInterpretation(session, 'Stop could not be matched to its turn; Cancel can resolve this hold.')
+ return true
+ }
+ const afterStop = (session: RegisteredSession): void => { turnReplacements.stop(session) }
/**
* Sessions that attached before their transcript existed, so nothing was folded and nothing has ever
* been streamed for them.
@@ -175,17 +215,18 @@ export function createAttach({
// history. A restore is not a resume to `bind.ts`, so a transcript under ten minutes old
// (lib/firstTurnReplay.ts) went out live again after a daemon restart: its turns, and their recaps
// and notifications, a second time (found end to end, e2e/machine.e2e.ts).
- const replayLive = relaunchedAt === undefined && (
+ const replayLive = !session.interpretationHold && relaunchedAt === undefined && (
(replayFromStart && !replayedFirstTurn.has(session.sessionId))
|| (session.engine === 'cursor' && replayCursorFromStart))
const historyEvents: LiveEvent[] = []
let historyTurnOpen = false
+ let historyExplicitlyClosed = false
let historySuperseded = false
let historyCurrent: (() => boolean) | undefined
let observed = false
sideRead('device', session.sessionId, () => { observed = !!device()?.needsTranscript(session.agentId, session.sessionId, session.engine) })
- const observe = observed
- ? (line: string): void => sideRead('device', session.sessionId, () => device()?.observeTranscript(session.agentId, session.sessionId, session.engine, line))
+ const observe = observed && !session.interpretationHold
+ ? (line: string): void => { if (current()) sideRead('device', session.sessionId, () => device()?.observeTranscript(session.agentId, session.sessionId, session.engine, line)) }
: undefined
// Returns `turnOpen` rather than assigning it: every engine folds exactly once, and a second call
// quietly overwriting the first is the kind of mistake a returned value makes impossible to write.
@@ -207,16 +248,29 @@ export function createAttach({
const fields = (line: string): readonly RuntimeField[] => runtimeProfiles.transcriptFields(session, line)
const rules = adapter?.attachRules?.(fields)
const fromEndFold = parser && rules
- ? { rules, ingest: (line: string) => parser.ingest(line).events, turnOpen: () => parser.turnOpen }
+ ? { rules, ingest: (line: string) => {
+ const events = parser.ingest(line).events
+ if (events.some(event => event.type === 'turn_started' || event.type === 'turn_ended')) historyExplicitlyClosed = false
+ return events
+ }, turnOpen: () => parser.turnOpen }
: null
let fromEnd: AttachRead | null = null
let prepared: PreparedLive | null = null
let profileHydration: ProfileHydration | null = null
+ const replacement = session.interpretationHold ? turnReplacements.stage(session) : undefined
+ const recoveryPlan = replacement?.plan()
+ const closes = recoveryPlan?.closes.length ? [
+ ...(relaunch?.engineStarted ? [{ offset: relaunch.offset, reason: 'abandoned' as const }] : []),
+ ...recoveryPlan.closes,
+ ].sort((a, b) => a.offset - b.offset) : undefined
+ let recoveryInstall = () => replacement!.commit(recoveryPlan!)
+ let recoveryReady = false
// A reset keeps the normalizer it meant to replace when its read failed, or outlasted the hold on the
// tail — which then let go, and delivery went back to that normalizer: it has seen every record since,
// this one has not.
const keepLiveNormalizer = (why: string): boolean => {
- console.warn(`[agent] ${sid(session.agentId)} kept its live normalizer · the re-read ${why}`)
+ console.warn(`[agent] ${sid(session.agentId)} ${session.interpretationHold ? 'transcript held' : 'kept its live normalizer'} · the re-read ${why}`)
+ if (session.interpretationHold && current()) explainRecovery(session, `Waiting for transcript interpretation: the re-read ${why}.`)
handover.hold?.release()
handover.next = null
if (relaunch) remote?.retry(session)
@@ -224,18 +278,18 @@ export function createAttach({
}
// A surviving shell can leave its old tail installed. Its cursor is the old engine's delivery
// position; a newly started engine's history ends at the launch boundary instead.
- const historyEnd = () => relaunch?.engineStarted ? relaunch.offset : handover.hold?.offset ?? relaunchedAt
+ const historyEnd = () => closes ? undefined : relaunch?.engineStarted ? relaunch.offset : handover.hold?.offset ?? relaunchedAt
if (remote) {
if (session.transcriptPath) handover.hold = await watcher.hold(session.sessionId, session.transcriptPath)
const live = replayLive && handover.hold === null
try {
const profile = runtimeProfiles.beginHydrate(session)
profileHydration = profile
- prepared = await remote.prepare(session, { live, end: historyEnd() }, frame => {
+ prepared = await remote.prepare(session, { live, end: historyEnd(), ...(closes ? { closes } : {}) }, frame => {
if (frame.profile && !profile.ingestFrames) sideRead('runtime profile', session.sessionId, () => profile.ingest(frame.raw))
if (frame.observe && observe) observe(frame.raw)
}, profile.ingestFrames)
- if (profile.config) await profile.config()
+ if (current() && profile.config) await profile.config()
} catch {
if (prepared) remote.discard(prepared)
remote.retry(session)
@@ -245,6 +299,7 @@ export function createAttach({
fromEnd = { next: prepared.page.cursor.offset, records: prepared.records, content: prepared.content }
handover.next = fromEnd.next
historyTurnOpen = !live && prepared.state.handle.turnOpen
+ historyExplicitlyClosed = !!prepared.page.cursor.closed
if (prepared.page.lastStarted) historyEvents.push(prepared.page.lastStarted)
} else if (session.transcriptPath && fromEndFold) {
// A session already being tailed — a reset — is re-read while its old normalizer is still the one
@@ -261,11 +316,13 @@ export function createAttach({
start: (span) => parser!.windowStart(span.turnFrom),
profile: (line) => profile.ingest(line),
fold: (line) => stream.push(line),
+ close: reason => { parser!.closeTurn(reason); historyExplicitlyClosed = true },
observe,
- }, { fromStart: live, end: historyEnd() })
- if (handover.hold && (read.failed || handover.hold.expired)) {
+ }, { fromStart: live, end: historyEnd(), closes })
+ if ((session.interpretationHold && read.failed) || (handover.hold && (read.failed || handover.hold.expired))) {
return keepLiveNormalizer(read.failed ? 'could not read the transcript' : 'outlasted its hold on the tail')
}
+ if (!current()) return false
try { await profile.config?.() }
catch { return keepLiveNormalizer('could not read its runtime profile') }
fromEnd = read
@@ -282,11 +339,20 @@ export function createAttach({
if (read.truncated) console.warn(`[agent] ${sid(session.agentId)} transcript over ${Math.round(wholeReadCapBytes / 1024 / 1024)} MB · folded from its newest ${Math.round(wholeReadCapBytes / 1024 / 1024)} MB`)
lines = read.lines
}
+ if (!current()) {
+ if (prepared) remote!.discard(prepared)
+ return false
+ }
if (!fromEnd) {
+ if (closes) throw new Error('the native reader cannot yet replay ordered cancellation boundaries')
if (observe) for (const line of lines) observe(line)
sideRead('runtime profile', session.sessionId, () => runtimeProfiles.hydrate(session, lines))
}
if (!profileHydration?.config) await runtimeProfiles.ingestConfig(session, true)
+ if (!current()) {
+ if (prepared) remote!.discard(prepared)
+ return false
+ }
// From here to the release in `attachSession` nothing is awaited for a held tail, so the hold cannot
// expire between installing the new normalizer and handing it the tail.
if (handover.hold?.expired) {
@@ -297,16 +363,19 @@ export function createAttach({
take(foldTranscript(ingest, lines, turnOpenAfter, { live: replayLive }))
if (prepared) {
const install = () => remote!.install(prepared!)
- if (!(profileHydration?.commitWith ? profileHydration.commitWith(install) : install())) {
+ if (!(session.interpretationHold ? install() : profileHydration?.commitWith ? profileHydration.commitWith(install) : install())) {
remote!.discard(prepared); remote!.retry(session)
return keepLiveNormalizer('was superseded while reading')
}
- if (!profileHydration?.commitWith) profileHydration?.commit()
- liveParsers.set(session.sessionId, prepared.state.handle)
+ if (!session.interpretationHold && !profileHydration?.commitWith) profileHydration?.commit()
+ const publish = () => { liveParsers.set(session.sessionId, prepared!.state.handle); return true }
+ if (replacement) recoveryInstall = () => replacement.commit(recoveryPlan!, prepared!.state.handle)
+ else publish()
} else if (parser) {
if (!fromEnd) historyTurnOpen = fold((line) => parser.ingest(line).events, () => parser.turnOpen)
const install = () => { liveParsers.set(session.sessionId, parser); return true }
- if (profileHydration?.commitWith) {
+ if (replacement) recoveryInstall = () => replacement.commit(recoveryPlan!, parser)
+ else if (profileHydration?.commitWith) {
if (!profileHydration.commitWith(install)) return keepLiveNormalizer('was superseded while reading')
} else { install(); profileHydration?.commit() }
} else if (engine('cursor')) {
@@ -447,18 +516,18 @@ export function createAttach({
historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)
commandcodeNormalizers.set(session.sessionId, normalizer)
}
+ if (!current()) return false
// Close the old engine's turn before starting the tail: addSession may synchronously deliver a
// new turn written after resume. Closing afterward would abandon that new turn instead.
- const abandonedHistory = !historySuperseded && historyTurnOpen && relaunch?.engineStarted
+ const abandonedHistory = !closes && !historySuperseded && historyTurnOpen && relaunch?.engineStarted
if (abandonedHistory) {
console.log(`[agent] ${sid(session.agentId)} left the turn open at attach as history · it began before its engine was started again`)
const folds: Array<Map<string, { closeTurn(): unknown }>> = [cursorNormalizers, museNormalizers, ampNormalizers,
grokNormalizers, agyNormalizers, copilotNormalizers, piNormalizers, commandcodeNormalizers]
for (const fold of folds) fold.get(session.sessionId)?.closeTurn()
- liveParsers.get(session.sessionId)?.closeTurn('abandoned')
+ const closing = prepared?.state.handle ?? parser ?? liveParsers.get(session.sessionId)
+ closing?.closeTurn('abandoned')
}
- // From this point the installed parser owns the boundary, including the closed-turn checkpoint.
- if (relaunch) relaunchMarks!.complete(session.sessionId, relaunch)
if (session.transcriptPath) {
neverFoldedHistory.delete(session.sessionId)
// Deliberately NOT `fromStart`, even when the caller asked for it: this branch has just folded the
@@ -468,13 +537,35 @@ export function createAttach({
// which folds nothing. A transcript read from its end hands the tail the exact byte it stopped at.
// A held tail is already this session's, and resumes from there when the hold is released.
if (!handover.hold || !watcher.tails(session.sessionId, session.transcriptPath)) {
- await watcher.addSession({ ...session, transcriptPath: session.transcriptPath }, fromEnd ? { fromOffset: fromEnd.next } : {})
+ await watcher.addSession({ ...session, transcriptPath: session.transcriptPath }, {
+ ...(fromEnd ? { fromOffset: fromEnd.next } : {}),
+ ...(session.interpretationHold ? { deliveryAllowed: () => recoveryReady } : {}),
+ })
}
} else if (session.engine !== 'cursor') {
// No transcript to fold: whatever this session writes later is its FIRST content, so the re-attach
// that brings the path must read the file whole rather than from its end.
neverFoldedHistory.add(session.sessionId)
}
+ if (!current()) return false
+ if (session.interpretationHold) {
+ if (closes && fromEnd!.next < closes.at(-1)!.offset) return keepLiveNormalizer('did not reach its cancellation boundary')
+ replacement!.check(recoveryPlan!)
+ // Both parser and tail are installed. Reads held during watcher installation kept their cursors;
+ // resume them only now, after clearing the obligation under the same evidence revision.
+ if (profileHydration?.commitWith) {
+ if (!profileHydration.commitWith(recoveryInstall)) return keepLiveNormalizer('was superseded during watcher installation')
+ } else {
+ if (!recoveryInstall()) return keepLiveNormalizer('was superseded during watcher installation')
+ profileHydration?.commit()
+ }
+ if (!explainRecovery(session)) return keepLiveNormalizer('lost its binding while clearing the hold')
+ if (relaunch) relaunchMarks!.complete(session.sessionId, relaunch)
+ recoveryReady = true
+ void watcher.pollSession(session.sessionId).catch(error => console.warn(
+ `[agent] ${sid(session.agentId)} recovered tail read failed: ${error instanceof Error ? error.message : error}`))
+ }
+ if (!session.interpretationHold && relaunch) relaunchMarks!.complete(session.sessionId, relaunch)
// Marked on the FOLD, not on the emission. A live fold that happened to produce nothing — the file
// was still empty when this attach ran — would otherwise leave the session unmarked, and the next
// `reset` attach (claude fires `SessionStart` on compact, which resets) would fold the by-then
@@ -500,7 +591,7 @@ export function createAttach({
// Nor for a turn left open before a new engine was started on the conversation (a resume, or a restore
// that rebuilt the pane): that turn died with the engine before, and announcing it showed the
// interrupted message starting anew (core/transcripts/relaunch.ts).
- if (!historySuperseded && historyTurnOpen && !handover.hold && !abandonedHistory) {
+ if (!session.interpretationHold && !historySuperseded && historyTurnOpen && !handover.hold && !abandonedHistory) {
const opened = historyEvents.findLast((event) => event.type === 'turn_started')
if (opened) {
console.log(`[agent] ${sid(session.agentId)} resumed the turn already open at attach`)
@@ -523,7 +614,7 @@ export function createAttach({
// A fold from the end keeps only the last turn's start as history (lib/normalize.ts TranscriptFold), so a turn
// that is no longer open is one that ended; a fold from the start keeps its end too, and says if it was killed.
const last = historyEvents.findLast((event) => event.type === 'turn_started' || event.type === 'turn_ended')
- if (!historySuperseded && !historyTurnOpen && last && !(last.type === 'turn_ended' && last.payload.aborted)) settled?.(session.sessionId)
+ if (!historyExplicitlyClosed && !historySuperseded && !historyTurnOpen && last && !(last.type === 'turn_ended' && last.payload.aborted)) settled?.(session.sessionId)
return true
}
@@ -541,9 +632,26 @@ export function createAttach({
replayFromStart = false,
retryCurrent?: () => boolean,
): Promise<boolean> => {
+ // Compaction and ordinary SessionStart also reconstruct parsers. A prior explicit closure still
+ // belongs to this conversation and must survive those resets, not only native-evidence recovery.
+ if (reset && turnReplacements.retains(session) && !session.identityHold && !session.interpretationHold
+ && paneReadIdentity(resolve(session.agentId)) === paneReadIdentity(session)) {
+ if (setInterpretationHold(session.agentId, session.evidenceRevision, 'Reapplying retained turn control.', true)) {
+ session = { ...resolve(session.agentId)! }
+ announceSession(session)
+ } else return Promise.resolve(true)
+ }
+ // An unavailable identity is still the agent's binding, but grants no interpretation authority.
+ // Snapshot the mutable row before yielding so a later bind cannot redirect this read's writes.
+ session = { ...session, interpretationHold: resolve(session.agentId)?.interpretationHold }
const authority = paneReadIdentity(session)
- const current = () => paneReadIdentity(resolve(session.agentId)) === authority
+ const lifetime = lifetimes.get(session.sessionId) ?? {}
+ lifetimes.set(session.sessionId, lifetime)
+ const current = () => lifetimes.get(session.sessionId) === lifetime && paneReadIdentity(resolve(session.agentId)) === authority
if (!current()) return Promise.resolve(false)
+ if (session.identityHold) return Promise.resolve(true)
+ // Every caller observes this obligation, including an ordinary hook racing discovery's reset.
+ if (session.interpretationHold) { reset = true; replayFromStart = false; replayCursorFromStart = false }
readerLoads.supersede(session.sessionId, authority)
// Location is core control, outside the optional reader pool. Four stalled readers must not
// prevent a fifth Cursor session finding its file. add records its candidate synchronously, so
@@ -560,13 +668,42 @@ export function createAttach({
// so delivery resumes into it, in order. Released on every exit, however the attach ends.
const handover = { hold: null as TailHold | null, next: null as number | null }
try {
- return await attachSessionNow(session, current, reset, replayCursorFromStart, replayFromStart, handover)
+ if (session.interpretationHold) {
+ if (!current()) return false
+ // Another queued recovery may already have fulfilled this same obligation.
+ if (!resolve(session.agentId)?.interpretationHold) return true
+ turnReplacements.stage(session)
+ await watcher.removeSession(session.sessionId)
+ if (!current()) return false
+ }
+ const attached = await attachSessionNow(session, current, reset, replayCursorFromStart, replayFromStart, handover)
+ // A hold that arrived during the read is not evidence that the terminal disappeared.
+ return attached || !!resolve(session.agentId)?.identityHold || !!resolve(session.agentId)?.interpretationHold
+ } catch (error) {
+ if (!session.interpretationHold) throw error
+ if (current()) explainRecovery(session, `Waiting for transcript interpretation: ${error instanceof Error ? error.message : error}`)
+ return true
} finally {
handover.hold?.release(handover.next)
+ const obligation = () => {
+ const latest = resolve(session.agentId)
+ return lifetimes.get(session.sessionId) === lifetime && latest?.sessionId === session.sessionId && latest.evidenceRevision === session.evidenceRevision
+ && !latest.identityHold && latest.interpretationHold ? latest : undefined
+ }
+ if (obligation() && !recoveryRetries.has(session.sessionId)) {
+ // One bounded, revision-fenced retry per conversation. An unavailable reader is still work
+ // to do even when its attach returned true to preserve the live binding.
+ recoveryRetries.set(session.sessionId, setTimeout(() => {
+ recoveryRetries.delete(session.sessionId)
+ const latest = obligation()
+ if (latest) void attachSession(latest, true)
+ }, 1_000))
+ recoveryRetries.get(session.sessionId)!.unref()
+ }
}
}, authority)
}
- return { attachSession, attaches, neverFoldedHistory, replayedFirstTurn, forget: readerLoads.forget }
+ return { attachSession, attaches, neverFoldedHistory, replayedFirstTurn, forget, beforeCancel, afterStop, holdStop, holdInterpretation }
}
export type Attach = ReturnType<typeof createAttach>
diff --git a/cli/src/core/transcripts/ingest.spec.ts b/cli/src/core/transcripts/ingest.spec.ts
index 956086f9c..2bcfaed69 100644
--- a/cli/src/core/transcripts/ingest.spec.ts
+++ b/cli/src/core/transcripts/ingest.spec.ts
@@ -86,6 +86,16 @@ describe('ingesting a transcript line', () => {
expect(deps.tokenUsage.changed).not.toHaveBeenCalled()
})
+ it('defers live interpretation, usage and profile effects while a saved binding is held', () => {
+ const run = setup({ s1: 'claude' })
+ run.sessions.get('s1')!.identityHold = 'header unavailable'
+ expect(run.ingest.ingestLine(line('s1', 'claude', CLAUDE_PROMPT))).toBeNull()
+ expect(run.normalizers.hasState('s1')).toBe(false)
+ expect(run.deps.tokenUsage.changed).not.toHaveBeenCalled()
+ expect(run.deps.runtimeProfiles.ingest).not.toHaveBeenCalled()
+ expect(run.service.needsTranscript).not.toHaveBeenCalled()
+ })
+
it('counts tokens, shows the device its raw lines when it asks, and reads the runtime from each line', () => {
const { ingest, deps, service, sessions } = setup({ s1: 'claude' })
ingest.ingestLine(line('s1', 'claude', CLAUDE_PROMPT))
diff --git a/cli/src/core/transcripts/ingest.ts b/cli/src/core/transcripts/ingest.ts
index a6988631e..b3ba8f293 100644
--- a/cli/src/core/transcripts/ingest.ts
+++ b/cli/src/core/transcripts/ingest.ts
@@ -50,7 +50,7 @@ export function createIngest({
const observeLine = (evt: Pick<LineEvent, 'sessionId' | 'engine' | 'text'>, profileAccepted = false): RegisteredSession | null => {
if (!has(evt.sessionId)) return null // scope to terminal-registered sessions
const session = bySession(evt.sessionId)
- if (!session || session.engine !== evt.engine) return null
+ if (!session || session.identityHold || session.interpretationHold || session.engine !== evt.engine) return null
tokenUsage.changed(session)
sideRead('device', evt.sessionId, () => {
const service = device()
diff --git a/cli/src/core/transcripts/readIdentity.spec.ts b/cli/src/core/transcripts/readIdentity.spec.ts
index 783cd0cd9..3c8ac77f3 100644
--- a/cli/src/core/transcripts/readIdentity.spec.ts
+++ b/cli/src/core/transcripts/readIdentity.spec.ts
@@ -15,6 +15,7 @@ it('copies binding identity before yielding, ignoring ordinary activity updates'
expect(transcriptReadIdentity({ ...session, processIdentity: { ...session.processIdentity!, pid: 8 } })).not.toBe(before)
expect(transcriptReadIdentity({ ...session, processIdentity: { ...session.processIdentity!, startMarker: 'two' } })).not.toBe(before)
expect(transcriptReadIdentity({ ...session, processIdentity: null })).not.toBe(before)
+ expect(transcriptReadIdentity({ ...session, identityHold: 'header incomplete' })).not.toBe(before)
})
it('keeps a Linux process bound across a wall-clock correction, but rejects pid reuse', () => {
@@ -26,3 +27,12 @@ it('keeps a Linux process bound across a wall-clock correction, but rejects pid
session.processIdentity!.startTicks = 43
expect(transcriptReadIdentity(session)).not.toBe(before)
})
+
+it('revokes old reads across a complete same-path hold and recovery', () => {
+ const session = { agentId: 'a', sessionId: 's', engine: 'claude', transcriptPath: '/t' } as RegisteredSession
+ const before = transcriptReadIdentity(session)
+ session.identityHold = 'header incomplete'; session.evidenceRevision = 1
+ expect(transcriptReadIdentity(session)).not.toBe(before)
+ delete session.identityHold; session.evidenceRevision = 2
+ expect(transcriptReadIdentity(session)).not.toBe(before)
+})
diff --git a/cli/src/core/transcripts/readIdentity.ts b/cli/src/core/transcripts/readIdentity.ts
index cee5abda5..6247d7d00 100644
--- a/cli/src/core/transcripts/readIdentity.ts
+++ b/cli/src/core/transcripts/readIdentity.ts
@@ -5,7 +5,9 @@ import { processIdentityKey } from '../../lib/terminalRuntime.js'
export function transcriptReadIdentity(session: RegisteredSession | undefined): string {
return session ? JSON.stringify([session.agentId, session.sessionId, session.engine, session.transcriptPath,
session.codexHome, session.boundAt,
- session.processIdentity ? processIdentityKey(session.engine, session.processIdentity) : undefined]) : ''
+ session.processIdentity ? processIdentityKey(session.engine, session.processIdentity) : undefined,
+ ...(session.identityHold ? ['identity-held'] : []),
+ ...(session.evidenceRevision === undefined ? [] : [session.evidenceRevision])]) : ''
}
/** A pane belongs to its process, conversation and current terminal routes. Copy before capture. */
diff --git a/cli/src/core/transcripts/turnReplacement.spec.ts b/cli/src/core/transcripts/turnReplacement.spec.ts
new file mode 100644
index 000000000..f03560bc1
--- /dev/null
+++ b/cli/src/core/transcripts/turnReplacement.spec.ts
@@ -0,0 +1,98 @@
+import { appendFileSync, mkdtempSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { LiveState } from '../../engines/facets/live.js'
+import { createSessionNormalizers } from './normalizers.js'
+import { createTurnReplacements } from './turnReplacement.js'
+import * as transcriptBoundary from '../../lib/transcriptBoundary.js'
+
+const dirs: string[] = []
+const setup = (file = true) => {
+ const dir = mkdtempSync(join(tmpdir(), 'replacement-control-')); dirs.push(dir)
+ const transcriptPath = join(dir, 'session.jsonl'); writeFileSync(transcriptPath, '{}\n')
+ const session = { agentId: 'agent', engine: 'claude', sessionId: 'session', transcriptPath: file ? transcriptPath : null } as RegisteredSession
+ const normalizers = createSessionNormalizers(), replacements = createTurnReplacements(normalizers)
+ return { session, normalizers, replacements }
+}
+const parser = (): LiveState => ({ engine: 'claude', turnOpen: true,
+ snapshot: () => ({ identity: 'old-turn', turnOpen: true, continued: true }), closeTurn: vi.fn() })
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); vi.restoreAllMocks() })
+
+it('retains exact ordered cancellation boundaries through retries without closing the replacement turn', () => {
+ const { session, normalizers, replacements } = setup(), old = parser(), next = parser()
+ normalizers.liveParsers.set(session.sessionId, old)
+ const pending = replacements.stage(session), initial = pending.plan()
+ expect(pending.handle.snapshot()).toEqual(old.snapshot())
+ pending.handle.closeTurn('cancel')
+ expect(pending.handle.turnOpen).toBe(false)
+ expect(() => pending.commit(initial, next)).toThrow('control changed')
+ expect(pending.plan().closes.map(close => close.offset)).toEqual([3])
+ expect(replacements.stage(session)).toBe(pending)
+ pending.handle.closeTurn('cancel')
+ expect(pending.plan().closes).toHaveLength(1)
+ appendFileSync(session.transcriptPath!, '{}\n')
+ pending.handle.closeTurn('cancel')
+ const plan = pending.plan()
+ expect(plan.closes.map(close => close.offset)).toEqual([3, 6])
+ expect(pending.commit(plan, next)).toBe(true)
+ expect(normalizers.liveParsers.get(session.sessionId)).toBe(next)
+ expect(next.closeTurn).not.toHaveBeenCalled()
+ expect(pending.commit(plan, next)).toBe(false)
+})
+it.each(['hook', 'abandoned', 'stop'] as const)('retains uncorrelated %s even when a cold parser has no open turn', reason => {
+ const { session, normalizers, replacements } = setup(), pending = replacements.stage(session)
+ expect(pending.handle.snapshot()).toMatchObject({ turnOpen: false, continued: false })
+ if (reason === 'stop') pending.stop(); else pending.handle.closeTurn(reason)
+ expect(() => pending.commit(pending.plan())).toThrow('Stop could not be matched')
+ pending.handle.closeTurn('cancel')
+ expect(pending.commit(pending.plan())).toBe(true)
+ expect(normalizers.liveParsers.size).toBe(0)
+})
+it.each(['replace', 'truncate', 'prefix', 'partial', 'missing', 'no-file'] as const)('holds %s evidence without advancing the recorded boundary', kind => {
+ const { session, replacements } = setup(kind !== 'no-file'), pending = replacements.stage(session)
+ if (kind === 'partial') writeFileSync(session.transcriptPath!, '{')
+ pending.handle.closeTurn('cancel')
+ if (kind === 'replace') { renameSync(session.transcriptPath!, session.transcriptPath! + '.old'); writeFileSync(session.transcriptPath!, '{}\n') }
+ if (kind === 'truncate') writeFileSync(session.transcriptPath!, '')
+ if (kind === 'prefix') writeFileSync(session.transcriptPath!, '[]\n')
+ if (kind === 'missing') renameSync(session.transcriptPath!, session.transcriptPath! + '.old')
+ expect(() => pending.plan()).toThrow()
+ if (kind === 'truncate') { pending.handle.closeTurn('cancel'); expect(pending.plan().closes.map(close => close.offset)).toEqual([0]) }
+})
+it('bounds retained control work without throwing through eager cancellation', () => {
+ const { session, replacements } = setup(), pending = replacements.stage(session)
+ for (let i = 0; i <= 128; i++) { pending.handle.closeTurn('cancel'); appendFileSync(session.transcriptPath!, '{}\n') }
+ expect(() => pending.plan()).toThrow('too many')
+})
+it('revokes forgotten, rebound and replaced interpretation without closing another parser', () => {
+ const { session, normalizers, replacements } = setup()
+ const first = replacements.stage(session), next = parser()
+ normalizers.liveParsers.set(session.sessionId, next)
+ expect(first.commit(first.plan(), next)).toBe(false)
+ const second = replacements.stage(session)
+ expect(second).toBe(first)
+ const third = replacements.stage({ ...session, transcriptPath: null })
+ expect(third).toBe(second)
+ replacements.forget(session.sessionId)
+ expect(third.commit(third.plan(), next)).toBe(false)
+ expect(next.closeTurn).not.toHaveBeenCalled()
+})
+
+it('contains a non-Error filesystem failure while eagerly closing the turn', () => {
+ const { session, replacements } = setup(), pending = replacements.stage(session)
+ vi.spyOn(transcriptBoundary, 'recoveryBoundary').mockImplementationOnce(() => { throw 'file service unavailable' })
+ expect(() => pending.handle.closeTurn('cancel')).not.toThrow()
+ expect(pending.handle.turnOpen).toBe(false)
+ expect(() => pending.plan()).toThrow('file service unavailable')
+})
+it('retains a completed control record when its installed parser is later absent', () => {
+ const { session, normalizers, replacements } = setup(), pending = replacements.stage(session)
+ pending.handle.closeTurn('cancel')
+ expect(pending.commit(pending.plan())).toBe(true)
+ expect(normalizers.liveParsers.has(session.sessionId)).toBe(false)
+ expect(replacements.stage(session)).toBe(pending)
+ expect(pending.handle.turnOpen).toBe(false)
+ expect(pending.plan().closes).toHaveLength(1)
+})
diff --git a/cli/src/core/transcripts/turnReplacement.ts b/cli/src/core/transcripts/turnReplacement.ts
new file mode 100644
index 000000000..16639f212
--- /dev/null
+++ b/cli/src/core/transcripts/turnReplacement.ts
@@ -0,0 +1,119 @@
+import type { LiveState } from '../../engines/facets/live.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { recoveryBoundary, type RecoveryBoundary } from '../../lib/transcriptBoundary.js'
+import type { TranscriptClose } from '../../lib/transcriptControls.js'
+import type { SessionNormalizers } from './normalizers.js'
+
+export interface ReplacementPlan { readonly revision: number; readonly closes: readonly TranscriptClose[] }
+
+/** Control remains eager while interpretation is replaced. A cancellation is replayed at its original
+ * file boundary, never against whichever turn a later retry happens to hydrate. Uncorrelated Stop
+ * intent remains visible until native evidence can resolve it. */
+export function createTurnReplacements(normalizers: Pick<SessionNormalizers, 'liveParsers' | 'sessionTurnState'>) {
+ const pending = new Map<string, ReturnType<typeof create>>()
+ let generation = 0
+ const create = (session: RegisteredSession, active = true) => {
+ const id = session.sessionId
+ const binding = JSON.stringify([session.agentId, id, session.engine])
+ let transcriptPath = session.transcriptPath
+ let state = normalizers.liveParsers.get(id)?.snapshot()
+ ?? { identity: `held:${++generation}`, turnOpen: normalizers.sessionTurnState(id) ?? false, continued: false }
+ let revision = 0, stopRevision = 0, cancelRevision = 0, failure: string | undefined
+ const boundaries: RecoveryBoundary[] = []
+ const verify = (): void => {
+ if (failure) throw new Error(failure)
+ for (const boundary of boundaries) recoveryBoundary(transcriptPath!, boundary)
+ }
+ const stop = (): void => { stopRevision = ++revision }
+ const handle: LiveState = {
+ engine: session.engine,
+ get turnOpen() { return state.turnOpen },
+ snapshot: () => ({ ...state }),
+ closeTurn(reason) {
+ state = { ...state, turnOpen: false }
+ revision++
+ if (reason !== 'cancel') { stop(); return }
+ try {
+ if (!transcriptPath) throw new Error('the native store has no file cancellation boundary')
+ const boundary = recoveryBoundary(transcriptPath)
+ const last = boundaries.at(-1)
+ // A new explicit cancellation also closes the current incarnation after a rewrite. This is
+ // a new control decision, never a retry moving the old decision to a more convenient EOF.
+ if (last) {
+ try { recoveryBoundary(transcriptPath, last) }
+ catch { boundaries.length = 0 }
+ }
+ const current = boundaries.at(-1)
+ if (current?.offset === boundary.offset) { recoveryBoundary(transcriptPath, current); cancelRevision = revision; failure = undefined; return }
+ if (boundaries.length === 128) throw new Error('too many unresolved cancellation boundaries')
+ boundaries.push(boundary)
+ cancelRevision = revision
+ failure = undefined
+ } catch (error) { failure = error instanceof Error ? error.message : String(error) }
+ },
+ }
+ const replacement = {
+ binding, handle, stop,
+ cancel(path: RegisteredSession['transcriptPath']): string | undefined {
+ transcriptPath = path
+ handle.closeTurn('cancel')
+ return failure
+ },
+ activate(path: RegisteredSession['transcriptPath']): void {
+ if (!active) {
+ state = normalizers.liveParsers.get(id)?.snapshot()
+ ?? { ...state, turnOpen: normalizers.sessionTurnState(id) ?? state.turnOpen }
+ active = true; revision++
+ }
+ if (path !== transcriptPath) { transcriptPath = path; revision++ }
+ normalizers.liveParsers.set(id, handle)
+ },
+ plan(): ReplacementPlan {
+ verify()
+ return { revision, closes: boundaries.map(boundary => ({ offset: boundary.offset, reason: 'cancel', boundary: { ...boundary } })) }
+ },
+ check(plan: ReplacementPlan): void {
+ if (revision !== plan.revision) throw new Error('turn control changed while interpretation was being prepared')
+ verify()
+ // Even a naturally closed fold may predate this Stop's opener. Only a later explicit cancel
+ // supersedes uncorrelated completion intent; parser availability does not grant that authority.
+ if (stopRevision > cancelRevision) throw new Error('Stop could not be matched to its turn; Cancel can resolve this hold')
+ },
+ commit(plan: ReplacementPlan, next?: LiveState): boolean {
+ if (!active || pending.get(id) !== replacement || normalizers.liveParsers.get(id) !== handle) return false
+ replacement.check(plan)
+ active = false
+ if (!boundaries.length && !stopRevision) pending.delete(id)
+ if (next) normalizers.liveParsers.set(id, next)
+ else normalizers.liveParsers.delete(id)
+ return true
+ },
+ }
+ if (active) normalizers.liveParsers.set(id, handle)
+ return replacement
+ }
+ const stage = (session: RegisteredSession) => {
+ const previous = pending.get(session.sessionId)
+ if (previous && previous.binding === JSON.stringify([session.agentId, session.sessionId, session.engine])) {
+ previous.activate(session.transcriptPath)
+ return previous
+ }
+ const replacement = create(session)
+ pending.set(session.sessionId, replacement)
+ return replacement
+ }
+ const remember = (session: RegisteredSession) => {
+ let record = pending.get(session.sessionId)
+ if (record?.binding !== JSON.stringify([session.agentId, session.sessionId, session.engine])) {
+ record = create(session, false)
+ pending.set(session.sessionId, record)
+ }
+ return record
+ }
+ return { stage,
+ retains: (session: RegisteredSession) => pending.get(session.sessionId)?.binding === JSON.stringify([session.agentId, session.sessionId, session.engine]),
+ cancel: (session: RegisteredSession) => remember(session).cancel(session.transcriptPath),
+ stop: (session: RegisteredSession) => remember(session).stop(),
+ forget: (sessionId: string) => { pending.delete(sessionId) },
+ }
+}
diff --git a/cli/src/core/turns/cancel.ts b/cli/src/core/turns/cancel.ts
index 06a41c777..e9f2a94ad 100644
--- a/cli/src/core/turns/cancel.ts
+++ b/cli/src/core/turns/cancel.ts
@@ -17,6 +17,7 @@ import type { SessionNormalizers } from '../transcripts/normalizers.js'
export interface CancelDeps {
resolve: (id: string) => RegisteredSession | undefined
+ beforeCancel?: (session: RegisteredSession) => void
normalizers: Pick<SessionNormalizers, 'closeTurns'>
cursorSubagents: Pick<CursorSubagentManager, 'forget'>
input: Pick<SessionInputController, 'cancel' | 'cancelConfirmed'>
@@ -35,7 +36,7 @@ export interface CancelDeps {
export function createCancel({
resolve, normalizers, cursorSubagents, input, device, stopHeartbeat, questionWatcher, mirror, turnActivity, turnStartedAt,
- agentIdFor, clients,
+ agentIdFor, clients, beforeCancel,
}: CancelDeps) {
// Web cancel (C-c) interrupts the turn — claude writes no end_turn line to close it, so stop the
// heartbeat and mark the turn closed here (mirrors the hosted runtime stopping its heartbeat on cancel). We do
@@ -44,6 +45,7 @@ export function createCancel({
const cancelAgent = (id: string, confirmed = false): Promise<boolean> => {
const record = resolve(id)
const sessionId = record?.sessionId ?? id
+ if (record) beforeCancel?.(record)
normalizers.closeTurns(sessionId)
cursorSubagents.forget(sessionId)
const cancelled = confirmed ? input.cancelConfirmed(record?.agentId ?? sessionId) : (input.cancel(record?.agentId ?? sessionId), Promise.resolve(true))
diff --git a/cli/src/core/turns/turnHooks.spec.ts b/cli/src/core/turns/turnHooks.spec.ts
index 898808eb6..9c5669e37 100644
--- a/cli/src/core/turns/turnHooks.spec.ts
+++ b/cli/src/core/turns/turnHooks.spec.ts
@@ -450,3 +450,78 @@ describe('turn hooks', () => {
expect(error.mock.calls).toEqual([['[hooks] claude stop hook failed:', 'tail gone'], ['[hooks] claude stop hook failed:', 'worse']])
})
})
+
+it.each([
+ ['cursor', 'tasks'], ['cursor', 'drain1'], ['commandcode', 'drain1'], ['commandcode', 'grace'], ['commandcode', 'drain2'],
+ ['copilot', 'drain1'], ['copilot', 'grace'], ['copilot', 'drain2'], ['agy', 'drain1'], ['agy', 'grace'], ['agy', 'drain2'],
+ ['devin', 'grace'], ['grok', 'drain1'], ['claude', 'drain1'], ['claude', 'grace'], ['claude', 'drain2'],
+])('retains %s Stop intent when evidence changes during %s', async (engine, phase) => {
+ vi.useFakeTimers()
+ const row = { agentId: 'a1', sessionId: 's1', engine, evidenceRevision: 0 } as RegisteredSession
+ const holdStop = vi.fn(() => true), run = setup(engine, { resolve: () => row, holdStop })
+ const state = engineState()
+ const maps = { cursor: run.normalizers.cursorNormalizers, commandcode: run.normalizers.commandcodeNormalizers,
+ copilot: run.normalizers.copilotNormalizers, agy: run.normalizers.agyNormalizers,
+ devin: run.normalizers.devinReaders, grok: run.normalizers.grokNormalizers }
+ if (engine === 'claude') setState(run, { turnOpen: true, pendingTools: new Set(), toolIdToName: new Map(), thinkingCounter: 0 })
+ else (maps[engine as keyof typeof maps] as Map<string, unknown>).set('s1', state)
+ let release!: () => void
+ const pending = () => new Promise<void>(resolve => { release = resolve })
+ if (phase === 'tasks') vi.mocked(run.deps.cursorTaskHooks.wait).mockImplementationOnce(pending)
+ else if (phase === 'drain1') vi.mocked(run.deps.drain).mockImplementationOnce(pending)
+ else if (phase === 'drain2') vi.mocked(run.deps.drain).mockResolvedValueOnce(undefined).mockImplementationOnce(pending)
+ run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })
+ await vi.advanceTimersByTimeAsync(phase === 'drain2' ? STOP_HOOK_GRACE_MS : 0)
+ row.evidenceRevision = 2 // A full hold and recovery can finish before the old callback resumes.
+ if (phase === 'grace') await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)
+ else { release(); await vi.advanceTimersByTimeAsync(0) }
+ expect(holdStop).toHaveBeenCalledWith(row, true)
+ expect(state.closeTurn).not.toHaveBeenCalled()
+ expect(state.abortTurn).not.toHaveBeenCalled()
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ expect(run.deps.announceTurnAborted).not.toHaveBeenCalled()
+ expect(run.deps.cursorSubagents.closeParent).not.toHaveBeenCalled()
+ vi.useRealTimers()
+})
+
+it.each(['cursor', 'commandcode', 'copilot', 'agy', 'devin', 'grok'])('holds %s completion eagerly before any optional drain', engine => {
+ const row = { agentId: 'a1', sessionId: 's1', engine, interpretationHold: 'pending' } as RegisteredSession
+ const holdStop = vi.fn(() => true), run = setup(engine, { resolve: () => row, holdStop })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ expect(holdStop).toHaveBeenCalledOnce()
+ expect(run.deps.drain).not.toHaveBeenCalled()
+ expect(run.deps.emit).not.toHaveBeenCalled()
+})
+
+it('rejects delayed engine emissions after its binding changes, even if the hold port rejects stale work', () => {
+ let context!: HookTurnContext
+ const spy = vi.spyOn(engineHooks.claude, 'onStop').mockImplementationOnce(value => { context = value })
+ try {
+ const row = { agentId: 'a1', sessionId: 's1', engine: 'claude', evidenceRevision: 0 } as RegisteredSession
+ const holdStop = vi.fn(() => false), run = setup('claude', { resolve: () => row, holdStop })
+ run.hooks.onTurnStop({ sessionId: 's1' })
+ row.evidenceRevision = 2
+ context.emit('s1', [{ type: 'turn_ended', payload: {} }])
+ expect(holdStop).toHaveBeenCalledWith(row, true)
+ expect(run.deps.emit).not.toHaveBeenCalled()
+ } finally { spy.mockRestore() }
+})
+
+it.each([
+ ['cursor', 'error'], ['commandcode', undefined], ['devin', undefined], ['grok', 'error'],
+ ['copilot', 'error'], ['copilot', undefined], ['agy', 'error'], ['agy', undefined],
+])('retains successful native %s completion (status=%s) without waiting for a reader', async (engine, status) => {
+ vi.useFakeTimers()
+ try {
+ const afterStop = vi.fn(), run = setup(engine!, { afterStop }), state = engineState()
+ const maps = { cursor: run.normalizers.cursorNormalizers, commandcode: run.normalizers.commandcodeNormalizers,
+ devin: run.normalizers.devinReaders, grok: run.normalizers.grokNormalizers,
+ copilot: run.normalizers.copilotNormalizers, agy: run.normalizers.agyNormalizers }
+ ;(maps[engine as keyof typeof maps] as Map<string, unknown>).set('s1', state)
+ run.hooks.onTurnStop({ sessionId: 's1', status })
+ await vi.runAllTimersAsync()
+ expect(afterStop).toHaveBeenCalledOnce()
+ expect(afterStop).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 's1', engine }))
+ expect(state.turnOpen).toBe(false)
+ } finally { vi.useRealTimers() }
+})
diff --git a/cli/src/core/turns/turnHooks.ts b/cli/src/core/turns/turnHooks.ts
index 40aa742f0..0e0caa554 100644
--- a/cli/src/core/turns/turnHooks.ts
+++ b/cli/src/core/turns/turnHooks.ts
@@ -28,6 +28,8 @@ export const STOP_HOOK_GRACE_MS = 1_500
const PROMPT_HOOKS_KEPT = 512
export interface TurnHookDeps {
+ holdStop?: (session: RegisteredSession, force?: boolean) => boolean
+ afterStop?: (session: RegisteredSession) => void
resolve: (id: string) => RegisteredSession | undefined
normalizers: SessionNormalizers
emit: (sessionId: string, events: LiveEvent[]) => void
@@ -45,7 +47,7 @@ export interface TurnHookDeps {
export function createTurnHooks({
resolve, normalizers, emit, drain, onCursorTaskStart, cursorTaskHooks, cursorSubagents, announceTurnAborted,
- armAgyIdleWatch, clearAgyIdleWatch, mirror, dataDir,
+ armAgyIdleWatch, clearAgyIdleWatch, mirror, dataDir, holdStop, afterStop,
}: TurnHookDeps) {
const { liveParsers, commandcodeNormalizers, cursorNormalizers, devinReaders, copilotNormalizers, agyNormalizers, grokNormalizers } = normalizers
// Command Code's PreToolUse — the one live "a turn is running" signal this engine has. Without it the
@@ -76,6 +78,7 @@ export function createTurnHooks({
const parser = liveParsers.get(sessionId)
if (!parser || parser.engine !== resolve(sessionId)?.engine || parser.snapshot().identity !== identity) return false
parser.closeTurn('hook')
+ afterStop?.(resolve(sessionId)!)
return true
},
latestPromptAt: (sessionId) => promptFiredAt.get(sessionId),
@@ -90,23 +93,54 @@ export function createTurnHooks({
const onTurnStop = ({ sessionId, status, firedAt }: { sessionId: string; status?: string; firedAt?: number }): void => {
const session = resolve(sessionId)
if (!session) return
+ const authority = JSON.stringify([session.agentId, session.sessionId, session.engine, session.transcriptPath,
+ session.evidenceRevision, session.identityHold])
+ const binding = JSON.stringify([session.agentId, session.sessionId, session.engine])
+ let retained = false
+ const current = (): boolean => {
+ const latest = resolve(sessionId)
+ if (!latest || JSON.stringify([latest.agentId, latest.sessionId, latest.engine]) !== binding) return false
+ const changed = authority !== JSON.stringify([latest.agentId, latest.sessionId, latest.engine, latest.transcriptPath,
+ latest.evidenceRevision, latest.identityHold])
+ if ((latest.identityHold || latest.interpretationHold || changed) && holdStop) {
+ // Claude already supplies positive stale-event evidence. A hold does not turn a proven old
+ // Stop into an unknown completion that would require cancelling the newer turn.
+ if (session.engine === 'claude' && firedAt !== undefined && (promptFiredAt.get(sessionId) ?? 0) > firedAt) return false
+ if (!retained) retained = holdStop(latest, changed)
+ if (retained) return false
+ }
+ return !changed
+ }
+ // Waiting is explicitly not a completion: preserve agy's eager backstop signal.
+ if (session.engine === 'agy' && status === 'waiting') { armAgyIdleWatch(sessionId); return }
const hooks = hooksFor(session.engine)
if (hooks) {
+ if (!hooks.onStop || !current()) return
// Invoke synchronously: the engine snapshots which turn the hook arrived about before draining.
const failed = (error: unknown): void => {
console.error(`[hooks] ${session.engine} stop hook failed:`, error instanceof Error ? error.message : error)
}
- try { void Promise.resolve(hooks.onStop?.(hookTurns, { sessionId, status, firedAt })).catch(failed) } catch (error) { failed(error) }
+ const context: HookTurnContext = { ...hookTurns,
+ turnState: id => current() ? hookTurns.turnState(id) : undefined,
+ closeTurn: (id, identity) => current() && hookTurns.closeTurn(id, identity),
+ noteEngineStopped: id => { if (current()) hookTurns.noteEngineStopped(id) },
+ emit: (id, events) => { if (current()) emit(id, events) },
+ }
+ try { void Promise.resolve(hooks.onStop(context, { sessionId, status, firedAt })).catch(failed) } catch (error) { failed(error) }
return
}
+ if (!current()) return
if (session.engine === 'cursor') {
void (async () => {
await cursorTaskHooks.wait(sessionId)
+ if (!current()) return
await drain(sessionId)
+ if (!current()) return
const normalizer = cursorNormalizers.get(sessionId)
if (!normalizer) return
cursorSubagents.closeParent(sessionId, status === 'error')
const closing = normalizer.closeTurn()
+ afterStop?.(session)
emit(sessionId, closing)
// Cursor can fail a turn BEFORE it writes anything to the transcript — observed as a Stop hook
// with status=error 2.4s after beforeSubmitPrompt, with no transcript file discovered and no
@@ -130,12 +164,16 @@ export function createTurnHooks({
if (session.engine === 'commandcode') {
void (async () => {
await drain(sessionId)
+ if (!current()) return
const normalizer = commandcodeNormalizers.get(sessionId)
if (!normalizer?.turnOpen) return
await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ if (!current()) return
await drain(sessionId)
+ if (!current()) return
if (!normalizer.turnOpen) return
normalizer.closeTurn()
+ afterStop?.(session)
console.log(`[turn] ${sid(sessionId)} force-closed by Stop hook (after grace)`)
emit(sessionId, [{ type: 'turn_ended', payload: {} }])
})().catch((err) => {
@@ -150,8 +188,10 @@ export function createTurnHooks({
const reader = devinReaders.get(sessionId)
if (!reader?.turnOpen) return
await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ if (!current()) return
if (!reader.turnOpen) return
reader.closeTurn()
+ afterStop?.(session)
console.log(`[turn] ${sid(sessionId)} force-closed by Stop hook (after grace)`)
emit(sessionId, [{ type: 'turn_ended', payload: {} }])
})().catch((err) => {
@@ -164,18 +204,25 @@ export function createTurnHooks({
if (session.engine === 'copilot') {
void (async () => {
await drain(sessionId)
+ if (!current()) return
const normalizer = copilotNormalizers.get(sessionId)
if (!normalizer?.turnOpen) return
await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ if (!current()) return
await drain(sessionId)
+ if (!current()) return
if (!normalizer.turnOpen) return
if (status === 'error') {
announceTurnAborted(sessionId, 'copilot', 'Copilot ended the turn early')
- emit(sessionId, normalizer.abortTurn())
+ const closing = normalizer.abortTurn()
+ afterStop?.(session)
+ emit(sessionId, closing)
return
}
console.log(`[turn] ${sid(sessionId)} closed by copilot agentStop hook (after grace)`)
- emit(sessionId, normalizer.closeTurn())
+ const closing = normalizer.closeTurn()
+ afterStop?.(session)
+ emit(sessionId, closing)
})().catch((err) => {
console.error('[hooks] copilot stop hook failed:', err instanceof Error ? err.message : err)
})
@@ -188,25 +235,28 @@ export function createTurnHooks({
// `waiting` = agy's loop stopped only because it is standing by for its sub-agents. The turn is
// NOT over, so nothing closes here — but the run that proved this necessary also finished its
// sub-agents and then never sent another Stop, so a backstop watches the pane instead.
- if (status === 'waiting') {
- armAgyIdleWatch(sessionId)
- return
- }
clearAgyIdleWatch(sessionId)
void (async () => {
await drain(sessionId)
+ if (!current()) return
const normalizer = agyNormalizers.get(sessionId)
if (!normalizer?.turnOpen) return
await new Promise((r) => setTimeout(r, STOP_HOOK_GRACE_MS))
+ if (!current()) return
await drain(sessionId)
+ if (!current()) return
if (!normalizer.turnOpen) return
if (status === 'error') {
announceTurnAborted(sessionId, 'agy', 'agy ended the turn early')
- emit(sessionId, normalizer.abortTurn())
+ const closing = normalizer.abortTurn()
+ afterStop?.(session)
+ emit(sessionId, closing)
return
}
console.log(`[turn] ${sid(sessionId)} closed by agy Stop hook (after grace)`)
- emit(sessionId, normalizer.closeTurn())
+ const closing = normalizer.closeTurn()
+ afterStop?.(session)
+ emit(sessionId, closing)
})().catch((err) => {
console.error('[hooks] agy stop hook failed:', err instanceof Error ? err.message : err)
})
@@ -215,10 +265,13 @@ export function createTurnHooks({
if (session.engine === 'grok') {
void (async () => {
await drain(sessionId)
+ if (!current()) return
const normalizer = grokNormalizers.get(sessionId)
if (status === 'error') {
announceTurnAborted(sessionId, 'grok', 'Grok ended the turn with an error')
- emit(sessionId, normalizer?.abortTurn() ?? [])
+ const closing = normalizer?.abortTurn() ?? []
+ afterStop?.(session)
+ emit(sessionId, closing)
}
})().catch((err) => {
console.error('[hooks] grok StopFailure hook failed:', err instanceof Error ? err.message : err)
diff --git a/cli/src/engines/kit/nativeFiles.ts b/cli/src/engines/kit/nativeFiles.ts
new file mode 100644
index 000000000..28219db2c
--- /dev/null
+++ b/cli/src/engines/kit/nativeFiles.ts
@@ -0,0 +1,151 @@
+/** Fresh synchronous file evidence for eager binding; each instance belongs to one operation. */
+import { closeSync, constants, fstatSync, lstatSync, openSync, opendirSync, readSync, type BigIntStats } from 'node:fs'
+import { dirname } from 'node:path'
+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'
+
+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 }
+
+export class NativeFiles {
+ readonly paths: NativePaths
+ private readonly reads = new Map<string, Read>()
+ private readonly directories = new Map<string, string>()
+ private entriesLeft = 4096
+ constructor(readonly budget = new NativeEvidenceBudget(250)) { this.paths = new NativePaths(budget) }
+
+ locate(path: string, missingOkay = false): Location | null {
+ return this.paths.resolveSync(path, missingOkay)
+ }
+
+ /** A readable regular file, tied to the path that was inspected, even for an empty file. */
+ file(path: string, missingOkay = false): Location | null {
+ const location = this.locate(path, missingOkay)
+ if (!location) return null
+ this.read(location, 1)
+ if (!this.reads.has(location.path)) this.reads.set(location.path, { location, limit: 1 })
+ return location
+ }
+
+ header(path: string, first: NativeFirstRecord) {
+ const location = this.locate(path)!
+ try {
+ const line = firstLine(this.read(location, first.maxBytes + 1), first.maxBytes)
+ const meta = nativeSessionMeta(line, first)
+ const earlier = this.reads.get(location.path)
+ if (earlier?.line !== undefined && earlier.line !== line) return nativeUnavailable('the binding header changed during inspection')
+ this.reads.set(location.path, { location, limit: first.maxBytes + 1, line })
+ return meta
+ } catch (error) {
+ if (error instanceof IdentityReadUnavailable) throw error
+ return nativeUnavailable('the binding header could not be read completely')
+ }
+ }
+
+ private read(location: Location, limit: number): Buffer {
+ this.budget.step()
+ let fd: number | undefined
+ try {
+ fd = openSync(location.path, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW)
+ const before = fstatSync(fd, { bigint: true })
+ if (!before.isFile() || nativeFileKey(before) !== nativeFileKey(location.info)
+ || (typeof process.getuid === 'function' && before.uid !== BigInt(process.getuid()))) {
+ return nativeUnavailable('the binding file has an unconfirmed identity, owner or type')
+ }
+ const bytes = Buffer.alloc(Math.min(Number(before.size), limit))
+ let length = 0
+ for (let calls = 0; length < bytes.length; calls++) {
+ this.budget.step()
+ if (calls >= 64) return nativeUnavailable('the binding file read-operation limit was reached')
+ const count = readSync(fd, bytes, length, bytes.length - length, length)
+ this.budget.step(count)
+ if (!count) return nativeUnavailable('the binding file ended during its read')
+ length += count
+ }
+ if (stamp(fstatSync(fd, { bigint: true })) !== stamp(before)) return nativeUnavailable('the binding file changed during its read')
+ return bytes
+ } catch (error) {
+ if (error instanceof IdentityReadUnavailable) throw error
+ return nativeUnavailable('the binding file could not be read')
+ } finally {
+ if (fd !== undefined) { try { closeSync(fd) } catch { nativeUnavailable('the binding file could not be closed') } }
+ }
+ }
+
+ /** Guard the iterator's acquisition too: an ancestor can move away and back around opendir.
+ * Content stamps on ancestors last only for this enumeration, not the entire pool lookup. */
+ private directoryRoute(path: string): Map<string, string> {
+ const result = new Map<string, string>()
+ for (let part = path;; part = dirname(part)) {
+ this.budget.step()
+ let info: BigIntStats
+ try { info = lstatSync(part, { bigint: true }) }
+ catch { return nativeUnavailable('a binding directory ancestor could not be inspected') }
+ if (!info.isDirectory()) return nativeUnavailable('a binding directory ancestor changed type')
+ result.set(part, stamp(info))
+ if (part === dirname(part)) return result
+ }
+ }
+
+ entries(path: string, missingOkay = false): string[] {
+ this.budget.step()
+ if (--this.entriesLeft < 0) return nativeUnavailable('the binding directory entry limit was reached')
+ const location = this.locate(path, missingOkay)
+ if (!location) return []
+ if (!location.info.isDirectory()) return nativeUnavailable('a binding session directory is not a directory')
+ const route = this.directoryRoute(location.path)
+ let before: BigIntStats
+ try { before = lstatSync(location.path, { bigint: true }) }
+ catch { return nativeUnavailable('a binding session directory became unreadable') }
+ if (nativeFileKey(before) !== nativeFileKey(location.info)) return nativeUnavailable('a binding session directory was replaced')
+ let directory
+ const names: string[] = []
+ try {
+ directory = opendirSync(location.path, { bufferSize: 32 })
+ for (;;) {
+ this.budget.step()
+ const entry = directory.readSync()
+ if (!entry) break
+ if (--this.entriesLeft < 0) return nativeUnavailable('the binding directory entry limit was reached')
+ names.push(entry.name)
+ }
+ } catch (error) {
+ if (error instanceof IdentityReadUnavailable) throw error
+ return nativeUnavailable('a binding session directory could not be read completely')
+ } finally {
+ if (directory) { try { directory.closeSync() } catch { nativeUnavailable('a binding session directory could not be closed') } }
+ }
+ const after = this.directoryRoute(location.path)
+ if (route.size !== after.size || [...route].some(([part, version]) => after.get(part) !== version)) {
+ return nativeUnavailable('a binding directory or ancestor changed during enumeration')
+ }
+ this.directories.set(location.path, stamp(before))
+ return names
+ }
+
+ /** Selected identity is checked last. Appended body text does not change a complete header. */
+ verify(selected?: string): void {
+ this.paths.verify()
+ for (const [path, before] of this.directories) {
+ this.budget.step()
+ try {
+ if (stamp(lstatSync(path, { bigint: true })) !== before) return nativeUnavailable('the binding directory pool changed')
+ } catch (error) {
+ if (error instanceof IdentityReadUnavailable) throw error
+ return nativeUnavailable('a binding directory became unreadable')
+ }
+ }
+ const last = selected && this.locate(selected, true)?.path
+ 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.line !== undefined && firstLine(bytes, record.limit - 1) !== record.line) {
+ return nativeUnavailable('the binding header changed during inspection')
+ }
+ }
+ this.paths.verify()
+ }
+}
diff --git a/cli/src/engines/kit/nativeHeader.ts b/cli/src/engines/kit/nativeHeader.ts
index 8391ff5bf..166fad9a0 100644
--- a/cli/src/engines/kit/nativeHeader.ts
+++ b/cli/src/engines/kit/nativeHeader.ts
@@ -7,9 +7,9 @@ import { firstRecordMeta, type SessionMeta } from './sessionRecords.js'
import { NativeEvidenceBudget, nativeText, nativeUnavailable } from './nativeEvidence.js'
import { nativeFileKey } from './nativePaths.js'
-type First = NonNullable<SessionStoreContract['first']>
+export type NativeFirstRecord = NonNullable<SessionStoreContract['first']>
const stamp = (info: BigIntStats) => `${nativeFileKey(info)}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`
-function firstLine(bytes: Buffer, maxBytes: number): string {
+export function firstLine(bytes: Buffer, maxBytes: number): string {
// Do not decode a truncated UTF-8 character in the body after the complete metadata line.
let start = 0
while (start < Math.min(bytes.length, maxBytes)) {
@@ -23,38 +23,44 @@ function firstLine(bytes: Buffer, maxBytes: number): string {
return nativeUnavailable('the native rollout header is incomplete or exceeds its limit')
}
+/** The same conclusive record rules serve descriptors, registry loading and hook admission. */
+export function nativeSessionMeta(line: string, first: NativeFirstRecord): SessionMeta {
+ const meta = firstRecordMeta(line, first)
+ if (!meta || (!meta.isSubagent && (!meta.id || !meta.cwd || !meta.cwd.startsWith('/')))) return nativeUnavailable('the native rollout header is invalid')
+ const record: unknown = JSON.parse(line)
+ const field = (path: readonly string[]) => path.reduce((at: any, key) => at && typeof at === 'object' && !Array.isArray(at) ? at[key] : undefined, record)
+ if (first.source) {
+ const source: unknown = field(first.source.field)
+ const object = source && typeof source === 'object' && !Array.isArray(source) ? source as Record<string, unknown> : null
+ const keys = object ? Object.keys(object) : []
+ const named = keys.length === 1 && first.source.named.includes(keys[0]) && typeof object![keys[0]] === 'string' && String(object![keys[0]]).trim()
+ const child = keys.length === 1 && keys[0] === first.child.at(-1) && meta.isSubagent
+ if (!(source === undefined && first.source.legacyMissing)
+ && !(typeof source === 'string' && first.source.values.includes(source)) && !named && !child) {
+ return nativeUnavailable('the native rollout source is invalid or unknown')
+ }
+ }
+ if (meta.isSubagent) {
+ const claim: unknown = field(first.child)
+ if (!(typeof claim === 'string' && claim.trim())
+ && !(claim && typeof claim === 'object' && !Array.isArray(claim) && meta.parentThreadId)) {
+ return nativeUnavailable('the native rollout delegated-source claim is invalid')
+ }
+ }
+ return meta
+}
+
export async function descriptorHeader(path: string, identity: { device: bigint; inode: bigint },
- first: First, budget: NativeEvidenceBudget,
+ first: NativeFirstRecord, budget: NativeEvidenceBudget,
): Promise<{ meta: SessionMeta; verify(): void }> {
budget.step()
- let line: string, meta: SessionMeta | null
+ let line: string, meta: SessionMeta
try {
const version = await lstat(path)
const bytes = await identityBytes(path, first.maxBytes + 1, { ...version, fileKey: identity }, budget)
budget.step()
line = firstLine(bytes, first.maxBytes)
- meta = firstRecordMeta(line, first)
- if (!meta || (!meta.isSubagent && (!meta.id || !meta.cwd || !meta.cwd.startsWith('/')))) return nativeUnavailable('the native rollout header is invalid')
- const record: unknown = JSON.parse(line)
- const field = (path: readonly string[]) => path.reduce((at: any, key) => at && typeof at === 'object' && !Array.isArray(at) ? at[key] : undefined, record)
- if (first.source) {
- const source: unknown = field(first.source.field)
- const object = source && typeof source === 'object' && !Array.isArray(source) ? source as Record<string, unknown> : null
- const keys = object ? Object.keys(object) : []
- const named = keys.length === 1 && first.source.named.includes(keys[0]) && typeof object![keys[0]] === 'string' && String(object![keys[0]]).trim()
- const child = keys.length === 1 && keys[0] === first.child.at(-1) && meta.isSubagent
- if (!(source === undefined && first.source.legacyMissing)
- && !(typeof source === 'string' && first.source.values.includes(source)) && !named && !child) {
- return nativeUnavailable('the native rollout source is invalid or unknown')
- }
- }
- if (meta.isSubagent) {
- const claim: unknown = field(first.child)
- if (!(typeof claim === 'string' && claim.trim())
- && !(claim && typeof claim === 'object' && !Array.isArray(claim) && meta.parentThreadId)) {
- return nativeUnavailable('the native rollout delegated-source claim is invalid')
- }
- }
+ meta = nativeSessionMeta(line, first)
} catch (error) {
if (error instanceof IdentityReadUnavailable) throw error
return nativeUnavailable('the native rollout header could not be read completely')
diff --git a/cli/src/engines/kit/nativePaths.ts b/cli/src/engines/kit/nativePaths.ts
index 22203132a..623b4424a 100644
--- a/cli/src/engines/kit/nativePaths.ts
+++ b/cli/src/engines/kit/nativePaths.ts
@@ -5,15 +5,55 @@ import { dirname, isAbsolute, join } from 'node:path'
import { NativeEvidenceBudget, nativeUnavailable } from './nativeEvidence.js'
export const nativeFileKey = (info: Pick<BigIntStats, 'dev' | 'ino'>) => `${info.dev}:${info.ino}`
-const identity = (info: BigIntStats | null) => info && `${nativeFileKey(info)}:${info.mode}`
+const identity = (info: BigIntStats | null) => info && `${nativeFileKey(info)}:${info.mode}:${info.uid}`
const version = (info: BigIntStats) => `${identity(info)}:${info.size}:${info.mtimeNs}:${info.ctimeNs}`
type Part = { info: BigIntStats | null; target?: string }
+type Location = { path: string; info: BigIntStats } | null
export class NativePaths {
private readonly parts = new Map<string, Part>()
constructor(private readonly budget: NativeEvidenceBudget) {}
- async resolve(path: string, missingOkay = false): Promise<{ path: string; info: BigIntStats } | null> {
+ async resolve(path: string, missingOkay = false): Promise<Location> {
+ const steps = this.walk(path, missingOkay)
+ let next = steps.next()
+ while (!next.done) {
+ let proof: Part
+ try {
+ const info = await lstat(next.value, { bigint: true })
+ proof = { info, ...(info.isSymbolicLink() ? { target: await readlink(next.value) } : {}) }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') proof = { info: null }
+ else return nativeUnavailable('a native location could not be inspected')
+ }
+ next = steps.next(proof)
+ }
+ return next.value
+ }
+
+ /** Eager binding and hook admission share exactly the same bounded ancestry rules. */
+ resolveSync(path: string, missingOkay = false): Location {
+ const steps = this.walk(path, missingOkay)
+ let next = steps.next()
+ while (!next.done) {
+ let proof: Part
+ try {
+ const info = lstatSync(next.value, { bigint: true })
+ proof = { info, ...(info.isSymbolicLink() ? { target: readlinkSync(next.value) } : {}) }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') proof = { info: null }
+ else return nativeUnavailable('a native location could not be inspected')
+ }
+ next = steps.next(proof)
+ }
+ return next.value
+ }
+
+ /** Only an observed absent leaf can be announced before creation. A dangling alias is
+ * still an existing leaf and must not borrow the authority of its original parent. */
+ absentLeaf(path: string): boolean { return this.parts.get(path)?.info === null }
+
+ private *walk(path: string, missingOkay: boolean): Generator<string, Location, Part> {
if (!isAbsolute(path) || path.includes('\0') || Buffer.byteLength(path) > 4096) return nativeUnavailable('a native location is invalid or exceeds its limit')
// Follow links in component order. Normalizing bridge/../home first would skip bridge.
let prefix = '/', pending = path.slice(1).split('/').filter(Boolean), links = 0
@@ -28,13 +68,7 @@ export class NativePaths {
const next = part === '.' ? prefix : join(prefix, part)
let proof = this.parts.get(next)
if (!proof) {
- try {
- info = await lstat(next, { bigint: true })
- proof = { info, ...(info.isSymbolicLink() ? { target: await readlink(next) } : {}) }
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') proof = { info: null }
- else return nativeUnavailable('a native location could not be inspected')
- }
+ proof = yield next
this.parts.set(next, proof)
}
info = proof.info
diff --git a/cli/src/engines/otherTranscripts.golden.spec.ts b/cli/src/engines/otherTranscripts.golden.spec.ts
index 5456f5238..d59222028 100644
--- a/cli/src/engines/otherTranscripts.golden.spec.ts
+++ b/cli/src/engines/otherTranscripts.golden.spec.ts
@@ -220,11 +220,13 @@ function livePath(core: Core, session: RegisteredSession, pane: string | null) {
}
const announceTurnAborted = (...args: unknown[]): void => { out.push(['aborted', ...args]) }
const attach = core.createAttach({
+ setInterpretationHold: () => false, announceSession: () => {},
liveFor: () => undefined,
resolve: () => session,
terminalGone: async () => false,
normalizers,
watcher: {
+ removeSession: async () => {}, pollSession: async () => {},
addSession: async (s, options) => { out.push(['tail', s.sessionId, options ?? null]) },
hold: async () => null,
tails: () => false,
diff --git a/cli/src/engines/sessionStore.golden.spec.ts b/cli/src/engines/sessionStore.golden.spec.ts
index 02f5449a4..97aebda3d 100644
--- a/cli/src/engines/sessionStore.golden.spec.ts
+++ b/cli/src/engines/sessionStore.golden.spec.ts
@@ -31,6 +31,19 @@ import type { RegisteredSession } from '../lib/registry.js'
const fixtureClock = vi.hoisted(() => ({ root: '', now: Date.parse('2026-10-09T00:00:00Z') }))
vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => 0 } }))
+// Other test processes create and remove siblings under the host's temporary directory. Those
+// mutations are outside this recording; keep ancestor content stamps stable, retaining native inode
+// identity and all content stamps within the fixture. The expected artifact remains unchanged.
+vi.mock('node:fs', async original => {
+ const fs = await original<typeof import('node:fs')>()
+ return { ...fs, lstatSync: (...args: Parameters<typeof fs.lstatSync>) => {
+ const info = Reflect.apply(fs.lstatSync, fs, args)
+ const path = String(args[0])
+ if (!info || !fixtureClock.root || path === fixtureClock.root || path.startsWith(fixtureClock.root + '/') || !info.isDirectory()) return info
+ return new Proxy(info, { get: (value, key) => ['size', 'mtimeNs', 'ctimeNs'].includes(String(key)) ? 0n : Reflect.get(value, key) })
+ } }
+})
+
vi.mock('../lib/bootId.js', async original => ({ ...await original<object>(), currentBootId: () => 'fixture-boot', bootChanged: () => false }))
vi.mock('../lib/processLiveness.js', async original => ({ ...await original<object>(),
diff --git a/cli/src/engines/transcriptBindings.spec.ts b/cli/src/engines/transcriptBindings.spec.ts
new file mode 100644
index 000000000..b7b6475f7
--- /dev/null
+++ b/cli/src/engines/transcriptBindings.spec.ts
@@ -0,0 +1,197 @@
+import * as fs from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import { NativeFiles } from './kit/nativeFiles.js'
+import { NativeEvidenceBudget } from './kit/nativeEvidence.js'
+
+vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => 0 } }))
+vi.mock('node:fs', async original => {
+ const actual = await original<typeof import('node:fs')>()
+ return { ...actual, openSync: vi.fn(actual.openSync), readSync: vi.fn(actual.readSync), closeSync: vi.fn(actual.closeSync),
+ opendirSync: vi.fn(actual.opendirSync), lstatSync: vi.fn(actual.lstatSync) }
+})
+let root: string, home: string, file: string, actual: typeof fs, bindings: typeof import('./transcriptBindings.js')
+const A = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa', B = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
+const record = (id = A, source: unknown = 'cli') => JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, source } }) + '\n'
+function write(path: string, text = record()): void { fs.mkdirSync(dirname(path), { recursive: true }); fs.writeFileSync(path, text, { mode: 0o600 }) }
+const proof = () => bindings.savedTranscriptEvidence('codex', A, file)
+beforeEach(async () => {
+ actual = await vi.importActual<typeof fs>('node:fs')
+ vi.mocked(fs.openSync).mockReset().mockImplementation(actual.openSync)
+ vi.mocked(fs.readSync).mockReset().mockImplementation(actual.readSync)
+ vi.mocked(fs.closeSync).mockReset().mockImplementation(actual.closeSync)
+ vi.mocked(fs.opendirSync).mockReset().mockImplementation(actual.opendirSync)
+ vi.mocked(fs.lstatSync).mockReset().mockImplementation(actual.lstatSync)
+ root = fs.realpathSync(fs.mkdtempSync(join(tmpdir(), 'binding-transcript-')))
+ home = join(root, 'codex'); file = join(home, 'sessions', 'day', `rollout-${A}.jsonl`)
+ vi.stubEnv('ADAPTER_DATA_DIR', join(root, 'data')); vi.stubEnv('CODEX_HOME', home)
+ vi.stubEnv('CLAUDE_PROJECTS_DIR', join(root, 'claude', 'projects'))
+ write(join(root, 'data', 'engine-homes.json'), '{}'); write(file)
+ vi.resetModules(); bindings = await import('./transcriptBindings.js')
+})
+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); fs.rmSync(root, { recursive: true, force: true }) })
+
+it('verifies an owned exact binding and follows a canonical alias', () => {
+ const alias = join(home, 'sessions', 'alias.jsonl'); fs.symlinkSync(file, alias)
+ for (const path of [file, alias]) {
+ const result = bindings.savedTranscriptEvidence('codex', A, path)
+ expect(result.path).toBe(path); expect(() => result.verify()).not.toThrow()
+ }
+})
+it('holds a fresh malformed catalog, but an explicit profile remains independent', () => {
+ const old = proof()
+ fs.writeFileSync(join(root, 'data', 'engine-homes.json'), '{')
+ expect(proof).toThrow('catalog')
+ expect(() => old.verify()).toThrow('catalog')
+ const explicit = bindings.savedTranscriptEvidence('codex', A, file, home)
+ expect(explicit.path).toBe(file); expect(() => explicit.verify()).not.toThrow()
+ fs.writeFileSync(join(root, 'data', 'engine-homes.json'), '{}')
+ expect(proof().path).toBe(file)
+})
+it('never uses a now-omitted moved home as permission to release its binding', () => {
+ fs.writeFileSync(join(root, 'data', 'engine-homes.json'), JSON.stringify({ codex: [join(root, 'moved')] }))
+ proof().verify()
+ fs.writeFileSync(join(root, 'data', 'engine-homes.json'), '{}')
+ expect(proof).toThrow('omits')
+})
+it('distinguishes a proven outside or absent file from an unreadable file', () => {
+ const outside = join(root, 'elsewhere.jsonl'); write(outside)
+ for (const path of [outside, join(home, 'sessions', 'absent.jsonl')]) {
+ const result = bindings.transcriptEvidence('codex', path)
+ expect(result.valid).toBe(false); expect(() => result.verify()).not.toThrow()
+ }
+ vi.mocked(fs.openSync).mockImplementation(((path: fs.PathLike, ...args: unknown[]) => {
+ if (String(path) === file) throw Object.assign(new Error('fixture denied'), { code: 'EACCES' })
+ return Reflect.apply(actual.openSync, actual, [path, ...args])
+ }) as typeof fs.openSync)
+ expect(proof).toThrow('binding file could not be read')
+})
+it('keeps an absent announced file fenced to its existing parent and root', () => {
+ const path = join(home, 'sessions', 'day', 'announced.jsonl')
+ const result = bindings.transcriptEvidence('codex', path, undefined, true)
+ expect(result.valid).toBe(true); result.verify()
+ write(path)
+ expect(() => result.verify()).toThrow('changed')
+})
+it('requires an owned announced parent and retains its ownership until publication', () => {
+ const path = join(dirname(file), 'announced.jsonl')
+ const result = bindings.transcriptEvidence('codex', path, undefined, true)
+ vi.mocked(fs.lstatSync).mockImplementation(((path: fs.PathLike, ...args: unknown[]) => {
+ const stat = Reflect.apply(actual.lstatSync, actual, [path, ...args])
+ return String(path) === dirname(file) ? Object.assign(stat, { uid: stat.uid + 1n }) : stat
+ }) as typeof fs.lstatSync)
+ expect(() => result.verify()).toThrow('changed')
+ expect(() => bindings.transcriptEvidence('codex', path, undefined, true)).toThrow('owner')
+})
+it('does not authorize a dangling leaf alias through its original parent', () => {
+ const path = join(dirname(file), 'announced.jsonl')
+ fs.symlinkSync(join(root, 'outside-absent.jsonl'), path)
+ expect(() => bindings.transcriptEvidence('codex', path, undefined, true)).toThrow('absent leaf')
+})
+it.each(['', '{', record().slice(0, -4), ' '.repeat(128 * 1024) + record(), record(A, { future: 'unknown' })])('holds an incomplete or unknown native header', text => {
+ fs.writeFileSync(file, text)
+ expect(proof).toThrow()
+})
+it('holds invalid UTF-8 in metadata but does not decode a truncated body after its complete line', () => {
+ fs.writeFileSync(file, Buffer.from([123, 255, 125]))
+ expect(proof).toThrow('UTF-8')
+ fs.writeFileSync(file, Buffer.concat([Buffer.from(record()), Buffer.from([255])]))
+ expect(proof().path).toBe(file)
+})
+it('finishes short reads and bounds a non-progressing or excessive read sequence', () => {
+ vi.mocked(fs.readSync).mockImplementation(((fd: number, bytes: Buffer, offset: number, length: number, position: number) =>
+ actual.readSync(fd, bytes, offset, Math.min(length, 7), position)) as typeof fs.readSync)
+ expect(proof().path).toBe(file)
+ vi.mocked(fs.readSync).mockReturnValue(0)
+ expect(proof).toThrow('ended')
+ vi.mocked(fs.readSync).mockImplementation(((fd: number, bytes: Buffer, offset: number, _length: number, position: number) =>
+ actual.readSync(fd, bytes, offset, 1, position)) as typeof fs.readSync)
+ expect(proof).toThrow('read-operation limit')
+})
+it('binds the opened descriptor even if a pathname is swapped and restored before the open returns', () => {
+ const foreign = join(root, 'foreign.jsonl'); write(foreign, record(B))
+ vi.mocked(fs.openSync).mockImplementation(((path: fs.PathLike, ...args: unknown[]) =>
+ Reflect.apply(actual.openSync, actual, [String(path) === file ? foreign : path, ...args])) as typeof fs.openSync)
+ expect(proof).toThrow('unconfirmed identity')
+})
+it('preserves a complete header across body appends and holds a changed header at commit', () => {
+ const first = proof(); fs.appendFileSync(file, '{"body":"new turn"}\n'); first.verify()
+ const next = proof(); fs.writeFileSync(file, record(B))
+ expect(() => next.verify()).toThrow('header changed')
+})
+it('does not let a repeated header read replace the earlier evidence in one operation', async () => {
+ const { sessionStoreOf } = await import('./sessionStoreContracts.js')
+ const files = new NativeFiles(), first = sessionStoreOf('codex')!.first!
+ files.header(file, first); fs.writeFileSync(file, record(B))
+ expect(() => files.header(file, first)).toThrow('header changed')
+})
+it('retains path ancestry across a replacement that keeps the same file inode', () => {
+ const read = proof(), replacement = join(root, 'replacement')
+ fs.mkdirSync(replacement); fs.linkSync(file, join(replacement, `rollout-${A}.jsonl`))
+ fs.renameSync(dirname(file), join(root, 'original')); fs.renameSync(replacement, dirname(file))
+ expect(() => read.verify()).toThrow('path or alias changed')
+})
+
+function child(): string {
+ const path = join(home, 'sessions', 'child', `rollout-${B}.jsonl`)
+ write(path, record(B, { subagent: { thread_spawn: { parent_thread_id: A, depth: 1 } } }))
+ return path
+}
+it('repairs a child overwrite only after proving the whole parent pool', () => {
+ const path = child(), held = bindings.savedTranscriptEvidence('codex', A, path)
+ expect(held.path).toBe(file); held.verify()
+ const competitor = join(home, 'sessions', 'later', `rollout-${A}.jsonl`)
+ write(competitor)
+ expect(() => held.verify()).toThrow('directory pool changed')
+ expect(() => bindings.savedTranscriptEvidence('codex', A, path)).toThrow('more than one')
+})
+it.each(['file', 'directory'])('does not repair through an outside %s alias', kind => {
+ const path = child(), outside = join(root, 'outside')
+ fs.mkdirSync(outside); fs.renameSync(file, join(outside, `rollout-${A}.jsonl`))
+ if (kind === 'file') fs.symlinkSync(join(outside, `rollout-${A}.jsonl`), file)
+ else fs.symlinkSync(outside, join(home, 'sessions', 'linked'))
+ expect(() => bindings.savedTranscriptEvidence('codex', A, path)).toThrow('escaped')
+})
+it('holds an escaped directory before reading even its empty candidate pool', () => {
+ const path = child(), outside = join(root, 'empty-outside')
+ fs.mkdirSync(outside); fs.symlinkSync(outside, join(home, 'sessions', 'linked'))
+ expect(() => bindings.savedTranscriptEvidence('codex', A, path)).toThrow('directory escaped')
+})
+it('retains absent and present roots in an explicit operation scope', () => {
+ const moved = join(root, 'moved'), sessions = join(moved, 'sessions')
+ fs.writeFileSync(join(root, 'data', 'engine-homes.json'), JSON.stringify({ codex: [moved] }))
+ const scope = bindings.transcriptRootEvidence('codex')
+ const result = bindings.savedTranscriptEvidence('codex', A, file, undefined, undefined, scope)
+ result.verify(); scope.verify()
+ fs.mkdirSync(sessions, { recursive: true })
+ expect(() => scope.verify()).toThrow('changed')
+})
+it('retains an unreadable competing directory even after the parent was found', () => {
+ const path = child(), blocked = join(home, 'sessions', 'blocked'); fs.mkdirSync(blocked)
+ vi.mocked(fs.opendirSync).mockImplementation(((path: fs.PathLike, ...args: unknown[]) => {
+ if (String(path) === blocked) throw Object.assign(new Error('fixture denied'), { code: 'EACCES' })
+ return Reflect.apply(actual.opendirSync, actual, [path, ...args])
+ }) as typeof fs.opendirSync)
+ expect(() => bindings.savedTranscriptEvidence('codex', A, path)).toThrow('could not be read completely')
+})
+it('does not infer an empty directory from an iterator acquired during an ancestor round trip', () => {
+ const path = child(), sessions = join(home, 'sessions'), elsewhere = join(root, 'empty')
+ fs.mkdirSync(elsewhere)
+ vi.mocked(fs.opendirSync).mockImplementation(((path: fs.PathLike, ...args: unknown[]) => {
+ if (String(path) !== sessions) return Reflect.apply(actual.opendirSync, actual, [path, ...args])
+ fs.renameSync(home, home + '-aside'); fs.mkdirSync(home); fs.mkdirSync(sessions)
+ const result = Reflect.apply(actual.opendirSync, actual, [sessions, ...args])
+ fs.renameSync(home, home + '-temporary'); fs.renameSync(home + '-aside', home)
+ return result
+ }) as typeof fs.opendirSync)
+ expect(() => bindings.savedTranscriptEvidence('codex', A, path)).toThrow('ancestor changed')
+})
+it('holds pool overflow, expired work and failed descriptor close', () => {
+ const directory = join(root, 'wide'); fs.mkdirSync(directory)
+ for (let index = 0; index < 4097; index++) fs.writeFileSync(join(directory, String(index)), '')
+ expect(() => new NativeFiles().entries(directory)).toThrow('entry limit')
+ expect(() => new NativeFiles(new NativeEvidenceBudget(-1)).file(file)).toThrow('deadline')
+ vi.mocked(fs.closeSync).mockImplementation(fd => { actual.closeSync(fd); throw new Error('fixture close failed') })
+ expect(() => new NativeFiles().file(file)).toThrow('could not be closed')
+}, 30_000)
diff --git a/cli/src/engines/transcriptBindings.ts b/cli/src/engines/transcriptBindings.ts
new file mode 100644
index 000000000..d80fdf09a
--- /dev/null
+++ b/cli/src/engines/transcriptBindings.ts
@@ -0,0 +1,129 @@
+/** Eager native transcript authority shared by binding, Stop and resume preflight. */
+import { basename, dirname, join } from 'node:path'
+import { env } from '../config/env.js'
+import { engineHomeSnapshot, sessionRoots, type EngineHomeSnapshot } from '../lib/engineHomes.js'
+import { cursorDataDir } from './cursor/contract.js'
+import { NativeFiles } from './kit/nativeFiles.js'
+import { nativeFileKey } from './kit/nativePaths.js'
+import { nativeUnavailable } from './kit/nativeEvidence.js'
+import { sessionStoreOf } from './sessionStoreContracts.js'
+import type { AgentEngine } from './types.js'
+
+/** Null means the engine stores conversations in a database, or is only a shell. */
+export const transcriptRoot: Readonly<Record<AgentEngine, (() => string) | 'store' | null>> = {
+ amp: () => env.AMP_SESSIONS_DIR,
+ muse: () => join(env.MUSE_HOME, 'sessions'),
+ codex: 'store',
+ grok: () => join(env.GROK_HOME, 'sessions'),
+ agy: () => join(env.AGY_HOME, 'brain'),
+ copilot: () => join(env.COPILOT_HOME, 'session-state'),
+ cursor: () => join(cursorDataDir(), 'projects'),
+ pi: () => join(env.PI_HOME, 'agent', 'sessions'),
+ commandcode: () => join(env.COMMANDCODE_HOME, 'projects'),
+ claude: 'store',
+ opencode: null, kilo: null, hermes: null, devin: null, terminal: null,
+}
+export const engineKeepsTranscriptFile = (engine: AgentEngine): boolean => transcriptRoot[engine] !== null
+export const needsHomeCatalog = (engine: AgentEngine, profile?: string | null): boolean =>
+ transcriptRoot[engine] === 'store' && !(sessionStoreOf(engine)?.sessions.profile && profile)
+
+/** One explicit load batch can reuse root ancestry, including absent roots, then fence it
+ * once before publishing its dependent rows. This proof never survives the operation. */
+export function transcriptRootEvidence(engine: AgentEngine, profile?: string, snapshot?: EngineHomeSnapshot) {
+ const files = new NativeFiles(), root = transcriptRoot[engine]
+ const ownSnapshot = !snapshot && needsHomeCatalog(engine, profile) ? engineHomeSnapshot() : undefined
+ const roots = root === 'store' ? sessionRoots(engine, profile, snapshot ?? ownSnapshot) : root ? [root()] : []
+ const directories = roots.flatMap(path => {
+ const location = files.locate(path, true)
+ if (!location) return []
+ if (!location.info.isDirectory()) return nativeUnavailable('a transcript root is not a directory')
+ return [{ original: path, ...location }]
+ })
+ return { directories, verify(): void { files.verify(); ownSnapshot?.verify() } }
+}
+
+/** A caller can supply its explicit synchronous batch proofs and verify them before publication. */
+export function transcriptEvidence(engine: AgentEngine, path: string, profile?: string,
+ allowMissing = false, snapshot?: EngineHomeSnapshot, roots?: ReturnType<typeof transcriptRootEvidence>,
+) {
+ const files = new NativeFiles(), root = transcriptRoot[engine]
+ const scope = roots ?? transcriptRootEvidence(engine, profile, snapshot)
+ const location = root ? files.file(path, true) : null
+ const parent = !location && allowMissing ? files.locate(dirname(path), true) : null
+ if (parent && !parent.info.isDirectory()) return nativeUnavailable('the announced transcript parent is not a directory')
+ if (parent && typeof process.getuid === 'function' && parent.info.uid !== BigInt(process.getuid())) {
+ return nativeUnavailable('the announced transcript parent has an unconfirmed owner')
+ }
+ if (parent && !files.paths.absentLeaf(join(parent.path, basename(path)))) {
+ return nativeUnavailable('the announced transcript is not a proven absent leaf')
+ }
+ const actual = location?.path ?? (parent ? join(parent.path, basename(path)) : null)
+ const matchingRoots = actual ? scope.directories.filter(directory => files.paths.within(actual, [directory.info])) : []
+ const valid = !!actual && matchingRoots.length > 0 && (engine !== 'cursor'
+ || (!!basename(actual).replace(/\.jsonl$/, '') && basename(dirname(actual)) === basename(actual).replace(/\.jsonl$/, '')
+ && basename(dirname(dirname(actual))) === 'agent-transcripts'))
+ return {
+ valid, files, matchingRoots,
+ verify(selected = path): void { files.verify(selected); if (!roots) scope.verify() },
+ }
+}
+
+/** Parent repair requires the complete declared pool, including unreadable or excluded candidates. */
+function parentTranscript(files: NativeFiles, engine: AgentEngine, id: string,
+ roots: ReturnType<typeof transcriptRootEvidence>['directories'],
+): string | null {
+ const store = sessionStoreOf(engine), rule = store?.byId
+ if (rule?.layout !== 'walk' || !store?.first || !rule.id.test(id)) return null
+ const visited = new Set<string>(), selected = new Map<string, string>()
+ let candidates = 0
+ const walk = (path: string, depth: number): void => {
+ if (depth > 32) return nativeUnavailable('the binding transcript depth limit was reached')
+ const location = files.locate(path, true)
+ if (!location) return
+ if (!location.info.isDirectory()) return nativeUnavailable('a binding transcript directory is not a directory')
+ if (!roots.some(root => nativeFileKey(root.info) === nativeFileKey(location.info))
+ && !files.paths.within(location.path, roots.map(root => root.info))) {
+ return nativeUnavailable('a binding parent directory escaped its transcript roots')
+ }
+ const key = nativeFileKey(location.info)
+ if (visited.has(key)) return
+ visited.add(key)
+ for (const name of files.entries(path)) {
+ const candidate = join(path, name)
+ if (name.endsWith(rule.suffix) && name.includes(id)) {
+ if (++candidates > 64) return nativeUnavailable('the binding transcript candidate limit was reached')
+ const file = files.file(candidate)!
+ if (!files.paths.within(file.path, roots.map(root => root.info))) {
+ return nativeUnavailable('a binding parent candidate escaped its transcript roots')
+ }
+ const meta = files.header(candidate, store.first!)
+ if (meta.id === id && !meta.isSubagent) selected.set(nativeFileKey(file.info), selected.get(nativeFileKey(file.info)) ?? candidate)
+ } else if (!name.includes('.')) {
+ const child = files.locate(candidate)!
+ if (child.info.isDirectory()) walk(candidate, depth + 1)
+ }
+ }
+ }
+ for (const root of roots) walk(root.original, 0)
+ if (selected.size > 1) return nativeUnavailable('more than one transcript matches the bound parent conversation')
+ return selected.values().next().value ?? null
+}
+
+/** Validate a saved binding and repair a conclusively identified child overwrite before committing. */
+export function savedTranscriptEvidence(engine: AgentEngine, sessionId: string, path: string,
+ profile?: string, snapshot?: EngineHomeSnapshot, roots?: ReturnType<typeof transcriptRootEvidence>,
+) {
+ const proof = transcriptEvidence(engine, path, profile, false, snapshot, roots)
+ let selected: string | null = proof.valid ? path : null
+ const store = sessionStoreOf(engine)
+ if (selected && store?.first) {
+ const meta = proof.files.header(selected, store.first)
+ if (meta.isSubagent) {
+ selected = store.repairsOverwrittenParent && meta.parentThreadId === sessionId
+ ? parentTranscript(proof.files, engine, sessionId, proof.matchingRoots) : null
+ } else if (meta.id !== sessionId) {
+ return nativeUnavailable('the saved transcript names a different conversation')
+ }
+ }
+ return { path: selected, verify: () => proof.verify(selected ?? path) }
+}
diff --git a/cli/src/engines/worker/liveFiles.ts b/cli/src/engines/worker/liveFiles.ts
index 6876221d6..290dfb64a 100644
--- a/cli/src/engines/worker/liveFiles.ts
+++ b/cli/src/engines/worker/liveFiles.ts
@@ -1,13 +1,15 @@
import { createHash } from 'node:crypto'
import { open } from 'node:fs/promises'
import type { LiveStamp } from './liveProtocol.js'
+import { verifyTranscriptHandle, type TranscriptFileIdentity } from '../../lib/transcriptBoundary.js'
/** Fingerprint a delivered prefix without rereading the conversation. At byte zero no content exists
* to preserve: an empty or missing transcript becoming a file is ordinary first-turn delivery. */
-export async function stampAt(file: string, offset: number): Promise<LiveStamp | null> {
+export async function stampAt(file: string, offset: number, expectedFile?: TranscriptFileIdentity): Promise<LiveStamp | null> {
if (offset === 0) return null
const handle = await open(file, 'r')
try {
+ if (expectedFile) await verifyTranscriptHandle(handle, expectedFile)
const stat = await handle.stat()
if (stat.size < offset) throw new Error('ENGINE_TRANSCRIPT_CHANGED')
const bytes = Math.min(offset, 512)
diff --git a/cli/src/engines/worker/liveProtocol.ts b/cli/src/engines/worker/liveProtocol.ts
index 2fdc7d5e8..3c2c33f87 100644
--- a/cli/src/engines/worker/liveProtocol.ts
+++ b/cli/src/engines/worker/liveProtocol.ts
@@ -5,6 +5,7 @@ import type { RegisteredSession } from '../../lib/registry.js'
import { record, sessionEvent } from './protocol.js'
import type { RuntimeRecord } from '../facets/runtime.js'
import { runtimeRecord } from './runtimeProtocol.js'
+import type { TranscriptClose } from '../../lib/transcriptControls.js'
export const LIVE_VERSION = 1
export const LIVE_CAPABILITIES = 'engine_live_capabilities'
@@ -133,4 +134,6 @@ export interface LivePull {
* A worker that never saw that read, or a file changed again since, hydrates as `rewritten` alone. */
rewrittenFrom?: string
end?: number
+ /** Eager core decisions retained across parser reconstruction, in native byte order. */
+ closes?: readonly TranscriptClose[]
}
diff --git a/cli/src/engines/worker/liveRequests.spec.ts b/cli/src/engines/worker/liveRequests.spec.ts
index d187877b6..0abba4359 100644
--- a/cli/src/engines/worker/liveRequests.spec.ts
+++ b/cli/src/engines/worker/liveRequests.spec.ts
@@ -322,7 +322,13 @@ describe('engine live checkpoints', () => {
expect(await requests[LIVE_PREPARE](t.payload, caller)).toMatchObject({ error: 'ENGINE_INVALID_REQUEST' })
}
for (const fields of [{ version: 2 }, { token: '' }, { cursor: {} }, { session: { ...t.session, engine: 'codex' } },
- { session: { ...t.session, transcriptPath: 'relative' } }, { fromStart: 'yes' }, { end: -1 }]) {
+ { session: { ...t.session, transcriptPath: 'relative' } }, { fromStart: 'yes' }, { end: -1 },
+ ...[null, {}, [null], [{ offset: -1, reason: 'cancel' }], [{ offset: 0, reason: 'unknown' }],
+ [{ offset: 2, reason: 'cancel' }, { offset: 1, reason: 'cancel' }],
+ Array.from({ length: 129 }, () => ({ offset: 0, reason: 'cancel' })),
+ [{ offset: 1, reason: 'cancel', boundary: { offset: 2, device: 1, inode: 1, digest: 'a'.repeat(64) } }],
+ [{ offset: 1, reason: 'cancel', boundary: { offset: 1, device: 1, inode: 1, digest: 'unknown' } }],
+ ].map(closes => ({ closes }))]) {
expect(await requests[LIVE_PREPARE]({ ...t.payload, ...fields }, who)).toMatchObject({ error: 'ENGINE_INVALID_REQUEST' })
}
expect(load).not.toHaveBeenCalled()
diff --git a/cli/src/engines/worker/liveRequests.ts b/cli/src/engines/worker/liveRequests.ts
index d0a11713b..b19c58c18 100644
--- a/cli/src/engines/worker/liveRequests.ts
+++ b/cli/src/engines/worker/liveRequests.ts
@@ -4,6 +4,7 @@ import type { ServiceRequests } from '../../core/api.js'
import type { RuntimeField } from '../facets/runtime.js'
import type { EngineLive } from '../facets/live.js'
import { transcriptFields } from '../kit/runtime.js'
+import { transcriptCloses } from '../../lib/transcriptControls.js'
import { record, READER_REPLY_BYTES, type ReaderEngine } from './protocol.js'
import { LiveStreams } from './liveStreams.js'
import {
@@ -41,11 +42,13 @@ function pullOf(payload: Record<string, unknown>, engine: ReaderEngine): LivePul
|| typeof payload.fromStart !== 'boolean' || typeof payload.replay !== 'boolean'
|| (payload.end !== undefined && !position(payload.end)) || (payload.liveStart !== undefined && typeof payload.liveStart !== 'boolean')
|| (payload.rewritten !== undefined && typeof payload.rewritten !== 'boolean')
+ || (payload.closes !== undefined && !transcriptCloses(payload.closes))
|| (payload.rewrittenFrom !== undefined && !label(payload.rewrittenFrom))) return null
return { token: payload.token, session, cursor: payload.cursor, fromStart: payload.fromStart,
replay: payload.replay, ...(payload.liveStart === undefined ? {} : { liveStart: payload.liveStart }),
...(payload.rewritten === undefined ? {} : { rewritten: payload.rewritten }),
...(payload.rewrittenFrom === undefined ? {} : { rewrittenFrom: payload.rewrittenFrom }),
+ ...(payload.closes === undefined ? {} : { closes: payload.closes }),
...(payload.end === undefined ? {} : { end: payload.end }) }
}
@@ -148,7 +151,8 @@ export function engineLiveRequests(engine: ReaderEngine, deps: LiveRequestDeps =
})()])
} catch (error) {
await forget(ask.token)
- return failure(error instanceof Error && error.message === 'ENGINE_TRANSCRIPT_CHANGED' ? error.message : 'ENGINE_UNAVAILABLE')
+ return failure(error instanceof Error && ['ENGINE_TRANSCRIPT_CHANGED', 'ENGINE_CONTROL_BOUNDARY_CHANGED'].includes(error.message)
+ ? error.message : 'ENGINE_UNAVAILABLE')
} finally { clearTimeout(timer); pending-- }
}
return Object.fromEntries([LIVE_CAPABILITIES, LIVE_PREPARE, LIVE_READ, LIVE_PART, LIVE_CLOSE, LIVE_FORGET].map(type => [type, handler(type)]))
diff --git a/cli/src/engines/worker/liveStreams.ts b/cli/src/engines/worker/liveStreams.ts
index 653096116..72a8f8a7e 100644
--- a/cli/src/engines/worker/liveStreams.ts
+++ b/cli/src/engines/worker/liveStreams.ts
@@ -6,6 +6,7 @@ import { isWholeRecord, locateAttachSpan, type AttachSpan } from '../../lib/atta
import type { RuntimeField, RuntimeRecord } from '../facets/runtime.js'
import { streamRecords } from '../../lib/transcriptTail.js'
import { sameStamp, stampAt } from './liveFiles.js'
+import { closeFileIdentity, replayCloses, verifyCloses } from '../../lib/transcriptControls.js'
import { LIVE_CACHE_SESSIONS, LIVE_HISTORY_BYTES, LIVE_PAGE_BYTES, type LiveCursor, type LiveFrame, type LivePage, type LiveSession,
type LivePull, type LiveStamp } from './liveProtocol.js'
@@ -19,6 +20,8 @@ interface Stream {
lastStarted: LiveEvent | null
head: boolean
activation: { end: number; history: boolean } | null
+ closeThrough(offset: number): void
+ closes: string
}
/** Where a read found its file rewritten: the length then, and the bytes and file identity there. */
@@ -111,7 +114,12 @@ export class LiveStreams {
const parser = this.adapter.create(ask.session)
const stream: Stream = { session: { ...ask.session }, parser, span: emptySpan(),
turn: { ...parser.snapshot(), identity: `${ask.token}:empty` }, closed: false,
- cursor: null, lastStarted: null, head: true, activation: null }
+ cursor: null, lastStarted: null, head: true, activation: null,
+ closes: JSON.stringify(ask.closes ?? []), closeThrough: replayCloses(ask.closes ?? [], reason => {
+ parser.closeTurn(reason)
+ stream.closed = reason
+ stream.turn = { ...stream.turn, turnOpen: false }
+ }) }
const file = ask.session.transcriptPath
const boundary = !ask.cursor && ask.rewritten ? await this.rewriteBoundary(ask) : undefined
if (!ask.cursor && (ask.liveStart || ask.rewritten)) {
@@ -126,12 +134,13 @@ export class LiveStreams {
}
if (!file) return stream
const cursor = ask.cursor
- if (cursor && !sameStamp(cursor.stamp, await stampAt(file, cursor.offset))) changed()
+ if (cursor && !sameStamp(cursor.stamp, await stampAt(file, cursor.offset, closeFileIdentity(ask.closes)))) changed()
const end = cursor ? cursor.origin : ask.rewritten ? boundary : ask.end
const rules = this.adapter.attachRules!((line) => this.fields(ask.session, line))
try {
- stream.span = await locateAttachSpan(file, rules, { end, fromStart: ask.fromStart })
+ stream.span = await locateAttachSpan(file, rules, { end, fromStart: ask.fromStart, closes: ask.closes })
?? changed()
+ if (ask.closes?.length) stream.span.end = Math.min(end ?? Infinity, (await stat(file)).size)
} catch (error) {
// An announced path can precede its file. It is an empty stream only before any byte is accepted.
if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || (cursor && cursor.offset > 0)) throw error
@@ -143,11 +152,13 @@ export class LiveStreams {
const start = Math.min(stream.span.turnFrom, cursor.offset)
if (cursor.offset > start) {
const read = await streamRecords(file, start, cursor.offset, (raw, offset) => {
+ stream.closeThrough(offset)
this.ingest(stream, ask.token, raw, offset)
- }, isWholeRecord)
+ }, isWholeRecord, undefined, closeFileIdentity(ask.closes))
if (!read || read.next !== cursor.offset) changed()
}
- if (!sameStamp(cursor.stamp, await stampAt(file, cursor.offset))) changed()
+ stream.closeThrough(cursor.offset)
+ if (!sameStamp(cursor.stamp, await stampAt(file, cursor.offset, closeFileIdentity(ask.closes)))) changed()
if (cursor.closed) parser.closeTurn(cursor.closed)
stream.turn = { ...cursor.turn }
stream.closed = cursor.closed
@@ -159,7 +170,8 @@ export class LiveStreams {
private async get(ask: LivePull): Promise<Stream> {
let stream = this.streams.get(ask.token)
- if (!stream || binding(stream.session) !== binding(ask.session) || !sameCursor(stream.cursor, ask.cursor)) {
+ if (!stream || binding(stream.session) !== binding(ask.session) || !sameCursor(stream.cursor, ask.cursor)
+ || stream.closes !== JSON.stringify(ask.closes ?? [])) {
stream = await this.create(ask)
this.streams.set(ask.token, stream)
}
@@ -167,7 +179,12 @@ export class LiveStreams {
}
async pull(ask: LivePull): Promise<LivePage> {
- try { return await this.read(ask) } catch (error) {
+ try {
+ if (ask.session.transcriptPath && ask.closes) verifyCloses(ask.session.transcriptPath, ask.closes)
+ const page = await this.read(ask)
+ if (ask.session.transcriptPath && ask.closes) verifyCloses(ask.session.transcriptPath, ask.closes)
+ return page
+ } catch (error) {
if (ask.cursor && error instanceof Error && error.message === 'ENGINE_TRANSCRIPT_CHANGED') await this.noteRewrite(ask)
throw error
}
@@ -189,7 +206,7 @@ export class LiveStreams {
const start = ask.cursor?.offset ?? stream.span.profileFrom
let end = preparing ? stream.span.end : start
if (file) {
- if (ask.cursor && !sameStamp(ask.cursor.stamp, await stampAt(file, start))) changed()
+ if (ask.cursor && !sameStamp(ask.cursor.stamp, await stampAt(file, start, closeFileIdentity(ask.closes)))) changed()
try { if (!preparing) end = ask.cursor?.completeUntil ?? (await stat(file)).size }
catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || start > 0) throw error }
}
@@ -205,6 +222,7 @@ export class LiveStreams {
stream.head = false
let stopped = false
const read = file && end > start ? await streamRecords(file, start, end, (raw, offset) => {
+ stream.closeThrough(offset)
const fold = !preparing || offset >= stream.span.turnFrom
const result = fold ? this.ingest(stream, ask.token, raw, offset) : { events: [] }
if (fold) records++
@@ -216,17 +234,18 @@ export class LiveStreams {
// the reply transport fragments it and enforces the independent hard result bound.
bytes += Buffer.byteLength(raw) + Buffer.byteLength(JSON.stringify(events)) + Buffer.byteLength(JSON.stringify(frame.runtime ?? null))
return stopped = bytes >= LIVE_PAGE_BYTES
- }, preparing || ask.cursor?.completeUntil != null ? isWholeRecord : () => false) : { next: start, partial: false, records: 0 }
+ }, preparing || ask.cursor?.completeUntil != null ? isWholeRecord : () => false, undefined, closeFileIdentity(ask.closes)) : { next: start, partial: false, records: 0 }
if (!read) changed()
+ stream.closeThrough(read.next)
const prepared = preparing && (!stopped || read.next >= end)
const cursor: LiveCursor = { serial: (ask.cursor?.serial ?? 0) + 1, origin: ask.cursor?.origin ?? stream.span.end,
offset: read.next, turn: { ...stream.turn }, closed: stream.closed,
prepareEnd: preparing && !prepared ? end : null,
completeUntil: stopped && read.next < end ? ask.cursor?.completeUntil ?? null : null,
...(ask.cursor?.historyUntil !== undefined && read.next < ask.cursor.historyUntil ? { historyUntil: ask.cursor.historyUntil } : {}),
- stamp: file ? await stampAt(file, read.next) : null }
+ stamp: file ? await stampAt(file, read.next, closeFileIdentity(ask.closes)) : null }
// Verify the old boundary again before publishing; a concurrent rewrite invalidates this page.
- if (file && ask.cursor && !sameStamp(ask.cursor.stamp, await stampAt(file, start))) changed()
+ if (file && ask.cursor && !sameStamp(ask.cursor.stamp, await stampAt(file, start, closeFileIdentity(ask.closes)))) changed()
stream.cursor = cursor
return { frames, cursor, ...(prepared ? { prepared: true } : {}), content: records > 0 || read.partial,
more: stopped && read.next < end || ask.cursor?.completeUntil != null && cursor.completeUntil === null,
diff --git a/cli/src/hookAdmission.golden.spec.ts b/cli/src/hookAdmission.golden.spec.ts
new file mode 100644
index 000000000..390299d6c
--- /dev/null
+++ b/cli/src/hookAdmission.golden.spec.ts
@@ -0,0 +1,120 @@
+/** Healthy HTTP hook behavior recorded from main before pending native admission is moved. */
+import type { Server } from 'node:http'
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from './lib/registry.js'
+
+vi.mock('node:child_process', () => {
+ const forbidden = () => { throw Error('Host binaries are forbidden in the hook admission 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('./lib/loginShellEnv.js', () => ({ loginShellEnvironment: () => ({}) }))
+vi.mock('./lib/bootId.js', async original => ({ ...await original<object>(), currentBootId: () => 'fixture-boot', bootChanged: () => false }))
+vi.mock('./lib/processLiveness.js', async original => ({ ...await original<object>(),
+ processLockIdentity: () => ({ startMarker: 'fixture-start', generationMarker: 'fixture-generation' }), lockOwnerAlive: () => true,
+}))
+
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/hook-admission.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_HOOK_ADMISSION_GOLDEN === '1'
+const expected = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8'))
+const captured: Record<string, unknown> = {}
+const A = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa', B = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
+const CHILD = 'cccccccc-3333-4333-8333-cccccccccccc'
+
+it.each(['linux', 'darwin'])('preserves healthy native hook admission on %s', async platform => {
+ const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'hook-admission-golden-')))
+ const path = (...parts: string[]) => join(root, ...parts)
+ const write = (file: string, text: string) => {
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); writeFileSync(file, text, { mode: 0o600 })
+ }
+ let server: Server | undefined
+ const labels = new Map<string, string>()
+ const shape = (row: RegisteredSession | undefined | null) => row ? {
+ agent: labels.get(row.agentId), engine: row.engine, session: row.sessionId,
+ transcript: row.transcriptPath, source: row.source,
+ } : null
+ const check = (name: string, value: unknown) => {
+ const key = `${platform}:${name}`
+ captured[key] = JSON.parse(JSON.stringify(value ?? null).split(root).join('<root>'))
+ if (!RECORD) expect({ key, value: captured[key] }).toEqual({ key, value: expected[key] })
+ }
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ Object.defineProperty(process, 'platform', { ...originalPlatform, value: platform })
+ vi.useFakeTimers({ toFake: ['Date'], now: Date.parse('2026-10-10T00:00:00Z') })
+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR',
+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'HARNESS_HOOK_ROUTES_DIR']) {
+ mkdirSync(path(name), { recursive: true, mode: 0o700 }); vi.stubEnv(name, path(name))
+ }
+ vi.stubEnv('CLAUDE_PROJECTS_DIR', path('CLAUDE_CONFIG_DIR', 'projects'))
+ vi.stubEnv('TZ', 'UTC')
+ write(path('ADAPTER_DATA_DIR', 'engine-homes.json'), '{}')
+ const claude = path('CLAUDE_CONFIG_DIR', 'projects', 'fixture', `${A}.jsonl`)
+ const codex = path('CODEX_HOME', 'sessions', `rollout-${B}.jsonl`)
+ const child = path('CODEX_HOME', 'sessions', `rollout-${CHILD}.jsonl`)
+ write(claude, JSON.stringify({ type: 'user', cwd: root, sessionId: A, isSidechain: false }) + '\n')
+ const meta = (id: string, source: unknown = 'cli') => JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, source } }) + '\n'
+ write(codex, meta(B)); write(child, meta(CHILD, { subagent: { thread_spawn: { parent_thread_id: B, depth: 1 } } }))
+ vi.resetModules()
+ const { registry } = await import('./lib/registry.js')
+ const { startHookServer } = await import('./hookServer.js')
+ const { readHookCredential } = await import('./lib/hookAuth.js')
+ const agents = new Map<string, RegisteredSession>()
+ for (const [index, engine] of (['claude', 'codex'] as const).entries()) {
+ const { entry } = registry.openProcessAgent({ engine, tmuxPane: `%${index + 1}`, cwd: root,
+ processIdentity: { pid: 4100 + index, startMarker: 'fixture-start', executable: `<${engine}>` } })!
+ agents.set(engine, entry); labels.set(entry.agentId, engine)
+ }
+ const registered: unknown[] = [], prompts: unknown[] = [], promptHooks: unknown[] = [], turns: unknown[] = [], ends: unknown[] = []
+ const started = await startHookServer(0, {
+ resolveHookAgent: async input => registry.byAgent(agents.get(input.engine)?.agentId ?? '') ?? null,
+ onRegistered: (entry, meta) => { registered.push({ row: shape(entry), ...meta }) },
+ onPromptSubmitted: (agentId, prompt) => { prompts.push({ agent: labels.get(agentId), prompt }) },
+ onPromptHook: (sessionId, firedAt) => { promptHooks.push({ sessionId, firedAt }) },
+ onTurnStart: value => { turns.push({ start: value }) },
+ onTurnStop: value => { turns.push({ stop: value }) },
+ onToolStart: value => { turns.push({ tool: value }) },
+ onSessionEnd: (sessionId, reason) => { ends.push({ sessionId, reason }) },
+ })
+ server = started.server
+ const send = async (endpoint: string, body: Record<string, unknown>, authorized = true) => {
+ const response = await fetch(`http://127.0.0.1:${started.port}/api/hook/${endpoint}`, {
+ method: 'POST', headers: { 'content-type': 'application/json', 'x-harness-hook-fired-at': '1791590400123',
+ ...(authorized ? { 'x-harness-hook-token': readHookCredential(path('ADAPTER_DATA_DIR'))! } : {}) },
+ body: JSON.stringify(body),
+ })
+ return { status: response.status, body: await response.json() }
+ }
+ const claudeBody = { engine: 'claude', tmuxPane: '%1', sessionId: A, transcriptPath: claude, cwd: root, source: 'fixture' }
+ const codexBody = { engine: 'codex', tmuxPane: '%2', sessionId: B, transcriptPath: codex, cwd: root, source: 'fixture' }
+ check('authentication', await send('session-start', claudeBody, false))
+ check('claude-start', await send('session-start', { ...claudeBody, hookEvent: 'SessionStart' }))
+ check('claude-prompt', await send('session-start', { ...claudeBody, hookEvent: 'UserPromptSubmit', prompt: 'healthy Claude prompt' }))
+ check('codex-start', await send('session-start', { ...codexBody, hookEvent: 'SessionStart' }))
+ check('codex-prompt', await send('session-start', { ...codexBody, hookEvent: 'UserPromptSubmit', prompt: 'healthy Codex prompt' }))
+ check('delegated', await send('session-start', { ...codexBody, sessionId: CHILD, transcriptPath: child,
+ hookEvent: 'UserPromptSubmit', prompt: 'delegated prompt' }))
+ check('bound-controls', [await send('turn-start', codexBody), await send('tool-start', { ...codexBody, toolUseId: 'tool-1', toolName: 'Read', input: { file: '<file>' } }),
+ await send('turn-stop', { ...codexBody, status: 'completed' }), await send('session-end', { ...codexBody, reason: 'exit' })])
+ check('unbound-control', await send('turn-stop', { ...codexBody, sessionId: CHILD }))
+ check('callbacks', { registered, prompts, promptHooks, turns, ends })
+ check('bindings', registry.list().map(shape).sort((a, b) => a!.agent!.localeCompare(b!.agent!)))
+ } finally {
+ if (server) await new Promise<void>(resolve => server!.close(() => resolve()))
+ log.mockRestore(); warn.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/__fixtures__/binding-evidence.golden.json b/cli/src/lib/__fixtures__/binding-evidence.golden.json
new file mode 100644
index 000000000..d78afe5eb
--- /dev/null
+++ b/cli/src/lib/__fixtures__/binding-evidence.golden.json
@@ -0,0 +1,314 @@
+{
+ "linux:loaded": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "eeeeeeee-5555-4555-8555-eeeeeeeeeeee",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/project/eeeeeeee-5555-4555-8555-eeeeeeeeeeee.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "moved",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/moved-codex/sessions/day/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "outside",
+ "engine": "codex",
+ "session": "",
+ "transcript": null,
+ "profile": null,
+ "source": null
+ },
+ {
+ "agent": "parent",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/day/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "profile",
+ "engine": "codex",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/profile/sessions/rollout-cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "profile": "<root>/profile",
+ "source": "fixture"
+ },
+ {
+ "agent": "terminal",
+ "engine": "terminal",
+ "session": "",
+ "transcript": null,
+ "profile": null,
+ "source": null
+ }
+ ],
+ "linux:paths": [
+ true,
+ true,
+ true,
+ true,
+ false,
+ true
+ ],
+ "linux:admission": [
+ {
+ "accepted": true
+ },
+ {
+ "accepted": false,
+ "reason": "codex_subagent"
+ },
+ {
+ "accepted": true
+ }
+ ],
+ "linux:homes": [
+ "<root>/CODEX_HOME",
+ "<root>/moved-codex",
+ "<root>/profile"
+ ],
+ "linux:stop": [
+ {
+ "agent": "parent",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/day/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "moved",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/moved-codex/sessions/day/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "profile": null,
+ "source": "fixture"
+ }
+ ],
+ "linux:registered-terminal": {
+ "row": {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "dddddddd-4444-4444-8444-dddddddddddd",
+ "transcript": "<root>/CODEX_HOME/sessions/day/rollout-dddddddd-4444-4444-8444-dddddddddddd.jsonl",
+ "profile": null,
+ "source": "fixture-register"
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null
+ },
+ "linux:saved": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "eeeeeeee-5555-4555-8555-eeeeeeeeeeee",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/project/eeeeeeee-5555-4555-8555-eeeeeeeeeeee.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "moved",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/moved-codex/sessions/day/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "outside",
+ "engine": "codex",
+ "session": "",
+ "transcript": null,
+ "profile": null,
+ "source": null
+ },
+ {
+ "agent": "parent",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/day/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "profile",
+ "engine": "codex",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/profile/sessions/rollout-cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "profile": "<root>/profile",
+ "source": "fixture"
+ },
+ {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "dddddddd-4444-4444-8444-dddddddddddd",
+ "transcript": "<root>/CODEX_HOME/sessions/day/rollout-dddddddd-4444-4444-8444-dddddddddddd.jsonl",
+ "profile": null,
+ "source": "fixture-register"
+ }
+ ],
+ "darwin:loaded": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "eeeeeeee-5555-4555-8555-eeeeeeeeeeee",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/project/eeeeeeee-5555-4555-8555-eeeeeeeeeeee.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "moved",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/moved-codex/sessions/day/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "outside",
+ "engine": "codex",
+ "session": "",
+ "transcript": null,
+ "profile": null,
+ "source": null
+ },
+ {
+ "agent": "parent",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/day/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "profile",
+ "engine": "codex",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/profile/sessions/rollout-cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "profile": "<root>/profile",
+ "source": "fixture"
+ },
+ {
+ "agent": "terminal",
+ "engine": "terminal",
+ "session": "",
+ "transcript": null,
+ "profile": null,
+ "source": null
+ }
+ ],
+ "darwin:paths": [
+ true,
+ true,
+ true,
+ true,
+ false,
+ true
+ ],
+ "darwin:admission": [
+ {
+ "accepted": true
+ },
+ {
+ "accepted": false,
+ "reason": "codex_subagent"
+ },
+ {
+ "accepted": true
+ }
+ ],
+ "darwin:homes": [
+ "<root>/CODEX_HOME",
+ "<root>/moved-codex",
+ "<root>/profile"
+ ],
+ "darwin:stop": [
+ {
+ "agent": "parent",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/day/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "moved",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/moved-codex/sessions/day/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "profile": null,
+ "source": "fixture"
+ }
+ ],
+ "darwin:registered-terminal": {
+ "row": {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "dddddddd-4444-4444-8444-dddddddddddd",
+ "transcript": "<root>/CODEX_HOME/sessions/day/rollout-dddddddd-4444-4444-8444-dddddddddddd.jsonl",
+ "profile": null,
+ "source": "fixture-register"
+ },
+ "isNew": true,
+ "evicted": null,
+ "rebound": null
+ },
+ "darwin:saved": [
+ {
+ "agent": "claude",
+ "engine": "claude",
+ "session": "eeeeeeee-5555-4555-8555-eeeeeeeeeeee",
+ "transcript": "<root>/CLAUDE_CONFIG_DIR/projects/project/eeeeeeee-5555-4555-8555-eeeeeeeeeeee.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "moved",
+ "engine": "codex",
+ "session": "bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb",
+ "transcript": "<root>/moved-codex/sessions/day/rollout-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "outside",
+ "engine": "codex",
+ "session": "",
+ "transcript": null,
+ "profile": null,
+ "source": null
+ },
+ {
+ "agent": "parent",
+ "engine": "codex",
+ "session": "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa",
+ "transcript": "<root>/CODEX_HOME/sessions/day/rollout-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",
+ "profile": null,
+ "source": "fixture"
+ },
+ {
+ "agent": "profile",
+ "engine": "codex",
+ "session": "cccccccc-3333-4333-8333-cccccccccccc",
+ "transcript": "<root>/profile/sessions/rollout-cccccccc-3333-4333-8333-cccccccccccc.jsonl",
+ "profile": "<root>/profile",
+ "source": "fixture"
+ },
+ {
+ "agent": "terminal",
+ "engine": "codex",
+ "session": "dddddddd-4444-4444-8444-dddddddddddd",
+ "transcript": "<root>/CODEX_HOME/sessions/day/rollout-dddddddd-4444-4444-8444-dddddddddddd.jsonl",
+ "profile": null,
+ "source": "fixture-register"
+ }
+ ]
+}
diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.ts
index 8a712c2d6..529bcebdc 100644
--- a/cli/src/lib/agentFrame.ts
+++ b/cli/src/lib/agentFrame.ts
@@ -217,7 +217,7 @@ export async function agentFrame(
closePlan: s.closePlan ? { state: s.closePlan.state, ...(s.closePlan.detail ? { detail: s.closePlan.detail } : {}) } : null,
closeSupported: true,
launch: s.launch ?? { state: 'ready' },
- ...(s.identityHold ? { identityHold: s.identityHold } : {}),
+ ...((s.identityHold || s.interpretationHold) ? { identityHold: s.identityHold || s.interpretationHold } : {}),
createdAt: new Date(s.registeredAt).toISOString(),
updatedAt: new Date(updatedAt).toISOString(),
// Null, never omitted, for the reason the module doc gives: a push without the key would erase
diff --git a/cli/src/lib/attachTranscript.ts b/cli/src/lib/attachTranscript.ts
index 39246549b..e645c01bf 100644
--- a/cli/src/lib/attachTranscript.ts
+++ b/cli/src/lib/attachTranscript.ts
@@ -30,6 +30,7 @@
import { stat } from 'node:fs/promises'
import { scanRecordsBackward, streamRecords } from './transcriptTail.js'
import type { RuntimeField } from './runtimeProfile.js'
+import { closeFileIdentity, replayCloses, type TranscriptClose } from './transcriptControls.js'
export interface AttachRules {
/** The record the engine's fold opens a turn on, judged from the record alone. */
@@ -75,6 +76,7 @@ export interface AttachConsumers {
profile(line: string): void
/** The turn fold — the seeds, then every record from `turnFrom`. */
fold(line: string): void
+ close?(reason: TranscriptClose['reason']): void
/** The device's transcript observer — every record from `turnFrom`. */
observe?(line: string): void
}
@@ -120,12 +122,13 @@ export interface LocateOptions {
end?: number
/** See `ATTACH_REACH_BYTES`. */
reach?: number
+ closes?: readonly TranscriptClose[]
}
/** Walk back from the end to everything an attach needs. Null when the file shrank under the walk. */
export async function locateAttachSpan(filePath: string, rules: AttachRules, options: LocateOptions = {}): Promise<AttachSpan | null> {
const { size } = await stat(filePath)
- const end = options.end === undefined ? size : Math.min(options.end, size)
+ const end = Math.min(options.end ?? size, options.closes?.[0]?.offset ?? size, size)
const reach = options.reach ?? ATTACH_REACH_BYTES
if (options.fromStart || end === 0) return wholeFile(end)
let opener: number | null = null
@@ -189,7 +192,7 @@ export async function locateAttachSpan(filePath: string, rules: AttachRules, opt
}
}
return opener !== null && !seekingBegin && !missing.size && !seedTest && !unresolved.size && !seekingCalls
- })
+ }, undefined, undefined, closeFileIdentity(options.closes))
if (!whole) return null
// No opener anywhere: the whole file is the turn, as the whole-history fold would have it.
const turnFrom = begin ?? opener ?? 0
@@ -199,7 +202,7 @@ export async function locateAttachSpan(filePath: string, rules: AttachRules, opt
await streamRecords(filePath, 0, Math.min(end, HEAD_RECORD_LIMIT), (record) => {
head = record
return true
- }, isWholeRecord)
+ }, isWholeRecord, undefined, closeFileIdentity(options.closes))
}
return {
end,
@@ -221,6 +224,7 @@ export async function replayAttachSpan(
filePath: string,
span: AttachSpan,
consumers: AttachConsumers,
+ closes: readonly TranscriptClose[] = [],
): Promise<AttachRead> {
let failures = 0
let firstFailure: unknown = null
@@ -228,17 +232,21 @@ export async function replayAttachSpan(
try { consume(line) } catch (error) { if (failures++ === 0) firstFailure = error }
}
const { profile, fold, observe } = consumers
+ const closeThrough = replayCloses(closes, reason => consumers.close!(reason))
consumers.start?.(span)
if (span.head !== null) feed(profile, span.head)
for (const seed of span.seeds) feed(fold, seed)
let records = 0
const read = await streamRecords(filePath, span.profileFrom, span.end, (line, offset) => {
+ closeThrough(offset)
feed(profile, line)
if (offset < span.turnFrom) return
records++
if (observe) feed(observe, line)
feed(fold, line)
- }, isWholeRecord)
+ }, isWholeRecord, undefined, closeFileIdentity(closes))
+ if (!read && closes.length) throw new Error('ENGINE_CONTROL_BOUNDARY_CHANGED')
+ if (read) closeThrough(read.next)
if (failures) console.warn(`[attach] ${filePath}: ${failures} record(s) could not be taken in: ${String(firstFailure)}`)
return { next: read?.next ?? span.end, records, content: records > 0 || !!read?.partial }
}
@@ -270,7 +278,8 @@ export async function attachTranscript(
span = await locateAttachSpan(filePath, rules, options)
?? await locateAttachSpan(filePath, rules, options)
?? wholeFile(Math.min(options.end ?? Infinity, (await stat(filePath)).size))
- return { ...span, ...await replayAttachSpan(filePath, span, consumers), failed: false }
+ if (options.closes?.length) span.end = Math.min(options.end ?? Infinity, (await stat(filePath)).size)
+ return { ...span, ...await replayAttachSpan(filePath, span, consumers, options.closes), failed: false }
} catch (error) {
console.warn(`[attach] ${filePath} could not be read: ${String(error)}`)
const end = span ? span.end : await reach(filePath, options.end)
diff --git a/cli/src/lib/bindingEvidence.golden.spec.ts b/cli/src/lib/bindingEvidence.golden.spec.ts
new file mode 100644
index 000000000..d9a7285ec
--- /dev/null
+++ b/cli/src/lib/bindingEvidence.golden.spec.ts
@@ -0,0 +1,109 @@
+/** Healthy registry, admission and Stop answers recorded from main before strict binding evidence. */
+import { mkdirSync, mkdtempSync, readFileSync, 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 { RegisteredSession } from './registry.js'
+
+vi.mock('node:child_process', () => {
+ const forbidden = () => { throw Error('Host binaries are forbidden in the binding 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__/binding-evidence.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_BINDING_EVIDENCE_GOLDEN === '1'
+const expected = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8'))
+const captured: Record<string, unknown> = {}
+const A = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa', B = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'
+const C = 'cccccccc-3333-4333-8333-cccccccccccc', D = 'dddddddd-4444-4444-8444-dddddddddddd'
+const E = 'eeeeeeee-5555-4555-8555-eeeeeeeeeeee', CHILD = 'ffffffff-6666-4666-8666-ffffffffffff'
+const shape = (row: RegisteredSession | undefined | null) => row ? {
+ agent: row.agentId, engine: row.engine, session: row.sessionId, transcript: row.transcriptPath,
+ profile: row.codexHome, source: row.source,
+} : null
+
+it.each(['linux', 'darwin'])('preserves healthy binding and capture answers on %s', async platform => {
+ const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'binding-evidence-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 ?? null).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-10T00:00:00Z') })
+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR',
+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME']) {
+ mkdirSync(path(name), { recursive: true, mode: 0o700 })
+ vi.stubEnv(name, path(name))
+ }
+ vi.stubEnv('CLAUDE_PROJECTS_DIR', path('CLAUDE_CONFIG_DIR', 'projects'))
+ vi.stubEnv('TZ', 'UTC')
+ const moved = path('moved-codex'), claude = path('CLAUDE_CONFIG_DIR', 'projects', 'project', `${E}.jsonl`)
+ const parent = path('CODEX_HOME', 'sessions', 'day', `rollout-${A}.jsonl`)
+ const child = path('CODEX_HOME', 'sessions', 'day', `rollout-${CHILD}.jsonl`)
+ const movedFile = join(moved, 'sessions', 'day', `rollout-${B}.jsonl`)
+ const profile = path('profile'), profiled = join(profile, 'sessions', `rollout-${C}.jsonl`)
+ const outside = path('elsewhere', `rollout-${D}.jsonl`)
+ const registeredFile = path('CODEX_HOME', 'sessions', 'day', `rollout-${D}.jsonl`)
+ const meta = (id: string, source: unknown = 'cli') => JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, source } }) + '\n'
+ write(parent, meta(A)); write(movedFile, meta(B)); write(profiled, meta(C)); write(outside, meta(D)); write(registeredFile, meta(D))
+ write(child, meta(CHILD, { subagent: { thread_spawn: { parent_thread_id: A, depth: 1 } } }))
+ write(claude, JSON.stringify({ type: 'user', cwd: root, sessionId: E, isSidechain: false }) + '\n')
+ symlinkSync(parent, path('alias.jsonl'))
+ write(path('ADAPTER_DATA_DIR', 'engine-homes.json'), JSON.stringify({ claude: [], codex: [moved] }))
+ const legacy = (agent: string, engine: string, sessionId: string, transcriptPath: string | null, pane: number, codexHome: string | null = null) => ({
+ launcherId: agent, engine, sessionId, transcriptPath, codexHome, tmuxPane: `%${pane}`, cwd: root,
+ source: 'fixture', projectDir: 'project', processIdentity: null, registeredAt: 1, updatedAt: 1,
+ lastHookAt: 1, lastTranscriptAt: 1,
+ })
+ write(path('ADAPTER_DATA_DIR', 'registry.json'), JSON.stringify([
+ legacy('parent', 'codex', A, child, 1), legacy('moved', 'codex', B, movedFile, 2),
+ legacy('profile', 'codex', C, profiled, 3, profile), legacy('outside', 'codex', D, outside, 4),
+ legacy('claude', 'claude', E, claude, 5), legacy('terminal', 'terminal', '', null, 6),
+ ]))
+ vi.resetModules()
+ const homes = await import('./engineHomes.js')
+ const { registry, validTranscriptPath } = await import('./registry.js')
+ const { admitHook } = await import('../engines/hooks.js')
+ const { captureResumeIdentity } = await import('./captureResumeIdentity.js')
+ registry.load()
+ check('loaded', registry.list().map(shape).sort((a, b) => a!.agent.localeCompare(b!.agent)))
+ check('paths', [validTranscriptPath('codex', parent), validTranscriptPath('codex', path('alias.jsonl')),
+ validTranscriptPath('codex', movedFile), validTranscriptPath('codex', profiled, profile),
+ validTranscriptPath('codex', outside), validTranscriptPath('claude', claude)])
+ check('admission', [admitHook('codex', { transcriptPath: parent }), admitHook('codex', { transcriptPath: child }),
+ admitHook('claude', { transcriptPath: claude })])
+ check('homes', [homes.sessionHomeOf('codex', { transcriptPath: parent }),
+ homes.sessionHomeOf('codex', { transcriptPath: movedFile }), homes.sessionHomeOf('codex', { profile, transcriptPath: profiled })])
+ check('stop', [shape(await captureResumeIdentity(registry.byAgent('parent')!)), shape(await captureResumeIdentity(registry.byAgent('moved')!))])
+ const bound = registry.register({ engine: 'codex', sessionId: D, transcriptPath: registeredFile, tmuxPane: '%6', cwd: root, source: 'fixture-register' })
+ check('registered-terminal', bound && { row: shape(bound.entry), isNew: bound.isNew, evicted: bound.evicted, rebound: bound.rebound })
+ check('saved', JSON.parse(readFileSync(path('ADAPTER_DATA_DIR', 'registry.json'), 'utf8')).map(shape).sort((a: any, b: any) => a.agent.localeCompare(b.agent)))
+ homes.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/nativeLocations.control.spec.ts b/cli/src/lib/nativeLocations.control.spec.ts
index 76039ba26..849acecdd 100644
--- a/cli/src/lib/nativeLocations.control.spec.ts
+++ b/cli/src/lib/nativeLocations.control.spec.ts
@@ -89,7 +89,9 @@ it('Copilot binding retains its previous conversation when native ownership move
const row = { engine: 'copilot', agentId: 'private-agent', sessionId: 'previous', registeredAt: 0, runtimes: [],
processIdentity: { pid: 4242, executable: 'copilot', startMarker: '2026-10-09T00:00:00Z' } } as unknown as RegisteredSession
const register = vi.fn(() => null)
- const deps = { registry: { byProcess: () => row, bySession: () => undefined, register },
+ const deps = { registry: { byProcess: () => row, bySession: () => undefined, register,
+ setIdentityHold: (_id: string, reason: string) => { row.identityHold = reason; return true } },
+ announceSession: vi.fn(),
homes: { copilot: join(root, 'copilot') } } as unknown as BindDeps
const observed: DiscoveredTerminalAgent = { engine: 'copilot', cwd: root, runtimes: [], primaryRuntimeKey: '',
args: 'copilot', resumeSessionId: null, processIdentity: row.processIdentity! }
diff --git a/cli/src/lib/registry.binding.spec.ts b/cli/src/lib/registry.binding.spec.ts
new file mode 100644
index 000000000..3eb3e44d3
--- /dev/null
+++ b/cli/src/lib/registry.binding.spec.ts
@@ -0,0 +1,214 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+
+vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => 0 } }))
+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,
+}))
+let root: string, home: string, file: string, registry: typeof import('./registry.js')['registry']
+const ids = ['aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa', 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb']
+const header = (id: string) => JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, source: 'cli' } }) + '\n'
+const transcript = (index: number) => join(home, 'sessions', `rollout-${ids[index]}.jsonl`)
+beforeEach(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'registry-binding-'))); home = join(root, 'codex'); file = join(root, 'data', 'registry.json')
+ vi.stubEnv('ADAPTER_DATA_DIR', join(root, 'data')); vi.stubEnv('CODEX_HOME', home)
+ mkdirSync(join(root, 'data')); mkdirSync(join(home, 'sessions'), { recursive: true })
+ writeFileSync(join(root, 'data', 'engine-homes.json'), '{}')
+ const rows = ids.map((id, index) => {
+ writeFileSync(transcript(index), header(id))
+ return { launcherId: `fixture-${index}`, engine: 'codex', sessionId: id, transcriptPath: transcript(index), tmuxPane: `%${index + 1}`,
+ projectDir: 'fixture', cwd: root, processIdentity: null, registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1 }
+ })
+ writeFileSync(file, JSON.stringify(rows), { mode: 0o600 })
+ vi.resetModules(); ({ registry } = await import('./registry.js'))
+ registry.load()
+})
+afterEach(() => { vi.restoreAllMocks(); vi.doUnmock('../engines/transcriptBindings.js'); vi.unstubAllEnvs(); vi.resetModules(); rmSync(root, { recursive: true, force: true }) })
+
+it.each(['', '{', 'wrong-id'])('holds a saved unreadable identity (%s), preserves its bytes, and retries without restarting', async text => {
+ const before = readFileSync(file, 'utf8')
+ writeFileSync(transcript(0), text === 'wrong-id' ? header(ids[1]!) : text)
+ registry.load()
+ expect(registry.byAgent('fixture-0')).toMatchObject({ sessionId: ids[0], transcriptPath: transcript(0), identityHold: expect.any(String) })
+ expect(registry.byAgent('fixture-1')).toMatchObject({ sessionId: ids[1], transcriptPath: transcript(1) })
+ expect(registry.byAgent('fixture-1')).not.toHaveProperty('identityHold')
+ expect(readFileSync(file, 'utf8')).toBe(before)
+ expect(() => registry.revalidateBinding('fixture-0')).toThrow()
+ expect(registry.byAgent('fixture-0')?.sessionId).toBe(ids[0])
+ writeFileSync(transcript(0), header(ids[0]!))
+ expect(registry.revalidateBinding('fixture-0')).not.toHaveProperty('identityHold')
+ expect(readFileSync(file, 'utf8')).toBe(before)
+ rmSync(transcript(0))
+ expect(registry.revalidateBinding('fixture-0')).toMatchObject({ sessionId: '', transcriptPath: null })
+ expect(registry.bySession(ids[0]!)).toBeUndefined()
+ expect(registry.bySession(ids[1]!)).toBeDefined()
+})
+
+it('restores every affected staged row when the shared root changes after file verification', async () => {
+ const before = readFileSync(file, 'utf8')
+ vi.doMock('../engines/transcriptBindings.js', async original => {
+ const actual = await original<typeof import('../engines/transcriptBindings.js')>()
+ return { ...actual, transcriptRootEvidence: (...args: Parameters<typeof actual.transcriptRootEvidence>) => {
+ const proof = actual.transcriptRootEvidence(...args)
+ return { ...proof, verify() {
+ renameSync(join(home, 'sessions'), join(home, 'previous')); mkdirSync(join(home, 'sessions'))
+ proof.verify()
+ } }
+ } }
+ })
+ vi.resetModules(); ({ registry } = await import('./registry.js')); registry.load()
+ for (const [index, id] of ids.entries()) expect(registry.byAgent(`fixture-${index}`)).toMatchObject({ sessionId: id,
+ transcriptPath: transcript(index), identityHold: expect.stringContaining('changed') })
+ expect(readFileSync(file, 'utf8')).toBe(before)
+})
+
+it('holds only the row whose header changed while its sibling was staged', async () => {
+ const before = readFileSync(file, 'utf8')
+ vi.doMock('../engines/transcriptBindings.js', async original => {
+ const actual = await original<typeof import('../engines/transcriptBindings.js')>()
+ return { ...actual, savedTranscriptEvidence: (...args: Parameters<typeof actual.savedTranscriptEvidence>) => {
+ const proof = actual.savedTranscriptEvidence(...args)
+ if (args[1] === ids[1]) writeFileSync(transcript(0), header(ids[1]!))
+ return proof
+ } }
+ })
+ vi.resetModules(); ({ registry } = await import('./registry.js')); registry.load()
+ expect(registry.byAgent('fixture-0')).toMatchObject({ sessionId: ids[0], transcriptPath: transcript(0), identityHold: expect.stringContaining('changed') })
+ expect(registry.byAgent('fixture-1')).not.toHaveProperty('identityHold')
+ expect(readFileSync(file, 'utf8')).toBe(before)
+})
+
+it('keeps holds transient and only retries bindings that still exist', () => {
+ expect(registry.setIdentityHold('missing', 'pending')).toBe(false)
+ expect(registry.revalidateBinding('missing')).toBeNull()
+ expect(registry.setIdentityHold('fixture-0', '')).toBe(true)
+ expect(registry.byAgent('fixture-0')?.identityHold).toBe('Waiting for conversation identity.')
+ expect(registry.setIdentityHold('fixture-0', 'x'.repeat(2000))).toBe(true)
+ expect(registry.byAgent('fixture-0')?.identityHold).toHaveLength(1024)
+ expect(registry.setIdentityHold('fixture-0', 'x'.repeat(2000))).toBe(false)
+ expect(registry.setIdentityHold('fixture-0')).toBe(true)
+ registry.unbindSession(ids[0]!)
+ expect(registry.revalidateBinding('fixture-0')).toMatchObject({ sessionId: '', transcriptPath: null })
+})
+
+it.each(['same', 'absent', 'repaired'] as const)('never overwrites a peer binding while retrying %s evidence', async outcome => {
+ const binding = await import('../engines/transcriptBindings.js')
+ const peer = new (registry.constructor as new () => typeof registry)()
+ peer.load()
+ const original = registry.byAgent('fixture-0')!
+ registry.setIdentityHold(original.agentId, 'waiting')
+ if (outcome === 'absent') rmSync(transcript(0))
+ if (outcome === 'repaired') {
+ writeFileSync(transcript(0), JSON.stringify({ type: 'session_meta', payload: {
+ id: 'cccccccc-3333-4333-8333-cccccccccccc', cwd: root,
+ source: { subagent: { thread_spawn: { parent_thread_id: ids[0] } } },
+ } }) + '\n')
+ const parent = join(home, 'sessions', `rollout-${ids[0]}-parent.jsonl`)
+ writeFileSync(parent, header(ids[0]!))
+ await vi.waitFor(() => expect(binding.savedTranscriptEvidence('codex', ids[0]!, transcript(0), home).path).toBe(parent), { timeout: 3_000, interval: 25 })
+ }
+ const nextId = 'dddddddd-4444-4444-8444-dddddddddddd'
+ const nextPath = join(home, 'sessions', `rollout-${nextId}.jsonl`)
+ writeFileSync(nextPath, header(nextId))
+ expect(peer.register({ engine: 'codex', sessionId: nextId, transcriptPath: nextPath, tmuxPane: '%1', cwd: root })).not.toBeNull()
+ const latest = readFileSync(file, 'utf8')
+ // A parallel private fixture can change a shared ancestor during enumeration. Require a fresh
+ // attempt to reach this exact durable-owner fence; an arbitrary native hold is not success.
+ await vi.waitFor(() => expect(() => registry.revalidateBinding(original.agentId)).toThrow('saved binding changed'), { timeout: 3_000, interval: 25 })
+ expect(readFileSync(file, 'utf8')).toBe(latest)
+ expect(registry.bySession(ids[0]!)).toBe(original)
+ expect(original).toMatchObject({ sessionId: ids[0], transcriptPath: transcript(0), identityHold: 'waiting' })
+ expect(peer.bySession(nextId)?.transcriptPath).toBe(nextPath)
+ // Ordinary reconciliation can refresh the peer's commit because the failed retry changed no facts.
+ registry.flush()
+ expect(registry.byAgent(original.agentId)).toMatchObject({ sessionId: nextId, transcriptPath: nextPath })
+ expect(registry.revalidateBinding(original.agentId)?.sessionId).toBe(nextId)
+})
+
+it('commits a conclusive release inside a discovery batch before its callback continues', async () => {
+ registry.setIdentityHold('fixture-0', 'waiting')
+ rmSync(transcript(0))
+ await registry.transaction(async () => {
+ const saved = registry.revalidateBinding('fixture-0')!
+ expect(saved.sessionId).toBe('')
+ expect(registry.bySession(ids[0]!)).toBeUndefined()
+ expect(JSON.parse(readFileSync(file, 'utf8')).find((row: { agentId: string }) => row.agentId === saved.agentId).sessionId).toBe('')
+ await Promise.resolve()
+ })
+})
+
+it('rechecks native evidence while holding the registry write lock and publishes nothing on a failed fence', async () => {
+ let retry = false, checked = false
+ vi.doMock('../engines/transcriptBindings.js', async original => {
+ const actual = await original<typeof import('../engines/transcriptBindings.js')>()
+ return { ...actual, savedTranscriptEvidence: (...args: Parameters<typeof actual.savedTranscriptEvidence>) => {
+ const proof = actual.savedTranscriptEvidence(...args)
+ return { ...proof, verify() {
+ if (retry) {
+ checked = true
+ expect(existsSync(`${file}.lock`)).toBe(true)
+ writeFileSync(transcript(0), header(ids[1]!))
+ }
+ proof.verify()
+ } }
+ } }
+ })
+ vi.resetModules(); ({ registry } = await import('./registry.js')); registry.load()
+ registry.setIdentityHold('fixture-0', 'waiting')
+ const before = readFileSync(file, 'utf8')
+ retry = true
+ expect(() => registry.revalidateBinding('fixture-0')).toThrow()
+ expect(checked).toBe(true)
+ expect(readFileSync(file, 'utf8')).toBe(before)
+ expect(registry.bySession(ids[0]!)).toMatchObject({ identityHold: 'waiting', transcriptPath: transcript(0) })
+})
+
+it('retains monotonic recovery authority through register and save, and never persists interpretation state', async () => {
+ const { transcriptReadIdentity } = await import('../core/transcripts/readIdentity.js')
+ const original = registry.byAgent('fixture-0')!, before = transcriptReadIdentity(original)
+ registry.setIdentityHold(original.agentId, 'waiting')
+ const held = original.evidenceRevision!
+ registry.register({ engine: 'codex', sessionId: ids[0]!, transcriptPath: transcript(0), tmuxPane: '%1', cwd: root })
+ expect(registry.byAgent(original.agentId)).toMatchObject({ evidenceRevision: held, identityHold: 'waiting' })
+ const recovered = registry.revalidateBinding(original.agentId)!
+ expect(recovered.evidenceRevision).toBeGreaterThan(held)
+ expect(recovered.interpretationHold).toBeTruthy()
+ expect(transcriptReadIdentity(recovered)).not.toBe(before)
+ registry.flush()
+ expect(registry.byAgent(original.agentId)).toBe(recovered)
+ expect(recovered.interpretationHold).toBeTruthy()
+ const persisted = JSON.parse(readFileSync(file, 'utf8'))[0]
+ for (const field of ['identityHold', 'interpretationHold', 'evidenceRevision']) expect(persisted).not.toHaveProperty(field)
+ expect(registry.setInterpretationHold('missing', held)).toBe(false)
+ expect(registry.setInterpretationHold(original.agentId, held)).toBe(false)
+ expect(registry.setInterpretationHold(original.agentId, recovered.evidenceRevision, 'retry reader')).toBe(true)
+ expect(recovered.interpretationHold).toBe('retry reader')
+ expect(registry.setInterpretationHold(original.agentId, recovered.evidenceRevision)).toBe(true)
+ expect(registry.setInterpretationHold(original.agentId, recovered.evidenceRevision)).toBe(false)
+ expect(recovered.interpretationHold).toBeUndefined()
+})
+
+it.each(['identity', 'interpretation', 'unbound'] as const)('does not transfer the old conversation’s %s obligation to a newly bound session', async hold => {
+ const old = registry.byAgent('fixture-0')!
+ if (hold === 'unbound') registry.unbindSession(old.sessionId)
+ registry.setIdentityHold(old.agentId, 'old header incomplete')
+ if (hold === 'interpretation') registry.revalidateBinding(old.agentId)
+ const revision = registry.byAgent(old.agentId)!.evidenceRevision
+ const id = 'eeeeeeee-5555-4555-8555-eeeeeeeeeeee', path = join(home, 'sessions', `rollout-${id}.jsonl`)
+ writeFileSync(path, header(id))
+ const result = registry.register({ engine: 'codex', sessionId: id, transcriptPath: path, tmuxPane: '%1', cwd: root })!
+ expect(result.isNew).toBe(true)
+ expect(result.entry).toMatchObject({ sessionId: id, evidenceRevision: revision })
+ expect(result.entry.identityHold).toBeUndefined(); expect(result.entry.interpretationHold).toBeUndefined()
+ const { createBinding } = await import('../core/agents/bind.js')
+ const attachSession = vi.fn(async () => true)
+ const binding = createBinding({ registry, attachSession, stoppedAgents: { save: vi.fn() },
+ mirror: { inheritSummary: vi.fn() }, forgetSession: vi.fn(), clients: { send: vi.fn() },
+ announceSession: vi.fn(), syncRecapPool: vi.fn(),
+ } as unknown as import('../core/agents/bind.js').BindDeps)
+ await binding.handleRegistered(result.entry, { ...result, hookEvent: 'UserPromptSubmit' })
+ expect(attachSession).toHaveBeenCalledWith(result.entry, true, false, hold === 'unbound')
+})
diff --git a/cli/src/lib/registry.homes.spec.ts b/cli/src/lib/registry.homes.spec.ts
index 185f26afa..f6635130d 100644
--- a/cli/src/lib/registry.homes.spec.ts
+++ b/cli/src/lib/registry.homes.spec.ts
@@ -31,7 +31,7 @@ it('repairs a child-overwritten parent from an adopted Codex home before the log
const parentId = '019f7f1b-195d-70f2-861b-de5d54a3e141'
const childId = '019f8dae-e5f4-7c11-90d1-600854063b2c'
const parent = join(sessions, `rollout-${parentId}.jsonl`), child = join(sessions, `rollout-${childId}.jsonl`)
- writeFileSync(parent, JSON.stringify({ type: 'session_meta', payload: { id: parentId, source: 'cli' } }) + '\n')
+ writeFileSync(parent, JSON.stringify({ type: 'session_meta', payload: { id: parentId, cwd: root, source: 'cli' } }) + '\n')
writeFileSync(child, JSON.stringify({ type: 'session_meta', payload: { id: childId,
source: { subagent: { thread_spawn: { parent_thread_id: parentId, depth: 1 } } },
} }) + '\n')
@@ -89,7 +89,7 @@ it.each(['healthy', 'unreadable', 'changed-at-commit'] as const)('stages a regis
const rows = Array.from({ length: 200 }, (_, index) => {
const id = `aaaaaaaa-1111-4222-8333-${String(index).padStart(12, '0')}`
const transcriptPath = join(sessions, `rollout-${id}.jsonl`)
- writeFileSync(transcriptPath, JSON.stringify({ type: 'session_meta', payload: { id, source: 'cli' } }) + '\n')
+ writeFileSync(transcriptPath, JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, source: 'cli' } }) + '\n')
return { launcherId: `fixture-${index}`, engine: 'codex', sessionId: id, transcriptPath, tmuxPane: `%${index + 1}`,
projectDir: 'fixture', cwd: root, processIdentity: null, registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1 }
})
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 8e98b3430..86718bbed 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -526,7 +526,7 @@ describe('registry remote display names', () => {
const childPath = join(sessionsDir, `rollout-${childId}.jsonl`)
writeFileSync(parentPath, JSON.stringify({
type: 'session_meta',
- payload: { id: parentId, source: 'cli' },
+ payload: { id: parentId, cwd: '/fixture/work', source: 'cli' },
}) + '\n')
writeFileSync(childPath, JSON.stringify({
type: 'session_meta',
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 41bd6d8ed..19748f14b 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -38,12 +38,12 @@ import {
import { randomUUID } from 'crypto'
import { join, basename, dirname, relative, isAbsolute } from 'path'
import { machineNames } from './machineNames.js'
-import { cursorDataDir } from '../engines/cursor/contract.js'
import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'
import { env } from '../config/env.js'
-import { engineHomeSnapshot, sessionFolderOf, sessionRoots, type EngineHomeSnapshot } from './engineHomes.js'
-import { findSessionFileOf, sessionMetaOf } from '../engines/sessionFiles.js'
-import { isSessionStoreEngine, sessionStoreContracts, sessionStoreOf } from '../engines/sessionStoreContracts.js'
+import { engineHomeSnapshot, sessionRoots, type EngineHomeSnapshot } from './engineHomes.js'
+import { transcriptRoot as TRANSCRIPT_ROOT, needsHomeCatalog, savedTranscriptEvidence, transcriptEvidence, transcriptRootEvidence } from '../engines/transcriptBindings.js'
+export { engineKeepsTranscriptFile } from '../engines/transcriptBindings.js'
+import { sessionStoreOf } from '../engines/sessionStoreContracts.js'
import { admitHook } from '../engines/hooks.js'
import { ENGINES, isTerminalEngine, type AgentEngine } from '../engines/types.js'
import type { GridAssignment } from './gridAssignment.js'
@@ -93,6 +93,10 @@ export interface RegisteredSession {
launch?: AgentLaunch
/** Fresh evidence is unavailable; retain the binding and expose its reason without persisting an authority verdict. */
identityHold?: string
+ /** Monotonic process-local authority: a hold/recovery cycle must never revive an older read. */
+ evidenceRevision?: number
+ /** Native identity recovered; interpretation stays paused until its replacement tail is installed. */
+ interpretationHold?: string
/** Enter on stopped work must never become a fresh conversation, including after a daemon restart. */
resumeOnly?: true
/** External admission survives a crash independently of any conversation Harness already owns. */
@@ -553,7 +557,7 @@ function tmuxProjection(runtimes: readonly TerminalRuntimeRef[]): string {
}
function persistedRow(entry: RegisteredSession): RegisteredSession | Omit<RegisteredSession, 'tmuxPane'> {
- const { identityHold: _hold, ...saved } = entry
+ const { identityHold: _hold, evidenceRevision: _revision, interpretationHold: _interpretation, ...saved } = entry
if (saved.tmuxPane) return { ...saved, runtimes: saved.runtimes.map((runtime) => ({ ...runtime })) }
const { tmuxPane: _legacy, ...row } = saved
return { ...row, runtimes: row.runtimes.map((runtime) => ({ ...runtime })) }
@@ -591,7 +595,7 @@ export function strictPersistedRow(raw: unknown): RegisteredSession | null {
// Taken out of the spread and put back only when it is a real moment: the spread would otherwise
// carry a hand-edited string or a negative number straight into the frame's `toISOString()`.
// `forkedFrom` is out too, so an invalid one is dropped rather than spread back in as-is.
- const { identityHold: _identityHold, lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, externalResume: _externalResume, ...rest } = row
+ const { identityHold: _identityHold, evidenceRevision: _revision, interpretationHold: _interpretation, lastOpenedAt: rawOpenedAt, closePlan: rawClosePlan, forkedFrom: rawForkedFrom, scmLaunch: rawScmLaunch, externalResume: _externalResume, ...rest } = row
const lastOpenedAt = normalizedOpenedAt(rawOpenedAt)
// Out of the spread for the same reason: a half-formed record is dropped, never relaunched with.
const scmLaunch = parseScmLaunchRecord(rawScmLaunch)
@@ -922,43 +926,6 @@ function isWithin(root: string, file: string): boolean {
return rel === '' || (!rel.startsWith('..') && !rel.startsWith(`/`) && !rel.startsWith(`\\`))
}
-/**
- * Where each engine's conversation file lives, or **null for an engine that keeps no file at all**.
- *
- * The null entries are not gaps: opencode, kilo, hermes and devin keep their conversations in a
- * SQLite database (`sessionRepair.ts`'s `dbEngineSession` reads an id out and has no path to
- * return), and a terminal has no conversation. Written as a table rather than the nested ternary it
- * replaces so "this engine has no transcript" is a fact a caller can ASK for — Pause and Resume both
- * need it, and both used to demand a file every engine was assumed to have.
- */
-const TRANSCRIPT_ROOT: Readonly<Record<AgentEngine, (() => string) | 'store' | null>> = {
- // Amp's root is OURS, not Amp's: the transcript is written by the adapter's own plugin because Amp
- // keeps no conversation on disk (see installAmpPlugin).
- amp: () => env.AMP_SESSIONS_DIR,
- muse: () => join(env.MUSE_HOME, 'sessions'),
- // Declared by the engine's session store (engines/sessionStoreContracts.ts): the folders `transcriptRoots` names.
- codex: 'store',
- grok: () => join(env.GROK_HOME, 'sessions'),
- agy: () => join(env.AGY_HOME, 'brain'),
- copilot: () => join(env.COPILOT_HOME, 'session-state'),
- cursor: () => join(cursorDataDir(), 'projects'),
- pi: () => join(env.PI_HOME, 'agent', 'sessions'),
- commandcode: () => join(env.COMMANDCODE_HOME, 'projects'),
- claude: 'store',
- opencode: null,
- kilo: null,
- hermes: null,
- devin: null,
- terminal: null,
-}
-
-/** Whether this engine's conversation is a FILE the daemon can point a resume at. False for the
- * database-backed engines and the shell — for them a recorded session id is the whole record, and
- * demanding a transcript would refuse a resume that works. */
-export function engineKeepsTranscriptFile(engine: AgentEngine): boolean {
- return TRANSCRIPT_ROOT[engine] !== null
-}
-
/**
* The folders an engine's transcripts may be in: its own, and for an engine with a declared session store each
* home the person moved in their shell profile (lib/engineHomes.ts). An agent's own profile (its CODEX_HOME) is
@@ -973,8 +940,10 @@ export function validTranscriptPath(engine: AgentEngine, filePath: string, codex
}
/** Existing control candidates: an unreadable path cannot be excluded from a complete identity pool. */
-export function inspectTranscriptPath(engine: AgentEngine, filePath: string): boolean {
- return checkTranscriptPath(engine, filePath, undefined, false, true)
+export function inspectTranscriptPath(engine: AgentEngine, filePath: string, codexHome?: string, allowMissing = false): boolean {
+ const proof = transcriptEvidence(engine, filePath, codexHome, allowMissing)
+ proof.verify()
+ return proof.valid
}
function checkTranscriptPath(engine: AgentEngine, filePath: string, codexHome: string | undefined, allowMissing: boolean, strict: boolean, snapshot?: EngineHomeSnapshot): boolean {
@@ -1022,6 +991,7 @@ function writeBoot(bootId: string): void {
class Registry {
/** agentId → record. The store. */
private agents = new Map<string, RegisteredSession>()
+ private evidenceRevision = 0
/** engine sessionId → agentId. Needed because web and device address turn control with a bare
* `sessionId` (`cancel`, `question_response`, `compact`, `session_get`) while everything else
* addresses the agent. `resolve()` is the one lookup that accepts either. */
@@ -1095,6 +1065,8 @@ class Registry {
this.sessionIndex.delete(entry.sessionId)
}
delete entry.identityHold
+ delete entry.interpretationHold
+ entry.evidenceRevision = ++this.evidenceRevision
entry.sessionId = ''
entry.boundAt = null
entry.transcriptPath = null
@@ -1176,8 +1148,22 @@ class Registry {
let snapshot: EngineHomeSnapshot | undefined, unavailableHomes: unknown
const dependent = new Map<string, Partial<RegisteredSession>>()
const staged = new Map<string, RegisteredSession>()
+ const bindingProofs = new Map<string, { proof: ReturnType<typeof savedTranscriptEvidence>; original: Partial<RegisteredSession> }>()
+ const rootScopes = new Map<string, { proof?: ReturnType<typeof transcriptRootEvidence>; error?: unknown;
+ rows: Map<string, Partial<RegisteredSession>> }>()
+ const rootsFor = (engine: AgentEngine, profile: string | undefined, catalog: EngineHomeSnapshot | undefined) => {
+ const key = JSON.stringify([engine, profile ?? null])
+ let scope = rootScopes.get(key)
+ if (!scope) {
+ scope = { rows: new Map() }; rootScopes.set(key, scope)
+ try { scope.proof = transcriptRootEvidence(engine, profile, catalog) }
+ catch (error) { scope.error = error }
+ }
+ if (scope.error) throw scope.error
+ return scope
+ }
const catalogFor = (engine: AgentEngine, profile?: string): EngineHomeSnapshot | undefined => {
- if (TRANSCRIPT_ROOT[engine] !== 'store' || sessionStoreOf(engine)?.sessions.profile && profile) return undefined
+ if (!needsHomeCatalog(engine, profile)) return undefined
if (unavailableHomes) throw unavailableHomes
try { return snapshot ??= engineHomeSnapshot() }
catch (error) { unavailableHomes = error; throw error }
@@ -1189,6 +1175,7 @@ class Registry {
row.source = row.sessionId && typeof original.source === 'string' ? original.source : null
row.projectDir = typeof original.projectDir === 'string' ? original.projectDir : row.transcriptPath ? basename(dirname(row.transcriptPath)) : row.sessionId || row.agentId
row.identityHold = error instanceof Error ? error.message : String(error)
+ row.evidenceRevision = ++this.evidenceRevision
}
for (const raw of Array.isArray(arr) ? arr : []) {
const engine = normalizedAgentEngine(raw?.engine)
@@ -1211,44 +1198,33 @@ class Registry {
// profile), else release the binding. Declared by the engine's session store (`repairsOverwrittenParent`)
// and read with the kit, in core.
let repairedParentTranscript = false, homeError: unknown
- const needsCatalog = !!transcriptPath && TRANSCRIPT_ROOT[engine] === 'store' && !(sessionStoreOf(engine)?.sessions.profile && rawCodexHome)
+ const needsCatalog = bound && !!transcriptPath && needsHomeCatalog(engine, rawCodexHome)
+ let bindingProof: ReturnType<typeof savedTranscriptEvidence> | undefined
+ let rootScope: ReturnType<typeof rootsFor> | undefined
try {
const rowSnapshot = needsCatalog ? catalogFor(engine, rawCodexHome) : undefined
- if (isSessionStoreEngine(engine) && sessionStoreContracts[engine].repairsOverwrittenParent && transcriptPath) {
- const meta = sessionMetaOf(engine, transcriptPath)
- if (meta?.isSubagent) {
- const repaired = meta.parentThreadId === rawSessionId
- ? findSessionFileOf(engine, rawSessionId, sessionFolderOf(engine, { profile: rawCodexHome, transcriptPath }, rowSnapshot))
- : null
- if (!repaired || !checkTranscriptPath(engine, repaired, rawCodexHome, false, false, rowSnapshot) || sessionMetaOf(engine, repaired)?.isSubagent) {
- changed = true
- bound = false
- transcriptPath = null
- } else {
- console.log(`[registry] repaired ${sessionStoreContracts[engine].label} parent ${rawSessionId.slice(0, 8)} transcript after child hook overwrite`)
- transcriptPath = repaired
- repairedParentTranscript = true
- changed = true
- }
- }
- }
- // A process agent remains valid without a session. A missing/invalid transcript releases only the
- // binding so the discovery/store repair path can bind it again if appropriate.
if (!bound) transcriptPath = null
- if (
- (bound && engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi' && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin' && !transcriptPath)
- || (bound && transcriptPath !== null && !checkTranscriptPath(engine, transcriptPath, rawCodexHome, false, false, rowSnapshot))
- ) {
+ if (bound && transcriptPath) {
+ rootScope = rootsFor(engine, rawCodexHome, rowSnapshot)
+ bindingProof = savedTranscriptEvidence(engine, rawSessionId, transcriptPath, rawCodexHome, rowSnapshot, rootScope.proof)
+ const verified = bindingProof.path
+ if (verified !== transcriptPath) {
+ changed = true
+ repairedParentTranscript = !!verified
+ transcriptPath = verified
+ }
+ if (!verified) bound = false
+ } else if (bound && engine !== 'cursor' && engine !== 'opencode' && engine !== 'kilo' && engine !== 'pi'
+ && engine !== 'hermes' && engine !== 'commandcode' && engine !== 'devin') {
bound = false
- transcriptPath = null
changed = true
}
} catch (error) {
- if (!(error instanceof IdentityReadUnavailable)) throw error
homeError = error
transcriptPath = typeof raw.transcriptPath === 'string' && raw.transcriptPath ? raw.transcriptPath : null
bound = !!rawSessionId
repairedParentTranscript = false
+ bindingProof = undefined
}
// Old launcher-owned records used launcherId as the public id. Preserve it while process discovery
// validates/adopts the live runtime, then save the record without the legacy ownership field.
@@ -1333,10 +1309,20 @@ class Registry {
this.quarantine('contains duplicate agent identities')
return
}
+ if (bindingProof) bindingProofs.set(s.agentId, { proof: bindingProof, original: raw })
+ rootScope?.rows.set(s.agentId, raw)
if (needsCatalog) dependent.set(s.agentId, raw)
if (homeError) preserve(s, raw, homeError)
staged.set(s.agentId, s)
}
+ for (const [id, { proof, original }] of bindingProofs) {
+ try { proof.verify() }
+ catch (error) { preserve(staged.get(id)!, original, error) }
+ }
+ for (const { proof, rows } of rootScopes.values()) {
+ try { proof?.verify() }
+ catch (error) { for (const [id, raw] of rows) preserve(staged.get(id)!, raw, error) }
+ }
if (snapshot) {
try { snapshot.verify() }
catch (error) {
@@ -1346,6 +1332,10 @@ class Registry {
for (const row of staged.values()) {
this.index(row)
if (row.identityHold) console.log(`[registry] ${row.agentId.slice(0, 8)} binding held · ${row.identityHold}`)
+ else if (row.transcriptPath && bindingProofs.has(row.agentId)
+ && bindingProofs.get(row.agentId)!.original.transcriptPath !== row.transcriptPath) {
+ console.log(`[registry] repaired ${sessionStoreOf(row.engine)!.label} parent ${row.sessionId.slice(0, 8)} transcript after child hook overwrite`)
+ }
}
if (!validatedRows(this.list().map(persistedRow))) {
this.quarantine('violates global identity invariants')
@@ -1686,6 +1676,53 @@ class Registry {
return this.list().filter((s) => !s.sessionId)
}
+ /** A current observation for frames; never persisted as conversation evidence. */
+ setIdentityHold(agentId: string, reason?: string): boolean {
+ const entry = this.agents.get(agentId)
+ const detail = reason === undefined ? undefined : reason.slice(0, 1024) || 'Waiting for conversation identity.'
+ if (!entry || entry.identityHold === detail) return false
+ entry.evidenceRevision = ++this.evidenceRevision
+ if (detail) entry.identityHold = detail
+ else delete entry.identityHold
+ return true
+ }
+
+ /** Only the attachment that read this revision can complete or explain its recovery. */
+ setInterpretationHold(agentId: string, revision: number | undefined, reason?: string, create = false): boolean {
+ const entry = this.agents.get(agentId)
+ if (!entry || entry.identityHold || entry.evidenceRevision !== revision || (!entry.interpretationHold && !(create && reason))) return false
+ if (!entry.interpretationHold) entry.evidenceRevision = ++this.evidenceRevision
+ if (reason) entry.interpretationHold = reason.slice(0, 1024)
+ else delete entry.interpretationHold
+ return true
+ }
+
+ /** Retry only this saved binding. A failed read leaves all of its prior facts intact. */
+ revalidateBinding(agentId: string): RegisteredSession | null {
+ const entry = this.agents.get(agentId)
+ if (!entry) return null
+ if (!entry.sessionId || !entry.transcriptPath) return entry
+ const proof = savedTranscriptEvidence(entry.engine, entry.sessionId, entry.transcriptPath, entry.codexHome ?? undefined)
+ // Stage the change without releasing the live index. A daemon-down hook may have bound another
+ // conversation since load; a three-way save of this repair must never overwrite that newer bind.
+ const candidate = { ...entry }
+ if (!proof.path) Object.assign(candidate, { sessionId: '', boundAt: null, transcriptPath: null, source: null, lastTranscriptAt: Date.now() })
+ else if (proof.path !== entry.transcriptPath) {
+ candidate.transcriptPath = proof.path
+ candidate.projectDir = basename(dirname(proof.path))
+ }
+ delete candidate.identityHold
+ this.save(true, false, undefined, { agentId, candidate, verify: () => proof.verify() })
+ // save refreshes the indices only after the durable commit. Even same-path recovery is fenced
+ // against another writer and rechecks the native evidence after obtaining the lock.
+ const saved = this.agents.get(agentId)!
+ delete saved.identityHold
+ saved.evidenceRevision = ++this.evidenceRevision
+ if (saved.sessionId) saved.interpretationHold = 'Waiting for transcript interpretation to recover.'
+ else delete saved.interpretationHold
+ return saved
+ }
+
/**
* Upsert a session. Idempotent — a re-register (e.g. from the UserPromptSubmit catch hook) just
* refreshes `touchedAt`. Deduped by tmux pane: one session per pane, so a `/clear` rotation
@@ -1844,9 +1881,13 @@ class Registry {
? (existing?.cwd && project.belongs(existing.cwd, effectiveTranscriptPath) ? existing.cwd
: project.cwdOf(effectiveTranscriptPath) ?? input.cwd)
: baseCwd
+ const retainEvidence = sameSession && existing.engine === engine && existing.transcriptPath === effectiveTranscriptPath
const entry: RegisteredSession = {
schemaVersion: 2,
active: existing?.active ?? true,
+ ...(existing?.evidenceRevision === undefined ? {} : { evidenceRevision: existing.evidenceRevision }),
+ ...(retainEvidence && existing.identityHold ? { identityHold: existing.identityHold } : {}),
+ ...(retainEvidence && existing.interpretationHold ? { interpretationHold: existing.interpretationHold } : {}),
// No `launch`: a hook is the engine reporting for duty, so whatever the launch was — starting,
// or failed by a watcher that gave up too early — it is over, and the frame reads `ready`.
agentId,
@@ -2477,8 +2518,11 @@ class Registry {
this.saveNames()
}
- private save(strict = false, exiting = false, externalAgentId?: string): void {
- if (this.transactionDepth > 0 && !exiting) {
+ private save(strict = false, exiting = false, externalAgentId?: string,
+ bindingCommit?: { agentId: string; candidate: RegisteredSession; verify: () => void }): void {
+ // Discovery batches observations, but a recovered binding must be durable before interpretation
+ // resumes. Commit a complete batch now; an incomplete batch remains held and retries next pass.
+ if (this.transactionDepth > 0 && !exiting && !bindingCommit) {
if (strict) throw new Error('Cannot acknowledge a close intent inside an uncommitted registry transaction')
this.savePending = true
return
@@ -2495,10 +2539,12 @@ class Registry {
const row = persistedRow(entry) as unknown as Record<string, unknown>
return [entry.agentId, row] as const
}))
+ if (bindingCommit) currentRows.set(bindingCommit.agentId, persistedRow(bindingCommit.candidate) as unknown as Record<string, unknown>)
// A discovery batch may be awaiting a reader after acknowledging a complete binding. Exit cannot
// wait for it. Check BEFORE merge conflict resolution: an incomplete pane swap must never be
// made to look valid by evicting its other owner. Its last durable snapshot remains untouched.
if (exiting && !validatedRows([...currentRows.values()])) throw new Error('Cannot flush an incomplete registry transaction at exit')
+ if (bindingCommit && !validatedRows([...currentRows.values()])) throw new IdentityReadUnavailable('the registry observation batch is incomplete')
// Discovery still calls save on an unchanged observation so a daemon-down hook's commit is
// noticed. If neither side changed, avoid the lock's process probe and all three fsyncs.
// Read through the normal ownership/mode/no-symlink checks; timestamps cannot prove equality.
@@ -2533,6 +2579,14 @@ class Registry {
if (id) latest.set(id, value as Record<string, unknown>)
}
+ if (bindingCommit) {
+ if ((latest.has(bindingCommit.agentId) ? rowFingerprint(latest.get(bindingCommit.agentId)) : undefined)
+ !== this.persistedBaseline.get(bindingCommit.agentId)) {
+ throw new IdentityReadUnavailable('the saved binding changed while its evidence was being read')
+ }
+ bindingCommit.verify()
+ }
+
if (externalAgentId && (latest.has(externalAgentId) ? rowFingerprint(latest.get(externalAgentId)) : undefined)
!== this.persistedBaseline.get(externalAgentId)) {
throw new Error('The durable adoption changed while it was being prepared')
@@ -2571,8 +2625,11 @@ class Registry {
for (const row of rows) {
const entry = previous.get(row.agentId) ?? row
if (entry !== row) {
- const identityHold = entry.engine === row.engine && entry.sessionId === row.sessionId
- && entry.transcriptPath === row.transcriptPath && entry.codexHome === row.codexHome ? entry.identityHold : undefined
+ const sameBinding = entry.engine === row.engine && entry.sessionId === row.sessionId
+ && entry.transcriptPath === row.transcriptPath && entry.codexHome === row.codexHome
+ const identityHold = sameBinding ? entry.identityHold : undefined
+ const interpretationHold = sameBinding ? entry.interpretationHold : undefined
+ const evidenceRevision = sameBinding ? entry.evidenceRevision : ++this.evidenceRevision
// External deletions count too: retaining a cancelled closePlan here would make the
// next observation write it back and turn a cancelled close into pending work again.
for (const key of Object.keys(entry)) {
@@ -2580,6 +2637,8 @@ class Registry {
}
Object.assign(entry, row)
if (identityHold) entry.identityHold = identityHold
+ if (interpretationHold) entry.interpretationHold = interpretationHold
+ if (evidenceRevision !== undefined) entry.evidenceRevision = evidenceRevision
}
this.index(entry)
}
diff --git a/cli/src/lib/runtimeProfileState.spec.ts b/cli/src/lib/runtimeProfileState.spec.ts
index 30303a335..620d09738 100644
--- a/cli/src/lib/runtimeProfileState.spec.ts
+++ b/cli/src/lib/runtimeProfileState.spec.ts
@@ -428,3 +428,29 @@ describe('runtime profiles without the pilot implementations', () => {
expect(manager.getState(agent.sessionId).cliVersion).toBe('1.0.0')
})
})
+
+describe('native evidence recovery', () => {
+ it.each(['configured effort', 'optional config', 'pane'] as const)('rejects a deferred %s after a complete hold/recovery cycle', async operation => {
+ const agent = session(operation === 'optional config' ? 'commandcode' : 'claude')
+ let finish!: () => void
+ const waiting = new Promise<void>(resolve => { finish = resolve })
+ const config = vi.fn(async ({ state }: InlineRuntimeContext) => { await waiting; state.effort = 'high'; return true })
+ vi.mocked(loadEngine).mockResolvedValue({ createRuntimeProfileReader: () => ({ engine: 'commandcode', config }) } as never)
+ const manager = new RuntimeProfileState(engine => engine === 'claude' ? { ...claudeRuntime,
+ configuredEffort: async () => { await waiting; return 'high' },
+ pane: ({ state }, text) => { state.model = text },
+ } : undefined, () => agent)
+ manager.hydrate(agent, [])
+ const before = { ...manager.getState(agent.sessionId) }
+ const pending = operation === 'pane'
+ ? manager.capturePane(agent, async () => { await waiting; return 'stale-model' }, 20, true)
+ : manager.ingestConfig(agent, true)
+ if (operation === 'optional config') await vi.waitFor(() => expect(config).toHaveBeenCalledOnce())
+ agent.identityHold = 'incomplete'; agent.evidenceRevision = 1
+ expect(manager.ingestPane(agent, 'held-model')).toBe(false)
+ delete agent.identityHold; agent.evidenceRevision = 2
+ finish(); await pending
+ expect(manager.getState(agent.sessionId)).toEqual(before)
+ manager.forget(agent.sessionId)
+ })
+})
diff --git a/cli/src/lib/runtimeProfileState.ts b/cli/src/lib/runtimeProfileState.ts
index 611bac25d..91cf0268a 100644
--- a/cli/src/lib/runtimeProfileState.ts
+++ b/cli/src/lib/runtimeProfileState.ts
@@ -34,7 +34,7 @@ const CHANGE_DEBOUNCE_MS = 120
const readIdentity = (session: RegisteredSession): string => JSON.stringify([session.agentId, session.sessionId,
session.engine, session.cwd, session.transcriptPath, session.codexHome, session.hermesHome,
session.model, session.cliVersion, session.boundAt, session.tmuxPane, session.primaryRuntimeKey, session.runtimes,
- session.active, session.processIdentity ? processIdentityKey(session.engine, session.processIdentity) : undefined])
+ session.active, session.evidenceRevision, !!session.identityHold, session.processIdentity ? processIdentityKey(session.engine, session.processIdentity) : undefined])
const copyControl = (control: RuntimeControl | undefined): RuntimeControl | undefined => control && {
...control, target: { ...control.target },
}
@@ -62,7 +62,7 @@ export class RuntimeProfileState {
}
private currentSession(session: RegisteredSession, identity = readIdentity(session)): RegisteredSession | undefined {
const current = this.resolve ? this.resolve(session.agentId) : session
- return current && readIdentity(current) === identity && readIdentity(session) === identity ? current : undefined
+ return current && !current.identityHold && readIdentity(current) === identity && readIdentity(session) === identity ? current : undefined
}
private observe(context: InlineRuntimeContext): InlineRuntimeContext {
diff --git a/cli/src/lib/sessionRepair.bounds.spec.ts b/cli/src/lib/sessionRepair.bounds.spec.ts
index 9752d31ca..ff46e7b9e 100644
--- a/cli/src/lib/sessionRepair.bounds.spec.ts
+++ b/cli/src/lib/sessionRepair.bounds.spec.ts
@@ -10,6 +10,10 @@ import { identityBytes, identityEntries, identityScanBudget } from '../engines/k
import type { RegisteredSession } from './registry.js'
import type { StopAgentServiceDeps } from './stopAgentService.js'
+// These cases exercise count/byte bounds and changing ownership, not host fsync speed.
+// homeAdoption.spec.ts separately advances this clock to prove the work deadline holds.
+vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => 0 } }))
+
vi.mock('node:fs/promises', async original => {
const actual = await original<typeof import('node:fs/promises')>()
return { ...actual, open: vi.fn(actual.open), opendir: vi.fn(actual.opendir), stat: vi.fn(actual.stat),
diff --git a/cli/src/lib/stoppedAgents.spec.ts b/cli/src/lib/stoppedAgents.spec.ts
index 40938ac99..f223b8153 100644
--- a/cli/src/lib/stoppedAgents.spec.ts
+++ b/cli/src/lib/stoppedAgents.spec.ts
@@ -22,10 +22,12 @@ afterEach(() => {
describe('saved catalog reads', () => {
it('saves a held conversation without persisting its transient identity verdict', async () => {
const { saved, store } = await fixture()
- store.save({ ...saved, identityHold: 'The session-home catalog is unavailable.' })
+ store.save({ ...saved, identityHold: 'The session-home catalog is unavailable.', evidenceRevision: 3, interpretationHold: 'pending' })
const raw = JSON.parse(readFileSync(join(directory, 'stopped-agents', `${saved.agentId}.json`), 'utf8'))
expect(raw.session.sessionId).toBe(saved.sessionId)
expect(raw.session).not.toHaveProperty('identityHold')
+ expect(raw.session).not.toHaveProperty('interpretationHold')
+ expect(raw.session).not.toHaveProperty('evidenceRevision')
expect(store.get(saved.agentId)).not.toHaveProperty('identityHold')
})
diff --git a/cli/src/lib/stoppedAgents.ts b/cli/src/lib/stoppedAgents.ts
index 0c7e170a0..69ac73bed 100644
--- a/cli/src/lib/stoppedAgents.ts
+++ b/cli/src/lib/stoppedAgents.ts
@@ -150,6 +150,8 @@ export class StoppedAgentStore {
delete snapshot.closePlan
// A hold describes this daemon's current observation, never durable conversation evidence.
delete snapshot.identityHold
+ delete snapshot.interpretationHold
+ delete snapshot.evidenceRevision
// A snapshot without a tmux pane omits the legacy alias just like registry persistence.
if (!snapshot.tmuxPane) delete (snapshot as Partial<RegisteredSession>).tmuxPane
atomicWriteJson(join(this.directory, `${session.agentId}.json`), { version: 1, session: snapshot })
diff --git a/cli/src/lib/tmuxExternalAdoption.spec.ts b/cli/src/lib/tmuxExternalAdoption.spec.ts
index 6d9fedad5..25b093cde 100644
--- a/cli/src/lib/tmuxExternalAdoption.spec.ts
+++ b/cli/src/lib/tmuxExternalAdoption.spec.ts
@@ -42,8 +42,8 @@ describe.skipIf(!resolveBinaryOnPath('tmux'))('external adoption on a private tm
expect(existsSync(output)).toBe(false)
expect(await backend.isHeld(pane, token)).toBe(true)
expect(await backend.respawn(pane, { ...request, expectedHeldToken: token })).toMatchObject({ state: 'succeeded' })
- await vi.waitFor(() => expect(existsSync(output)).toBe(true))
- expect(readFileSync(output, 'utf8').split('\n')).toEqual([value, folder, value, ''])
+ // The shell creates its redirected file before printf fills it; existence is not completion.
+ await vi.waitFor(() => expect(readFileSync(output, 'utf8').split('\n')).toEqual([value, folder, value, '']))
expect(await backend.isHeld(pane, token)).toBe(false)
expect(await backend.killHeld(pane, token, () => true)).toMatchObject({ dispatch: 'not_started' })
await backend.kill(pane)
diff --git a/cli/src/lib/transcriptBoundary.ts b/cli/src/lib/transcriptBoundary.ts
new file mode 100644
index 000000000..eb4a7248f
--- /dev/null
+++ b/cli/src/lib/transcriptBoundary.ts
@@ -0,0 +1,41 @@
+import { createHash } from 'node:crypto'
+import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs'
+import type { FileHandle } from 'node:fs/promises'
+
+export interface RecoveryBoundary { offset: number; device: number; inode: number; digest: string }
+export type TranscriptFileIdentity = Pick<RecoveryBoundary, 'device' | 'inode'>
+
+export async function verifyTranscriptHandle(handle: FileHandle, expected?: TranscriptFileIdentity): Promise<void> {
+ if (!expected) return
+ const actual = await handle.stat()
+ if (!actual.isFile() || actual.dev !== expected.device || actual.ino !== expected.inode) {
+ throw new Error('ENGINE_CONTROL_BOUNDARY_CHANGED')
+ }
+}
+
+/** The control action does not wait for an interpreter. At most 1 KiB is read synchronously to bind
+ * its boundary to a regular file and its surrounding bytes. Unknown evidence is retained as a hold. */
+export function recoveryBoundary(file: string, at?: RecoveryBoundary): RecoveryBoundary {
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ try {
+ const before = fstatSync(fd), offset = at?.offset ?? before.size
+ if (!before.isFile() || before.size < offset) throw new Error('the transcript was replaced or truncated')
+ const bytes = Math.min(offset, 512), first = Buffer.alloc(bytes), last = Buffer.alloc(bytes)
+ if (readSync(fd, first, 0, bytes, 0) !== bytes || readSync(fd, last, 0, bytes, offset - bytes) !== bytes) {
+ throw new Error('the transcript boundary is unreadable')
+ }
+ if (offset && last[bytes - 1] !== 10) throw new Error('the transcript boundary is an incomplete record')
+ const after = fstatSync(fd), path = lstatSync(file)
+ if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size
+ || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs
+ || path.dev !== after.dev || path.ino !== after.ino || path.isSymbolicLink()) {
+ throw new Error('the transcript changed while its boundary was read')
+ }
+ const result = { offset, device: after.dev, inode: after.ino,
+ digest: createHash('sha256').update(first).update(last).digest('hex') }
+ if (at && (at.device !== result.device || at.inode !== result.inode || at.digest !== result.digest)) {
+ throw new Error('the transcript no longer matches the control boundary')
+ }
+ return result
+ } finally { closeSync(fd) }
+}
diff --git a/cli/src/lib/transcriptControls.ts b/cli/src/lib/transcriptControls.ts
new file mode 100644
index 000000000..afbf53ea9
--- /dev/null
+++ b/cli/src/lib/transcriptControls.ts
@@ -0,0 +1,34 @@
+/** Explicit core decisions replay at their original byte boundary, before any later record. */
+import { recoveryBoundary, type RecoveryBoundary } from './transcriptBoundary.js'
+
+export interface TranscriptClose {
+ readonly offset: number
+ readonly reason: 'cancel' | 'abandoned' | 'hook'
+ readonly boundary?: RecoveryBoundary
+}
+
+export function transcriptCloses(value: unknown): value is readonly TranscriptClose[] {
+ return Array.isArray(value) && value.length <= 128 && value.every((item, index) =>
+ item !== null && typeof item === 'object' && Number.isSafeInteger(item.offset) && item.offset >= 0
+ && ['cancel', 'abandoned', 'hook'].includes(item.reason)
+ && (item.boundary === undefined || (item.boundary !== null && typeof item.boundary === 'object'
+ && item.boundary.offset === item.offset && Number.isSafeInteger(item.boundary.device)
+ && Number.isSafeInteger(item.boundary.inode) && typeof item.boundary.digest === 'string'
+ && /^[a-f0-9]{64}$/.test(item.boundary.digest)))
+ && (!index || value[index - 1].offset <= item.offset))
+}
+
+export function verifyCloses(file: string, closes: readonly TranscriptClose[]): void {
+ try { for (const close of closes) if (close.boundary) recoveryBoundary(file, close.boundary) }
+ catch { throw new Error('ENGINE_CONTROL_BOUNDARY_CHANGED') }
+}
+
+export const closeFileIdentity = (closes: readonly TranscriptClose[] | undefined): RecoveryBoundary | undefined =>
+ closes?.find(close => close.boundary)?.boundary
+
+export function replayCloses(closes: readonly TranscriptClose[], close: (reason: TranscriptClose['reason']) => void) {
+ let next = 0
+ return (offset: number): void => {
+ while (next < closes.length && closes[next].offset <= offset) close(closes[next++].reason)
+ }
+}
diff --git a/cli/src/lib/transcriptTail.ts b/cli/src/lib/transcriptTail.ts
index 919b61830..2f5d1af2d 100644
--- a/cli/src/lib/transcriptTail.ts
+++ b/cli/src/lib/transcriptTail.ts
@@ -1,6 +1,7 @@
import { open, stat, type FileHandle } from 'node:fs/promises'
import { createReadStream } from 'node:fs'
import { createInterface } from 'node:readline'
+import { verifyTranscriptHandle, type TranscriptFileIdentity } from './transcriptBoundary.js'
const CHUNK_BYTES = 64 * 1024
@@ -41,9 +42,11 @@ export async function scanRecordsBackward(
visit: (record: Buffer, offset: number) => boolean | void,
maxRecordBytes = MAX_RECORD_BYTES,
passed?: (offset: number) => boolean | void,
+ expectedFile?: TranscriptFileIdentity,
): Promise<boolean> {
const handle = await open(filePath, 'r')
try {
+ if (expectedFile) await verifyTranscriptHandle(handle, expectedFile)
let position = end
// Pieces of the record being assembled, newest first; only ever one record's worth.
let fragments: Buffer[] = []
@@ -103,9 +106,11 @@ export async function streamRecords(
onRecord: (line: string, offset: number) => boolean | void,
complete: (line: string) => boolean,
maxRecordBytes = MAX_RECORD_BYTES,
+ expectedFile?: TranscriptFileIdentity,
): Promise<{ next: number; records: number; partial: boolean } | null> {
const handle = await open(filePath, 'r')
try {
+ if (expectedFile) await verifyTranscriptHandle(handle, expectedFile)
let position = start
let next = start
let records = 0
diff --git a/cli/src/watcher/watcher.ts b/cli/src/watcher/watcher.ts
index 338c9d4c7..8bc115b7d 100644
--- a/cli/src/watcher/watcher.ts
+++ b/cli/src/watcher/watcher.ts
@@ -68,6 +68,8 @@ export const HISTORY_MAX_BYTES = 32 * 1024 * 1024
export const HOLD_TIMEOUT_MS = 30_000
interface FileState extends WatchedSession {
+ /** A replacement tail cannot consume bytes before its attachment commits. */
+ deliveryAllowed?: () => boolean
offset: number
/** Bytes below this were on disk before the current read cursor was placed — history, not live. */
historicalUntil: number
@@ -126,7 +128,7 @@ export class Watcher extends EventEmitter {
/** Attach one trusted transcript. Runtime hydration is handled by cli.ts; the tail starts at EOF, or at
* `fromOffset` — where that hydration stopped reading — so a record written while it read is tailed
* rather than lost between the two. */
- async addSession(session: WatchedSession, opts: { fromStart?: boolean; fromOffset?: number } = {}): Promise<void> {
+ async addSession(session: WatchedSession, opts: { fromStart?: boolean; fromOffset?: number; deliveryAllowed?: () => boolean } = {}): Promise<void> {
const oldPath = this.bySession.get(session.sessionId)
if (oldPath && oldPath !== session.transcriptPath) await this.removeSession(session.sessionId)
@@ -153,6 +155,7 @@ export class Watcher extends EventEmitter {
console.log(`[watcher] tail ${session.engine} ${session.sessionId.slice(0, 8)} @${offset} · ${session.transcriptPath}`)
this.files.set(session.transcriptPath, {
...session,
+ deliveryAllowed: opts.deliveryAllowed,
offset,
// A `fromStart` tail of a file that already has content reads that content as history.
historicalUntil: opts.fromStart ? size : 0,
@@ -323,7 +326,7 @@ export class Watcher extends EventEmitter {
private async readNew(filePath: string): Promise<void> {
const state = this.files.get(filePath)
- if (!state) return
+ if (!state || state.deliveryAllowed?.() === false) return
if (state.reading || state.holds.size) { state.pending = true; return }
state.reading = true
try {
@@ -344,6 +347,7 @@ export class Watcher extends EventEmitter {
}
let size: number
try { size = (await stat(filePath)).size } catch { return }
+ if (this.files.get(filePath) !== state || state.deliveryAllowed?.() === false) return
if (size < state.offset) {
state.partial = []
state.partialBytes = 0
@@ -370,7 +374,7 @@ export class Watcher extends EventEmitter {
const start = state.offset
const chunk = Buffer.alloc(Math.min(this.readChunkBytes, size - start))
const { bytesRead } = await fh.read(chunk, 0, chunk.length, start)
- if (!bytesRead) break
+ if (!bytesRead || this.files.get(filePath) !== state || state.deliveryAllowed?.() === false) break
state.offset = start + bytesRead
this.takeChunk(filePath, state, chunk.subarray(0, bytesRead), start, history)
// A hold taken meanwhile stops the read here; `release` reads what is left.
@@ -382,7 +386,7 @@ export class Watcher extends EventEmitter {
} catch (err) {
console.error(`[watcher] read failed (${basename(filePath)}):`, err)
}
- if (history.length) this.flushHistory(state, history)
+ if (history.length && this.files.get(filePath) === state && state.deliveryAllowed?.() !== false) this.flushHistory(state, history)
}
/**
@@ -428,6 +432,7 @@ export class Watcher extends EventEmitter {
private async readCursor(filePath: string, state: FileState): Promise<void> {
let next: string[]
try { next = completeLines(await readFile(filePath, 'utf8')) } catch { return }
+ if (this.files.get(filePath) !== state || state.deliveryAllowed?.() === false) return
let common = 0
while (common < state.cursorLines.length && common < next.length && state.cursorLines[common] === next[common]) common++
state.cursorLines = next
diff --git a/docs/research/2026-10-09-daemon-core-completion.md b/docs/research/2026-10-09-daemon-core-completion.md
index 079e22be5..416b3ac6a 100644
--- a/docs/research/2026-10-09-daemon-core-completion.md
+++ b/docs/research/2026-10-09-daemon-core-completion.md
@@ -21,10 +21,11 @@ This is the remaining completion scope as of October 9, after the six extraction
- [x] Fresh complete native home catalog evidence (#1126); durable writers and legacy consumers remain below.
- [x] Complete native descriptor/process/header ownership evidence (#1131, merged as `9eafacf3b` at October 10 00:33:06 UTC).
+- [x] Durable engine-home adoption, crash recovery and core retry (#1132, merged as `c7d460b1d` at October 10 01:43:24 UTC).
## 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 [under validation](2026-10-10-durable-home-adoption.md); legacy registry repair and the remaining saved-home consumers 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 [under validation](2026-10-10-saved-binding-evidence.md). Hook admission, remaining saved-home consumers and pending delivery ownership still require migration. The [catalog audit](2026-10-09-native-home-catalog.md) records its fresh-evidence boundary and required remaining caller/writer migration. The native Hermes pool is landed; optional home promotion and shared handle-cache lifetime still need their authority/resource audit. An unreadable or truncated pool cannot prove absence or uniqueness. Every binding entry and transcript poll retains pending work, isolates a failed lookup, and retries without blocking sibling sessions or readiness. Surface the hold reason through the shared session state.
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 91b593ada..351a724c7 100644
--- a/docs/research/2026-10-09-daemon-separation-progress.md
+++ b/docs/research/2026-10-09-daemon-separation-progress.md
@@ -218,4 +218,6 @@ and the final unavailable-service/readiness audit. Line counts do not establish
[PR #1131](https://github.com/autonomous-ai/openharness/pull/1131) merged as `9eafacf3b512a0b1ffd23e0d446115896b01f7ed` on October 10 at 00:33:06 UTC. Its [report](2026-10-09-native-descriptor-evidence.md) records the unchanged 29-observation golden, 21 assertion-failing mutations, native/private acceptance, full coverage, 150 matched cost samples, and exact-head/base independent review. Automatic CI run `38008750415` completed all applicable checks including `ci/required`. Merge verification ran 00:32:53–00:33:06. No release occurred.
-The owner resumed the paused task on October 9 at 22:25:51 UTC. Work is now on [durable home adoption](2026-10-10-durable-home-adoption.md), including crash recovery, retained observations, core hook retries and a staged registry batch. Validation and review are in progress; this is not a claim that the native-identity group or the complete refactor is finished.
+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.
diff --git a/docs/research/2026-10-10-binding-evidence-cost.json b/docs/research/2026-10-10-binding-evidence-cost.json
new file mode 100644
index 000000000..b564de2df
--- /dev/null
+++ b/docs/research/2026-10-10-binding-evidence-cost.json
@@ -0,0 +1,909 @@
+{
+ "started": "2026-10-10T04:08:13.706589+00:00",
+ "finished": "2026-10-10T04:09:34.557112+00:00",
+ "baseline": "c7d460b1d8018ed56126c662702fd44db886d07d",
+ "candidate": "937e9e6d4713a5ed2fd334aae72e970eebe76745",
+ "runs": [
+ {
+ "repetition": 1,
+ "source": "baseline",
+ "family": "registry",
+ "workload": "single",
+ "rows": 1,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 5
+ },
+ "latenciesMs": [
+ 45.078981999999996,
+ 42.21240599999999,
+ 43.882490000000075,
+ 41.93426699999998,
+ 43.62741699999992
+ ],
+ "elapsedMs": 216.773007,
+ "cpuMs": 19.176,
+ "peakRssMiB": 95.26171875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "candidate",
+ "family": "registry",
+ "workload": "single",
+ "rows": 1,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 5
+ },
+ "latenciesMs": [
+ 44.37731999999994,
+ 42.15499299999999,
+ 46.185483999999974,
+ 45.55201699999998,
+ 44.13802799999996
+ ],
+ "elapsedMs": 222.445153,
+ "cpuMs": 22.99,
+ "peakRssMiB": 95.94921875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "baseline",
+ "family": "registry",
+ "workload": "batch",
+ "rows": 200,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 87.70071499999995,
+ 81.01176700000008,
+ 82.93809799999997,
+ 82.20828000000006,
+ 79.2725220000001
+ ],
+ "elapsedMs": 413.387364,
+ "cpuMs": 265.968,
+ "peakRssMiB": 197.8984375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "candidate",
+ "family": "registry",
+ "workload": "batch",
+ "rows": 200,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 102.44376299999999,
+ 94.51687700000002,
+ 98.08074499999998,
+ 97.70435399999997,
+ 91.25068599999997
+ ],
+ "elapsedMs": 484.29705199999995,
+ "cpuMs": 366.449,
+ "peakRssMiB": 133.71484375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "baseline",
+ "family": "registry",
+ "workload": "many-homes",
+ "rows": 200,
+ "homes": 63,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 171.56075399999997,
+ 166.89537399999995,
+ 165.02660100000014,
+ 168.87366300000008,
+ 163.25617499999998
+ ],
+ "elapsedMs": 835.877489,
+ "cpuMs": 667.309,
+ "peakRssMiB": 142.89453125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "candidate",
+ "family": "registry",
+ "workload": "many-homes",
+ "rows": 200,
+ "homes": 63,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 140.44814199999996,
+ 131.74637099999995,
+ 131.079069,
+ 125.71879000000001,
+ 128.18920200000002
+ ],
+ "elapsedMs": 657.4404549999999,
+ "cpuMs": 538.081,
+ "peakRssMiB": 127.7578125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "baseline",
+ "family": "descriptor",
+ "workload": "one",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 941.7631,
+ 508.2416,
+ 518.137,
+ 519.0176,
+ 515.9295
+ ],
+ "cpuMs": 136.516,
+ "peakRssMiB": 107.29296875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "candidate",
+ "family": "descriptor",
+ "workload": "one",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 804.9926,
+ 510.0704,
+ 516.7414,
+ 507.6126,
+ 516.7994
+ ],
+ "cpuMs": 138.575,
+ "peakRssMiB": 106.8515625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "baseline",
+ "family": "descriptor",
+ "workload": "duplicate",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 808.9752,
+ 512.8639,
+ 517.2394,
+ 521.4722,
+ 513.6047
+ ],
+ "cpuMs": 139.703,
+ "peakRssMiB": 102.19140625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "candidate",
+ "family": "descriptor",
+ "workload": "duplicate",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 811.8479,
+ 509.0536,
+ 514.3658,
+ 514.9943,
+ 511.1284
+ ],
+ "cpuMs": 140.179,
+ "peakRssMiB": 101.7578125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "baseline",
+ "family": "descriptor",
+ "workload": "competing",
+ "iterations": 5,
+ "outcomes": {
+ "held": 5
+ },
+ "holds": [
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation."
+ ],
+ "latenciesMs": [
+ 813.647,
+ 516.9431,
+ 512.4166,
+ 564.2017,
+ 534.2414
+ ],
+ "cpuMs": 142.787,
+ "peakRssMiB": 108.24609375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "candidate",
+ "family": "descriptor",
+ "workload": "competing",
+ "iterations": 5,
+ "outcomes": {
+ "held": 5
+ },
+ "holds": [
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation."
+ ],
+ "latenciesMs": [
+ 813.8188,
+ 510.0193,
+ 513.4995,
+ 520.3469,
+ 516.0812
+ ],
+ "cpuMs": 138.439,
+ "peakRssMiB": 111.26171875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "baseline",
+ "family": "registry",
+ "workload": "single",
+ "rows": 1,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 5
+ },
+ "latenciesMs": [
+ 42.03702500000003,
+ 42.198398,
+ 40.96556200000009,
+ 42.515562000000045,
+ 42.575657999999976
+ ],
+ "elapsedMs": 210.32179299999996,
+ "cpuMs": 16.215,
+ "peakRssMiB": 95.39453125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "candidate",
+ "family": "registry",
+ "workload": "single",
+ "rows": 1,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 5
+ },
+ "latenciesMs": [
+ 46.24526300000002,
+ 42.686103,
+ 42.85932100000002,
+ 43.735571999999934,
+ 44.361039000000005
+ ],
+ "elapsedMs": 219.930248,
+ "cpuMs": 23.411,
+ "peakRssMiB": 94.0703125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "baseline",
+ "family": "registry",
+ "workload": "batch",
+ "rows": 200,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 89.48597799999999,
+ 86.42928800000004,
+ 83.89242100000001,
+ 84.44782199999997,
+ 74.260404
+ ],
+ "elapsedMs": 418.80392499999994,
+ "cpuMs": 275.069,
+ "peakRssMiB": 193.6171875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "candidate",
+ "family": "registry",
+ "workload": "batch",
+ "rows": 200,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 101.63756199999995,
+ 95.16420599999992,
+ 103.61922600000003,
+ 94.47065799999996,
+ 94.02346799999998
+ ],
+ "elapsedMs": 489.19444500000003,
+ "cpuMs": 361.357,
+ "peakRssMiB": 127.609375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "baseline",
+ "family": "registry",
+ "workload": "many-homes",
+ "rows": 200,
+ "homes": 63,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 168.91621199999997,
+ 175.19742900000006,
+ 162.85792600000013,
+ 166.580641,
+ 163.16229099999987
+ ],
+ "elapsedMs": 836.982031,
+ "cpuMs": 666.503,
+ "peakRssMiB": 141.9375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "candidate",
+ "family": "registry",
+ "workload": "many-homes",
+ "rows": 200,
+ "homes": 63,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 134.31104699999992,
+ 132.869016,
+ 129.72273099999995,
+ 123.24402699999996,
+ 121.87080100000003
+ ],
+ "elapsedMs": 642.2634989999999,
+ "cpuMs": 519.155,
+ "peakRssMiB": 132.12109375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "baseline",
+ "family": "descriptor",
+ "workload": "one",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 804.2659,
+ 513.8213,
+ 506.6598,
+ 516.3192,
+ 517.722
+ ],
+ "cpuMs": 135.687,
+ "peakRssMiB": 106.99609375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "candidate",
+ "family": "descriptor",
+ "workload": "one",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 815.0472,
+ 517.6336,
+ 506.5742,
+ 523.2377,
+ 505.6087
+ ],
+ "cpuMs": 136.404,
+ "peakRssMiB": 102.82421875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "baseline",
+ "family": "descriptor",
+ "workload": "duplicate",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 821.5963,
+ 541.7298,
+ 521.737,
+ 523.1457,
+ 512.4704
+ ],
+ "cpuMs": 154.402,
+ "peakRssMiB": 109.26171875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "candidate",
+ "family": "descriptor",
+ "workload": "duplicate",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 805.3797,
+ 523.649,
+ 510.4526,
+ 521.0744,
+ 508.7255
+ ],
+ "cpuMs": 139.691,
+ "peakRssMiB": 106.3125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "baseline",
+ "family": "descriptor",
+ "workload": "competing",
+ "iterations": 5,
+ "outcomes": {
+ "held": 5
+ },
+ "holds": [
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation."
+ ],
+ "latenciesMs": [
+ 808.7392,
+ 516.6396,
+ 515.1715,
+ 521.0029,
+ 510.9103
+ ],
+ "cpuMs": 142.02,
+ "peakRssMiB": 109.890625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "candidate",
+ "family": "descriptor",
+ "workload": "competing",
+ "iterations": 5,
+ "outcomes": {
+ "held": 5
+ },
+ "holds": [
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation."
+ ],
+ "latenciesMs": [
+ 802.2472,
+ 516.8434,
+ 507.3533,
+ 534.1504,
+ 521.1326
+ ],
+ "cpuMs": 141.572,
+ "peakRssMiB": 103.92578125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "baseline",
+ "family": "registry",
+ "workload": "single",
+ "rows": 1,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 5
+ },
+ "latenciesMs": [
+ 42.82799,
+ 42.364502000000016,
+ 42.46117499999997,
+ 41.33444200000008,
+ 42.882533999999964
+ ],
+ "elapsedMs": 211.90381200000007,
+ "cpuMs": 18.495,
+ "peakRssMiB": 92.56640625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "candidate",
+ "family": "registry",
+ "workload": "single",
+ "rows": 1,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 5
+ },
+ "latenciesMs": [
+ 59.56053000000003,
+ 45.05279399999995,
+ 44.681580000000054,
+ 42.31992300000002,
+ 44.08674199999996
+ ],
+ "elapsedMs": 235.738583,
+ "cpuMs": 22.266,
+ "peakRssMiB": 90.13671875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "baseline",
+ "family": "registry",
+ "workload": "batch",
+ "rows": 200,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 80.21214000000003,
+ 83.07210199999997,
+ 81.88154800000007,
+ 93.145354,
+ 85.11247300000002
+ ],
+ "elapsedMs": 423.71228899999994,
+ "cpuMs": 279.083,
+ "peakRssMiB": 195.10546875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "candidate",
+ "family": "registry",
+ "workload": "batch",
+ "rows": 200,
+ "homes": 1,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 100.75159999999994,
+ 93.03938299999993,
+ 93.93903999999998,
+ 98.107346,
+ 96.19369500000005
+ ],
+ "elapsedMs": 482.35985700000003,
+ "cpuMs": 360,
+ "peakRssMiB": 131.96875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "baseline",
+ "family": "registry",
+ "workload": "many-homes",
+ "rows": 200,
+ "homes": 63,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 173.72304100000008,
+ 170.82815900000003,
+ 171.137836,
+ 166.97341299999994,
+ 177.07410500000015
+ ],
+ "elapsedMs": 860.031878,
+ "cpuMs": 695.63,
+ "peakRssMiB": 148.84765625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "candidate",
+ "family": "registry",
+ "workload": "many-homes",
+ "rows": 200,
+ "homes": 63,
+ "iterations": 5,
+ "outcomes": {
+ "complete": 1000
+ },
+ "latenciesMs": [
+ 138.31116899999995,
+ 137.01838899999996,
+ 133.897834,
+ 128.04341799999986,
+ 122.7567869999998
+ ],
+ "elapsedMs": 660.3172139999999,
+ "cpuMs": 549.047,
+ "peakRssMiB": 133.19921875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "baseline",
+ "family": "descriptor",
+ "workload": "one",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 802.1326,
+ 513.5103,
+ 514.4907,
+ 509.1142,
+ 528.5594
+ ],
+ "cpuMs": 135.189,
+ "peakRssMiB": 102.39453125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "candidate",
+ "family": "descriptor",
+ "workload": "one",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 811.7751,
+ 587.8639,
+ 562.7581,
+ 511.9062,
+ 637.4539
+ ],
+ "cpuMs": 147.771,
+ "peakRssMiB": 104.48828125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "baseline",
+ "family": "descriptor",
+ "workload": "duplicate",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 808.1362,
+ 513.8101,
+ 527.5346,
+ 513.1001,
+ 516.9744
+ ],
+ "cpuMs": 140.801,
+ "peakRssMiB": 106.8984375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "candidate",
+ "family": "descriptor",
+ "workload": "duplicate",
+ "iterations": 5,
+ "outcomes": {
+ "bound": 5
+ },
+ "holds": [],
+ "latenciesMs": [
+ 802.4939,
+ 508.3059,
+ 518.1068,
+ 518.6709,
+ 514.2602
+ ],
+ "cpuMs": 134.33,
+ "peakRssMiB": 104.1015625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "baseline",
+ "family": "descriptor",
+ "workload": "competing",
+ "iterations": 5,
+ "outcomes": {
+ "held": 5
+ },
+ "holds": [
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation."
+ ],
+ "latenciesMs": [
+ 805.8066,
+ 510.2051,
+ 514.0463,
+ 514.9063,
+ 519.1548
+ ],
+ "cpuMs": 141.792,
+ "peakRssMiB": 107.26953125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "candidate",
+ "family": "descriptor",
+ "workload": "competing",
+ "iterations": 5,
+ "outcomes": {
+ "held": 5
+ },
+ "holds": [
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation.",
+ "Conversation identity is held: more than one open rollout could own the conversation."
+ ],
+ "latenciesMs": [
+ 806.3485,
+ 519.6815,
+ 515.5743,
+ 507.3862,
+ 518.9602
+ ],
+ "cpuMs": 139.925,
+ "peakRssMiB": 110.0390625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ }
+ ],
+ "scope": "Whole registry load and native descriptor workloads. Measured source 937e9e6d4; the later ordinary Cancel and Stop corrections touch only core recovery/control modules and their main wiring/specs, outside these workload import/call paths. Active cancellation latency is not covered by these measurements."
+}
diff --git a/docs/research/2026-10-10-cancel-cost.json b/docs/research/2026-10-10-cancel-cost.json
new file mode 100644
index 000000000..a8b270277
--- /dev/null
+++ b/docs/research/2026-10-10-cancel-cost.json
@@ -0,0 +1,2864 @@
+{
+ "started": "2026-10-10T04:34:20.486111+00:00",
+ "finished": "2026-10-10T04:34:29.745433+00:00",
+ "baseline": "c7d460b1d8018ed56126c662702fd44db886d07d",
+ "candidate": "c061a769787331d243c4927b079a4ec388ff5e65",
+ "runs": [
+ {
+ "repetition": 1,
+ "source": "baseline",
+ "workload": "small-first",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.10374500000000353,
+ 0.005661000000003469,
+ 0.0046079999999903976,
+ 0.004225999999988517,
+ 0.005249999999989541,
+ 0.004006000000003951,
+ 0.004232999999999265,
+ 0.003907999999995582,
+ 0.10393799999999942,
+ 0.010101999999989175,
+ 0.0034359999999935553,
+ 0.0029380000000003292,
+ 0.0029990000000168493,
+ 0.002895999999992682,
+ 0.0027589999999975134,
+ 0.00266399999998157,
+ 0.0028190000000165583,
+ 0.004952000000002954,
+ 0.0030589999999790507,
+ 0.002859000000000833,
+ 0.002803000000000111,
+ 0.0028140000000007603,
+ 0.002628000000015618,
+ 0.0026019999999959964,
+ 0.002554000000003498,
+ 0.002502999999990152,
+ 0.0025559999999984484,
+ 0.0025430000000028485,
+ 0.0025379999999870506,
+ 0.0024919999999895026,
+ 0.002564000000006672,
+ 0.002536000000020522,
+ 0.002532000000002199,
+ 0.002490000000022974,
+ 0.002613999999994121,
+ 0.002645999999998594,
+ 0.005702000000013641,
+ 0.002544999999997799,
+ 0.002563000000009197,
+ 0.0025150000000166983,
+ 0.0024750000000040018,
+ 0.004716000000001941,
+ 0.003208000000000766,
+ 0.002375000000000682,
+ 0.002210000000019363,
+ 0.002240999999997939,
+ 0.0020920000000046457,
+ 0.0020899999999812735,
+ 0.0021300000000223918,
+ 0.0020719999999982974,
+ 0.002067000000010921,
+ 0.0020970000000204436,
+ 0.002025000000003274,
+ 0.003830999999991036,
+ 0.0019439999999804058,
+ 0.0020190000000184227,
+ 0.0019279999999923803,
+ 0.001979000000005726,
+ 0.0019849999999905776,
+ 0.001949999999993679,
+ 0.001936000000000604,
+ 0.002329000000003134,
+ 0.0023569999999892843,
+ 0.002087999999986323,
+ 0.001978000000008251,
+ 0.0019900000000063756,
+ 0.001907999999986032,
+ 0.001965000000012651,
+ 0.001884999999987258,
+ 0.002413000000018428,
+ 0.0019169999999917309,
+ 0.0019159999999942556,
+ 0.0020079999999893516,
+ 0.001969000000002552,
+ 0.0019609999999943284,
+ 0.001905000000022028,
+ 0.0023160000000075343,
+ 0.004075999999997748,
+ 0.0020360000000039236,
+ 0.0019949999999937518,
+ 0.001958999999999378,
+ 0.0032620000000065374,
+ 0.002600000000001046,
+ 0.0025329999999996744,
+ 0.002250000000003638,
+ 0.0039009999999848333,
+ 0.002192999999977019,
+ 0.0021050000000002456,
+ 0.0020079999999893516,
+ 0.0019849999999905776,
+ 0.0022109999999884167,
+ 0.0020869999999888478,
+ 0.0022020000000111395,
+ 0.00230600000000436,
+ 0.0021100000000160435,
+ 0.0021639999999933934,
+ 0.0021419999999920947,
+ 0.00208900000001222,
+ 0.0022749999999973625,
+ 0.0020679999999799747
+ ],
+ "cpuMs": 0.9510000000000005,
+ "peakRssMiB": 91.3046875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "candidate",
+ "workload": "small-first",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.8189069999999958,
+ 0.11673999999999296,
+ 0.15408700000000408,
+ 0.11320000000000618,
+ 0.16159700000000043,
+ 0.10371800000001485,
+ 0.10033699999999612,
+ 0.09921299999999178,
+ 0.2913289999999904,
+ 0.13445700000002603,
+ 0.09336300000001074,
+ 0.07931800000000067,
+ 0.07574200000001952,
+ 0.07540099999999939,
+ 0.07450099999999793,
+ 0.07393500000000586,
+ 0.07852599999998233,
+ 0.08070299999999975,
+ 0.0739900000000091,
+ 0.07392400000000521,
+ 0.07276699999999892,
+ 0.07379199999999742,
+ 0.08739899999997647,
+ 0.07789199999999141,
+ 0.07283400000000029,
+ 0.07246799999998643,
+ 0.07164399999999205,
+ 0.07146900000000755,
+ 0.07062799999999925,
+ 0.07255499999999415,
+ 0.07663800000000265,
+ 0.07138199999999983,
+ 0.07091900000000351,
+ 0.07156899999998245,
+ 0.07142600000000243,
+ 0.07400200000000723,
+ 0.07357899999999518,
+ 0.07492300000001251,
+ 0.07162600000000907,
+ 0.07317199999999957,
+ 0.07111800000001267,
+ 0.08111099999999283,
+ 0.07310900000001652,
+ 0.06956900000000132,
+ 0.07095200000000546,
+ 0.07070500000000379,
+ 0.07093399999999406,
+ 0.07088100000001418,
+ 0.07637700000000791,
+ 0.07191699999998491,
+ 0.0730259999999987,
+ 0.06985699999998474,
+ 0.06980699999999729,
+ 0.06998400000000515,
+ 0.06986699999998791,
+ 0.07147000000000503,
+ 0.06971099999998387,
+ 0.06968699999998762,
+ 0.06847999999999388,
+ 0.07174200000000042,
+ 0.07404999999999973,
+ 0.07117499999998245,
+ 0.08436900000000946,
+ 0.0704979999999864,
+ 0.07038199999999506,
+ 0.07247899999998708,
+ 0.07012699999998517,
+ 0.06954199999998423,
+ 0.07322600000000534,
+ 0.09294400000001701,
+ 0.07161399999998252,
+ 0.0948630000000037,
+ 0.0775069999999971,
+ 0.0767060000000015,
+ 0.07348500000000513,
+ 0.07214899999999602,
+ 0.0706700000000069,
+ 0.0700469999999882,
+ 0.07107400000001007,
+ 0.07222699999999804,
+ 0.06877900000000636,
+ 0.06864699999999857,
+ 0.07056299999999283,
+ 0.06853499999999713,
+ 0.07233299999998621,
+ 0.0685139999999933,
+ 0.641491000000002,
+ 0.07156000000000518,
+ 0.06703899999999408,
+ 0.06482199999999239,
+ 0.06453999999999382,
+ 0.06404800000001387,
+ 0.06353300000000672,
+ 0.06301799999999957,
+ 0.0629109999999855,
+ 0.06246999999999048,
+ 0.06733599999998319,
+ 0.06502100000000155,
+ 0.0631219999999928,
+ 0.062894
+ ],
+ "cpuMs": 10.794000000000004,
+ "peakRssMiB": 92.4765625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "baseline",
+ "workload": "large-first",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.11405700000000252,
+ 0.006698000000000093,
+ 0.005065999999999349,
+ 0.004832000000021708,
+ 0.005642999999992071,
+ 0.004704000000003816,
+ 0.0071619999999938955,
+ 0.004627999999996746,
+ 0.11812599999998952,
+ 0.011509000000017977,
+ 0.0037349999999776173,
+ 0.003306000000009135,
+ 0.0031699999999830197,
+ 0.003113000000013244,
+ 0.0031399999999734973,
+ 0.0030030000000067503,
+ 0.0033479999999883603,
+ 0.005041000000005624,
+ 0.0033490000000142572,
+ 0.0028700000000014825,
+ 0.002819999999985612,
+ 0.002686999999980344,
+ 0.0026529999999809206,
+ 0.002583000000015545,
+ 0.0025610000000142463,
+ 0.002512999999993326,
+ 0.002540000000010423,
+ 0.002486000000004651,
+ 0.0024919999999895026,
+ 0.00255600000002687,
+ 0.002557999999993399,
+ 0.002602000000024418,
+ 0.002544999999997799,
+ 0.002529999999978827,
+ 0.002596000000011145,
+ 0.0025720000000148957,
+ 0.0025660000000016225,
+ 0.0025749999999788997,
+ 0.0025229999999965003,
+ 0.0025070000000084747,
+ 0.0024629999999774554,
+ 0.004794000000003962,
+ 0.002896000000021104,
+ 0.0021560000000135915,
+ 0.002105999999997721,
+ 0.0019319999999822812,
+ 0.0019390000000214513,
+ 0.001926999999994905,
+ 0.001880999999997357,
+ 0.0018149999999934607,
+ 0.0019340000000056534,
+ 0.001919000000015103,
+ 0.0019620000000202253,
+ 0.0020040000000278724,
+ 0.0019700000000000273,
+ 0.0018939999999929569,
+ 0.0019609999999943284,
+ 0.0019029999999986558,
+ 0.0020279999999957,
+ 0.001936000000000604,
+ 0.0019450000000063028,
+ 0.0019029999999986558,
+ 0.001926999999994905,
+ 0.0018910000000005311,
+ 0.0019139999999993051,
+ 0.0018110000000035598,
+ 0.001968000000005077,
+ 0.0018330000000048585,
+ 0.0018910000000005311,
+ 0.0018359999999972842,
+ 0.0019010000000037053,
+ 0.001909000000011929,
+ 0.0019010000000037053,
+ 0.0018660000000068067,
+ 0.0018560000000036325,
+ 0.001827000000020007,
+ 0.0018719999999916581,
+ 0.0018469999999979336,
+ 0.0018859999999847332,
+ 0.001877000000007456,
+ 0.0018369999999947595,
+ 0.0018499999999903594,
+ 0.001852999999982785,
+ 0.001831000000009908,
+ 0.0018469999999979336,
+ 0.0018200000000092587,
+ 0.0018369999999947595,
+ 0.0018709999999941829,
+ 0.0019900000000063756,
+ 0.00191300000000183,
+ 0.0018309999999814863,
+ 0.0018439999999770862,
+ 0.0018560000000036325,
+ 0.001840000000015607,
+ 0.0018790000000024065,
+ 0.0018509999999878346,
+ 0.0017510000000129367,
+ 0.0018309999999814863,
+ 0.0018160000000193577,
+ 0.0017849999999839383
+ ],
+ "cpuMs": 2.250999999999994,
+ "peakRssMiB": 123.4765625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "candidate",
+ "workload": "large-first",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 1.0123370000000023,
+ 0.14635699999999474,
+ 0.1818179999999927,
+ 0.14341200000001209,
+ 3.0955439999999896,
+ 0.13247400000000198,
+ 0.12012300000000664,
+ 0.1413310000000081,
+ 0.3067529999999863,
+ 0.15083899999999062,
+ 0.10567900000000918,
+ 0.08418199999999842,
+ 0.08767299999999523,
+ 0.0863029999999867,
+ 0.08189699999999789,
+ 0.08155600000000618,
+ 0.08496100000002116,
+ 0.08275199999999927,
+ 0.08978700000000117,
+ 0.07767699999999422,
+ 0.07882399999999734,
+ 0.08445299999999634,
+ 0.07997000000000298,
+ 0.08258600000002048,
+ 0.08095699999998374,
+ 0.07594499999999016,
+ 0.07685200000000236,
+ 0.07818399999999315,
+ 0.08094600000001151,
+ 0.07871099999999842,
+ 0.07601700000000733,
+ 0.07629799999997999,
+ 0.08148199999999406,
+ 0.07819299999999885,
+ 0.07858799999999633,
+ 0.07916900000000737,
+ 0.08387600000000361,
+ 0.08267800000001557,
+ 0.07899199999997109,
+ 0.08044799999998986,
+ 0.07656800000000885,
+ 0.08286900000001651,
+ 0.08749700000004168,
+ 0.0776779999999917,
+ 0.07622100000003229,
+ 0.07710200000002487,
+ 0.07724300000000994,
+ 0.06448899999998048,
+ 0.06372900000002346,
+ 0.06682499999999436,
+ 0.0656399999999735,
+ 0.06184799999999768,
+ 0.06312700000000859,
+ 0.06639799999999241,
+ 0.06317200000000867,
+ 0.06330200000002151,
+ 0.06216699999998809,
+ 0.06204999999999927,
+ 0.06285000000002583,
+ 0.06606200000004492,
+ 0.07397800000001098,
+ 0.06275999999996884,
+ 0.0630570000000148,
+ 0.08237000000002581,
+ 0.06297000000000708,
+ 0.06249099999996588,
+ 0.06166200000001254,
+ 0.06548399999996946,
+ 0.06542400000000725,
+ 0.06258200000002034,
+ 0.06182000000001153,
+ 0.06589299999996001,
+ 0.06672700000001441,
+ 0.06470300000000861,
+ 0.07101399999999103,
+ 0.0684400000000096,
+ 0.06341199999997116,
+ 0.0629289999999969,
+ 0.06575600000002169,
+ 0.06356900000002952,
+ 0.06228800000002366,
+ 0.061887000000012904,
+ 0.06219299999997929,
+ 0.062475000000006276,
+ 0.06198899999998275,
+ 0.06511799999998402,
+ 0.062007999999991625,
+ 0.061922999999978856,
+ 0.06184600000000273,
+ 0.062413999999989755,
+ 0.06245799999999235,
+ 0.06262000000003809,
+ 0.06220000000001846,
+ 0.0625699999999938,
+ 0.06235700000001998,
+ 0.0649710000000141,
+ 0.06736100000000533,
+ 0.062069000000008145,
+ 0.061156999999980144,
+ 0.06280900000001566
+ ],
+ "cpuMs": 19.167,
+ "peakRssMiB": 122.1875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "baseline",
+ "workload": "small-retained",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.10276300000001015,
+ 0.006014000000021724,
+ 0.004485999999985779,
+ 0.0041369999999858464,
+ 0.005098000000003822,
+ 0.003781000000003587,
+ 0.003908000000024003,
+ 0.0035220000000038,
+ 0.057931000000024824,
+ 0.011136999999990849,
+ 0.003761999999994714,
+ 0.0033080000000040855,
+ 0.0029859999999928277,
+ 0.0028110000000083346,
+ 0.0028000000000076852,
+ 0.00272499999999809,
+ 0.00309000000001447,
+ 0.003264999999998963,
+ 0.0028140000000007603,
+ 0.0025919999999928223,
+ 0.002512999999993326,
+ 0.002463000000005877,
+ 0.0023449999999911597,
+ 0.0022610000000042874,
+ 0.002326999999979762,
+ 0.00223199999999224,
+ 0.002273000000002412,
+ 0.002290999999985388,
+ 0.0023309999999980846,
+ 0.002282000000008111,
+ 0.0022759999999948377,
+ 0.002309999999994261,
+ 0.0022649999999941883,
+ 0.002341999999998734,
+ 0.003883000000001857,
+ 0.0023439999999936845,
+ 0.002361000000007607,
+ 0.003932999999989306,
+ 0.0022580000000118616,
+ 0.0022979999999961365,
+ 0.0023040000000094096,
+ 0.00454899999999725,
+ 0.0030650000000207456,
+ 0.0021919999999795436,
+ 0.002384000000006381,
+ 0.0021820000000047912,
+ 0.0020350000000064483,
+ 0.001985999999988053,
+ 0.0019010000000037053,
+ 0.0018699999999967076,
+ 0.0019059999999910815,
+ 0.0018249999999966349,
+ 0.0017540000000053624,
+ 0.0018269999999915854,
+ 0.001840000000015607,
+ 0.0018510000000162563,
+ 0.002309999999994261,
+ 0.001923000000005004,
+ 0.0019270000000233267,
+ 0.0018599999999935335,
+ 0.003753000000017437,
+ 0.0018090000000086093,
+ 0.0018490000000213058,
+ 0.001854000000008682,
+ 0.0018760000000099808,
+ 0.0018939999999929569,
+ 0.0018260000000225318,
+ 0.0018760000000099808,
+ 0.0018689999999992324,
+ 0.001844000000005508,
+ 0.0018220000000042091,
+ 0.0018369999999947595,
+ 0.0018139999999959855,
+ 0.001882000000023254,
+ 0.0018890000000055807,
+ 0.0018780000000049313,
+ 0.0018780000000049313,
+ 0.0018320000000073833,
+ 0.0018530000000112068,
+ 0.001861999999988484,
+ 0.0032389999999793417,
+ 0.0018589999999960582,
+ 0.0018010000000003856,
+ 0.0018179999999858865,
+ 0.0018000000000029104,
+ 0.0018290000000149575,
+ 0.0018560000000036325,
+ 0.001857999999998583,
+ 0.0018239999999991596,
+ 0.0019220000000075288,
+ 0.0018589999999960582,
+ 0.0018660000000068067,
+ 0.0018129999999985102,
+ 0.0018090000000086093,
+ 0.001861999999988484,
+ 0.0035160000000189484,
+ 0.0018489999999928841,
+ 0.0018589999999960582,
+ 0.0033950000000118052,
+ 0.00179800000000796
+ ],
+ "cpuMs": 0.8140000000000005,
+ "peakRssMiB": 86.59765625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "candidate",
+ "workload": "small-retained",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.8099210000000028,
+ 0.25856200000001195,
+ 0.24310799999997812,
+ 0.17232300000000578,
+ 0.3017030000000034,
+ 0.2146359999999845,
+ 0.14188900000002036,
+ 0.13259300000001417,
+ 0.23670300000000566,
+ 0.1573940000000107,
+ 0.13472300000000814,
+ 0.12937700000000518,
+ 0.13294899999999643,
+ 0.12696900000000255,
+ 0.12112899999999627,
+ 0.12567299999997772,
+ 0.12941200000000208,
+ 0.1387589999999932,
+ 0.12892000000002213,
+ 0.128294000000011,
+ 0.12721399999998084,
+ 0.1310139999999933,
+ 0.12866800000000467,
+ 0.13584699999998406,
+ 0.11827500000001123,
+ 0.13375099999998952,
+ 0.11943800000000238,
+ 0.1244999999999834,
+ 0.1118669999999895,
+ 0.12061699999998154,
+ 0.12886199999999803,
+ 0.12376399999999421,
+ 0.13163800000000947,
+ 0.1271910000000105,
+ 0.1328670000000045,
+ 0.1165680000000009,
+ 0.12019799999998781,
+ 0.11178999999998496,
+ 0.133072999999996,
+ 0.11034000000000788,
+ 0.11166800000000876,
+ 0.13270199999999477,
+ 0.12633400000001416,
+ 0.13180400000001669,
+ 0.11816500000000474,
+ 0.12028099999997721,
+ 0.11952199999998925,
+ 0.12081200000000081,
+ 0.11267000000000849,
+ 0.11466200000000981,
+ 0.12019300000000044,
+ 0.11598400000002584,
+ 0.12945600000000468,
+ 0.15144799999998781,
+ 0.12335600000000113,
+ 0.11936299999999278,
+ 0.11672000000001503,
+ 0.11819800000000669,
+ 0.12848900000000185,
+ 0.1287450000000092,
+ 0.1344569999999976,
+ 0.1287540000000149,
+ 0.12497899999999618,
+ 0.1269100000000094,
+ 0.1363059999999905,
+ 0.1318849999999827,
+ 0.1487239999999872,
+ 0.1315050000000042,
+ 0.13520100000002344,
+ 0.13241500000000883,
+ 0.13351999999997588,
+ 0.12622099999998682,
+ 0.127443999999997,
+ 0.13056199999999762,
+ 0.1343169999999816,
+ 0.12842399999999543,
+ 0.10972200000000498,
+ 0.1184159999999963,
+ 0.12997500000000173,
+ 0.12852000000000885,
+ 0.11647500000000832,
+ 0.1193789999999808,
+ 0.12004000000001724,
+ 0.18825499999999806,
+ 0.15029400000000237,
+ 0.13499500000000353,
+ 0.132126999999997,
+ 0.12997500000000173,
+ 0.12477199999997879,
+ 0.12942099999997936,
+ 0.1323020000000099,
+ 0.12912000000000035,
+ 0.12864700000000084,
+ 0.1093089999999961,
+ 0.12797499999999218,
+ 0.11426999999997633,
+ 0.1210619999999949,
+ 0.13673900000000572,
+ 0.13107899999999972,
+ 0.12999500000000808
+ ],
+ "cpuMs": 14.61499999999999,
+ "peakRssMiB": 91.51171875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "baseline",
+ "workload": "large-retained",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.11307499999998072,
+ 0.0064710000000047785,
+ 0.004833999999988237,
+ 0.00452300000000605,
+ 0.005438999999995531,
+ 0.004436999999995805,
+ 0.004514000000000351,
+ 0.004227999999983467,
+ 0.0625,
+ 0.01220499999999447,
+ 0.004121999999995296,
+ 0.0035790000000019973,
+ 0.0034010000000250784,
+ 0.003444000000001779,
+ 0.003342000000003509,
+ 0.005356000000006134,
+ 0.0035090000000082,
+ 0.004245999999994865,
+ 0.004453999999981306,
+ 0.0034410000000093532,
+ 0.0037739999999928386,
+ 0.0041509999999789216,
+ 0.003872999999998683,
+ 0.002908999999988282,
+ 0.002937000000002854,
+ 0.002859000000000833,
+ 0.0028219999999805623,
+ 0.005829000000005635,
+ 0.003256000000021686,
+ 0.0028110000000083346,
+ 0.0026159999999890715,
+ 0.002494000000012875,
+ 0.002488999999997077,
+ 0.0025249999999914507,
+ 0.0024129999999900065,
+ 0.002377999999964686,
+ 0.0023770000000240543,
+ 0.0023669999999924585,
+ 0.0022440000000187865,
+ 0.002415999999982432,
+ 0.0023599999999532884,
+ 0.005569999999977426,
+ 0.003054999999960728,
+ 0.0021179999999958454,
+ 0.0019619999999918036,
+ 0.001978000000008251,
+ 0.001906999999960135,
+ 0.0028260000000273067,
+ 0.0035210000000347463,
+ 0.003045999999983451,
+ 0.002920000000017353,
+ 0.0022689999999556676,
+ 0.001958999999999378,
+ 0.0018620000000169057,
+ 0.0017840000000433065,
+ 0.0017589999999927386,
+ 0.001782000000048356,
+ 0.0017819999999915126,
+ 0.0017310000000065884,
+ 0.0017720000000167602,
+ 0.001725000000021737,
+ 0.001767000000029384,
+ 0.001745999999968717,
+ 0.0016739999999799693,
+ 0.0017049999999585452,
+ 0.0016469999999912943,
+ 0.0017639999999801148,
+ 0.001763000000039483,
+ 0.0017889999999738393,
+ 0.0018039999999928114,
+ 0.0017330000000015389,
+ 0.0017070000000103391,
+ 0.001737999999988915,
+ 0.0016899999999964166,
+ 0.001698000000033062,
+ 0.0018190000000117834,
+ 0.0019209999999816318,
+ 0.0017760000000066611,
+ 0.0017540000000053624,
+ 0.001721000000031836,
+ 0.0017000000000280124,
+ 0.0016840000000115651,
+ 0.0017530000000078871,
+ 0.00179800000000796,
+ 0.001813000000026932,
+ 0.0018479999999954089,
+ 0.0017920000000231084,
+ 0.0018119999999726133,
+ 0.001795999999956166,
+ 0.0018279999999890606,
+ 0.0017509999999560932,
+ 0.0017639999999801148,
+ 0.0017979999999511165,
+ 0.0018689999999992324,
+ 0.0017470000000230357,
+ 0.0017550000000028376,
+ 0.00176499999997759,
+ 0.0017179999999825668,
+ 0.0017530000000078871,
+ 0.0017869999999788888
+ ],
+ "cpuMs": 2.112999999999995,
+ "peakRssMiB": 118.3203125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 1,
+ "source": "candidate",
+ "workload": "large-retained",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.8811049999999909,
+ 0.25374999999996817,
+ 0.31259299999999257,
+ 0.1636169999999879,
+ 0.2911359999999945,
+ 0.1756770000000074,
+ 2.6863459999999577,
+ 0.1219520000000216,
+ 0.2191039999999589,
+ 0.13327000000003864,
+ 0.11481500000002143,
+ 0.11705999999998085,
+ 0.11204400000002579,
+ 0.10870700000003808,
+ 0.11049400000001697,
+ 0.11041899999997895,
+ 0.11351600000000417,
+ 0.11485700000002907,
+ 0.10856400000000122,
+ 0.10580999999996266,
+ 0.10515099999997801,
+ 0.10976099999999178,
+ 0.10503299999999172,
+ 0.11198799999999665,
+ 0.10511999999999944,
+ 0.11210300000004736,
+ 0.1043690000000197,
+ 0.106871999999953,
+ 0.10405099999996992,
+ 0.10433100000000195,
+ 0.10272700000001578,
+ 0.10258799999996882,
+ 0.10330300000003945,
+ 0.10319699999996601,
+ 0.10997199999997065,
+ 0.10254800000001296,
+ 0.10744999999997162,
+ 0.10325599999998758,
+ 0.10949199999998882,
+ 0.1108899999999835,
+ 0.10949899999997115,
+ 0.11532999999997173,
+ 0.10948200000001407,
+ 0.1048799999999801,
+ 0.10768500000000358,
+ 0.1032629999999699,
+ 0.10625799999996843,
+ 0.1021910000000048,
+ 0.10505299999999806,
+ 0.10097100000001547,
+ 0.1011930000000234,
+ 0.10274899999996023,
+ 0.10584699999998293,
+ 0.1048020000000065,
+ 0.10507700000005116,
+ 0.10416199999997389,
+ 0.10179900000002817,
+ 0.10803099999998267,
+ 0.101366999999982,
+ 0.10431599999998298,
+ 0.1047860000000469,
+ 0.10459399999996322,
+ 0.1083730000000287,
+ 0.10431400000004487,
+ 0.10157099999997854,
+ 0.1008899999999926,
+ 0.10291200000000345,
+ 0.10184800000001815,
+ 0.10178500000000668,
+ 0.10158300000000509,
+ 0.10960799999998017,
+ 0.10122000000001208,
+ 0.10786500000000387,
+ 0.10680300000001353,
+ 0.10551800000001776,
+ 0.10217799999998078,
+ 0.10440399999998817,
+ 0.10122899999998936,
+ 0.10888099999999667,
+ 0.10194299999994882,
+ 0.10449299999999084,
+ 0.10543999999998732,
+ 0.10158799999999246,
+ 0.10950500000001284,
+ 0.10136700000003884,
+ 0.10466500000001133,
+ 0.10093899999998257,
+ 0.10445599999997057,
+ 0.1051270000000386,
+ 0.10882500000002437,
+ 0.10095799999999144,
+ 0.10484199999996235,
+ 0.10258499999997639,
+ 0.10570899999999028,
+ 0.10162600000001021,
+ 0.10489899999998897,
+ 0.10185200000000805,
+ 0.10220299999997451,
+ 0.10134400000004007,
+ 0.1015920000000392
+ ],
+ "cpuMs": 21.56600000000001,
+ "peakRssMiB": 125.58203125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "baseline",
+ "workload": "small-first",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.10453400000000101,
+ 0.005972999999983131,
+ 0.004396000000014055,
+ 0.004202999999989743,
+ 0.005189999999998918,
+ 0.004322999999999411,
+ 0.004249000000015712,
+ 0.004253000000005613,
+ 0.10822100000001456,
+ 0.01032899999998449,
+ 0.0033359999999902357,
+ 0.0029749999999921783,
+ 0.0028219999999805623,
+ 0.0029559999999833053,
+ 0.0029130000000066048,
+ 0.0027500000000202363,
+ 0.0029759999999896536,
+ 0.0031050000000050204,
+ 0.003152999999997519,
+ 0.002757000000002563,
+ 0.00267699999997717,
+ 0.0025570000000243454,
+ 0.0024980000000027758,
+ 0.004994999999979655,
+ 0.0025509999999826505,
+ 0.002623999999997295,
+ 0.002499000000000251,
+ 0.002478000000024849,
+ 0.002551000000011072,
+ 0.0025980000000060954,
+ 0.004469000000000278,
+ 0.0026760000000081163,
+ 0.002585999999979549,
+ 0.002574000000009846,
+ 0.002652000000011867,
+ 0.002515999999985752,
+ 0.002587000000005446,
+ 0.004750000000001364,
+ 0.0025760000000047967,
+ 0.0024229999999931806,
+ 0.002509000000003425,
+ 0.004993000000013126,
+ 0.0032160000000089894,
+ 0.0023400000000037835,
+ 0.002198999999990292,
+ 0.001992000000001326,
+ 0.001949999999993679,
+ 0.005380999999999858,
+ 0.002077999999983149,
+ 0.00198700000001395,
+ 0.0022310000000231867,
+ 0.0021050000000002456,
+ 0.0020120000000076743,
+ 0.002037999999998874,
+ 0.00206899999997745,
+ 0.002082999999998947,
+ 0.002052000000020371,
+ 0.0019709999999975025,
+ 0.004360999999988735,
+ 0.004080000000016071,
+ 0.002047000000004573,
+ 0.001982999999995627,
+ 0.002070000000003347,
+ 0.002095000000025493,
+ 0.0019950000000221735,
+ 0.0019749999999874035,
+ 0.002058999999974276,
+ 0.0020180000000209475,
+ 0.0020320000000140226,
+ 0.001978000000008251,
+ 0.0019939999999962765,
+ 0.001968000000005077,
+ 0.0019520000000170512,
+ 0.002047000000004573,
+ 0.0019990000000120745,
+ 0.0020169999999950505,
+ 0.0020039999999994507,
+ 0.004326999999989312,
+ 0.0021449999999845204,
+ 0.0020219999999824267,
+ 0.001992000000001326,
+ 0.0020729999999957727,
+ 0.004438999999990756,
+ 0.0020399999999938245,
+ 0.0020729999999957727,
+ 0.0020820000000014716,
+ 0.004377000000005182,
+ 0.0020860000000197942,
+ 0.0020629999999925985,
+ 0.0019529999999861047,
+ 0.0019799999999747797,
+ 0.0021050000000002456,
+ 0.0019979999999861775,
+ 0.002018999999990001,
+ 0.001915000000025202,
+ 0.002011000000010199,
+ 0.0020550000000127966,
+ 0.002077999999983149,
+ 0.004367999999999483,
+ 0.002048000000002048
+ ],
+ "cpuMs": 0.9530000000000005,
+ "peakRssMiB": 87.03515625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "candidate",
+ "workload": "small-first",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.7469020000000057,
+ 0.1092739999999992,
+ 0.15094300000001226,
+ 0.11105100000000334,
+ 0.17244999999999777,
+ 0.0973459999999875,
+ 0.09652600000001144,
+ 0.09855099999998629,
+ 0.28714299999998616,
+ 0.13679299999998307,
+ 0.08702800000000366,
+ 0.07506599999999253,
+ 0.07270800000000577,
+ 0.07308199999999943,
+ 0.07525400000000104,
+ 0.07136399999998844,
+ 0.07741199999998116,
+ 0.07540199999999686,
+ 0.07245599999998831,
+ 0.07120899999998187,
+ 0.07125099999998952,
+ 0.07140599999999608,
+ 0.07328400000000101,
+ 0.07138000000000488,
+ 0.06994100000000003,
+ 0.07221499999999992,
+ 0.0680940000000021,
+ 0.06883899999999699,
+ 0.06902499999998213,
+ 0.06786899999997331,
+ 0.07193799999998873,
+ 0.0681380000000047,
+ 0.06865999999999417,
+ 0.06888699999998948,
+ 0.07129100000000221,
+ 0.06832700000001068,
+ 0.06853399999999965,
+ 0.06853399999999965,
+ 0.06760300000001962,
+ 0.06789100000000303,
+ 0.06823900000000549,
+ 0.0786030000000153,
+ 0.0746469999999988,
+ 0.06788700000001313,
+ 0.07029600000001324,
+ 0.0694080000000099,
+ 0.06788299999999481,
+ 0.0679670000000101,
+ 0.07443600000001993,
+ 0.07200800000001095,
+ 0.06967399999999202,
+ 0.0681459999999845,
+ 0.0674590000000137,
+ 0.06730799999999704,
+ 0.07301200000000563,
+ 0.07038699999998244,
+ 0.06711399999997525,
+ 0.07193499999999631,
+ 0.06825500000002194,
+ 0.06764899999998875,
+ 0.06719000000001074,
+ 0.06649600000000078,
+ 0.07081199999998944,
+ 0.07210699999998837,
+ 0.06657300000000532,
+ 0.0654169999999965,
+ 0.06686999999999443,
+ 0.0665480000000116,
+ 0.0665779999999927,
+ 0.08046699999999873,
+ 0.0666259999999852,
+ 0.0664430000000209,
+ 0.06595299999997906,
+ 0.07079500000000394,
+ 0.06652700000000777,
+ 0.06633699999997589,
+ 0.0665079999999989,
+ 0.06681299999999624,
+ 0.07005299999997305,
+ 0.06708000000000425,
+ 0.06920700000000579,
+ 0.067056000000008,
+ 0.07214400000000865,
+ 0.06862200000000485,
+ 0.0675189999999759,
+ 0.06691299999999956,
+ 0.08520100000001207,
+ 0.07399599999999396,
+ 0.07082500000001346,
+ 0.06929799999997499,
+ 0.06801600000000008,
+ 0.06803200000001652,
+ 0.0680070000000228,
+ 0.06687199999998938,
+ 0.06834399999999619,
+ 0.06739799999999718,
+ 0.07178700000000049,
+ 0.07226600000001326,
+ 0.06845200000000773,
+ 0.07167400000000157
+ ],
+ "cpuMs": 8.757,
+ "peakRssMiB": 94.5234375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "baseline",
+ "workload": "large-first",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.1114650000000097,
+ 0.006094999999959327,
+ 0.004852000000028056,
+ 0.004502999999999702,
+ 0.005486000000018976,
+ 0.004761999999971067,
+ 0.0044060000000172295,
+ 0.00449700000001485,
+ 0.10887100000002192,
+ 0.011556999999982054,
+ 0.0035300000000120235,
+ 0.0034880000000043765,
+ 0.0031329999999911706,
+ 0.0031710000000089167,
+ 0.0031979999999975917,
+ 0.0030349999999543797,
+ 0.0031359999999835964,
+ 0.00825499999996282,
+ 0.0038940000000025066,
+ 0.0028870000000438267,
+ 0.002889000000038777,
+ 0.002659999999991669,
+ 0.002567999999996573,
+ 0.004453000000012253,
+ 0.0033500000000117325,
+ 0.003191000000015265,
+ 0.002930999999989581,
+ 0.0028599999999983083,
+ 0.002717000000018288,
+ 0.0027410000000145374,
+ 0.002594999999985248,
+ 0.002694000000019514,
+ 0.002629999999953725,
+ 0.002668999999968946,
+ 0.002728999999987991,
+ 0.00275800000002846,
+ 0.0027719999999931133,
+ 0.0026839999999879183,
+ 0.0027489999999943393,
+ 0.002721000000008189,
+ 0.002744000000006963,
+ 0.0054580000000328255,
+ 0.0033380000000420296,
+ 0.0022860000000264336,
+ 0.002273000000002412,
+ 0.002138999999999669,
+ 0.002034000000037395,
+ 0.004462999999987005,
+ 0.002165999999988344,
+ 0.0020389999999679276,
+ 0.0020920000000046457,
+ 0.0021229999999832216,
+ 0.0021250000000350155,
+ 0.0021100000000160435,
+ 0.0021300000000223918,
+ 0.0022109999999884167,
+ 0.0021700000000350883,
+ 0.002158999999949174,
+ 0.0021800000000098407,
+ 0.002168000000040138,
+ 0.0022060000000010405,
+ 0.002104000000031192,
+ 0.002187000000049011,
+ 0.002100000000041291,
+ 0.0021029999999768734,
+ 0.0021419999999920947,
+ 0.0021520000000236905,
+ 0.0022189999999682186,
+ 0.002090000000009695,
+ 0.002138999999999669,
+ 0.0020840000000248438,
+ 0.0020719999999982974,
+ 0.002161999999998443,
+ 0.002044000000012147,
+ 0.0020820000000298933,
+ 0.002070000000003347,
+ 0.0020309999999881256,
+ 0.002078999999980624,
+ 0.002036999999972977,
+ 0.0020119999999792526,
+ 0.0021179999999958454,
+ 0.0020489999999995234,
+ 0.0020880000000147447,
+ 0.002104000000031192,
+ 0.002105999999969299,
+ 0.002105999999969299,
+ 0.0024639999999749307,
+ 0.0021740000000249893,
+ 0.00214299999998957,
+ 0.002166999999985819,
+ 0.0021639999999933934,
+ 0.002128999999968073,
+ 0.0020370000000298205,
+ 0.0021110000000135187,
+ 0.0021010000000387663,
+ 0.002067000000010921,
+ 0.002172000000030039,
+ 0.0020910000000071705,
+ 0.002120999999988271,
+ 0.0020550000000412183
+ ],
+ "cpuMs": 1.7779999999999947,
+ "peakRssMiB": 122.21875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "candidate",
+ "workload": "large-first",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.8339510000000132,
+ 0.11934999999999718,
+ 0.1581059999999752,
+ 0.11833400000000438,
+ 0.18017599999996037,
+ 0.10462000000001126,
+ 0.10397599999998874,
+ 0.16708099999999604,
+ 0.3127560000000358,
+ 0.139712999999972,
+ 0.09596800000002759,
+ 0.07611200000002327,
+ 0.07443200000000161,
+ 0.0731490000000008,
+ 0.07288399999998774,
+ 0.07221999999995887,
+ 0.08026599999999462,
+ 0.07605000000000928,
+ 0.07399800000001733,
+ 0.07200699999998506,
+ 0.07138899999995374,
+ 0.07088600000002998,
+ 0.0714360000000056,
+ 0.07960000000002765,
+ 0.07191199999999753,
+ 0.07072099999999182,
+ 0.07055700000000797,
+ 0.07081199999998944,
+ 0.07236799999998311,
+ 0.07025300000003654,
+ 0.07605200000000423,
+ 0.07330899999999474,
+ 0.07300399999996898,
+ 0.06926599999997052,
+ 0.06937900000002628,
+ 0.0688610000000267,
+ 0.06982499999998026,
+ 0.06918000000001712,
+ 0.0692229999999654,
+ 0.07092099999999846,
+ 0.06866899999999987,
+ 0.0764260000000263,
+ 0.07206800000000158,
+ 0.06996800000001713,
+ 0.07283100000000786,
+ 0.06854299999997693,
+ 0.07181100000002516,
+ 0.06730699999997114,
+ 0.06731700000000274,
+ 0.07010600000000977,
+ 0.0679670000000101,
+ 0.07096799999999348,
+ 0.06728299999997489,
+ 0.06807900000001155,
+ 0.06795099999999366,
+ 0.06768799999997555,
+ 0.06663599999995995,
+ 0.07100800000000618,
+ 0.07106199999998353,
+ 0.06708200000002762,
+ 0.0670109999999795,
+ 0.0737959999999589,
+ 0.06789599999996199,
+ 0.06766700000002857,
+ 0.06730499999997619,
+ 0.0670210000000111,
+ 0.06712999999996327,
+ 0.06730099999998629,
+ 0.07037199999996346,
+ 0.07083599999998569,
+ 0.06714499999998225,
+ 0.06836099999998169,
+ 0.07193599999999378,
+ 0.07539300000001958,
+ 0.06759200000004739,
+ 0.06766800000002604,
+ 0.06803600000000642,
+ 0.06822399999998652,
+ 0.06826100000000679,
+ 0.10481699999996863,
+ 0.07506799999998748,
+ 0.07000099999999065,
+ 0.06723399999998492,
+ 0.06663699999995742,
+ 0.06809899999996105,
+ 0.06583699999998771,
+ 0.06866799999994555,
+ 0.06410400000004302,
+ 0.06332800000001271,
+ 0.06391800000000103,
+ 0.06352100000003702,
+ 0.0631649999999695,
+ 0.06352400000002945,
+ 0.0635199999999827,
+ 0.0641549999999711,
+ 0.0629109999999855,
+ 0.06224200000002611,
+ 0.06259000000000015,
+ 0.06183400000003303,
+ 0.06303200000002107
+ ],
+ "cpuMs": 13.265999999999993,
+ "peakRssMiB": 124.0390625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "baseline",
+ "workload": "small-retained",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.102926999999994,
+ 0.006089000000002898,
+ 0.004489000000006627,
+ 0.004269999999991114,
+ 0.00530900000001111,
+ 0.004302999999993062,
+ 0.0043870000000083564,
+ 0.0038839999999993324,
+ 0.0604460000000131,
+ 0.01199900000000298,
+ 0.0038289999999960855,
+ 0.0034079999999789834,
+ 0.0032829999999819393,
+ 0.003058000000009997,
+ 0.0031319999999936954,
+ 0.0029210000000148284,
+ 0.0032580000000166365,
+ 0.003325000000018008,
+ 0.002952000000021826,
+ 0.0026620000000150412,
+ 0.004929999999973234,
+ 0.005023999999991702,
+ 0.0026249999999947704,
+ 0.0026749999999822194,
+ 0.002609000000006745,
+ 0.0025760000000047967,
+ 0.0026349999999979445,
+ 0.0025020000000210985,
+ 0.0026270000000181426,
+ 0.00458400000002257,
+ 0.0026429999999777465,
+ 0.002574000000009846,
+ 0.002441999999973632,
+ 0.00258200000001807,
+ 0.0025120000000242726,
+ 0.0025990000000035707,
+ 0.002517000000011649,
+ 0.0025059999999825777,
+ 0.0025430000000028485,
+ 0.0024980000000027758,
+ 0.005014999999986003,
+ 0.0048390000000040345,
+ 0.003088999999988573,
+ 0.002225999999978967,
+ 0.0020239999999773772,
+ 0.0019249999999999545,
+ 0.001923000000005004,
+ 0.004131000000000995,
+ 0.0019200000000125783,
+ 0.005731999999994741,
+ 0.0018269999999915854,
+ 0.0018489999999928841,
+ 0.0018250000000250566,
+ 0.0018650000000093314,
+ 0.0018369999999947595,
+ 0.0018769999999790343,
+ 0.0022799999999847387,
+ 0.0019900000000063756,
+ 0.0018269999999915854,
+ 0.0018060000000161835,
+ 0.001877000000007456,
+ 0.001861999999988484,
+ 0.001867000000004282,
+ 0.0019670000000076016,
+ 0.0017960000000130094,
+ 0.0018479999999954089,
+ 0.0018450000000029831,
+ 0.0019159999999942556,
+ 0.0018709999999941829,
+ 0.0019340000000056534,
+ 0.004103000000014845,
+ 0.0018790000000024065,
+ 0.003971000000007052,
+ 0.004223999999993566,
+ 0.0020020000000045,
+ 0.0018699999999967076,
+ 0.0018680000000017571,
+ 0.001877000000007456,
+ 0.0018799999999998818,
+ 0.0018469999999979336,
+ 0.0018859999999847332,
+ 0.001812000000001035,
+ 0.0019049999999936063,
+ 0.0017960000000130094,
+ 0.0018870000000106302,
+ 0.0017910000000256332,
+ 0.0018289999999865358,
+ 0.003892000000007556,
+ 0.0018719999999916581,
+ 0.001882000000023254,
+ 0.0018000000000029104,
+ 0.0018259999999941101,
+ 0.0018180000000143082,
+ 0.0018660000000068067,
+ 0.004041999999998325,
+ 0.0018840000000182044,
+ 0.0019220000000075288,
+ 0.0041440000000250166,
+ 0.001844000000005508,
+ 0.0018169999999884112
+ ],
+ "cpuMs": 0.8810000000000006,
+ "peakRssMiB": 88.62109375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "candidate",
+ "workload": "small-retained",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.786122000000006,
+ 0.2342079999999953,
+ 0.225026999999983,
+ 0.17258400000000051,
+ 0.29396800000000667,
+ 0.17358200000001034,
+ 0.13330300000001216,
+ 0.13095899999999006,
+ 0.2224429999999984,
+ 0.15001899999998614,
+ 0.12620599999999627,
+ 0.1233660000000043,
+ 0.12316100000001029,
+ 0.12280800000002046,
+ 0.12355300000001534,
+ 0.12059500000000867,
+ 0.12424300000000699,
+ 0.12713999999999714,
+ 0.123864999999995,
+ 0.12005499999997937,
+ 0.12291599999997516,
+ 0.11739199999999528,
+ 0.12096400000001495,
+ 0.12139400000000933,
+ 0.1174490000000219,
+ 0.13318200000000502,
+ 0.12212500000001114,
+ 0.116831000000019,
+ 0.11862099999999032,
+ 0.11720800000000509,
+ 0.11772799999999961,
+ 0.11909900000000562,
+ 0.11704800000001114,
+ 0.11900099999999725,
+ 0.11378899999999703,
+ 0.11919100000000071,
+ 0.11686299999999505,
+ 0.11776600000001736,
+ 0.11465599999999654,
+ 0.12089900000000853,
+ 0.11723100000000386,
+ 0.12548499999999763,
+ 0.11847599999998693,
+ 0.11453000000000202,
+ 0.12467200000000389,
+ 0.11627900000002,
+ 0.11666900000000169,
+ 0.11694299999999203,
+ 0.12326500000000351,
+ 0.1188060000000064,
+ 0.11805400000000077,
+ 0.11639200000001892,
+ 0.11879500000000576,
+ 0.11655200000001287,
+ 0.11743300000000545,
+ 0.11542800000000852,
+ 0.11460099999999329,
+ 0.11815400000000409,
+ 0.12259699999998475,
+ 0.11445799999998485,
+ 0.11419200000000274,
+ 0.12017600000001494,
+ 0.15223700000001372,
+ 0.1250580000000241,
+ 0.1169050000000027,
+ 0.11297500000000582,
+ 0.11411499999999819,
+ 0.11188400000000343,
+ 0.11055500000000507,
+ 0.1201109999999801,
+ 0.11302200000000084,
+ 0.10854000000000497,
+ 0.1099529999999902,
+ 0.11147600000001034,
+ 0.10904499999998052,
+ 0.10985099999999193,
+ 0.10824700000000576,
+ 0.10730099999997833,
+ 0.11397300000001565,
+ 0.1149599999999964,
+ 0.10964599999999791,
+ 0.10847599999999602,
+ 0.10978699999998298,
+ 0.10813099999998599,
+ 0.10542599999999425,
+ 0.10959000000002561,
+ 0.1123800000000017,
+ 0.10950900000000274,
+ 0.10617700000000241,
+ 0.1155819999999892,
+ 0.10810000000000741,
+ 0.10861199999999371,
+ 0.10648000000000479,
+ 0.10780499999998483,
+ 0.11005699999998342,
+ 0.10772000000000048,
+ 0.11589000000000738,
+ 0.1073729999999955,
+ 0.1120249999999885,
+ 0.10967700000000491
+ ],
+ "cpuMs": 13.474000000000009,
+ "peakRssMiB": 90.3828125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "baseline",
+ "workload": "large-retained",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.11428200000000288,
+ 0.006622999999990498,
+ 0.0048620000000028085,
+ 0.004798999999991338,
+ 0.0056960000000003674,
+ 0.004389000000003307,
+ 0.004512000000033822,
+ 0.004118000000005395,
+ 0.06385699999998451,
+ 0.01252199999998993,
+ 0.00410999999996875,
+ 0.003742999999985841,
+ 0.0035310000000094988,
+ 0.0034660000000030777,
+ 0.003444999999999254,
+ 0.003478000000029624,
+ 0.0038589999999771862,
+ 0.0038129999999796382,
+ 0.0032990000000268083,
+ 0.00490100000001803,
+ 0.0030090000000200234,
+ 0.0029379999999719075,
+ 0.002927999999997155,
+ 0.0035039999999639804,
+ 0.002874999999960437,
+ 0.003429999999980282,
+ 0.0028950000000236287,
+ 0.0065429999999651045,
+ 0.0033880000000294785,
+ 0.002862999999990734,
+ 0.0026399999999853208,
+ 0.002555000000029395,
+ 0.0023659999999949832,
+ 0.002329000000031556,
+ 0.003910000000018954,
+ 0.0032939999999825886,
+ 0.0028679999999781103,
+ 0.0031789999999887186,
+ 0.002525999999988926,
+ 0.002557999999964977,
+ 0.002521999999999025,
+ 0.006653000000028442,
+ 0.0032009999999900174,
+ 0.002242000000023836,
+ 0.0020949999999970714,
+ 0.0020499999999969987,
+ 0.0018910000000005311,
+ 0.002066000000013446,
+ 0.0017929999999637403,
+ 0.0018980000000397013,
+ 0.001860999999962587,
+ 0.0019440000000372493,
+ 0.0018169999999599895,
+ 0.0018249999999966349,
+ 0.001882000000023254,
+ 0.0018460000000004584,
+ 0.0018709999999941829,
+ 0.0017889999999738393,
+ 0.00180500000004713,
+ 0.0018719999999916581,
+ 0.0018519999999853098,
+ 0.0018230000000016844,
+ 0.0018390000000181317,
+ 0.0017960000000130094,
+ 0.0018979999999828578,
+ 0.0018919999999980064,
+ 0.0018709999999941829,
+ 0.00187999999997146,
+ 0.0018049999999902866,
+ 0.0018769999999790343,
+ 0.0019009999999752836,
+ 0.001806999999985237,
+ 0.0019429999999829306,
+ 0.001924000000030901,
+ 0.0018840000000182044,
+ 0.0018570000000295295,
+ 0.0018410000000130822,
+ 0.0018790000000308282,
+ 0.001863000000014381,
+ 0.0018200000000092587,
+ 0.001856999999972686,
+ 0.0018460000000004584,
+ 0.0018600000000219552,
+ 0.0019209999999816318,
+ 0.0019019999999727588,
+ 0.0017819999999915126,
+ 0.0018079999999827123,
+ 0.0018479999999954089,
+ 0.0018460000000004584,
+ 0.0018369999999663378,
+ 0.001790000000028158,
+ 0.001783999999986463,
+ 0.0017709999999624415,
+ 0.0018059999999877618,
+ 0.001837999999963813,
+ 0.0017199999999775173,
+ 0.0017780000000016116,
+ 0.00179800000000796,
+ 0.0018680000000017571,
+ 0.001844000000005508
+ ],
+ "cpuMs": 2.168999999999994,
+ "peakRssMiB": 120.26953125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 2,
+ "source": "candidate",
+ "workload": "large-retained",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.8946980000000053,
+ 0.25917399999997315,
+ 0.2598289999999679,
+ 0.16637299999996458,
+ 0.318349000000012,
+ 0.17803600000002007,
+ 3.1835080000000175,
+ 0.12675500000000284,
+ 0.2105720000000133,
+ 0.4918350000000373,
+ 0.12279399999999896,
+ 0.11475699999999733,
+ 0.11174900000003163,
+ 0.1093370000000391,
+ 0.10863599999998996,
+ 0.10676599999999326,
+ 0.11493899999999257,
+ 0.1109480000000076,
+ 0.10678500000000213,
+ 0.10553500000003169,
+ 0.10431599999998298,
+ 0.10469100000000253,
+ 0.10560500000002548,
+ 0.11313400000000229,
+ 0.11396500000000742,
+ 0.1094749999999749,
+ 0.10418600000002698,
+ 0.10317900000001146,
+ 0.10288699999995288,
+ 0.10318300000000136,
+ 0.10240700000002789,
+ 0.10232500000000755,
+ 0.10808500000001686,
+ 0.1023089999999911,
+ 0.1028079999999818,
+ 0.10276199999998425,
+ 0.10316299999999501,
+ 0.10302500000000236,
+ 0.10354499999999689,
+ 0.10289099999999962,
+ 0.10163199999999506,
+ 0.11009500000000116,
+ 0.10514299999999821,
+ 0.10685699999999088,
+ 0.10235599999998612,
+ 0.10710599999998749,
+ 0.10152700000003279,
+ 0.10126500000001215,
+ 0.10469299999999748,
+ 0.10045900000000074,
+ 0.10102799999998524,
+ 0.10166599999996606,
+ 0.10030199999999923,
+ 0.10131300000000465,
+ 0.10131000000001222,
+ 0.10110700000001316,
+ 0.10042199999998047,
+ 0.10090500000001157,
+ 0.10133500000000595,
+ 0.10086200000000645,
+ 0.10215099999999211,
+ 0.10412400000001298,
+ 0.10065400000002,
+ 0.10042300000003479,
+ 0.10399799999999004,
+ 0.10009800000000268,
+ 0.10809899999998152,
+ 0.10836999999997943,
+ 0.10011800000000903,
+ 0.10422899999997526,
+ 0.10168299999997998,
+ 0.10457199999996192,
+ 0.14427100000000337,
+ 0.13710500000001957,
+ 0.11276300000002948,
+ 0.11510500000002821,
+ 0.2192670000000021,
+ 0.10919699999999466,
+ 0.10870299999999133,
+ 0.11296399999997675,
+ 0.10750499999994645,
+ 0.11226599999997688,
+ 0.10776900000001888,
+ 0.11081000000001495,
+ 0.10711299999996982,
+ 0.11092500000000882,
+ 0.10595200000000204,
+ 0.10694300000000112,
+ 0.11012900000002901,
+ 0.10668400000002976,
+ 0.11067700000000968,
+ 0.11064200000004121,
+ 0.11011100000001761,
+ 0.10601700000000847,
+ 0.11011199999995824,
+ 0.1095149999999876,
+ 0.11053100000003724,
+ 0.105399000000034,
+ 0.11030199999999013,
+ 0.10537599999997838
+ ],
+ "cpuMs": 21.62400000000001,
+ "peakRssMiB": 120.10546875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "baseline",
+ "workload": "small-first",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.10533899999998653,
+ 0.005580999999978076,
+ 0.004466000000007853,
+ 0.004023000000017873,
+ 0.005178000000000793,
+ 0.004202000000020689,
+ 0.0044480000000248765,
+ 0.004229000000009364,
+ 0.10833599999998,
+ 0.010216999999983045,
+ 0.003227000000009639,
+ 0.0028750000000172804,
+ 0.0027960000000177843,
+ 0.0027029999999967913,
+ 0.0026850000000138152,
+ 0.0027589999999975134,
+ 0.0028630000000191558,
+ 0.00313099999999622,
+ 0.0051879999999755455,
+ 0.002721000000008189,
+ 0.0024600000000134514,
+ 0.002540000000010423,
+ 0.0025799999999946976,
+ 0.0024750000000040018,
+ 0.002468000000021675,
+ 0.004271999999986065,
+ 0.0024319999999988795,
+ 0.0024640000000033524,
+ 0.002544999999997799,
+ 0.00243399999999383,
+ 0.0024980000000027758,
+ 0.0024359999999887805,
+ 0.004364999999978636,
+ 0.0024329999999963547,
+ 0.002458000000018501,
+ 0.002423999999990656,
+ 0.002509000000003425,
+ 0.0023630000000025575,
+ 0.0024280000000089785,
+ 0.004150000000009868,
+ 0.0024999999999977263,
+ 0.004781000000008362,
+ 0.0030249999999796273,
+ 0.0022249999999814918,
+ 0.0021420000000205164,
+ 0.0019489999999962038,
+ 0.0019149999999967804,
+ 0.001979000000005726,
+ 0.001992000000001326,
+ 0.02577800000000252,
+ 0.0019979999999861775,
+ 0.002338000000008833,
+ 0.001981999999998152,
+ 0.0018560000000036325,
+ 0.001857999999998583,
+ 0.0018269999999915854,
+ 0.0019169999999917309,
+ 0.001875999999981559,
+ 0.001988000000011425,
+ 0.0018650000000093314,
+ 0.0018249999999966349,
+ 0.0034729999999854044,
+ 0.001861999999988484,
+ 0.001886000000013155,
+ 0.0018880000000081054,
+ 0.0019099999999809825,
+ 0.003816999999997961,
+ 0.001968000000005077,
+ 0.0019169999999917309,
+ 0.0019020000000011805,
+ 0.0018280000000174823,
+ 0.0019109999999784577,
+ 0.00195399999998358,
+ 0.00191300000000183,
+ 0.0018519999999853098,
+ 0.0018139999999959855,
+ 0.001890000000003056,
+ 0.001831000000009908,
+ 0.003956999999985555,
+ 0.001861999999988484,
+ 0.0019660000000101263,
+ 0.0019470000000012533,
+ 0.0019399999999905049,
+ 0.001949999999993679,
+ 0.0017949999999871125,
+ 0.0018550000000061573,
+ 0.0035430000000076234,
+ 0.0018460000000004584,
+ 0.003816999999997961,
+ 0.001890000000003056,
+ 0.0018660000000068067,
+ 0.0018490000000213058,
+ 0.0019520000000170512,
+ 0.003568999999998823,
+ 0.0019080000000144537,
+ 0.0018660000000068067,
+ 0.0019120000000043547,
+ 0.0019400000000189266,
+ 0.0019279999999923803,
+ 0.001875999999981559
+ ],
+ "cpuMs": 0.9400000000000005,
+ "peakRssMiB": 89.42578125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "candidate",
+ "workload": "small-first",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.7631919999999752,
+ 0.11000300000000607,
+ 0.14901199999999903,
+ 0.12442900000002055,
+ 0.1584969999999828,
+ 0.1018410000000074,
+ 0.09729100000001267,
+ 0.0989059999999995,
+ 0.290268999999995,
+ 0.13261099999999715,
+ 0.09053299999999354,
+ 0.07614399999999932,
+ 0.07806500000000938,
+ 0.07338899999999171,
+ 0.07298600000001443,
+ 0.07570200000000682,
+ 0.07530900000000429,
+ 0.0760490000000118,
+ 0.07392300000000773,
+ 0.08280899999999747,
+ 0.06928500000000781,
+ 0.07091600000001108,
+ 0.07336799999998789,
+ 0.06950400000002332,
+ 0.06979200000000674,
+ 0.06896199999999908,
+ 0.07005799999998885,
+ 0.07306500000001392,
+ 0.07043400000000588,
+ 0.07096199999998021,
+ 0.07499899999999116,
+ 0.07469900000000962,
+ 0.07025300000000811,
+ 0.07152300000001333,
+ 0.07015100000000984,
+ 0.06929400000001351,
+ 0.06958600000001525,
+ 0.06912900000000377,
+ 0.06998999999999,
+ 0.07106099999998605,
+ 0.07226900000000569,
+ 0.07605499999999665,
+ 0.07435599999999454,
+ 0.06962400000000457,
+ 0.071975000000009,
+ 0.068491999999992,
+ 0.06849200000002043,
+ 0.06976299999999469,
+ 0.10351400000001831,
+ 0.08453000000000088,
+ 0.0816379999999981,
+ 0.0774940000000015,
+ 0.07566700000000992,
+ 0.0776000000000181,
+ 0.07523000000000479,
+ 0.07399700000001985,
+ 0.07470700000001784,
+ 0.07442600000001676,
+ 0.07323699999997757,
+ 0.07404800000000478,
+ 0.07442100000000096,
+ 0.0729690000000005,
+ 0.07469500000001972,
+ 0.07486599999998589,
+ 0.07357399999997938,
+ 0.07332800000000361,
+ 0.07542499999999563,
+ 0.07195999999999003,
+ 0.07320699999999647,
+ 0.07376700000000369,
+ 0.07326199999999972,
+ 0.07353599999999005,
+ 0.07323900000000094,
+ 0.07519700000000284,
+ 0.07164299999999457,
+ 0.07218999999997777,
+ 0.07245299999999588,
+ 0.07225099999999429,
+ 0.07470299999999952,
+ 0.07877099999998904,
+ 0.0719789999999989,
+ 0.07136299999999096,
+ 0.07245599999998831,
+ 0.07245100000000093,
+ 0.09549000000001229,
+ 0.0755489999999952,
+ 0.07180500000001189,
+ 0.06871899999998732,
+ 0.06805099999999698,
+ 0.06826999999998407,
+ 0.0675109999999961,
+ 0.06696600000000785,
+ 0.06690399999999386,
+ 0.07103499999999485,
+ 0.06701800000001867,
+ 0.0668940000000191,
+ 0.0865699999999947,
+ 0.07430500000000961,
+ 0.07148200000000315,
+ 0.07255900000001247
+ ],
+ "cpuMs": 9.170000000000002,
+ "peakRssMiB": 93.0859375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "baseline",
+ "workload": "large-first",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.11283599999995886,
+ 0.008384999999975662,
+ 0.005060000000014497,
+ 0.004705999999998767,
+ 0.007126999999968575,
+ 0.004749000000003889,
+ 0.005261999999959244,
+ 0.0048429999999939355,
+ 0.12440600000002178,
+ 0.016511999999977434,
+ 0.004210999999997966,
+ 0.0035799999999994725,
+ 0.003313999999988937,
+ 0.003222999999991316,
+ 0.0037750000000187356,
+ 0.0033549999999991087,
+ 0.003417000000013104,
+ 0.005178999999998268,
+ 0.0034200000000055297,
+ 0.003065999999989799,
+ 0.0028499999999667125,
+ 0.0029719999999997526,
+ 0.0028940000000261534,
+ 0.00408900000002177,
+ 0.0028719999999680113,
+ 0.002835000000004584,
+ 0.00275800000002846,
+ 0.0027039999999942665,
+ 0.0027569999999741412,
+ 0.002694000000019514,
+ 0.0038250000000061846,
+ 0.002808000000015909,
+ 0.002881000000002132,
+ 0.0028319999999553147,
+ 0.002792999999996937,
+ 0.0029139999999756583,
+ 0.002874000000019805,
+ 0.0027610000000208856,
+ 0.002762000000018361,
+ 0.0026889999999752945,
+ 0.002682999999990443,
+ 0.005239000000017313,
+ 0.003998000000024149,
+ 0.003238000000010288,
+ 0.0021760000000199398,
+ 0.002544999999997799,
+ 0.0020460000000070977,
+ 0.0018749999999840838,
+ 0.002969000000007327,
+ 0.0018850000000156797,
+ 0.002001000000007025,
+ 0.0024420000000304753,
+ 0.0019649999999842294,
+ 0.0019889999999804786,
+ 0.002009999999984302,
+ 0.002004999999996926,
+ 0.001989999999977954,
+ 0.0020180000000209475,
+ 0.0018919999999980064,
+ 0.002613999999994121,
+ 0.0031480000000101427,
+ 0.002030000000047494,
+ 0.0019849999999905776,
+ 0.0026110000000016953,
+ 0.0019650000000410728,
+ 0.002529999999978827,
+ 0.002530999999976302,
+ 0.00197400000001835,
+ 0.0019950000000221735,
+ 0.0020420000000171967,
+ 0.0019689999999741303,
+ 0.0019300000000157524,
+ 0.0021529999999643223,
+ 0.001985999999988053,
+ 0.002009999999984302,
+ 0.0019300000000157524,
+ 0.001978000000008251,
+ 0.001929999999958909,
+ 0.0020400000000222462,
+ 0.0019379999999955544,
+ 0.002004999999996926,
+ 0.0019710000000259242,
+ 0.002624000000025717,
+ 0.002030000000047494,
+ 0.001985999999988053,
+ 0.0019730000000208747,
+ 0.0019460000000321998,
+ 0.002031999999985601,
+ 0.002009999999984302,
+ 0.002028999999993175,
+ 0.0023350000000164073,
+ 0.0021229999999832216,
+ 0.0019530000000145264,
+ 0.0020039999999994507,
+ 0.002479999999991378,
+ 0.002066000000013446,
+ 0.001928000000020802,
+ 0.0019570000000044274,
+ 0.0020420000000171967,
+ 0.0035799999999994725
+ ],
+ "cpuMs": 2.6229999999999953,
+ "peakRssMiB": 125.30078125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "candidate",
+ "workload": "large-first",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.8275899999999865,
+ 0.12572799999998097,
+ 0.16184099999998125,
+ 0.12038799999999128,
+ 0.2184389999999894,
+ 0.10595999999998185,
+ 0.10845199999999977,
+ 0.12298099999998158,
+ 0.30105300000002444,
+ 0.13484200000004876,
+ 0.09008699999998271,
+ 0.07596599999999398,
+ 0.07519499999995105,
+ 0.07457600000003595,
+ 0.07427799999999252,
+ 0.07339600000000246,
+ 0.075095000000033,
+ 0.0735480000000166,
+ 0.07017100000001619,
+ 0.0720389999999611,
+ 0.06731100000001788,
+ 0.06642400000004045,
+ 0.07080000000001974,
+ 0.07081299999998691,
+ 0.06738799999999401,
+ 0.06685400000003483,
+ 0.0659790000000271,
+ 0.06637899999998353,
+ 0.06657500000000027,
+ 0.06894799999997758,
+ 0.06523700000002464,
+ 0.06469300000003386,
+ 0.06475000000000364,
+ 0.06518399999998792,
+ 0.0653920000000312,
+ 0.06481099999996331,
+ 0.06467600000001994,
+ 0.06464099999999462,
+ 0.06468599999999469,
+ 0.07089000000001988,
+ 0.06587200000001303,
+ 0.07344699999998738,
+ 0.06925499999999829,
+ 0.06677000000001954,
+ 0.06613600000002862,
+ 0.06605899999999565,
+ 0.06617799999997942,
+ 0.06569300000001022,
+ 0.09060899999997218,
+ 0.08714599999996153,
+ 0.08046399999994946,
+ 0.07603699999998526,
+ 0.07182199999999739,
+ 0.06792999999998983,
+ 0.07215499999995245,
+ 0.07222900000004984,
+ 0.07574200000004794,
+ 0.06571199999996225,
+ 0.06647500000002537,
+ 0.06597599999997783,
+ 0.06879299999997102,
+ 0.12736000000001013,
+ 0.09183400000000574,
+ 0.08514100000002145,
+ 0.0777699999999868,
+ 0.1163970000000063,
+ 0.07883099999997967,
+ 0.0740989999999897,
+ 0.0671989999999596,
+ 0.06628999999998086,
+ 0.0666519999999764,
+ 0.06894899999997506,
+ 0.06883099999998876,
+ 0.06585799999999153,
+ 0.06443500000000313,
+ 0.06440900000001193,
+ 0.0645420000000172,
+ 0.06735500000002048,
+ 0.0649450000000229,
+ 0.06508800000000292,
+ 0.06360599999999295,
+ 0.06423899999998639,
+ 0.06399600000003147,
+ 0.06857500000000982,
+ 0.06425300000000789,
+ 0.06472899999999981,
+ 0.06360599999999295,
+ 0.06321000000002641,
+ 0.06380400000000463,
+ 0.06405699999999115,
+ 0.06350200000002815,
+ 0.06701999999995678,
+ 0.06346600000000535,
+ 0.06370299999997542,
+ 0.06386599999996179,
+ 0.0636599999999703,
+ 0.06363700000002837,
+ 0.06325700000002143,
+ 0.06325900000001639,
+ 0.06359800000001314
+ ],
+ "cpuMs": 12.816000000000011,
+ "peakRssMiB": 123.98046875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "baseline",
+ "workload": "small-retained",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.1057169999999985,
+ 0.006055000000003474,
+ 0.004267999999996164,
+ 0.004091999999985774,
+ 0.004756999999983691,
+ 0.0039260000000069795,
+ 0.0038570000000106575,
+ 0.003558999999995649,
+ 0.05916100000001734,
+ 0.01127999999999929,
+ 0.0036709999999970933,
+ 0.003276999999997088,
+ 0.003064999999992324,
+ 0.0029130000000066048,
+ 0.0028099999999824377,
+ 0.0028709999999989577,
+ 0.005258000000026186,
+ 0.0030679999999847496,
+ 0.003038000000003649,
+ 0.005304999999992788,
+ 0.0026920000000245636,
+ 0.0025289999999813517,
+ 0.0024520000000052278,
+ 0.0024870000000021264,
+ 0.0024410000000045784,
+ 0.0024789999999939027,
+ 0.002463000000005877,
+ 0.0023899999999912325,
+ 0.002415999999982432,
+ 0.002332999999993035,
+ 0.002442999999999529,
+ 0.0023949999999786087,
+ 0.002390000000019654,
+ 0.0044049999999913325,
+ 0.0023439999999936845,
+ 0.0023869999999988067,
+ 0.0023070000000018354,
+ 0.002369999999984884,
+ 0.0023869999999988067,
+ 0.002369999999984884,
+ 0.0023019999999860374,
+ 0.004695999999995593,
+ 0.0031830000000070413,
+ 0.002052000000020371,
+ 0.0019179999999892061,
+ 0.0023620000000050823,
+ 0.001936000000000604,
+ 0.001958999999999378,
+ 0.0019619999999918036,
+ 0.0018819999999948323,
+ 0.0018239999999991596,
+ 0.001789000000002261,
+ 0.0018689999999992324,
+ 0.0018880000000081054,
+ 0.001812000000001035,
+ 0.0017959999999845877,
+ 0.0033700000000180808,
+ 0.001829999999984011,
+ 0.0018320000000073833,
+ 0.003431000000006179,
+ 0.0017959999999845877,
+ 0.0018369999999947595,
+ 0.0018029999999953361,
+ 0.0018490000000213058,
+ 0.0017530000000078871,
+ 0.0017589999999927386,
+ 0.0017919999999946867,
+ 0.0018019999999978609,
+ 0.0018139999999959855,
+ 0.0017899999999997362,
+ 0.0017919999999946867,
+ 0.0017899999999997362,
+ 0.0018129999999985102,
+ 0.0018059999999877618,
+ 0.0017650000000060118,
+ 0.0017899999999997362,
+ 0.0036220000000071195,
+ 0.0018019999999978609,
+ 0.0018420000000105574,
+ 0.0018179999999858865,
+ 0.0017949999999871125,
+ 0.0017819999999915126,
+ 0.0017320000000040636,
+ 0.0017529999999794654,
+ 0.0018059999999877618,
+ 0.001746999999994614,
+ 0.0017640000000085365,
+ 0.0017869999999788888,
+ 0.0018049999999902866,
+ 0.0017819999999915126,
+ 0.0017610000000161108,
+ 0.001775000000009186,
+ 0.0018010000000003856,
+ 0.0017489999999895645,
+ 0.003411999999997306,
+ 0.0017959999999845877,
+ 0.0018780000000049313,
+ 0.003388999999998532,
+ 0.0019149999999967804,
+ 0.0018450000000029831
+ ],
+ "cpuMs": 0.8430000000000005,
+ "peakRssMiB": 90.140625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "candidate",
+ "workload": "small-retained",
+ "bytes": 79,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.7854480000000024,
+ 0.23289099999999507,
+ 0.22978599999999005,
+ 0.15974399999998923,
+ 0.290440000000018,
+ 0.17806900000002202,
+ 0.137408999999991,
+ 0.1338010000000054,
+ 0.23513499999998544,
+ 0.15561800000000403,
+ 0.12540000000001328,
+ 0.12758300000001555,
+ 0.12131099999999151,
+ 0.12261899999998604,
+ 0.12251799999998525,
+ 0.12674999999998704,
+ 0.12328500000000986,
+ 0.1264579999999853,
+ 0.12030300000000693,
+ 0.12056499999999915,
+ 0.11650499999998942,
+ 0.12009100000000217,
+ 0.12000699999998687,
+ 0.12182199999998033,
+ 0.12178099999999858,
+ 0.11586400000001618,
+ 0.1183759999999836,
+ 0.14774799999997867,
+ 0.1204180000000008,
+ 0.11660299999999779,
+ 0.11062699999999381,
+ 0.11730600000001346,
+ 0.11424400000001356,
+ 0.1148860000000127,
+ 0.10967800000000238,
+ 0.1224849999999833,
+ 0.11335100000002285,
+ 0.11148299999999267,
+ 0.11060500000002094,
+ 0.10885999999999285,
+ 0.11351099999998837,
+ 0.11776000000000408,
+ 0.12219699999999989,
+ 0.10794799999999327,
+ 0.1113820000000203,
+ 0.11058300000001964,
+ 0.11029499999997938,
+ 0.10756399999999644,
+ 0.1185869999999909,
+ 0.11134699999999498,
+ 0.111487000000011,
+ 0.11164800000000241,
+ 0.10992600000000152,
+ 0.10934299999999553,
+ 0.10748299999997357,
+ 0.10478299999999763,
+ 0.1052270000000135,
+ 0.11030199999999013,
+ 0.10826400000001968,
+ 0.10978000000000065,
+ 0.11877099999998109,
+ 0.10943000000000325,
+ 0.10802599999999529,
+ 0.11307099999999082,
+ 0.10889399999999227,
+ 0.1083420000000217,
+ 0.10822400000000698,
+ 0.11215500000000134,
+ 0.10701299999999492,
+ 0.10512700000001018,
+ 0.10737999999997783,
+ 0.10670099999998683,
+ 0.11011299999998414,
+ 0.10520600000000968,
+ 0.12760800000000927,
+ 0.11607800000001589,
+ 0.1114729999999895,
+ 0.10504700000001321,
+ 0.1072240000000022,
+ 0.11507500000001869,
+ 0.11046300000000997,
+ 0.1074299999999937,
+ 0.1155080000000055,
+ 0.10948199999998565,
+ 0.10586800000001517,
+ 0.1224990000000048,
+ 0.10926000000000613,
+ 0.10839200000000915,
+ 0.10599999999999454,
+ 0.10777799999999615,
+ 0.10689400000001115,
+ 0.11051699999998732,
+ 0.10641699999999332,
+ 0.10797900000000027,
+ 0.10728800000001115,
+ 0.10941199999999185,
+ 0.11140499999999065,
+ 0.11266799999998511,
+ 0.10728199999999788,
+ 0.11451700000000642
+ ],
+ "cpuMs": 13.223,
+ "peakRssMiB": 89.34765625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "baseline",
+ "workload": "large-retained",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.18510199999997212,
+ 0.010857999999984713,
+ 0.008338999999978114,
+ 0.007348999999976513,
+ 0.009336000000018885,
+ 0.007473000000004504,
+ 0.024656999999990603,
+ 0.006593000000009397,
+ 0.07340899999996964,
+ 0.013770999999962896,
+ 0.0045860000000175205,
+ 0.004105999999978849,
+ 0.003869000000008782,
+ 0.006233000000008815,
+ 0.003527000000019598,
+ 0.003566999999975451,
+ 0.0038799999999810098,
+ 0.00494799999995621,
+ 0.0042140000000472355,
+ 0.003899999999987358,
+ 0.0030679999999847496,
+ 0.002927999999997155,
+ 0.002842999999984386,
+ 0.0029199999999605097,
+ 0.002736999999967793,
+ 0.003611000000034892,
+ 0.002708000000041011,
+ 0.007444000000020878,
+ 0.003872000000001208,
+ 0.0028140000000007603,
+ 0.0026680000000283144,
+ 0.004052000000001499,
+ 0.0033490000000142572,
+ 0.0032049999999799184,
+ 0.002859000000000833,
+ 0.002828000000022257,
+ 0.002621999999973923,
+ 0.0025699999999915235,
+ 0.002632000000005519,
+ 0.0025650000000041473,
+ 0.0026310000000080436,
+ 0.006389000000012857,
+ 0.003378999999995358,
+ 0.003712000000007265,
+ 0.0020230000000083237,
+ 0.002096999999992022,
+ 0.0019119999999475112,
+ 0.0019039999999677093,
+ 0.0019330000000081782,
+ 0.0019439999999804058,
+ 0.0018919999999980064,
+ 0.0019179999999892061,
+ 0.0019350000000031287,
+ 0.0018760000000384025,
+ 0.0019110000000068794,
+ 0.0018840000000182044,
+ 0.0018749999999840838,
+ 0.0018990000000371765,
+ 0.0019399999999905049,
+ 0.0018789999999739848,
+ 0.001886000000013155,
+ 0.0018650000000093314,
+ 0.0019800000000032014,
+ 0.0019540000000120017,
+ 0.0019269999999664833,
+ 0.002593000000047141,
+ 0.001902999999970234,
+ 0.0020499999999969987,
+ 0.0019310000000132277,
+ 0.001959999999996853,
+ 0.003352000000006683,
+ 0.0028369999999995343,
+ 0.002345000000048003,
+ 0.002201999999954296,
+ 0.002039000000024771,
+ 0.001993999999967855,
+ 0.0020069999999918764,
+ 0.0018789999999739848,
+ 0.0018969999999853826,
+ 0.0018729999999891334,
+ 0.0018999999999778083,
+ 0.0018570000000295295,
+ 0.0018610000000194304,
+ 0.0018959999999879074,
+ 0.0018969999999853826,
+ 0.002364999999997508,
+ 0.0017930000000205837,
+ 0.0018200000000092587,
+ 0.0018639999999550128,
+ 0.001794000000018059,
+ 0.0018929999999954816,
+ 0.0018460000000004584,
+ 0.001837999999963813,
+ 0.0018369999999663378,
+ 0.0017930000000205837,
+ 0.0017770000000041364,
+ 0.0017889999999738393,
+ 0.0023320000000239816,
+ 0.0017870000000357322,
+ 0.0017439999999737665
+ ],
+ "cpuMs": 2.775999999999993,
+ "peakRssMiB": 125.1875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ },
+ {
+ "repetition": 3,
+ "source": "candidate",
+ "workload": "large-retained",
+ "bytes": 16775247,
+ "iterations": 100,
+ "outcomes": {
+ "closed": 100,
+ "held": 0
+ },
+ "signals": 100,
+ "latenciesMs": [
+ 0.8896999999999764,
+ 0.26064199999999005,
+ 0.2947729999999922,
+ 0.1733780000000138,
+ 0.312767000000008,
+ 0.19298100000000318,
+ 2.7226339999999993,
+ 0.12837100000001556,
+ 0.2240199999999959,
+ 0.14935800000000654,
+ 0.12380199999998354,
+ 0.12660600000000954,
+ 0.11633500000002073,
+ 0.11969899999999711,
+ 0.1164879999999755,
+ 0.11713199999999802,
+ 0.11692800000000148,
+ 0.12167300000001546,
+ 0.1140219999999772,
+ 0.11820700000001239,
+ 0.11145200000004252,
+ 0.11180699999999888,
+ 0.11410300000000007,
+ 0.11395000000004529,
+ 0.11812099999997372,
+ 0.11067499999995789,
+ 0.1142990000000168,
+ 0.11385300000000598,
+ 0.11442600000003722,
+ 0.1098700000000008,
+ 0.11307499999998072,
+ 0.10916099999997186,
+ 0.11333000000001903,
+ 0.1142770000000155,
+ 0.11007000000000744,
+ 0.11348099999997885,
+ 0.10997199999997065,
+ 0.11231499999996686,
+ 0.11026399999997238,
+ 0.11372499999998809,
+ 0.1203649999999925,
+ 0.13125700000000506,
+ 0.11610799999999699,
+ 0.11831399999999803,
+ 0.1103570000000218,
+ 0.11342599999994718,
+ 0.10845999999997957,
+ 0.1109159999999747,
+ 0.11026499999996986,
+ 0.11877599999996846,
+ 0.14118100000001732,
+ 0.11298599999997805,
+ 0.1098779999999806,
+ 0.10430900000000065,
+ 0.103746000000001,
+ 0.10204099999998562,
+ 0.10648900000001049,
+ 0.10184699999996383,
+ 0.10953500000005079,
+ 0.10166700000002038,
+ 0.10933599999998478,
+ 0.10023599999999533,
+ 0.10436199999998053,
+ 0.10095200000000659,
+ 0.10350900000003094,
+ 0.10946799999999257,
+ 0.10292799999996305,
+ 0.1011490000000208,
+ 0.10170699999997623,
+ 0.10700400000001764,
+ 0.10511099999996532,
+ 0.10396500000001652,
+ 0.10722700000002305,
+ 0.1079459999999699,
+ 0.10095799999999144,
+ 0.10470099999997728,
+ 0.10457600000000866,
+ 0.10445000000004256,
+ 0.10022999999995363,
+ 0.10438000000004877,
+ 0.1009159999999838,
+ 0.10644700000000284,
+ 0.10069300000003523,
+ 0.09964100000001963,
+ 0.10012799999998379,
+ 0.10071199999998726,
+ 0.10406000000000404,
+ 0.09996100000000752,
+ 0.10292899999996052,
+ 0.10425400000002583,
+ 0.10642200000000912,
+ 0.10061200000001236,
+ 0.1078960000000393,
+ 0.10105699999996887,
+ 0.10687100000001237,
+ 0.10478999999997995,
+ 0.10517300000003615,
+ 0.10129200000000083,
+ 0.1053150000000187,
+ 0.1007680000000164
+ ],
+ "cpuMs": 22.090000000000025,
+ "peakRssMiB": 122.265625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64"
+ }
+ ]
+}
diff --git a/docs/research/2026-10-10-cancel-cost.mts b/docs/research/2026-10-10-cancel-cost.mts
new file mode 100644
index 000000000..3869100d1
--- /dev/null
+++ b/docs/research/2026-10-10-cancel-cost.mts
@@ -0,0 +1,59 @@
+/** Compare complete eager Cancel calls against a chosen CLI tree. No daemon, process signals or clients. */
+import { appendFileSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join, resolve } from 'node:path'
+import { performance } from 'node:perf_hooks'
+import { pathToFileURL } from 'node:url'
+
+const workload = process.argv[2] ?? 'small-first'
+if (!['small-first', 'large-first', 'small-retained', 'large-retained'].includes(workload)) throw Error('Unknown workload')
+const cli = process.env.CANCEL_COST_CLI ?? resolve('cli')
+const root = realpathSync(mkdtempSync(join(tmpdir(), 'eager-cancel-cost-')))
+for (const key of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME']) {
+ process.env[key] = join(root, key); mkdirSync(process.env[key]!, { recursive: true, mode: 0o700 })
+}
+process.env.CLAUDE_PROJECTS_DIR = join(process.env.CLAUDE_CONFIG_DIR!, 'projects')
+process.env.HARNESS_CONNECTIONS_PORT = '0'
+try {
+ const load = (part: string) => import(pathToFileURL(join(cli, 'src', part)).href)
+ const { createCancel } = await load('core/turns/cancel.ts')
+ const { createAttach } = await load('core/transcripts/attach.ts')
+ const { createSessionNormalizers } = await load('core/transcripts/normalizers.ts')
+ const { liveFor } = await load('engines/live.ts')
+ const file = join(root, 'session.jsonl')
+ const prompt = JSON.stringify({ type: 'user', uuid: 'fixture', message: { role: 'user', content: 'fixture' } })
+ const prefix = workload.startsWith('large') ? (JSON.stringify({ type: 'system', text: 'x'.repeat(65500) }) + '\n').repeat(256) : ''
+ writeFileSync(file, prefix + prompt + '\n', { mode: 0o600 })
+ const row = { agentId: 'fixture-agent', sessionId: 'fixture-session', engine: 'claude', transcriptPath: file, codexHome: null }
+ const normalizers = createSessionNormalizers()
+ const reader = liveFor('claude').create(row)
+ normalizers.liveParsers.set(row.sessionId, reader)
+ const nothing = () => {}
+ const attachment = () => createAttach({ normalizers, watcher: { removeSession: nothing }, resolve: () => row })
+ let attach = attachment(), signals = 0
+ const cancel = createCancel({ resolve: () => row, normalizers,
+ beforeCancel: (session: unknown) => attach.beforeCancel?.(session),
+ cursorSubagents: { forget: nothing }, input: { cancel: () => { signals++ }, cancelConfirmed: async () => true },
+ device: () => undefined, stopHeartbeat: nothing, questionWatcher: { stop: nothing }, mirror: { cancel: nothing },
+ turnActivity: { observe: nothing, snapshot: () => undefined }, turnStartedAt: new Map(), agentIdFor: () => row.agentId,
+ clients: { send: nothing } })
+ const latenciesMs: number[] = [], outcomes = { closed: 0, held: 0 }
+ let cpuMs = 0
+ for (let i = 0; i < 100; i++) {
+ if (workload.endsWith('first')) attach = attachment()
+ const next = JSON.stringify({ type: 'user', uuid: `fixture-${i}`, message: { role: 'user', content: `prompt ${i}` } })
+ appendFileSync(file, next + '\n')
+ reader.ingest(next)
+ if (!reader.turnOpen) throw Error('The measured Cancel must begin with an open turn')
+ const cpu = process.cpuUsage(), started = performance.now()
+ await cancel(row.agentId)
+ latenciesMs.push(performance.now() - started)
+ const used = process.cpuUsage(cpu); cpuMs += (used.user + used.system) / 1000
+ if (!reader.turnOpen) outcomes.closed++
+ if ('interpretationHold' in row) outcomes.held++
+ }
+ if (outcomes.closed !== 100 || outcomes.held || signals !== 100) throw Error('Cancel did not finish its eager control work')
+ console.log(JSON.stringify({ workload, bytes: Buffer.byteLength(prefix + prompt + '\n'), iterations: 100,
+ outcomes, signals, latenciesMs, cpuMs, peakRssMiB: process.resourceUsage().maxRSS / 1024,
+ node: process.version, platform: process.platform, arch: process.arch }))
+} finally { rmSync(root, { recursive: true, force: true }) }
diff --git a/docs/research/2026-10-10-saved-binding-evidence.md b/docs/research/2026-10-10-saved-binding-evidence.md
new file mode 100644
index 000000000..4840211bb
--- /dev/null
+++ b/docs/research/2026-10-10-saved-binding-evidence.md
@@ -0,0 +1,313 @@
+# Saved binding evidence and recovery
+
+This step of the [completion checklist](2026-10-09-daemon-core-completion.md) moves
+saved-binding validation and Codex parent repair onto eager native evidence. A
+partial, unreadable, changing or ambiguous source keeps the original session id,
+transcript and ownership with a visible `identityHold`. The next discovery pass
+retries that same live binding without waiting for an optional engine worker.
+Daemon readiness and sibling sessions remain independent.
+
+## Former-code evidence
+
+`8cd510844e4e152d28d6486e65b5572508a86a07` records the healthy binding golden in its own
+commit, before implementation. It was recorded from then-main `9eafacf3b` and replayed
+unchanged after integrating main `c7d460b1d` (#1132). The artifact contains fourteen
+observations: seven each under pinned Linux and macOS platforms. It covers saved
+rows, path admission, moved/profile homes, Stop capture and terminal registration.
+The fixture fixes the clock, uses UTC and `/tmp`, and forbids host subprocesses.
+Neither that artifact nor older golden artifacts are re-recorded for this change.
+Three older unit fixtures gain the complete native `cwd` field their healthy Codex
+header was missing; the parser contract is unchanged.
+
+## Boundary
+
+`engines/transcriptBindings.ts` owns saved path/header admission and parent repair.
+`kit/nativeFiles.ts` retains a fresh bounded descriptor, header and directory proof
+for one operation. Native path resolution and first-record parsing are shared with
+existing descriptor evidence. The resolver observes aliases component by component;
+a matching spelling alone never establishes directory membership. Reads use the
+opened file identity, owner, type and stable complete header. Ordinary body appends
+after a completed read remain valid. Exhausted read, candidate, directory or time
+budgets hold the decision.
+
+A registry load stages all rows. Its explicit root scopes share present, absent and
+alias ancestry within that operation only. Each row retains its own file/header
+proof; one row's failure does not hold its siblings. Final row proofs, then root
+scopes and the fresh catalog proof, run before any row is indexed. A failed root
+scope restores every affected staged binding. There is no cross-operation root
+cache. Parent repair must examine the complete declared walk pool, including
+candidates excluded by metadata; the existing dotted-directory exclusion remains
+part of that declared lookup contract.
+
+The initial independent primitive review found three defects, corrected with
+regressions: missing announced files needed a retained parent-owner check; parent
+repair needed physical membership checks after following links; and a dangling
+leaf alias could borrow its original parent's authority. The last is an explicit
+safety correction to an existing unsafe corner, not a healthy golden change.
+A genuinely absent leaf is distinguished from an existing dangling alias.
+
+`Registry.revalidateBinding` retries a held saved binding without rebuilding the
+registry or restarting the daemon. Successful registration or proven binding
+release clears its transient hold. Discovery contains registration/read failures,
+announces changed reasons, and does not archive, unbind or save unavailable evidence.
+
+The composed review found three further defects. Held rows could enter attachment;
+recovery could retain an inline parser of the old path; and cleanup after releasing
+the session index lost its agent key. Discovery and interpretation now defer held
+bindings, delayed reads lose authority when a hold arrives, and recovery rebuilds
+both unchanged and repaired paths without replaying saved history as a new turn.
+Agent-scoped input and scopes use the retained agent id during cleanup.
+
+Review also found a concurrent-write hazard. Revalidation now stages its candidate
+without changing the live row or indices. Inside the registry write lock it compares
+the exact durable baseline, re-verifies native evidence and commits before publishing.
+A peer's newer binding is preserved. A complete discovery batch may commit there;
+an incomplete batch or failed write holds the retry. Two independent Registry
+instances cover same-path recovery, release and parent repair against a peer write.
+
+## Validation plan and progress
+
+The required plan is typecheck; architecture; core/services and harnessd per-file
+100% statements/branches; touched binding, registry, path/header and native golden
+specs; composed resume coverage run alone; private engine-home, machine and chaos
+lanes; and the available private tmux fixture rows. Automatic ready-PR CI supplies
+the full Linux default suite. Mutation checks run only in a separate disposable
+worktree after their unchanged baseline passes. Runtime measurements run alone,
+interleaving former and candidate processes on the same fixtures and Node toolchain.
+
+Development checks have passed 102 focused tests, including unchanged binding and
+session-store goldens. The new private e2e proves that an incomplete saved Codex
+header retains its binding and visible hold while readiness and a Claude sibling
+work, then recovers in place and takes a turn without another daemon restart.
+The e2e fixture initially read a transcript path from a public frame which correctly
+does not expose it; it now reads only its disposable daemon's private registry.
+An initial registry unit run was invalidated by macOS sandbox rejection of uptime;
+the authorized rerun isolated one incomplete healthy header fixture, now corrected.
+Final exact-source receipts and review are recorded in [PR #1133](https://github.com/autonomous-ai/openharness/pull/1133) before landing.
+
+The initial full validation receipt `20261010T021955.961388Z-42225` passed types,
+274 focused tests in 14 files, architecture, core/services (1,960 tests, 100%),
+harnessd (265 tests, 100%; one existing skip), 35 private engine-home/machine/chaos
+cases and 57 private tmux cases. Fifteen installed-vendor tmux cases are explicitly
+excluded because those tools are not installed in the fixture. After the composed
+review corrections, core/services passed 1,977 tests in 163 files at 100% statements,
+branches, functions and lines (27 seconds, October 10 02:40 UTC); typecheck passed.
+The current e2e case additionally appends a valid turn under the incomplete header,
+asserts no held-session turn is emitted, and runs with workers and explicit inline
+mode. Final affected lanes and composed resume are rerun after these changes.
+
+## Matched runtime cost
+
+The [raw measurements](2026-10-10-binding-evidence-cost.json) compare main `c7d460b1d`
+and this implementation, using Node 22.23.2 on macOS x64. Three interleaved fresh-process
+repetitions of `937e9e6d4` ran alone 04:08:13–04:09:34 UTC (36 processes). Each process measured five
+complete operations after fixture setup. The registry workloads completed all 12,030
+row decisions; native descriptor workloads produced the expected unique bindings or
+ambiguity holds in all 90 calls. No held result was counted as a successful binding.
+
+| Whole operation | Former median latency ms | Candidate median latency ms | Former/candidate process CPU ms | Former/candidate peak RSS MiB |
+| --- | ---: | ---: | ---: | ---: |
+| One saved row, one home | 42.46 | 44.36 | 18.50 / 22.99 | 95.26 / 94.07 |
+| 200 saved rows, one home | 83.07 | 96.19 | 275.07 / 361.36 | 195.11 / 131.97 |
+| 200 saved rows, 63 homes | 168.87 | 131.08 | 667.31 / 538.08 | 142.89 / 132.12 |
+| Native descriptor, one file | 516.32 | 517.63 | 135.69 / 138.57 | 107.00 / 104.49 |
+| Native descriptor, duplicate handles | 521.47 | 514.99 | 140.80 / 139.69 | 106.90 / 104.10 |
+| Native descriptor, competing files | 516.94 | 518.96 | 142.02 / 139.93 | 108.25 / 110.04 |
+
+Latency covers a complete load or native lookup, including final proofs. CPU is the
+median for a process's five operations; peak RSS is the median of process peaks.
+The single-home batch pays for complete file/header evidence; sharing roots within
+the operation reduces the former many-home traversal cost. These samples are cost
+evidence for the specified workloads, not a host-independent performance gate.
+The later first-Cancel and ordinary-Stop corrections affect neither measured import/call path; these
+measurements do not cover active cancellation latency.
+
+## Eager Cancel cost
+
+The additional [Cancel workload](2026-10-10-cancel-cost.mts) and [raw results](2026-10-10-cancel-cost.json)
+compare complete eager core Cancel calls on main `c7d460b1d` and reviewed `c061a7697`.
+Three interleaved fresh-process repetitions ran alone at 04:34:20–04:34:29 UTC, using
+the same Node 22.23.2/macOS x64 toolchain. Each of the 24 processes measures 100 calls.
+Every call starts with a distinct user record appended to the private transcript and
+an open real Claude parser; all 2,400 calls close it and issue exactly one stubbed
+interrupt, with no interpretation hold. First-Cancel samples use a fresh attachment
+controller; retained samples keep 100 successive cancellation boundaries. Histories
+start at 79 bytes or approximately 16 MiB. File setup and prompt ingestion are
+outside each latency and CPU interval. No daemon, terminal, worker or actual signal
+participates; this measures core control overhead, not terminal delivery or recovery replay.
+
+| History / control ledger | Former / candidate median ms | Candidate p95 ms | Former / candidate CPU ms per 100 calls | Former / candidate peak RSS MiB |
+| --- | ---: | ---: | ---: | ---: |
+| Small / first | 0.0024 / 0.0719 | 0.1326 | 0.95 / 9.17 | 89.43 / 93.09 |
+| Large / first | 0.0022 / 0.0688 | 0.1434 | 2.25 / 13.27 | 123.48 / 123.98 |
+| Small / retained | 0.0022 / 0.1189 | 0.2146 | 0.84 / 13.47 | 88.62 / 90.38 |
+| Large / retained | 0.0020 / 0.1068 | 0.2537 | 2.17 / 21.62 | 120.27 / 122.27 |
+
+Latency percentiles combine the 300 calls per source/workload. CPU and peak RSS are
+medians of three processes; RSS includes module loading and private fixture setup.
+The bounded file witnesses add measurable work (about 0.07–0.12 ms median here)
+without reading the whole transcript. These measurements establish cost for these
+workloads; they are not a performance guarantee on another filesystem or host.
+Run the script from the repository root with `CANCEL_COST_CLI` selecting the source
+CLI tree, `TZ=UTC TMPDIR=/tmp`, and the selected Node toolchain's `tsx` loader.
+
+## Remaining scope and timing
+
+This does not complete native identity as a group. Registration/hook admission still
+uses its former entry boundary: its strict replacement must retain pending prompt
+deliveries and commit admission before crediting them. The draft strict registration
+was kept out of this change so a newly held file cannot become an unhandled HTTP
+error or lost hook. Remaining Stop/resume/checkpoint consumers, saved-home selection,
+Hermes optional home promotion, Cursor pending discovery visibility, launch facts,
+durable lifecycle intent and the other named completion groups remain open.
+
+## Recovery control review corrections
+
+The independent composed review found that replacing interpretation could lose a
+Cancel or apply it to a later turn. Core now retains ordered cancellation boundaries
+for the conversation, including the first ordinary Cancel before any outage, successful replacement,
+another reset, repaired path, and worker reconstruction. A new explicit Cancel can supersede a rewritten file;
+an automatic retry cannot move the old decision to a later file position. Each
+boundary records the regular file's device/inode and a digest of at most 1 KiB at
+the beginning and boundary. This samples those bytes; it is not a digest of the
+entire preceding transcript. Replay also checks its actual opened descriptor.
+Incomplete or changed evidence keeps interpretation held with a reason.
+
+The replacement is staged behind a core control handle. Parser, runtime profile and
+watcher installation complete before the registry clears its interpretation hold.
+Every await is fenced by a copied binding/evidence revision and the session lifetime.
+Clearing a hold without authority cannot release the watcher's pending bytes.
+Cancellation remains eager, never waits on a worker, and cancelled history does not
+produce a completion recap. New prompts after the recorded boundary remain open.
+
+A successful ordinary native Stop is retained too, without replacing its live
+parser or delaying its completion. The first later reconstruction cannot discard
+that completion and reopen its still-open disk history. Uncorrelated Stop is
+deliberately retained as an explicit hold. An empty parser or
+an older completed turn does not establish which turn a delayed Stop belongs to.
+Existing positive stale Claude timestamps remain usable; otherwise a subsequent
+explicit Cancel resolves the hold. Exact per-engine Stop correlation remains in
+completion group 4. Legacy readers that cannot replay ordered file boundaries hold
+that interpretation rather than apply the cancellation to a guessed turn. Durable
+control intent across daemon restart remains part of the lifecycle completion work.
+
+The final legacy interaction review identified two additional regressions and their
+composed tests. An ordinary database Cancel after a retained Stop stays on its eager
+native control path; lack of a file cutoff holds only a future reconstruction. A
+held legacy Stop snapshots the known turn state from the existing core normalizer
+maps, including an inactive control ledger whose next turn has since opened. A real
+Copilot normalizer remains open through both held-Stop/recovery sequences. No parser
+or service is loaded to obtain that eager state.
+
+The former core HTTP hook-admission golden was recorded separately from main
+`c7d460b1d` in `d331c49a4`; its twenty Linux/macOS observations and artifact are
+unchanged. Additional actual-composition regressions cover both inline parsing and
+the real worker request/transport/reconstruction path. At 04:23 UTC, 230 affected
+core tests passed at 100% coverage for the changed attachment, replacement-control
+and turn-hook modules. Independent review approved production head `4a05df81a`
+and the assertion-only successor `c061a7697` against main `c7d460b1d` with no
+remaining blockers in this PR's scope. Forty deliberately broken safeguards failed
+assertions after an unchanged baseline. The final composition mutant exposed a
+TypeError in the e2e assertion rather than a valid assertion failure; the corrected
+test now polls the expected held reason directly, and its baseline/mutant is rerun.
+The two interrupted preliminary validation batches are not counted as complete.
+PR #1133 records the final required full gates, private lanes, composed resume and
+all 41 mutation outcomes before merge.
+
+The task resumed October 9 at 22:25:51 UTC. This step's golden was committed October
+10 at 01:39:46 UTC, while the preceding independent adoption validation finished.
+Implementation and preliminary review corrections followed the #1132 merge at
+01:43:24. Validation, independent review/CI waiting and merge time are recorded
+separately in the PR and final receipts. Publication remains zero; no release is
+authorized.
+
+
+## Final validation and test race corrections
+
+Receipt `20261010T043754.267016Z-78890` tested clean reviewed `43db408c1` at
+04:37:54–04:45:57 UTC. Types passed in 4.6 seconds; core/services passed 2,089 tests
+in 165 files at 100% statements, branches, functions and lines (30.5 seconds), and
+harnessd passed 265 tests plus one existing skip at 100% (29.5 seconds). The private
+engine-home/machine/chaos lane passed in 442.2 seconds, and the private tmux lane
+passed 57 cases in 108.4 seconds, with fifteen unavailable installed-vendor cases
+explicitly excluded.
+
+The receipt is overall **failed**, because one of 967 focused tests observed a
+valid native-enumeration hold before reaching its expected durable-owner fence.
+The corrected registry test retries fresh reads for at most three seconds and still
+requires that exact ownership error, followed by unchanged live and durable rows.
+Automatic Linux run `38024635620` separately exposed an existing tmux fixture race:
+redirecting its output creates an empty file before printf writes the expected
+literal arguments. That test now waits for complete expected contents, retaining
+the same literal argv/environment/cwd assertions. Neither correction changes
+production. All affected checks run again; unchanged production coverage and private
+end-to-end evidence remain attributable to `43db408c1` rather than being described
+as a new full passing suite.
+
+The first forty mutation variants each failed assertions after their unchanged
+baseline. The final core Cancel-wiring variant passed its corrected unchanged e2e
+baseline and then failed an assertion on `c061a7697`. Only the six variants whose
+registry test changed need another baseline/mutation pass. The independent reviewer
+approved the production, assertion correction and cost documentation at exact heads;
+the final test-only delta also requires review. Composed resume runs alone. Final
+receipts, exact-head review, CI and merge accounting are recorded in PR #1133.
+
+
+The corrected single-worker focused command passed all 969 tests in 26 files
+(one skipped file) on `d3c607e68`, receipt `20261010T045306.949449Z-89491`, in
+75.1 seconds. The prior delta command accidentally dropped its worker-limit flag;
+its failed concurrent run is not counted as passing. Types were reused from the
+same-source receipt. Linux run `38025366227` then found a composed test racing a
+file replacement against the detached tail read started by recovery. The test now
+explicitly drains that read and proves the cancelled state before replacing the
+file and restarting the worker. Its exact boundary-error, visible hold and later
+explicit-Cancel assertions remain unchanged. Only tests and this report change;
+affected composed tests and their mutation variants run again.
+
+
+Receipt `20261010T045933.778026Z-20994` passed types, 70 composed control/worker
+checks and all 17 large-transcript resume cases on clean `7691335b4`. Its serial
+resume check is **failed** (508 passed, two failed): fixture home adoption exhausted
+its real 250 ms journal deadline during fsync, before the intended count/authority
+assertions. The ownership/count fixture now pins the monotonic clock; production
+limits are unchanged. The separate journal deadline regressions still advance that
+clock and passed alongside all four affected ownership/count cases (seven selected
+cases total). Serial resume runs again. Automatic Linux run `38025771424` passed
+all head checks, including `ci/required`, for `7691335b4`; the final test-only clock
+correction receives its own review and automatic CI.
+
+
+## Final gate receipts
+
+The final source-specific evidence is complete on `06d2ff7c8` (production unchanged
+since `4a05df81a`). Receipt `20261010T050314.141907Z-44077` passed types and the full
+serial resume/native-pool/journal composition: 551 tests in eleven files, at 100%
+statements, branches, functions and lines. The earlier valid production evidence
+is retained: 2,089 core/services tests and 265 harnessd tests at 100%, 36 private
+engine-home/machine/chaos cases, 57 private tmux cases, 969 focused/architecture/golden
+checks, 70 composed control/worker checks and seventeen large-history resume cases.
+The receipt/source distinctions above remain part of this evidence; interrupted or
+failed batches are not relabelled green.
+
+All 41 deliberately broken variants have assertion-failure evidence following their
+unchanged baselines. The nineteen variants affected by the registry/control fixture
+changes were rerun alone on `06d2ff7c8` and passed that requirement; unaffected variants
+reuse the production-identical `4a05df81a` run and the corrected `c061a7697` private
+Cancel-wiring run. The disposable worktree restored every mutated file.
+
+The independent reviewer approved exact head `06d2ff7c830a8c521b6771bd6aba3e3fc579f4bd`
+against `c7d460b1d8018ed56126c662702fd44db886d07d`. All automatic head checks, including
+`ci/required`, passed in [run 38026193103](https://github.com/autonomous-ai/openharness/actions/runs/38026193103).
+Main then advanced with #1134, which adds the separate Memories Store package and
+its report. Integration has no CLI code conflict or shared module change. Existing
+local evidence remains valid for unchanged CLI behavior; the combined head receives
+independent review and a fresh automatic CI run before merge. No extra full local
+suite is required solely for that integration.
+
+Accounting (UTC; overlapping windows are not added): golden creation started
+01:39:46; implementation and review corrections ran from the preceding merge at
+01:43:24 through the last production commit at 04:24:14. Validation started 02:19
+and the final affected mutation pass completed by 05:09. Test-only corrections ended
+05:03:11. Independent review and CI waiting overlapped that validation; the combined
+head's final review/CI and actual merge receipt are recorded in PR #1133 and the
+following progress entry. Publication remains zero.