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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Hold exact resume until native transcript evidence is complete (#1123)
Deefb834fb18c86
diff --git a/cli/e2e/eagerRepair.e2e.ts b/cli/e2e/eagerRepair.e2e.tsindex 0dd9b1e9b..388edaf8c 100644--- a/cli/e2e/eagerRepair.e2e.ts+++ b/cli/e2e/eagerRepair.e2e.ts@@ -80,6 +80,14 @@ console.log('fixture-${engine}-ready'); setInterval(() => {}, 1000);expect(held.detail).toContain('could not be read')expect((await rows()).find(row => row.id === pi.id)).toMatchObject({ status: 'active', sessionId: id })writeFileSync(path, JSON.stringify({ type: 'session', id, cwd }) + '\n')+ // A second native file cannot turn exact resume into a first-file guess at Close.+ const duplicate = join(dirname(path), `2026-10-10_${id}.jsonl`)+ writeFileSync(duplicate, JSON.stringify({ type: 'session', id, cwd }) + '\n')+ const ambiguous = await close()+ expect(ambiguous.error).toBeTruthy()+ expect(ambiguous.detail).toContain('More than one file')+ expect((await rows()).find(row => row.id === pi.id)).toMatchObject({ status: 'active', sessionId: id })+ rmSync(duplicate)}expect(await close()).toMatchObject({ closed: true })expect((await rows()).find(row => row.id === pi.id)).toMatchObject({ status: 'stopped', sessionId: id })diff --git a/cli/scripts/handoff-2026-10-08/exact-resume-cost.ts b/cli/scripts/handoff-2026-10-08/exact-resume-cost.tsnew file mode 100644index 000000000..1904123db--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/exact-resume-cost.ts@@ -0,0 +1,57 @@+/** Fresh private native stores; no vendor binary, daemon, saved-home catalog or owner input. */+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, resolve } from 'node:path'+import { pathToFileURL } from 'node:url'+import { performance } from 'node:perf_hooks'+const root = realpathSync(mkdtempSync(join(tmpdir(), 'exact-resume-cost-')))+const workload = process.argv[2] ?? 'claude'+const cli = process.env.EXACT_COST_CLI ?? resolve(import.meta.dirname, '../..')+const id = 'aaaaaaaa-1111-4222-8333-444444444444'+const cwd = join(root, 'work')+for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CLAUDE_CONFIG_DIR',+ 'CODEX_HOME', 'CURSOR_HOME', 'COPILOT_HOME', 'GROK_HOME', 'AGY_HOME', 'PI_HOME', 'MUSE_HOME', 'COMMANDCODE_HOME',+ 'HERMES_HOME', 'AMP_SESSIONS_DIR', 'OPENCODE_DATA_DIR', 'KILO_DATA_DIR', 'DEVIN_HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME']) {+ process.env[name] = join(root, name)+}+process.env.CLAUDE_PROJECTS_DIR = join(process.env.CLAUDE_CONFIG_DIR!, 'projects')+try {+ mkdirSync(cwd)+ const engine = workload === 'claude' || workload === 'unavailable' ? 'claude' : workload === 'pi' ? 'pi' : 'codex'+ const folder = engine === 'claude' ? join(process.env.CLAUDE_PROJECTS_DIR!, 'work') : engine === 'codex'+ ? join(process.env.CODEX_HOME!, 'sessions', 'day') : join(process.env.PI_HOME!, 'agent', 'sessions', `--${cwd.replace(/^[/\\]/, '').replace(/[/\\:]/g, '-')}--`)+ mkdirSync(folder, { recursive: true })+ const filename = engine === 'claude' ? `${id}.jsonl` : `${engine === 'pi' ? 'day_' : 'rollout-'}${id}.jsonl`+ const header = JSON.stringify(engine === 'codex' ? { type: 'session_meta', payload: { id, cwd, source: 'cli' } }+ : engine === 'pi' ? { type: 'session', id, cwd } : { type: 'user', sessionId: id, cwd }) + '\n'+ writeFileSync(join(folder, filename), header)+ const unrelated = workload === 'populated' ? 1000 : workload === 'limit' ? 4200 : 0+ for (let i = 0; i < unrelated; i++) writeFileSync(join(folder, `unrelated-${i}.jsonl`), '{}\n')+ if (workload === 'duplicate') {+ const other = join(process.env.CODEX_HOME!, 'sessions', 'other'); mkdirSync(other)+ writeFileSync(join(other, filename), header)+ }+ const { findResumedTranscript } = await import(pathToFileURL(join(cli, 'src/lib/sessionRepair.ts')).href)+ if (workload === 'unavailable') {+ const moved = join(root, 'moved'); mkdirSync(moved); writeFileSync(join(moved, 'projects'), 'not a directory')+ const { adoptHomes } = await import(pathToFileURL(join(cli, 'src/lib/engineHomes.ts')).href)+ adoptHomes({ CLAUDE_CONFIG_DIR: moved })+ }+ const latenciesMs: number[] = [], outcomes: Record<string, number> = {}+ const cpu = process.cpuUsage()+ for (let i = 0; i < 10; i++) {+ const at = performance.now()+ let outcome: string+ try { outcome = await findResumedTranscript(engine, id, { cwd }) ? 'exact' : 'absent' }+ catch (error) {+ if ((error as { code?: string }).code !== 'IDENTITY_UNAVAILABLE') throw error+ outcome = 'held'+ }+ latenciesMs.push(Number((performance.now() - at).toFixed(2)))+ outcomes[outcome] = (outcomes[outcome] ?? 0) + 1+ }+ const used = process.cpuUsage(cpu)+ console.log(JSON.stringify({ workload, iterations: 10, unrelated, outcomes, latenciesMs,+ 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-exact-resume.py b/cli/scripts/handoff-2026-10-08/mutate-exact-resume.pynew file mode 100644index 000000000..94f69f40b--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/mutate-exact-resume.py@@ -0,0 +1,71 @@+"""Run only in an owned disposable worktree; every broken connection must assertion-fail."""+import os+from pathlib import Path+import subprocess+import sys++cli = Path(sys.argv[1]).resolve()+kit = 'src/engines/kit/exactTranscript.ts'+repair = 'src/lib/sessionRepair.ts'+spec = 'src/engines/kit/exactTranscript.spec.ts'+golden = 'src/engines/exactResume.golden.spec.ts'+mutations = [+ ('native declaration disconnected', 'src/engines/claude/sessionStore.ts', "byId: { layout: 'projects', suffix: '.jsonl' }", "byId: { layout: 'projects', suffix: '.missing' }", golden),+ ('Codex header id ignored', repair, 'meta.id === sessionId', 'true', spec),+ ('Pi workspace header ignored', repair, 'head.sessionId === sessionId && await workspaces.same(head.cwd, opts.cwd!)', 'true', golden),+ ('only first root inspected', kit, 'for (const root of roots) await walk(root)', 'for (const root of roots.slice(0, 1)) await walk(root)', spec),+ ('alias inspection errors become absent', kit, "if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n", 'return\n', spec),+ ('directory budget enlarged silently', kit, 'const budget = identityScanBudget(),', 'const budget = { remaining: 8192 },', spec),+ ('known home limit removed', kit, 'if (roots.length > 64)', 'if (false)', spec),+ ('candidate limit removed', kit, 'if (++candidates > 64)', 'if (false)', spec),+ ('depth limit removed', kit, 'if (depth > 32)', 'if (false)', spec),+ ('shared deadline removed', kit, 'if (performance.now() - started > 2000)', 'if (false)', spec),+ ('regular file check removed', kit, 'if (!info.isFile())', 'if (false)', spec),+ ('pool revalidation removed', kit, 'if (fingerprint(now) !== fingerprint(proof.info))', 'if (false)', spec),+ ('dangling alias evidence dropped', kit, ' proofs.push({ path, info, content: true })\n return info?.isDirectory() ?? false', ' return info?.isDirectory() ?? false', spec),+ ('ambiguous files accepted', kit, 'if (selected.size > 1)', 'if (false)', spec),+ ('readability not checked', kit, 'await identityBytes(path, 1, info)', 'await Promise.resolve(Buffer.alloc(0))', spec),+ ('directory alias evidence omitted', kit, ' await inspectAliases(path)', ' // alias proof disconnected', spec),+ ('directory alias revalidation omitted', kit, 'if (signature(lstatSync(path)) !== signature(info))', 'if (false)', spec),+ ('relative link target normalized too early', kit, 'const targetParts = evidence.target.slice(targetRoot.length)', "const targetParts = resolve('/', evidence.target).slice(targetRoot.length)", spec),+ ('new native homes ignored', 'src/lib/sessionRepair.ts', "if (repairRoots(engine, opts?.codexHome).join('\\0') !== roots.join('\\0'))", 'if (false)', 'src/engines/kit/exactTranscript.spec.ts'),+ ('workspace proof not revalidated', 'src/engines/kit/exactTranscript.ts', ' options.verify?.()', ' // workspace revalidation disconnected', 'src/engines/kit/exactTranscript.spec.ts'),+ ('unavailable workspace excluded', 'src/engines/kit/exactTranscript.ts', "catch { throw new IdentityReadUnavailable('the Pi workspace identity could not be read') }", "catch { return '' }", 'src/engines/kit/exactTranscript.spec.ts'),+ ('Pi unreadable loses retry code', 'src/lib/sessionRepair.ts', "new IdentityReadUnavailable('the Pi conversation file could not be read', 'The Pi conversation file could not be read.')", "new Error('The Pi conversation file could not be read.')", 'src/lib/closeAgentService.spec.ts'),+ ('Pi ambiguous loses retry code', 'src/engines/kit/exactTranscript.ts', 'new IdentityReadUnavailable(options.ambiguous, options.ambiguous)', 'new Error(options.ambiguous)', 'src/lib/closeAgentService.spec.ts'),+ ('checkpoint swallows identity hold', 'src/lib/sessionCheckpoint.ts', "error instanceof SessionCheckpointError || (error as { code?: unknown } | null)?.code === 'IDENTITY_UNAVAILABLE'", 'error instanceof SessionCheckpointError', 'src/lib/sessionCheckpoint.spec.ts'),+ ('opened candidate version ignored', 'src/engines/kit/identityScan.ts', 'if (expected && (before.dev', 'if (false && (before.dev', 'src/engines/kit/exactTranscript.spec.ts'),+ ('matching-name unknown child excluded', 'src/lib/sessionRepair.ts', "if (!meta?.id || !byId.id.test(meta.id)) throw new IdentityReadUnavailable('the exact rollout header has no conclusive conversation id')", 'if (!meta?.id || !byId.id.test(meta.id)) return false', 'src/engines/kit/exactTranscript.spec.ts'),+]+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-tmux-fixture')).is_dir():+ raise SystemExit('An existing private TMUX_TMPDIR is required')+++def run(specs):+ return subprocess.run(['node', 'node_modules/vitest/vitest.mjs', 'run', *specs, '--maxWorkers=2'],+ cwd=cli, env=env, capture_output=True, text=True, timeout=120)+++baseline = run([spec, golden, 'src/lib/sessionCheckpoint.spec.ts', 'src/lib/closeAgentService.spec.ts'])+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) == 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/engines/__fixtures__/exact-resume.golden.json b/cli/src/engines/__fixtures__/exact-resume.golden.jsonnew file mode 100644index 000000000..425578fb8--- /dev/null+++ b/cli/src/engines/__fixtures__/exact-resume.golden.json@@ -0,0 +1,20 @@+{+ "claude:own": "<root>/CLAUDE_CONFIG_DIR/projects/project-1/aaaaaaaa-1111-4222-8333-000000000001.jsonl",+ "claude:unadopted": null,+ "claude:absent": null,+ "claude:invalid": null,+ "codex:own": "<root>/CODEX_HOME/sessions/2026/10/09/rollout-2026-10-09T12-00-00-aaaaaaaa-1111-4222-8333-000000000001.jsonl",+ "codex:unadopted": null,+ "codex:absent": null,+ "codex:invalid": null,+ "claude:moved": "<root>/moved-claude/projects/project-2/aaaaaaaa-1111-4222-8333-000000000002.jsonl",+ "codex:moved": "<root>/moved-codex/sessions/2026/10/09/rollout-2026-10-09T12-00-00-aaaaaaaa-1111-4222-8333-000000000002.jsonl",+ "codex:profile": "<root>/profile/sessions/2026/10/09/rollout-2026-10-09T12-00-00-aaaaaaaa-1111-4222-8333-000000000003.jsonl",+ "codex:profile-excludes-own": null,+ "codex:missing-profile": null,+ "unsupported": null,+ "pi:exact": "<root>/PI_HOME/agent/sessions/--work-pi-a-b--/2026-10-09_custom.id-12.jsonl",+ "pi:other-cwd": null,+ "pi:unwritten": null,+ "pi:missing-directory": null+}diff --git a/cli/src/engines/exactResume.golden.spec.ts b/cli/src/engines/exactResume.golden.spec.tsnew file mode 100644index 000000000..1bc1cb07b--- /dev/null+++ b/cli/src/engines/exactResume.golden.spec.ts@@ -0,0 +1,98 @@+/** Exact resume answers recorded on main before bounding its native search.+ * Linux, UTC, fixed time and private stores; optional readers and host binaries are forbidden. */+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, beforeAll, expect, it, vi } from 'vitest'++vi.mock('node:child_process', async original => ({ ...await original<object>(),+ execFile: () => { throw new Error('Host binaries are forbidden in this golden') },+ execFileSync: () => { throw new Error('Host binaries are forbidden in this golden') },+}))+vi.mock('node:fs/promises', async original => {+ const fs = await original<typeof import('node:fs/promises')>()+ return { ...fs, realpath: (name: string) => fs.realpath(name.startsWith('/work/') ? join(root, 'workspaces', name.slice(6)) : name) }+})+vi.mock('node:fs', async original => {+ const fs = await original<typeof import('node:fs')>()+ const mapped = (name: string) => name.startsWith('/work/') ? join(root, 'workspaces', name.slice(6)) : name+ return { ...fs, realpathSync: (name: string) => fs.realpathSync(mapped(name)), statSync: (name: string) => fs.statSync(mapped(name)) }+})+vi.mock('./inProcess.js', async original => ({ ...await original<object>(),+ loadEngine: () => { throw new Error('Optional engine loading is forbidden in this golden') },+}))+const GOLDEN = fileURLToPath(new URL('./__fixtures__/exact-resume.golden.json', import.meta.url))+const RECORD = process.env.RECORD_EXACT_RESUME_GOLDEN === '1'+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!+const captured: Record<string, unknown> = {}+const id = (n: number) => `aaaaaaaa-1111-4222-8333-${String(n).padStart(12, '0')}`+let root = ''+let expected: Record<string, unknown>+let repair: typeof import('../lib/sessionRepair.js')+let homes: typeof import('../lib/engineHomes.js')+let identities: typeof import('./repairIdentities.js')+const path = (...parts: string[]) => join(root, ...parts)+function file(name: string, value: unknown): string {+ mkdirSync(dirname(name), { recursive: true })+ writeFileSync(name, JSON.stringify(value) + '\n')+ return name+}+const claude = (home: string, n: number) => file(join(home, 'projects', `project-${n}`, `${id(n)}.jsonl`), { cwd: path('work'), sessionId: id(n) })+const codex = (home: string, n: number) => file(join(home, 'sessions', '2026', '10', '09', `rollout-2026-10-09T12-00-00-${id(n)}.jsonl`),+ { type: 'session_meta', payload: { id: id(n), cwd: path('work'), source: 'cli' } })+async function check(key: string, value: Promise<unknown>): Promise<void> {+ captured[key] = JSON.parse(JSON.stringify(await value ?? null).split(root).join('<root>'))+ if (!RECORD) expect({ key, value: captured[key] }).toEqual({ key, value: expected[key] })+}+beforeAll(async () => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'exact-resume-golden-')))+ for (const cwd of ['pi/a-b', 'pi-a/b']) mkdirSync(path('workspaces', cwd), { recursive: true })+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR',+ 'PI_HOME', 'MUSE_HOME', 'HERMES_HOME', 'CURSOR_HOME', 'COPILOT_HOME', 'GROK_HOME', 'AGY_HOME',+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME']) vi.stubEnv(name, path(name))+ vi.stubEnv('CLAUDE_PROJECTS_DIR', path('CLAUDE_CONFIG_DIR', 'projects'))+ vi.stubEnv('TZ', 'UTC')+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })+ vi.useFakeTimers({ toFake: ['Date'], now: Date.parse('2026-10-09T12:00:00Z') })+ vi.resetModules()+ repair = await import('../lib/sessionRepair.js')+ homes = await import('../lib/engineHomes.js')+ identities = await import('./repairIdentities.js')+ expected = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8'))+})+afterAll(() => {+ if (RECORD) writeFileSync(GOLDEN, JSON.stringify(captured, null, 2) + '\n')+ homes?.resetEngineHomes(); vi.useRealTimers(); vi.unstubAllEnvs()+ Object.defineProperty(process, 'platform', platform)+ rmSync(root, { recursive: true, force: true })+})++it('records exact files, moved homes, explicit profiles and proven absence', async () => {+ claude(path('CLAUDE_CONFIG_DIR'), 1); codex(path('CODEX_HOME'), 1)+ claude(path('moved-claude'), 2); codex(path('moved-codex'), 2); codex(path('profile'), 3)+ for (const engine of ['claude', 'codex'] as const) {+ await check(`${engine}:own`, repair.findResumedTranscript(engine, id(1)))+ await check(`${engine}:unadopted`, repair.findResumedTranscript(engine, id(2)))+ await check(`${engine}:absent`, repair.findResumedTranscript(engine, id(4)))+ await check(`${engine}:invalid`, repair.findResumedTranscript(engine, '../escape'))+ }+ homes.adoptHomes({ CLAUDE_CONFIG_DIR: path('moved-claude'), CODEX_HOME: path('moved-codex') })+ for (const engine of ['claude', 'codex'] as const) await check(`${engine}:moved`, repair.findResumedTranscript(engine, id(2)))+ await check('codex:profile', repair.findResumedTranscript('codex', id(3), { codexHome: path('profile') }))+ await check('codex:profile-excludes-own', repair.findResumedTranscript('codex', id(1), { codexHome: path('profile') }))+ await check('codex:missing-profile', repair.findResumedTranscript('codex', id(1), { codexHome: path('missing') }))+ await check('unsupported', repair.findResumedTranscript('cursor', id(1)))+})++it('records Pi custom ids, lossy folders and unwritten conversations', async () => {+ const cwd = '/work/pi-a/b', collision = '/work/pi/a-b'+ const directory = path('PI_HOME', 'agent', 'sessions', identities.piSessionFolder(cwd))+ file(join(directory, '2026-10-09_custom.id-12.jsonl'), { type: 'session', id: 'custom.id-12', cwd })+ file(join(directory, '2026-10-09_other.id-12.jsonl'), { type: 'session', id: 'other.id-12', cwd: collision })+ await check('pi:exact', repair.findResumedTranscript('pi', 'custom.id-12', { cwd }))+ await check('pi:other-cwd', repair.findResumedTranscript('pi', 'custom.id-12', { cwd: collision }))+ await check('pi:unwritten', repair.findResumedTranscript('pi', 'not-written', { cwd }))+ await check('pi:missing-directory', repair.findResumedTranscript('pi', 'not-written', { cwd: path('absent') }))+})+it('records every observation', () => { if (!RECORD) expect(Object.keys(captured).sort()).toEqual(Object.keys(expected).sort()) })diff --git a/cli/src/engines/kit/exactTranscript.spec.ts b/cli/src/engines/kit/exactTranscript.spec.tsnew file mode 100644index 000000000..20329e214--- /dev/null+++ b/cli/src/engines/kit/exactTranscript.spec.ts@@ -0,0 +1,300 @@+import { execFileSync } from 'node:child_process'+import { linkSync, mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync, type Dirent } from 'node:fs'+import * as fs from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const clock = vi.hoisted(() => ({ now: 0 }))+vi.mock('node:perf_hooks', async original => ({ ...await original<object>(), performance: { now: () => clock.now } }))+vi.mock('node:fs/promises', async original => {+ const actual = await original<typeof import('node:fs/promises')>()+ return { ...actual, lstat: vi.fn(actual.lstat), opendir: vi.fn(actual.opendir), open: vi.fn(actual.open), realpath: vi.fn(actual.realpath) }+})+vi.mock('../inProcess.js', async original => ({ ...await original<object>(), loadEngine: () => { throw new Error('Optional reader unavailable') } }))++let root = ''+let repair: typeof import('../../lib/sessionRepair.js')+let lookup: typeof import('./exactTranscript.js')['exactTranscript']+const ID = 'aaaaaaaa-1111-4222-8333-444444444444'+const OTHER = 'bbbbbbbb-1111-4222-8333-444444444444'+const path = (...parts: string[]) => join(root, ...parts)+const projects = { kind: 'projects' as const, filename: `${ID}.jsonl` }+const walk = { kind: 'walk' as const, matches: (name: string) => name.endsWith(`${ID}.jsonl`) }+function file(name: string, body = '{}\n'): string {+ mkdirSync(dirname(name), { recursive: true }); writeFileSync(name, body); return name+}+const claude = (folder = 'work', home = path('claude')) => file(join(home, 'projects', folder, `${ID}.jsonl`))+const codex = (folder = 'day', id = ID) => file(path('codex', 'sessions', folder, `rollout-${ID}.jsonl`),+ JSON.stringify({ type: 'session_meta', payload: { id, cwd: path('work'), source: 'cli' } }) + '\n')++beforeEach(async () => {+ clock.now = 0+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.lstat).mockReset().mockImplementation(actual.lstat)+ vi.mocked(fs.opendir).mockReset().mockImplementation(actual.opendir)+ vi.mocked(fs.open).mockReset().mockImplementation(actual.open)+ vi.mocked(fs.realpath).mockReset().mockImplementation(actual.realpath)+ root = realpathSync(mkdtempSync(join(tmpdir(), 'exact-transcript-')))+ for (const [name, value] of Object.entries({ HOME: path('home'), ADAPTER_DATA_DIR: path('data'),+ ADAPTER_RUNTIME_DIR: path('runtime'), CLAUDE_CONFIG_DIR: path('claude'), CLAUDE_PROJECTS_DIR: path('claude', 'projects'),+ CODEX_HOME: path('codex'), PI_HOME: path('pi'), HERMES_HOME: path('hermes') })) vi.stubEnv(name, value)+ vi.resetModules()+ repair = await import('../../lib/sessionRepair.js')+ lookup = (await import('./exactTranscript.js')).exactTranscript+})+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); rmSync(root, { recursive: true, force: true }) })++describe('exact resume uses complete native evidence', () => {+ it.each(['claude', 'codex'] as const)('holds multiple %s files and recovers when the conflict is removed', async engine => {+ const first = engine === 'claude' ? claude('first') : codex('first')+ const second = engine === 'claude' ? claude('second') : codex('second')+ await expect(repair.findResumedTranscript(engine, ID)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ rmSync(second)+ await expect(repair.findResumedTranscript(engine, ID)).resolves.toBe(first)+ })+ it('checks all moved homes before accepting a default-home answer', async () => {+ claude(); claude('work', path('moved'))+ ;(await import('../../lib/engineHomes.js')).adoptHomes({ CLAUDE_CONFIG_DIR: path('moved') })+ await expect(repair.findResumedTranscript('claude', ID)).rejects.toThrow('more than one transcript')+ })+ it('does not treat an unreadable later home as absence', async () => {+ claude(); mkdirSync(path('moved', 'projects'), { recursive: true })+ ;(await import('../../lib/engineHomes.js')).adoptHomes({ CLAUDE_CONFIG_DIR: path('moved') })+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.opendir).mockImplementation(async (name, options) => {+ if (String(name) === path('moved', 'projects')) throw Object.assign(new Error('fixture denied'), { code: 'EACCES' })+ return actual.opendir(name, options)+ })+ await expect(repair.findResumedTranscript('claude', ID)).rejects.toThrow('could not be read')+ vi.mocked(fs.opendir).mockImplementation(actual.opendir)+ await expect(repair.findResumedTranscript('claude', ID)).resolves.toBe(claude())+ })+ it('requires a readable file even when the filename gives its id', async () => {+ const transcript = claude()+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.open).mockImplementation(async (name, flags, mode) => {+ if (String(name) === transcript) throw Object.assign(new Error('fixture denied'), { code: 'EACCES' })+ return actual.open(name, flags, mode)+ })+ await expect(repair.findResumedTranscript('claude', ID)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ })+ it('uses the Codex header id rather than a coincidental filename substring', async () => {+ codex('wrong', OTHER)+ await expect(repair.findResumedTranscript('codex', ID)).resolves.toBeNull()+ const right = codex('right')+ await expect(repair.findResumedTranscript('codex', ID)).resolves.toBe(right)+ })+ it('holds malformed Codex metadata instead of choosing a readable sibling', async () => {+ codex('right'); file(path('codex', 'sessions', 'unknown', `rollout-${ID}.jsonl`), '{')+ await expect(repair.findResumedTranscript('codex', ID)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ })+ it('rejects an overlong argv id before any native lookup', async () => {+ await expect(repair.findResumedTranscript('codex', 'a'.repeat(129))).resolves.toBeNull()+ expect(fs.opendir).not.toHaveBeenCalled()+ })+ it('refuses a private FIFO without opening or waiting for a writer', async () => {+ const name = path('claude', 'projects', 'work', `${ID}.jsonl`)+ mkdirSync(dirname(name), { recursive: true }); execFileSync('mkfifo', [name])+ await expect(repair.findResumedTranscript('claude', ID)).rejects.toThrow('not a regular file')+ expect(fs.open).not.toHaveBeenCalled()+ })+ it('streams the directory bound and closes the iterator on exhaustion', async () => {+ mkdirSync(path('pool'))+ let reads = 0, closed = false+ vi.mocked(fs.opendir).mockResolvedValueOnce({ async *[Symbol.asyncIterator]() {+ try { while (true) yield { name: `unrelated-${++reads}`, isDirectory: () => false, isSymbolicLink: () => false } }+ finally { closed = true }+ } } as never)+ await expect(lookup([path('pool')], walk)).rejects.toThrow('directory entry limit')+ // Inspecting this private path spends part of the same budget before enumeration starts.+ expect(reads).toBeLessThan(4096); expect(reads).toBeGreaterThan(4000); expect(closed).toBe(true)+ expect(fs.opendir).toHaveBeenCalledWith(path('pool'), { bufferSize: 32 })+ })+ it('bounds homes even when all are absent', async () => {+ await expect(lookup(Array.from({ length: 65 }, (_, n) => path(String(n))), projects)).rejects.toThrow('session-home limit')+ expect(fs.lstat).not.toHaveBeenCalled()+ })+ it('bounds existing candidates while allowing many proven negative projects', async () => {+ for (let n = 0; n < 80; n++) mkdirSync(path('claude', 'projects', String(n)), { recursive: true })+ const exact = claude()+ await expect(repair.findResumedTranscript('claude', ID)).resolves.toBe(exact)+ for (let n = 0; n < 64; n++) claude(String(n))+ await expect(repair.findResumedTranscript('claude', ID)).rejects.toThrow('candidate limit')+ })+ it('holds an unfinished deep tree rather than concluding no exact file exists', async () => {+ mkdirSync(path('pool', ...Array.from({ length: 33 }, () => 'directory')), { recursive: true })+ await expect(lookup([path('pool')], walk)).rejects.toThrow('depth limit')+ })+ it('shares the deadline across native header checks', async () => {+ const exact = file(path('pool', `${ID}.jsonl`))+ await expect(lookup([path('pool')], walk, { accepts: async name => { expect(name).toBe(exact); clock.now = 2001; return true } }))+ .rejects.toThrow('deadline')+ })+ it('deduplicates physical file and directory aliases without hiding their paths', async () => {+ const exact = file(path('pool', 'first', `${ID}.jsonl`))+ mkdirSync(path('pool', 'second')); linkSync(exact, path('pool', 'second', `${ID}.jsonl`))+ symlinkSync(path('pool'), path('alias'))+ symlinkSync(path('pool'), path('pool', 'cycle'))+ const found = await lookup([path('pool'), path('alias')], walk)+ expect([exact, path('pool', 'second', `${ID}.jsonl`)]).toContain(found)+ })+ it('rechecks an absent earlier candidate before returning a later exact file', async () => {+ mkdirSync(path('first', 'work'), { recursive: true }); file(path('second', 'work', `${ID}.jsonl`))+ await expect(lookup([path('first'), path('second')], projects, { accepts: async () => {+ file(path('first', 'work', `${ID}.jsonl`)); return true+ } })).rejects.toThrow('pool changed')+ })+ it('rechecks a previously absent root', async () => {+ file(path('second', 'work', `${ID}.jsonl`))+ await expect(lookup([path('first'), path('second')], projects, { accepts: async () => {+ file(path('first', 'work', `${ID}.jsonl`)); return true+ } })).rejects.toThrow('pool changed')+ })+ it('rechecks an alias whose previously missing target appeared', async () => {+ mkdirSync(path('first')); symlinkSync(path('target'), path('first', 'alias'))+ file(path('second', 'work', `${ID}.jsonl`))+ await expect(lookup([path('first'), path('second')], projects, { accepts: async () => {+ file(path('target', `${ID}.jsonl`)); return true+ } })).rejects.toThrow('pool changed')+ })+ it.each(['replace', 'rewrite', 'remove'] as const)('holds a selected file that a later native read can %s', async change => {+ const exact = file(path('pool', `${ID}.jsonl`))+ await expect(lookup([path('pool')], walk, { accepts: async () => {+ if (change === 'replace') { const next = file(path('replacement')); renameSync(next, exact) }+ if (change === 'rewrite') writeFileSync(exact, 'different header\n')+ if (change === 'remove') rmSync(exact)+ return true+ } })).rejects.toThrow('pool changed')+ })+ it('rechecks an excluded header before treating the pool as empty', async () => {+ const exact = file(path('pool', `${ID}.jsonl`))+ await expect(lookup([path('pool')], walk, { accepts: async () => { writeFileSync(exact, 'now matches\n'); return false } }))+ .rejects.toThrow('pool changed')+ })+ it('holds inspection failures and retries without cached absence', async () => {+ const exact = claude()+ vi.mocked(fs.lstat).mockRejectedValueOnce(Object.assign(new Error('fixture denied'), { code: 'EACCES' }))+ await expect(repair.findResumedTranscript('claude', ID)).rejects.toThrow('could not be inspected')+ await expect(repair.findResumedTranscript('claude', ID)).resolves.toBe(exact)+ })+ it('requires a directory at each declared root', async () => {+ file(path('pool'))+ await expect(lookup([path('pool')], walk)).rejects.toThrow('not a directory')+ })+ it.each(['claude', 'codex'] as const)('fences a newly adopted %s home during an exact read', async engine => {+ if (engine === 'claude') claude(); else codex()+ const homes = await import('../../lib/engineHomes.js')+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.open).mockImplementationOnce(async (name, flags, mode) => {+ homes.adoptHomes({ [engine === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME']: path('new-home') })+ return actual.open(name, flags, mode)+ })+ await expect(repair.findResumedTranscript(engine, ID)).rejects.toThrow('known session homes changed')+ })+ it('keeps an explicit Codex profile independent of unrelated adopted homes', async () => {+ const exact = codex()+ const homes = await import('../../lib/engineHomes.js')+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.open).mockImplementationOnce(async (name, flags, mode) => {+ homes.adoptHomes({ CODEX_HOME: path('new-home') }); return actual.open(name, flags, mode)+ })+ await expect(repair.findResumedTranscript('codex', ID, { codexHome: path('codex') })).resolves.toBe(exact)+ })+ it.each([undefined, 42, ''])('holds a matching-name subagent with inconclusive id %s', async id => {+ codex('right')+ file(path('codex', 'sessions', 'unknown', `rollout-${ID}.jsonl`),+ JSON.stringify({ type: 'session_meta', payload: { id, source: { subagent: 'tool' } } }) + '\n')+ await expect(repair.findResumedTranscript('codex', ID)).rejects.toThrow('no conclusive conversation id')+ })+ it.each(['codex', 'pi'] as const)('ties the %s header to its inspected inode through an ancestor alias ABA', async engine => {+ const cwd = path('work'); mkdirSync(cwd)+ const { piSessionFolder } = await import('../repairIdentities.js')+ const relative = engine === 'codex' ? ['sessions', `rollout-${ID}.jsonl`]+ : ['agent', 'sessions', piSessionFolder(cwd), `day_${ID}.jsonl`]+ const body = (id: string) => JSON.stringify(engine === 'codex'+ ? { type: 'session_meta', payload: { id, cwd, source: 'cli' } } : { type: 'session', id, cwd }) + '\n'+ file(path('target-a', ...relative), body(OTHER)); file(path('target-b', ...relative), body(ID))+ symlinkSync(path('target-a'), path(engine))+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.open).mockImplementation(async (name, flags, mode) => {+ rmSync(path(engine)); symlinkSync(path('target-b'), path(engine))+ const handle = await actual.open(name, flags, mode)+ rmSync(path(engine)); symlinkSync(path('target-a'), path(engine))+ return handle+ })+ await expect(repair.findResumedTranscript(engine, ID, { cwd })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ })+ it.each(['codex', 'pi'] as const)('fences the %s descriptor when an ordinary ancestor directory is replaced and restored', async engine => {+ const cwd = path('work'); mkdirSync(cwd)+ const { piSessionFolder } = await import('../repairIdentities.js')+ const relative = engine === 'codex' ? ['codex', 'sessions', `rollout-${ID}.jsonl`]+ : ['pi', 'agent', 'sessions', piSessionFolder(cwd), `day_${ID}.jsonl`]+ const body = (id: string) => JSON.stringify(engine === 'codex'+ ? { type: 'session_meta', payload: { id, cwd, source: 'cli' } } : { type: 'session', id, cwd }) + '\n'+ file(path('anchor', ...relative), body(OTHER)); file(path('alternate', ...relative), body(ID))+ if (engine === 'pi') (await import('../../config/env.js')).env.PI_HOME = path('anchor', 'pi')+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.open).mockImplementation(async (name, flags, mode) => {+ // The sessions directory and transcript retain their own metadata: only an ancestor is renamed.+ // Both opens see the alternate descriptor while the visible path is restored after each open.+ renameSync(path('anchor'), path('holding')); renameSync(path('alternate'), path('anchor'))+ const handle = await actual.open(name, flags, mode)+ renameSync(path('anchor'), path('alternate')); renameSync(path('holding'), path('anchor'))+ return handle+ })+ await expect(repair.findResumedTranscript(engine, ID, { codexHome: path('anchor', 'codex'), cwd }))+ .rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ })+ it.each(['root', 'ancestor', 'chained target', 'relative parent'] as const)('holds a directory listing redirected through a %s alias and restored', async kind => {+ const relative = kind === 'relative parent'+ claude('conflict', relative ? path('target-a', 'home') : path('target-a'))+ const competing = claude('other', path('moved'))+ mkdirSync(relative ? path('target-b', 'home', 'projects') : path('target-b', 'projects'), { recursive: true })+ if (relative) for (const name of ['target-a', 'target-b']) mkdirSync(path(name, 'leaf'), { recursive: true })+ const alias = relative ? path('bridge') : kind === 'root' ? path('claude', 'projects') : kind === 'ancestor' ? path('claude') : path('outer')+ if (kind === 'root') mkdirSync(path('claude'))+ const target = (name: string) => relative ? path(name, 'leaf') : kind === 'root' ? path(name, 'projects') : path(name)+ symlinkSync(target('target-a'), alias)+ if (kind === 'chained target') symlinkSync(path('outer'), path('claude'))+ if (relative) symlinkSync('bridge/../home', path('claude'))+ ;(await import('../../lib/engineHomes.js')).adoptHomes({ CLAUDE_CONFIG_DIR: path('moved') })+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.opendir).mockImplementationOnce(async (name, options) => {+ rmSync(alias); symlinkSync(target('target-b'), alias)+ const directory = await actual.opendir(name, options)+ rmSync(alias); symlinkSync(target('target-a'), alias)+ return directory+ })+ await expect(repair.findResumedTranscript('claude', ID)).rejects.toThrow('alias changed during lookup')+ rmSync(competing)+ await expect(repair.findResumedTranscript('claude', ID)).resolves.toBe(path('claude', 'projects', 'conflict', `${ID}.jsonl`))+ })+ it.each(['accepted', 'excluded'] as const)('revalidates an %s Pi cwd alias after later native reads', async kind => {+ const cwd = path('work'), other = path('other'), alias = path('cwd-alias')+ mkdirSync(cwd); mkdirSync(other); symlinkSync(kind === 'accepted' ? cwd : other, alias)+ const { piSessionFolder } = await import('../repairIdentities.js')+ const directory = path('pi', 'agent', 'sessions', piSessionFolder(cwd))+ file(join(directory, `first_${ID}.jsonl`), JSON.stringify({ type: 'session', id: ID, cwd: alias }) + '\n')+ const second = file(join(directory, `second_${ID}.jsonl`), JSON.stringify({ type: 'session', id: OTHER, cwd }) + '\n')+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.opendir).mockImplementation(async (name, options) => {+ const dir = await actual.opendir(name, options), entries: Dirent[] = []+ for await (const entry of dir) entries.push(entry)+ entries.sort((a, b) => a.name.localeCompare(b.name))+ return { async *[Symbol.asyncIterator]() { yield* entries } } as never+ })+ vi.mocked(fs.open).mockImplementation(async (name, flags, mode) => {+ if (String(name) === second) { rmSync(alias); symlinkSync(kind === 'accepted' ? other : cwd, alias) }+ return actual.open(name, flags, mode)+ })+ await expect(repair.findResumedTranscript('pi', ID, { cwd })).rejects.toThrow('workspace identity changed')+ })+ it('holds unavailable Pi workspace evidence instead of excluding that candidate', async () => {+ const cwd = path('work'); mkdirSync(cwd)+ const { piSessionFolder } = await import('../repairIdentities.js')+ file(path('pi', 'agent', 'sessions', piSessionFolder(cwd), `day_${ID}.jsonl`),+ JSON.stringify({ type: 'session', id: ID, cwd: path('unavailable') }) + '\n')+ await expect(repair.findResumedTranscript('pi', ID, { cwd })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ })+})diff --git a/cli/src/engines/kit/exactTranscript.ts b/cli/src/engines/kit/exactTranscript.tsnew file mode 100644index 000000000..2be7ab3c7--- /dev/null+++ b/cli/src/engines/kit/exactTranscript.ts@@ -0,0 +1,177 @@+/** A complete, bounded native pool for an exact resume id. No optional reader or cross-poll cache. */+import { lstatSync, realpathSync, statSync, type Stats } from 'node:fs'+import { lstat, readlink, realpath } from 'node:fs/promises'+import { dirname, isAbsolute, join, parse, resolve, sep } from 'node:path'+import { performance } from 'node:perf_hooks'+import { identityBytes, identityEntries, identityScanBudget, IdentityReadUnavailable, type IdentityVersion } from './identityScan.js'++type Layout = { kind: 'projects'; filename: string }+ | { kind: 'walk' | 'directory'; matches: (name: string) => boolean }+type Proof = { path: string; info: Stats | null; content: boolean }+const identity = (info: Stats | null) => info && `${info.dev}:${info.ino}:${info.mode}`+const signature = (info: Stats | null) => info && `${identity(info)}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`++/** Filename authority remains engine-declared. An optional native header can reject another id/cwd;+ * every such exclusion is retained until the complete pool has been checked. */+export async function exactTranscript(roots: readonly string[], layout: Layout,+ options: { accepts?: (path: string, version: IdentityVersion) => Promise<boolean>; verify?: () => void; ambiguous?: string } = {},+): Promise<string | null> {+ if (roots.length > 64) throw new IdentityReadUnavailable('the known session-home limit was reached')+ const budget = identityScanBudget(), started = performance.now()+ const proofs: Proof[] = [], visited = new Set<string>()+ const pathParts = new Map<string, { info: Stats; target?: string }>()+ const aliases = new Map<string, Stats>()+ const selected = new Map<string, Proof>()+ let candidates = 0+ const deadline = () => {+ if (performance.now() - started > 2000) throw new IdentityReadUnavailable('the exact transcript lookup deadline was reached')+ }+ // A directory opened through A -> B -> A can list B while both target stats name A.+ // Retain the links themselves, including links in ancestors and in another link's target.+ // Ordinary ancestor directories retain no content stamp: unrelated activity in /tmp is not ours.+ const inspectAliases = async (path: string) => {+ const location = resolve(path), root = parse(location).root+ let prefix = root, pending = location.slice(root.length).split(sep).filter(Boolean), links = 0+ while (pending.length) {+ deadline()+ const part = pending.shift()!+ if (part === '.') continue+ if (part === '..') { prefix = dirname(prefix); continue }+ const next = join(prefix, part)+ let evidence = pathParts.get(next)+ if (!evidence) {+ if (budget.remaining-- <= 0) throw new IdentityReadUnavailable('the directory entry limit was reached')+ try {+ const info = await lstat(next)+ evidence = { info, ...(info.isSymbolicLink() ? { target: await readlink(next) } : {}) }+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return+ throw new IdentityReadUnavailable('an exact transcript alias could not be inspected')+ }+ pathParts.set(next, evidence)+ }+ if (evidence.target !== undefined) {+ if (++links > 32) throw new IdentityReadUnavailable('the exact transcript alias depth limit was reached')+ aliases.set(next, evidence.info)+ const targetRoot = isAbsolute(evidence.target) ? parse(evidence.target).root : ''+ if (targetRoot) prefix = targetRoot+ // Follow each link before consuming a later '..'. Lexically normalizing bridge/../home+ // could skip bridge when it actually points at another directory's child.+ const targetParts = evidence.target.slice(targetRoot.length).split(sep === '/' ? /\// : /[\\/]/).filter(Boolean)+ pending = [...targetParts, ...pending]+ } else prefix = next+ }+ }++ const inspect = async (path: string): Promise<Stats | null> => {+ deadline()+ await inspectAliases(path)+ try {+ const info = await lstat(path)+ return info.isSymbolicLink() ? await lstat(await realpath(path)) : info+ }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw new IdentityReadUnavailable('an exact transcript location could not be inspected')+ }+ }+ const candidate = async (path: string) => {+ const info = await inspect(path)+ const proof = { path, info, content: !!options.accepts }+ proofs.push(proof)+ if (!info) return+ if (++candidates > 64) throw new IdentityReadUnavailable('the exact transcript candidate limit was reached')+ if (!info.isFile()) throw new IdentityReadUnavailable('an exact transcript is not a regular file')+ // Even filename-based authority needs a readable regular file. Opening one byte is bounded and+ // nonblocking; stat alone would let an unreadable file authorize a binding.+ if (options.accepts ? await options.accepts(path, info) : await identityBytes(path, 1, info).then(() => true).catch(() => {+ throw new IdentityReadUnavailable('an exact transcript could not be read')+ })) {+ selected.set(identity(info)!, selected.get(identity(info)!) ?? proof)+ }+ deadline()+ }+ const linkedDirectory = async (path: string): Promise<boolean> => {+ const info = await inspect(path)+ proofs.push({ path, info, content: true })+ return info?.isDirectory() ?? false+ }+ const walk = async (path: string, depth = 0): Promise<void> => {+ if (depth > 32) throw new IdentityReadUnavailable('the exact transcript depth limit was reached')+ const info = await inspect(path)+ proofs.push({ path, info, content: true })+ if (!info) return+ if (!info.isDirectory()) throw new IdentityReadUnavailable('an exact transcript directory is not a directory')+ const key = identity(info)!+ if (visited.has(key)) return // Directory aliases retain their path proof without another scan.+ visited.add(key)+ for await (const entry of identityEntries(path, budget, false)) {+ deadline()+ const full = join(path, entry.name)+ if (layout.kind === 'projects') {+ const directory = entry.isDirectory() || (entry.isSymbolicLink() && await linkedDirectory(full))+ if (directory) await candidate(join(full, layout.filename))+ } else if (layout.matches(entry.name)) {+ await candidate(full)+ } else if (layout.kind === 'walk' && !entry.name.includes('.')) {+ const directory = entry.isDirectory() || (entry.isSymbolicLink() && await linkedDirectory(full))+ if (directory) await walk(full, depth + 1)+ }+ }+ }+ for (const root of roots) await walk(root)+ deadline()+ // Keep the final pool check synchronous and the selected file last: no later native await may+ // invalidate the selected header. This is bounded change detection, not an atomic filesystem view.+ const only = selected.size === 1 ? selected.values().next().value! : undefined+ options.verify?.()+ for (const [path, info] of aliases) {+ deadline()+ try {+ if (signature(lstatSync(path)) !== signature(info)) throw new Error('changed alias')+ } catch { throw new IdentityReadUnavailable('an exact transcript alias changed during lookup') }+ }+ for (const proof of [...proofs.filter(proof => proof !== only), ...(only ? [only] : [])]) {+ deadline()+ let now: Stats | null+ try { now = statSync(proof.path) }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') now = null+ else throw new IdentityReadUnavailable('an exact transcript location became unavailable')+ }+ const fingerprint = proof.content ? signature : identity+ if (fingerprint(now) !== fingerprint(proof.info)) {+ throw new IdentityReadUnavailable('the exact transcript pool changed during lookup')+ }+ }+ if (selected.size > 1) {+ if (options.ambiguous) throw new IdentityReadUnavailable(options.ambiguous, options.ambiguous)+ throw new IdentityReadUnavailable('more than one transcript matches the resumed conversation')+ }+ return only?.path ?? null+}++/** A lossy workspace folder needs canonical evidence for both matches and exclusions. */+export function exactWorkspaces(): { same: (left: string, right: string) => Promise<boolean>; verify: () => void } {+ const proofs = new Map<string, { target: string; identity: string }>()+ const read = async (path: string): Promise<string> => {+ try {+ const target = await realpath(path), info = await lstat(target)+ if (!info.isDirectory()) throw new Error('not a directory')+ const proof = { target, identity: identity(info)! }, previous = proofs.get(path)+ if (previous && (previous.target !== proof.target || previous.identity !== proof.identity)) throw new Error('changed workspace')+ proofs.set(path, proof)+ return target+ } catch { throw new IdentityReadUnavailable('the Pi workspace identity could not be read') }+ }+ return {+ same: async (left, right) => await read(left) === await read(right),+ verify: () => {+ for (const [path, proof] of proofs) {+ try {+ if (realpathSync(path) !== proof.target || identity(statSync(path)) !== proof.identity) throw new Error('changed workspace')+ } catch { throw new IdentityReadUnavailable('the Pi workspace identity changed during lookup') }+ }+ },+ }+}diff --git a/cli/src/engines/kit/identityScan.ts b/cli/src/engines/kit/identityScan.tsindex bb8fba69a..abaee8634 100644--- a/cli/src/engines/kit/identityScan.ts+++ b/cli/src/engines/kit/identityScan.ts@@ -1,21 +1,29 @@/** Bounded native evidence. An unfinished lookup cannot prove that a conversation is unique. */-import { constants, type Dirent } from 'node:fs'+import { constants, type Dirent, type Stats } from 'node:fs'import { open, opendir } from 'node:fs/promises'export class IdentityReadUnavailable extends Error {readonly code = 'IDENTITY_UNAVAILABLE'- constructor(reason: string) { super(`Conversation identity is held: ${reason}.`) }+ constructor(reason: string, message = `Conversation identity is held: ${reason}.`) { super(message) }}+export type IdentityVersion = Pick<Stats, 'dev' | 'ino' | 'size' | 'mtimeMs' | 'ctimeMs'>+/** Shared across every directory/root in one lookup, including entries that are not transcripts. */export const identityScanBudget = () => ({ remaining: 4096 })/** A regular file only. Nonblocking open prevents a native-store FIFO from hanging session control. */-export async function identityBytes(path: string, maxBytes: number): Promise<Buffer> {+export async function identityBytes(path: string, maxBytes: number, expected?: IdentityVersion): Promise<Buffer> {const handle = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)try {const before = await handle.stat()if (!before.isFile()) throw new IdentityReadUnavailable('the native record is not a regular file')+ // A pathname can switch to another inode and back while a caller awaits its header. The+ // opened descriptor must be the candidate that authorized this read, not only the path at return.+ if (expected && (before.dev !== expected.dev || before.ino !== expected.ino || before.size !== expected.size+ || before.mtimeMs !== expected.mtimeMs || before.ctimeMs !== expected.ctimeMs)) {+ throw new IdentityReadUnavailable('the opened native record differs from the inspected candidate')+ }const length = Math.min(before.size, maxBytes)const bytes = Buffer.alloc(length)let read = 0@@ -80,8 +88,8 @@ export async function identityFile(path: string, maxBytes = 64 * 1024): Promise<}/** Only complete lines from a bounded prefix; EOF may complete the final line without a newline. */-export async function identityHead(path: string, lines: number, maxBytes = 256 * 1024): Promise<{ lines: string[]; complete: boolean }> {- const bytes = await identityBytes(path, maxBytes + 1).catch(error => {+export async function identityHead(path: string, lines: number, maxBytes = 256 * 1024, expected?: IdentityVersion): Promise<{ lines: string[]; complete: boolean }> {+ const bytes = await identityBytes(path, maxBytes + 1, expected).catch(error => {if (error instanceof IdentityReadUnavailable) throw errorthrow new IdentityReadUnavailable('the native header could not be read')})diff --git a/cli/src/engines/kit/sessionRecords.ts b/cli/src/engines/kit/sessionRecords.tsindex 3fb7b9419..9af8b6b92 100644--- a/cli/src/engines/kit/sessionRecords.ts+++ b/cli/src/engines/kit/sessionRecords.ts@@ -7,7 +7,7 @@import { closeSync, existsSync, openSync, readdirSync, readSync } from 'node:fs'import { isAbsolute, join } from 'node:path'import type { SessionStoreContract } from '../facets/sessionStore.js'-import { identityHead, IdentityReadUnavailable } from './identityScan.js'+import { identityHead, IdentityReadUnavailable, type IdentityVersion } from './identityScan.js'type JsonObject = Record<string, unknown>@@ -79,9 +79,9 @@ function firstRecordMeta(firstLine: string, first: NonNullable<SessionStoreContr/** Repair pools require conclusive metadata for every candidate. A short, cut or unreadable* rollout cannot make a sibling unique. Compatibility readers retain their nullable result. */-export async function readIdentityFirstRecord(file: string, first: NonNullable<SessionStoreContract['first']>): Promise<SessionMeta> {+export async function readIdentityFirstRecord(file: string, first: NonNullable<SessionStoreContract['first']>, expected?: IdentityVersion): Promise<SessionMeta> {try {- const head = await identityHead(file, Number.MAX_SAFE_INTEGER, first.maxBytes)+ const head = await identityHead(file, Number.MAX_SAFE_INTEGER, first.maxBytes, expected)const line = head.lines.find(line => line.trim())if (!line) throw new IdentityReadUnavailable('the rollout header is incomplete or exceeds the read limit')const meta = firstRecordMeta(line, first)diff --git a/cli/src/engines/otherIdentity.golden.spec.ts b/cli/src/engines/otherIdentity.golden.spec.tsindex ce25cbcd8..cbb9f94e9 100644--- a/cli/src/engines/otherIdentity.golden.spec.ts+++ b/cli/src/engines/otherIdentity.golden.spec.ts@@ -30,6 +30,7 @@ const descriptors = vi.hoisted(() => new Map<string, string[]>())vi.mock('fs/promises', async (original) => {const fs = await original<typeof import('node:fs/promises')>()return { ...fs,+ realpath: (name: string) => fs.realpath(name.startsWith('/work/') ? join(root, 'workspaces', name.slice(6)) : name),// Keep a streamed descriptor listing private as well as the former readdir path.opendir: async (path: string, ...args: unknown[]) => /^\/proc\/\d+\/fd$/.test(String(path))? { async *[Symbol.asyncIterator]() {@@ -45,6 +46,11 @@ vi.mock('fs/promises', async (original) => {},}})+vi.mock('node:fs', async original => {+ const fs = await original<typeof import('node:fs')>()+ const mapped = (name: string) => name.startsWith('/work/') ? join(root, 'workspaces', name.slice(6)) : name+ return { ...fs, realpathSync: (name: string) => fs.realpathSync(mapped(name)), statSync: (name: string) => fs.statSync(mapped(name)) }+})const GOLDEN = fileURLToPath(new URL('./__fixtures__/other-identity.golden.json', import.meta.url))const RECORD = process.env.RECORD_OTHER_ENGINES_GOLDEN === '1'@@ -89,6 +95,7 @@ let m: ModulesbeforeAll(async () => {root = realpathSync(mkdtempSync(join(tmpdir(), 'other-identity-golden-')))+ for (const cwd of ['r', 'other']) mkdirSync(join(root, 'workspaces', cwd), { recursive: true })Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })vi.useFakeTimers({ toFake: ['Date'], now: NOW })const home = join(root, 'home')diff --git a/cli/src/engines/repairIdentity.golden.spec.ts b/cli/src/engines/repairIdentity.golden.spec.tsindex 7fbfdb52c..e6ceef4d6 100644--- a/cli/src/engines/repairIdentity.golden.spec.ts+++ b/cli/src/engines/repairIdentity.golden.spec.ts@@ -10,13 +10,19 @@ import { afterAll, beforeAll, expect, it, vi } from 'vitest'const clock = vi.hoisted(() => ({ root: '', time: Date.parse('2026-10-09T00:00:00Z') }))vi.mock('fs/promises', async original => {const fs = await original<typeof import('node:fs/promises')>()- return { ...fs, stat: async (path: string, ...args: unknown[]) => {+ return { ...fs, realpath: (name: string) => fs.realpath(name.startsWith('/work/') ? join(clock.root, 'workspaces', name.slice(6)) : name),+ stat: async (path: string, ...args: unknown[]) => {const result = await Reflect.apply(fs.stat, fs, [path, ...args])return String(path).startsWith(clock.root + '/')? new Proxy(result, { get: (value, key) => key === 'birthtimeMs' ? clock.time : Reflect.get(value, key) }): result} }})+vi.mock('node:fs', async original => {+ const fs = await original<typeof import('node:fs')>()+ const mapped = (name: string) => name.startsWith('/work/') ? join(clock.root, 'workspaces', name.slice(6)) : name+ return { ...fs, realpathSync: (name: string) => fs.realpathSync(mapped(name)), statSync: (name: string) => fs.statSync(mapped(name)) }+})const GOLDEN = fileURLToPath(new URL('./__fixtures__/repair-identity.golden.json', import.meta.url))const RECORD = process.env.RECORD_REPAIR_IDENTITY_GOLDEN === '1'@@ -57,6 +63,7 @@ async function check(key: string, run: () => unknown | Promise<unknown>): PromisbeforeAll(async () => {clock.root = realpathSync(mkdtempSync(join(tmpdir(), 'repair-identity-golden-')))+ for (const cwd of ['pi/resume', 'pi/a-b', 'pi-a/b']) mkdirSync(join(clock.root, 'workspaces', cwd), { recursive: true })Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })vi.useFakeTimers({ toFake: ['Date'], now: clock.time })const home = join(clock.root, 'home')diff --git a/cli/src/engines/sessionFiles.ts b/cli/src/engines/sessionFiles.tsindex ed8b52ab7..27e153967 100644--- a/cli/src/engines/sessionFiles.ts+++ b/cli/src/engines/sessionFiles.ts@@ -8,6 +8,7 @@ import { sessionRoots } from '../lib/engineHomes.js'import { continuedIn } from './kit/continuation.js'import { findSessionFile, readFirstRecord, readIdentityFirstRecord, type SessionMeta } from './kit/sessionRecords.js'import { sessionStoreOf } from './sessionStoreContracts.js'+import type { IdentityVersion } from './kit/identityScan.js'import type { AgentEngine } from './types.js'export type { SessionMeta }@@ -20,9 +21,9 @@ export function sessionMetaOf(engine: AgentEngine | string, path: string): Sessi}/** Strict, asynchronous evidence for discovery and Stop; unrelated readers keep their compatibility API. */-export async function sessionIdentityMetaOf(engine: AgentEngine | string, path: string): Promise<SessionMeta | null> {+export async function sessionIdentityMetaOf(engine: AgentEngine | string, path: string, expected?: IdentityVersion): Promise<SessionMeta | null> {const first = sessionStoreOf(engine)?.first- return first ? readIdentityFirstRecord(path, first) : null+ return first ? readIdentityFirstRecord(path, first, expected) : null}/**diff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.tsindex 9a3f2808c..38dcf1291 100644--- a/cli/src/harnessd/master.spec.ts+++ b/cli/src/harnessd/master.spec.ts@@ -572,7 +572,7 @@ describe('runMaster', { timeout: 60_000 }, () => {env: { ...process.env, HARNESSD_SERVICES: 'search' },exit: (code) => exits.push(code), onSignal: (signal, listener) => signals.set(signal, listener),})- const said = (): Array<Record<string, string>> => existsSync(seen) ? readFileSync(seen, 'utf8').trim().split('\n').map((line) => JSON.parse(line)) : []+ const said = (): Array<Record<string, string>> => jsonLines(seen)await until('search to say it staged a build', () => said().some((line) => line.role === 'service:search' && line.what === 'staged'))// Long enough for a handover the master had asked for to reach the core.await new Promise((resolve) => setTimeout(resolve, 500))diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.tsindex 43f5cb1af..e3d8a1f53 100644--- a/cli/src/lib/closeAgentService.spec.ts+++ b/cli/src/lib/closeAgentService.spec.ts@@ -2,11 +2,13 @@ import { screenFor } from '../engines/screens.js'import { afterEach, beforeEach, expect, it, vi } from 'vitest'import { CloseAgentService, inspectCloseActivity as inspectCloseReading, type CloseActivity, type CloseAgentServiceDeps, type AgentCloseRequest } from './closeAgentService.js'import { registry, type RegisteredSession } from './registry.js'-import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'+import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { env } from '../config/env.js'import { SessionCheckpointStore } from './sessionCheckpoint.js'import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'+import { findResumedTranscript } from './sessionRepair.js'+import { piSessionFolder } from '../engines/repairIdentities.js'let row: RegisteredSessionlet service: CloseAgentService@@ -81,6 +83,46 @@ it('a queued Close preserves its intent and reason while native identity is unavexpect(deps.checkpoint).toHaveBeenCalledOnce()expect(registry.byAgent(row.agentId)).toBeUndefined()})+it.each(['capture', 'checkpoint'] as const)('a queued Pi Close retries real native evidence held during %s', async phase => {+ const previousHome = env.PI_HOME+ env.PI_HOME = join(env.ADAPTER_DATA_DIR, 'pi-close', row.agentId)+ const cwd = join(env.PI_HOME, 'workspace'), directory = join(env.PI_HOME, 'checkpoints')+ mkdirSync(cwd, { recursive: true })+ Object.assign(row, { engine: 'pi', sessionId: 'queued-conversation', transcriptPath: null, cwd, codexHome: undefined })+ const folder = join(env.PI_HOME, 'agent', 'sessions', piSessionFolder(cwd))+ mkdirSync(folder, { recursive: true }); mkdirSync(directory)+ const native = join(folder, `day_${row.sessionId}.jsonl`), duplicate = join(folder, `next_${row.sessionId}.jsonl`)+ const header = JSON.stringify({ type: 'session', id: row.sessionId, cwd }) + '\n'+ const store = new SessionCheckpointStore(directory)+ deps.checkpoint = vi.fn(s => store.save(s, { screen: 'The private terminal is idle' }))+ deps.stop = vi.fn(async (id, options) => {+ const captured = { ...row }+ if (phase === 'capture') captured.transcriptPath = await findResumedTranscript('pi', row.sessionId, { cwd })+ await options.checkpoint!(captured, 'before')+ await options.beforeStop!(captured)+ expect(options.current!()).toBe(true)+ registry.removeAgent(id)+ })+ try {+ writeFileSync(native, '{partial')+ expect(await service.request(request('after_task'))).toEqual({ deferred: true })+ const plan = row.closePlan!+ await service.tick(); time += 5_000; await service.tick()+ expect(registry.byAgent(row.agentId)?.closePlan).toMatchObject({ id: plan.id, state: 'waiting', detail: expect.stringContaining('could not be read') })+ expect(readdirSync(directory)).toEqual([])+ writeFileSync(native, header); writeFileSync(duplicate, header)+ await service.tick()+ expect(registry.byAgent(row.agentId)?.closePlan).toMatchObject({ id: plan.id, state: 'waiting', detail: 'More than one file matches this Pi conversation.' })+ expect(readdirSync(directory)).toEqual([])+ rmSync(duplicate)+ await service.tick()+ expect(registry.byAgent(row.agentId)).toBeUndefined()+ const saved = JSON.parse(readFileSync(join(directory, readdirSync(directory).find(file => /^[a-f0-9]{64}\.json$/.test(file))!), 'utf8'))+ expect(saved.source).toBe(native)+ expect(readFileSync(join(directory, saved.file), 'utf8')).toBe(header)+ expect(deps.stop).toHaveBeenCalledTimes(3)+ } finally { env.PI_HOME = previousHome }+})it('cleanup requires open-tab support and checks again after history is saved', async () => {const close = { ...request('now'), onlyIfHidden: true }expect(await service.request(close)).toMatchObject({ error: 'UNSUPPORTED' })diff --git a/cli/src/lib/sessionCheckpoint.spec.ts b/cli/src/lib/sessionCheckpoint.spec.tsindex 902906f27..8d429ae6b 100644--- a/cli/src/lib/sessionCheckpoint.spec.ts+++ b/cli/src/lib/sessionCheckpoint.spec.ts@@ -35,7 +35,8 @@ async function piSession() {const previousHome = env.PI_HOMEenv.PI_HOME = join(root, 'pi')// This fixture owns every possible source; never scan the developer's Pi store.- Object.assign(row, { engine: 'pi', sessionId: 'preallocated-session', transcriptPath: null })+ const cwd = join(root, 'workspace'); await mkdir(cwd)+ Object.assign(row, { engine: 'pi', sessionId: 'preallocated-session', transcriptPath: null, cwd })const folder = join(env.PI_HOME, 'agent', 'sessions', piSessionFolder(row.cwd!))await mkdir(folder, { recursive: true })const path = join(folder, `2026-10-04T12-00-00-000Z_${row.sessionId}.jsonl`)@@ -122,7 +123,8 @@ it.each(['known', 'unreadable', 'ambiguous', 'unreadable store'] as const)('doesit('does not back up a different Pi ID or a project with the same encoded folder', async () => {const pi = await piSession()try {- await writeFile(pi.path, `${JSON.stringify({ type: 'session', id: row.sessionId, cwd: '/different/project' })}\n`)+ const other = join(root, 'different-project'); await mkdir(other)+ await writeFile(pi.path, `${JSON.stringify({ type: 'session', id: row.sessionId, cwd: other })}\n`)await store.save(row, { screen: 'Startup screen' })expect((await manifest()).source).toBeNull()await writeFile(pi.path, `${JSON.stringify({ type: 'session', id: `other_${row.sessionId}`, cwd: row.cwd })}\n`)@@ -131,6 +133,24 @@ it('does not back up a different Pi ID or a project with the same encoded folder} finally { pi.restore() }})+it.each(['partial', 'ambiguous', 'workspace unavailable'] as const)('holds %s Pi evidence without changing an earlier checkpoint or screen', async state => {+ const pi = await piSession()+ try {+ await store.save(row, { screen: 'The original unsent draft' })+ const before = Object.fromEntries(await Promise.all((await readdir(directory)).map(async file => [file, await readFile(join(directory, file), 'utf8')])))+ const duplicate = join(pi.path, '..', `other_${row.sessionId}.jsonl`)+ if (state === 'partial') await writeFile(pi.path, '{partial')+ if (state === 'ambiguous') { await writeFile(pi.path, pi.history); await writeFile(duplicate, pi.history) }+ if (state === 'workspace unavailable') await writeFile(pi.path, JSON.stringify({ type: 'session', id: row.sessionId, cwd: join(root, 'missing-workspace') }) + '\n')+ await expect(store.save(row, { screen: 'A later unsent draft' })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ const after = Object.fromEntries(await Promise.all((await readdir(directory)).map(async file => [file, await readFile(join(directory, file), 'utf8')])))+ expect(after).toEqual(before)+ await rm(duplicate, { force: true }); await writeFile(pi.path, pi.history)+ await store.save(row, { screen: 'A later unsent draft' })+ expect((await manifest()).source).toBe(pi.path)+ } finally { pi.restore() }+})+it('preserves a newly typed draft even when native history has not changed', async () => {await store.save(row, { screen: 'first draft' })const first = await manifest()diff --git a/cli/src/lib/sessionCheckpoint.ts b/cli/src/lib/sessionCheckpoint.tsindex 68b6e816b..7b82044df 100644--- a/cli/src/lib/sessionCheckpoint.ts+++ b/cli/src/lib/sessionCheckpoint.ts@@ -98,6 +98,8 @@ export class SessionCheckpointStore {try { previous = JSON.parse(readPrivateStateFile(manifest, 16384)) as Checkpoint } catch (e) {if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e}+ const source = s.transcriptPath ?? (s.engine === 'pi' && s.sessionId+ ? await findResumedTranscript('pi', s.sessionId, { cwd: s.cwd ?? undefined }) : null)if (options.screen != null && s.sessionId) {// Save even when the native transcript is unchanged: a newly typed draft// belongs to the terminal, not to that transcript. Never submit it.@@ -106,8 +108,6 @@ export class SessionCheckpointStore {}const checkpoint: Checkpoint = { version: 1, agentId: s.agentId, sessionId: s.sessionId,engine: s.engine, codexHome: s.codexHome ?? null, savedAt: Date.now(), source: null, file, bytes: 0 }- const source = s.transcriptPath ?? (s.engine === 'pi' && s.sessionId- ? await findResumedTranscript('pi', s.sessionId, { cwd: s.cwd ?? undefined }) : null)// Pi announces a session ID before it writes any history. In particular,// missing credentials can leave it here indefinitely. Preserve the screen// just as for an unbound chat; a known transcript, or one backed up before, must still save.@@ -166,7 +166,7 @@ export class SessionCheckpointStore {await rm(join(this.directory, previous.file), { force: true }).catch(() => {})}} catch (error) {- if (error instanceof SessionCheckpointError) throw error+ if (error instanceof SessionCheckpointError || (error as { code?: unknown } | null)?.code === 'IDENTITY_UNAVAILABLE') throw errorthrow new SessionCheckpointError('Could not back up this conversation to disk. Check free space and try again; its existing history is kept.')} finally {await rm(temporary, { force: true }).catch(() => {})diff --git a/cli/src/lib/sessionRepair.eager.spec.ts b/cli/src/lib/sessionRepair.eager.spec.tsindex f1a7c9f33..661e8a1e1 100644--- a/cli/src/lib/sessionRepair.eager.spec.ts+++ b/cli/src/lib/sessionRepair.eager.spec.ts@@ -14,7 +14,8 @@ vi.mock('../engines/inProcess.js', () => ({ loadEngine: vi.fn(async (name: strin}) }))const STARTED_AT = Date.parse('2026-10-08T09:00:00Z')-const CWD = '/work/project'+let CWD = ''+let piDirectory = ''const UUID = '0b6f4f2e-6c1a-4c55-9a51-000000000001'let root = ''const saved: Record<string, string | undefined> = {}@@ -22,6 +23,7 @@ let repair: typeof import('./sessionRepair.js')beforeAll(async () => {root = mkdtempSync(join(tmpdir(), 'repair-lazy-'))+ CWD = join(root, 'work'); mkdirSync(CWD)const env = {MUSE_HOME: join(root, 'muse'), COPILOT_HOME: join(root, 'copilot'), HERMES_HOME: join(root, 'hermes'),AGY_HOME: join(root, 'agy'), PI_HOME: join(root, 'pi'), GROK_HOME: join(root, 'grok'), CLAUDE_PROJECTS_DIR: join(root, 'claude'), CODEX_HOME: join(root, 'codex'),@@ -36,7 +38,7 @@ beforeAll(async () => {JSON.stringify({ payload: { kind: 'run', event: { kind: 'started', prompt: 'hi' } } }),].join('\n') + '\n')utimesSync(museFile, new Date(STARTED_AT + 5_000), new Date(STARTED_AT + 5_000))- const piDirectory = join(root, 'pi', 'agent', 'sessions', '--work-project--')+ piDirectory = join(root, 'pi', 'agent', 'sessions', `--${CWD.replace(/^[/\\]/, '').replace(/[/\\:]/g, '-')}--`)mkdirSync(piDirectory, { recursive: true })writeFileSync(join(piDirectory, '2026-10-09_abc123.jsonl'), JSON.stringify({ type: 'session', id: 'abc123', cwd: CWD }) + '\n')vi.resetModules()@@ -59,7 +61,7 @@ describe('session repair, independent of optional readers', () => {new Promise(resolve => { timer = setTimeout(() => resolve('blocked on optional code'), 1000) }),])expect(value).toEqual([{ sessionId: UUID, transcriptPath: join(root, 'muse', 'sessions', '2026', '10', '08', UUID, 'session.jsonl') },- join(root, 'pi', 'agent', 'sessions', '--work-project--', '2026-10-09_abc123.jsonl')])+ join(piDirectory, '2026-10-09_abc123.jsonl')])expect(loader.asked).toEqual([])} finally { clearTimeout(timer); loader.stalled = false }})diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex 3d40e7e00..c9652ac2d 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -20,14 +20,16 @@ import { basename, dirname, isAbsolute, join, sep } from 'path'import { env } from '../config/env.js'import type { SessionStoreContract } from '../engines/facets/sessionStore.js'import { identityBytes, identityEntries, identityFile, identityHead, identityScanBudget, IdentityReadUnavailable } from '../engines/kit/identityScan.js'-import { findSessionFileOf, sessionIdentityMetaOf } from '../engines/sessionFiles.js'+import { sessionIdentityMetaOf } from '../engines/sessionFiles.js'+import { exactTranscript, exactWorkspaces } from '../engines/kit/exactTranscript.js'+import { readSessionHeader } from '../engines/kit/sessionIdentity.js'import { sessionStoreOf } from '../engines/sessionStoreContracts.js'import type { AgentEngine } from '../engines/types.js'import { HERMES_HOMES, HERMES_HISTORY_ID_RE, HERMES_ID_SQL, HERMES_SOURCE, HERMES_SOURCE_SQL } from '../engines/hermes/contract.js'import { readStorePool } from '../engines/kit/storePool.js'import { isInteractiveSource } from '../engines/kit/storeSource.js'import { museSessionIdentity, piSessionFolder, readPiHead } from '../engines/repairIdentities.js'-import { PI_SESSION_ID } from '../engines/pi/contract.js'+import { PI_HEADER, PI_SESSION_ID } from '../engines/pi/contract.js'import { transcriptOf, processSessionOf as nativeProcessSession } from '../engines/identities.js'import { COPILOT_CWD } from '../engines/copilot/contract.js'import { recordCwd } from '../engines/kit/sessionLocation.js'@@ -530,46 +532,46 @@ export async function findResumedTranscript(if (engine === 'pi') {// Pi allocates an ID before its first reply creates the file. Look up that// exact ID again at Close, including after exit, without guessing by mtime.- if (!opts?.cwd || !PI_SESSION_ID.test(sessionId)) throw new Error('The Pi conversation location is unavailable.')+ if (!opts?.cwd || !PI_SESSION_ID.test(sessionId)) {+ throw new IdentityReadUnavailable('the Pi conversation location is unavailable', 'The Pi conversation location is unavailable.')+ }// The folder and header are native identity, available even when Pi's history reader cannot load.const directory = join(env.PI_HOME, 'agent', 'sessions', piSessionFolder(opts.cwd))- let files: string[]- try { files = await readdir(directory) } catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null- throw error // An unreadable store is not an unwritten conversation.- }- const matches: string[] = []- for (const file of files.filter(file => file.endsWith(`_${sessionId}.jsonl`))) {- const head = await readPiHead(join(directory, file))- if (!head || typeof head === 'symbol') throw new Error('The Pi conversation file could not be read.')- if (head.sessionId === sessionId && await sameDir(head.cwd, opts.cwd)) matches.push(file)- }- if (matches.length > 1) throw new Error('More than one file matches this Pi conversation.')- return matches.length ? join(directory, matches[0]) : null+ const workspaces = exactWorkspaces()+ return exactTranscript([directory], { kind: 'directory', matches: file => file.endsWith(`_${sessionId}.jsonl`) }, {+ accepts: async (path, version) => {+ const head = await readSessionHeader(PI_HEADER, async bytes => (await identityBytes(path, bytes, version)).toString('utf8'))+ .catch(() => null)+ if (!head || typeof head === 'symbol') {+ throw new IdentityReadUnavailable('the Pi conversation file could not be read', 'The Pi conversation file could not be read.')+ }+ return head.sessionId === sessionId && await workspaces.same(head.cwd, opts.cwd!)+ },+ verify: workspaces.verify,+ ambiguous: 'More than one file matches this Pi conversation.',+ })}- if (!/^[0-9a-f-]{16,}$/i.test(sessionId)) return null+ if (!/^[0-9a-f-]{16,128}$/i.test(sessionId)) return nullconst byId = sessionStoreOf(engine)?.byIdif (!byId) return null// In every folder the registry takes a transcript from (registry.validTranscriptPath): the daemon's own and// each home the person moved in their shell profile (lib/engineHomes.ts), or an agent's own profile alone.// Only the default folders were looked in, so a resume typed into a pane for a conversation in a moved home// found no file and never bound, though the registry would have taken it.- for (const root of sessionRoots(engine, opts?.codexHome)) {- if (byId.layout === 'walk') {- const found = findSessionFileOf(engine, sessionId, root)- if (found) return found- continue- }- let projects: string[]- try { projects = await readdir(root) } catch { continue }- for (const project of projects) {- const candidate = join(root, project, `${sessionId}${byId.suffix}`)- try {- if ((await stat(candidate)).isFile()) return candidate- } catch { /* not this project */ }- }+ const roots = repairRoots(engine, opts?.codexHome)+ const found = await (byId.layout === 'walk'+ ? exactTranscript(roots, { kind: 'walk', matches: file => file.endsWith(byId.suffix) && file.includes(sessionId) }, {+ accepts: async (path, version) => {+ const meta = await sessionIdentityMetaOf(engine, path, version)+ if (!meta?.id || !byId.id.test(meta.id)) throw new IdentityReadUnavailable('the exact rollout header has no conclusive conversation id')+ return meta.id === sessionId+ },+ })+ : exactTranscript(roots, { kind: 'projects', filename: `${sessionId}${byId.suffix}` }))+ if (repairRoots(engine, opts?.codexHome).join('\0') !== roots.join('\0')) {+ throw new IdentityReadUnavailable('the known session homes changed during exact lookup')}- return null+ return found}/** The files a process holds open: `/proc` on Linux, `lsof` elsewhere. Empty when neither can say. */diff --git a/docs/research/2026-10-09-daemon-core-completion.md b/docs/research/2026-10-09-daemon-core-completion.mdindex 539c00694..6ec04b891 100644--- a/docs/research/2026-10-09-daemon-core-completion.md+++ b/docs/research/2026-10-09-daemon-core-completion.md@@ -16,9 +16,11 @@ This is the remaining completion scope as of October 9, after the six extraction- [x] Bounded repair pools and native headers hold incomplete evidence; Stop/Close preserve intent (#1114, merged as `138ae6766` at 13:59:26 UTC).- [x] Exact Cursor/Grok locations, Copilot/agy process claims and discovery retries retain incomplete evidence (#1118, merged as `902ab6038` at 15:01:46 UTC).+- [x] Fresh bounded Hermes pools and Stop home preservation (#1120, merged as `a847441e5` at 16:39:44 UTC).+## Remaining blockers-1. **Complete native identity and retry.** Bound exact transcript lookup, lock/descriptor enumeration and the saved-home catalog; make Hermes home/database pools fresh and complete. 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.** Bound exact transcript lookup, lock/descriptor enumeration and the saved-home catalog. 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.mdindex e134718ef..7b0cbd021 100644--- a/docs/research/2026-10-09-daemon-separation-progress.md+++ b/docs/research/2026-10-09-daemon-separation-progress.md@@ -208,3 +208,7 @@ and the final unavailable-service/readiness audit. Line counts do not establish## Native locations and retry isolation[PR #1118](https://github.com/autonomous-ai/openharness/pull/1118) bounds exact Cursor/Grok locations and Copilot/agy process claims, rejects incomplete or changing evidence, and retains/retries failed bindings and pending transcript discovery without blocking siblings. The [implementation, independent review corrections, validation and measured cost](2026-10-09-native-location-discovery.md) are recorded separately. Former-code golden artifacts remain unchanged and all 21 broken-wiring variants assertion-fail. Native identity as a whole remains open in the completion checklist: exact resume/legacy records, saved-home catalogs, Hermes pools and shared visible hold state still need completion.++## Fresh Hermes stores and retained Stop homes++[PR #1120](https://github.com/autonomous-ai/openharness/pull/1120) merged as `a847441e5` at 16:39:44 UTC on October 9. Fresh complete native pools hold unreadable, ambiguous, oversized or changing evidence; Stop preserves the proven home. The [report](2026-10-09-hermes-store-pools.md) contains the unchanged golden, 27 assertion-failing mutants, full coverage/native acceptance and matched cost. Final source had independent exact-head/base approval and every automatic head check, including `ci/required`. Implementation/review corrections ended at 15:52, local acceptance and cost by 15:57, and final documentation review at 16:00. CI waiting and integration extended to 16:39 after the recorded legacy-golden safety correction and three documentation-only main advances. The merge helper ran 16:39:30–16:39:44. Publication remains zero. Native identity as a group remains open; exact resume is next, followed by legacy records, saved-home failure handling and shared hold visibility.diff --git a/docs/research/2026-10-09-exact-resume-cost.json b/docs/research/2026-10-09-exact-resume-cost.jsonnew file mode 100644index 000000000..523052339--- /dev/null+++ b/docs/research/2026-10-09-exact-resume-cost.json@@ -0,0 +1,1226 @@+{+ "startedAt": "2026-10-09T17:03:05.200620+00:00",+ "finishedAt": "2026-10-09T17:03:28.528905+00:00",+ "method": "Three interleaved fresh processes per source/workload, ten lookups per process. Identical private files. Setup and imports excluded from lookup CPU/latency; peak RSS includes setup/import. No daemon or vendor binary. Reference measurements, no numerical performance gate.",+ "driver": "/** Fresh private native stores; no vendor binary, daemon, saved-home catalog or owner input. */\nimport { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { performance } from 'node:perf_hooks'\nconst root = realpathSync(mkdtempSync(join(tmpdir(), 'exact-resume-cost-')))\nconst workload = process.argv[2] ?? 'claude'\nconst cli = process.env.EXACT_COST_CLI ?? resolve(import.meta.dirname, '../..')\nconst id = 'aaaaaaaa-1111-4222-8333-444444444444'\nconst cwd = join(root, 'work')\nfor (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'CLAUDE_CONFIG_DIR',\n 'CODEX_HOME', 'CURSOR_HOME', 'COPILOT_HOME', 'GROK_HOME', 'AGY_HOME', 'PI_HOME', 'MUSE_HOME', 'COMMANDCODE_HOME',\n 'HERMES_HOME', 'AMP_SESSIONS_DIR', 'OPENCODE_DATA_DIR', 'KILO_DATA_DIR', 'DEVIN_HOME', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME']) {\n process.env[name] = join(root, name)\n}\nprocess.env.CLAUDE_PROJECTS_DIR = join(process.env.CLAUDE_CONFIG_DIR!, 'projects')\ntry {\n mkdirSync(cwd)\n const engine = workload === 'claude' || workload === 'unavailable' ? 'claude' : workload === 'pi' ? 'pi' : 'codex'\n const folder = engine === 'claude' ? join(process.env.CLAUDE_PROJECTS_DIR!, 'work') : engine === 'codex'\n ? join(process.env.CODEX_HOME!, 'sessions', 'day') : join(process.env.PI_HOME!, 'agent', 'sessions', `--${cwd.replace(/^[/\\\\]/, '').replace(/[/\\\\:]/g, '-')}--`)\n mkdirSync(folder, { recursive: true })\n const filename = engine === 'claude' ? `${id}.jsonl` : `${engine === 'pi' ? 'day_' : 'rollout-'}${id}.jsonl`\n const header = JSON.stringify(engine === 'codex' ? { type: 'session_meta', payload: { id, cwd, source: 'cli' } }\n : engine === 'pi' ? { type: 'session', id, cwd } : { type: 'user', sessionId: id, cwd }) + '\\n'\n writeFileSync(join(folder, filename), header)\n const unrelated = workload === 'populated' ? 1000 : workload === 'limit' ? 4200 : 0\n for (let i = 0; i < unrelated; i++) writeFileSync(join(folder, `unrelated-${i}.jsonl`), '{}\\n')\n if (workload === 'duplicate') {\n const other = join(process.env.CODEX_HOME!, 'sessions', 'other'); mkdirSync(other)\n writeFileSync(join(other, filename), header)\n }\n const { findResumedTranscript } = await import(pathToFileURL(join(cli, 'src/lib/sessionRepair.ts')).href)\n if (workload === 'unavailable') {\n const moved = join(root, 'moved'); mkdirSync(moved); writeFileSync(join(moved, 'projects'), 'not a directory')\n const { adoptHomes } = await import(pathToFileURL(join(cli, 'src/lib/engineHomes.ts')).href)\n adoptHomes({ CLAUDE_CONFIG_DIR: moved })\n }\n const latenciesMs: number[] = [], outcomes: Record<string, number> = {}\n const cpu = process.cpuUsage()\n for (let i = 0; i < 10; i++) {\n const at = performance.now()\n let outcome: string\n try { outcome = await findResumedTranscript(engine, id, { cwd }) ? 'exact' : 'absent' }\n catch (error) {\n if ((error as { code?: string }).code !== 'IDENTITY_UNAVAILABLE') throw error\n outcome = 'held'\n }\n latenciesMs.push(Number((performance.now() - at).toFixed(2)))\n outcomes[outcome] = (outcomes[outcome] ?? 0) + 1\n }\n const used = process.cpuUsage(cpu)\n console.log(JSON.stringify({ workload, iterations: 10, unrelated, outcomes, latenciesMs,\n cpuMs: (used.user + used.system) / 1000, peakRssMiB: process.resourceUsage().maxRSS / 1024,\n node: process.version, platform: process.platform, arch: process.arch }))\n} finally { rmSync(root, { recursive: true, force: true }) }\n",+ "samples": [+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 0,+ "wallSeconds": 0.553,+ "workload": "claude",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.67,+ 0.15,+ 0.1,+ 0.1,+ 0.11,+ 0.11,+ 0.15,+ 0.11,+ 0.26,+ 0.13+ ],+ "cpuMs": 2.239,+ "peakRssMiB": 95.5390625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 0,+ "wallSeconds": 0.492,+ "workload": "claude",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 2.89,+ 0.95,+ 0.92,+ 0.83,+ 1.07,+ 0.93,+ 0.92,+ 0.82,+ 1,+ 0.77+ ],+ "cpuMs": 12.457,+ "peakRssMiB": 106.140625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 0,+ "wallSeconds": 0.419,+ "workload": "codex",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.56,+ 0.17,+ 0.11,+ 0.12,+ 0.12,+ 0.1,+ 0.1,+ 0.1,+ 0.28,+ 0.13+ ],+ "cpuMs": 1.865,+ "peakRssMiB": 94.421875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 0,+ "wallSeconds": 0.415,+ "workload": "codex",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 3.91,+ 1.3,+ 1.21,+ 1.17,+ 1.73,+ 1.01,+ 0.99,+ 0.98,+ 1.08,+ 0.94+ ],+ "cpuMs": 15.887,+ "peakRssMiB": 90.2890625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 0,+ "wallSeconds": 0.411,+ "workload": "pi",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.49,+ 0.41,+ 0.5,+ 0.43,+ 0.5,+ 0.38,+ 0.38,+ 0.4,+ 0.49,+ 0.36+ ],+ "cpuMs": 6.126,+ "peakRssMiB": 93.9296875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 0,+ "wallSeconds": 0.425,+ "workload": "pi",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 5.28,+ 2.15,+ 1.59,+ 1.58,+ 1.62,+ 1.35,+ 1.12,+ 0.94,+ 1.07,+ 0.91+ ],+ "cpuMs": 19.281,+ "peakRssMiB": 95.40625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 0,+ "wallSeconds": 0.685,+ "workload": "populated",+ "iterations": 10,+ "unrelated": 1000,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.51,+ 1.09,+ 1.04,+ 1.06,+ 1.05,+ 1.02,+ 0.99,+ 0.98,+ 1.19,+ 1+ ],+ "cpuMs": 11.021,+ "peakRssMiB": 93.4765625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 0,+ "wallSeconds": 0.726,+ "workload": "populated",+ "iterations": 10,+ "unrelated": 1000,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 11.48,+ 6.64,+ 10.31,+ 7.75,+ 5.56,+ 5.79,+ 7.41,+ 7.44,+ 7.27,+ 5+ ],+ "cpuMs": 130.707,+ "peakRssMiB": 105.3984375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 0,+ "wallSeconds": 0.4,+ "workload": "duplicate",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.56,+ 0.17,+ 0.12,+ 0.12,+ 0.12,+ 0.11,+ 0.1,+ 0.1,+ 0.3,+ 0.13+ ],+ "cpuMs": 1.904,+ "peakRssMiB": 95.90625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 0,+ "wallSeconds": 0.393,+ "workload": "duplicate",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 4.49,+ 1.87,+ 1.92,+ 1.85,+ 1.98,+ 1.52,+ 1.38,+ 1.78,+ 1.58,+ 1.38+ ],+ "cpuMs": 23.852,+ "peakRssMiB": 93.37109375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 0,+ "wallSeconds": 0.373,+ "workload": "unavailable",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.58,+ 0.16,+ 0.13,+ 0.26,+ 0.15,+ 0.15,+ 0.13,+ 0.14,+ 0.29,+ 0.12+ ],+ "cpuMs": 2.344,+ "peakRssMiB": 94.546875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 0,+ "wallSeconds": 0.391,+ "workload": "unavailable",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 3.08,+ 1,+ 1.01,+ 0.9,+ 1.06,+ 0.85,+ 0.94,+ 0.89,+ 1.02,+ 0.77+ ],+ "cpuMs": 14.392,+ "peakRssMiB": 94.875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 0,+ "wallSeconds": 1.25,+ "workload": "limit",+ "iterations": 10,+ "unrelated": 4200,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 4.69,+ 4.14,+ 4.03,+ 4.06,+ 4.13,+ 4.06,+ 4.6,+ 4.14,+ 4.15,+ 3.96+ ],+ "cpuMs": 43.084,+ "peakRssMiB": 92.66796875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 0,+ "wallSeconds": 1.384,+ "workload": "limit",+ "iterations": 10,+ "unrelated": 4200,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 22.72,+ 14.73,+ 12.73,+ 12.24,+ 11.81,+ 12.91,+ 13.21,+ 11.91,+ 11.87,+ 11.46+ ],+ "cpuMs": 199.827,+ "peakRssMiB": 104.07421875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 1,+ "wallSeconds": 0.371,+ "workload": "claude",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 2.77,+ 0.85,+ 0.86,+ 0.73,+ 0.9,+ 0.85,+ 0.85,+ 0.75,+ 0.9,+ 0.77+ ],+ "cpuMs": 11.455,+ "peakRssMiB": 92.83984375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 1,+ "wallSeconds": 0.372,+ "workload": "claude",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.58,+ 0.2,+ 0.26,+ 0.17,+ 0.16,+ 0.18,+ 0.2,+ 0.15,+ 0.32,+ 0.16+ ],+ "cpuMs": 2.673,+ "peakRssMiB": 96.45703125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 1,+ "wallSeconds": 0.375,+ "workload": "codex",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 3.69,+ 1.26,+ 1.18,+ 1.09,+ 1.15,+ 1.01,+ 0.91,+ 0.92,+ 1.08,+ 0.89+ ],+ "cpuMs": 14.73,+ "peakRssMiB": 95.97265625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 1,+ "wallSeconds": 0.36,+ "workload": "codex",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.49,+ 0.16,+ 0.11,+ 0.11,+ 0.11,+ 0.1,+ 0.1,+ 0.09,+ 0.3,+ 0.13+ ],+ "cpuMs": 1.777,+ "peakRssMiB": 91.52734375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 1,+ "wallSeconds": 0.378,+ "workload": "pi",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 3.55,+ 1.02,+ 1.05,+ 0.9,+ 1.05,+ 0.93,+ 0.98,+ 0.93,+ 0.98,+ 0.92+ ],+ "cpuMs": 13.783,+ "peakRssMiB": 96.2421875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 1,+ "wallSeconds": 0.364,+ "workload": "pi",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.29,+ 0.38,+ 0.42,+ 0.35,+ 0.4,+ 0.31,+ 0.29,+ 0.33,+ 0.43,+ 0.33+ ],+ "cpuMs": 5.148,+ "peakRssMiB": 93.015625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 1,+ "wallSeconds": 0.615,+ "workload": "populated",+ "iterations": 10,+ "unrelated": 1000,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 9.02,+ 7.9,+ 4.66,+ 5.8,+ 4.02,+ 5.51,+ 3.91,+ 3.81,+ 3.94,+ 3.54+ ],+ "cpuMs": 93.314,+ "peakRssMiB": 104.45703125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 1,+ "wallSeconds": 0.588,+ "workload": "populated",+ "iterations": 10,+ "unrelated": 1000,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.43,+ 1.06,+ 1.03,+ 1.03,+ 1.05,+ 1.03,+ 1.03,+ 1,+ 1.2,+ 1.01+ ],+ "cpuMs": 10.957,+ "peakRssMiB": 94.01953125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 1,+ "wallSeconds": 0.402,+ "workload": "duplicate",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 4.49,+ 1.9,+ 1.85,+ 1.82,+ 1.92,+ 1.63,+ 1.53,+ 1.98,+ 1.81,+ 1.74+ ],+ "cpuMs": 25.025,+ "peakRssMiB": 94.0703125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 1,+ "wallSeconds": 0.373,+ "workload": "duplicate",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.49,+ 0.16,+ 0.11,+ 0.12,+ 0.11,+ 0.15,+ 0.13,+ 0.1,+ 0.28,+ 0.12+ ],+ "cpuMs": 1.853,+ "peakRssMiB": 95.79296875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 1,+ "wallSeconds": 0.377,+ "workload": "unavailable",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 3.07,+ 0.93,+ 1,+ 0.88,+ 0.91,+ 0.77,+ 0.84,+ 0.83,+ 0.95,+ 0.76+ ],+ "cpuMs": 14.037,+ "peakRssMiB": 96.30859375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 1,+ "wallSeconds": 0.363,+ "workload": "unavailable",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.52,+ 0.15,+ 0.1,+ 0.15,+ 0.1,+ 0.09,+ 0.09,+ 0.1,+ 0.24,+ 0.11+ ],+ "cpuMs": 1.867,+ "peakRssMiB": 93.09765625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 1,+ "wallSeconds": 1.344,+ "workload": "limit",+ "iterations": 10,+ "unrelated": 4200,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 23.09,+ 14.79,+ 12.79,+ 12.34,+ 11.99,+ 12.6,+ 11.98,+ 11.48,+ 12.18,+ 11.41+ ],+ "cpuMs": 199.384,+ "peakRssMiB": 104.94921875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 1,+ "wallSeconds": 1.31,+ "workload": "limit",+ "iterations": 10,+ "unrelated": 4200,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 4.69,+ 4.16,+ 4.04,+ 4.09,+ 4.11,+ 4.09,+ 4.16,+ 4.55,+ 4.2,+ 4.08+ ],+ "cpuMs": 43.344,+ "peakRssMiB": 96.95703125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 2,+ "wallSeconds": 0.375,+ "workload": "claude",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.6,+ 0.19,+ 0.17,+ 0.14,+ 0.13,+ 0.13,+ 0.2,+ 0.16,+ 0.34,+ 0.17+ ],+ "cpuMs": 2.557,+ "peakRssMiB": 97.49609375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 2,+ "wallSeconds": 0.385,+ "workload": "claude",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 2.95,+ 0.95,+ 0.92,+ 0.74,+ 0.93,+ 0.81,+ 0.9,+ 0.76,+ 0.88,+ 0.72+ ],+ "cpuMs": 11.837,+ "peakRssMiB": 96.18359375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 2,+ "wallSeconds": 0.358,+ "workload": "codex",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.53,+ 0.16,+ 0.11,+ 0.15,+ 0.12,+ 0.1,+ 0.1,+ 0.09,+ 0.27,+ 0.12+ ],+ "cpuMs": 1.816,+ "peakRssMiB": 93.67578125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 2,+ "wallSeconds": 0.389,+ "workload": "codex",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 3.76,+ 1.28,+ 1.2,+ 1.14,+ 1.19,+ 1,+ 1,+ 1.02,+ 1.06,+ 0.94+ ],+ "cpuMs": 15.134,+ "peakRssMiB": 95.109375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 2,+ "wallSeconds": 0.363,+ "workload": "pi",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.27,+ 0.37,+ 0.43,+ 0.42,+ 0.42,+ 0.31,+ 0.32,+ 0.34,+ 0.44,+ 0.34+ ],+ "cpuMs": 5.305,+ "peakRssMiB": 92.58984375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 2,+ "wallSeconds": 0.375,+ "workload": "pi",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 3.39,+ 1.05,+ 1.12,+ 0.94,+ 1.16,+ 0.95,+ 1.02,+ 0.92,+ 1.07,+ 0.91+ ],+ "cpuMs": 14.042,+ "peakRssMiB": 95.5390625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 2,+ "wallSeconds": 0.553,+ "workload": "populated",+ "iterations": 10,+ "unrelated": 1000,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.42,+ 1.05,+ 0.99,+ 0.98,+ 0.99,+ 0.98,+ 0.97,+ 0.98,+ 1.15,+ 0.99+ ],+ "cpuMs": 10.576,+ "peakRssMiB": 92.84375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 2,+ "wallSeconds": 0.63,+ "workload": "populated",+ "iterations": 10,+ "unrelated": 1000,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 9.74,+ 6.94,+ 9.29,+ 6.84,+ 5.6,+ 6.12,+ 5.37,+ 4.9,+ 4.68,+ 4.41+ ],+ "cpuMs": 113.025,+ "peakRssMiB": 106.1953125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 2,+ "wallSeconds": 0.37,+ "workload": "duplicate",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.5,+ 0.16,+ 0.12,+ 0.17,+ 0.13,+ 0.11,+ 0.1,+ 0.1,+ 0.29,+ 0.12+ ],+ "cpuMs": 1.845,+ "peakRssMiB": 95.19921875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 2,+ "wallSeconds": 0.38,+ "workload": "duplicate",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 4.22,+ 1.84,+ 1.73,+ 1.5,+ 1.57,+ 1.36,+ 1.4,+ 1.79,+ 1.47,+ 1.45+ ],+ "cpuMs": 22.326,+ "peakRssMiB": 97.20703125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 2,+ "wallSeconds": 0.362,+ "workload": "unavailable",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 0.55,+ 0.16,+ 0.13,+ 0.18,+ 0.11,+ 0.09,+ 0.09,+ 0.1,+ 0.25,+ 0.11+ ],+ "cpuMs": 2.043,+ "peakRssMiB": 95.68359375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 2,+ "wallSeconds": 0.37,+ "workload": "unavailable",+ "iterations": 10,+ "unrelated": 0,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 3.12,+ 0.87,+ 0.91,+ 0.93,+ 0.89,+ 0.79,+ 0.84,+ 0.88,+ 0.96,+ 0.73+ ],+ "cpuMs": 13.779,+ "peakRssMiB": 96.19921875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "former",+ "commit": "a847441e566cf9c34c960bbd43a5ec8b3ff83e10",+ "repeat": 2,+ "wallSeconds": 1.179,+ "workload": "limit",+ "iterations": 10,+ "unrelated": 4200,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 4.5,+ 4.04,+ 3.91,+ 4.12,+ 3.97,+ 3.96,+ 4.38,+ 3.94,+ 4.07,+ 3.93+ ],+ "cpuMs": 41.908,+ "peakRssMiB": 92.87890625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ },+ {+ "source": "current",+ "commit": "fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea",+ "repeat": 2,+ "wallSeconds": 1.321,+ "workload": "limit",+ "iterations": 10,+ "unrelated": 4200,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 22.97,+ 14.87,+ 12.89,+ 15.62,+ 13.74,+ 12.24,+ 11.58,+ 11.54,+ 11.61,+ 11.76+ ],+ "cpuMs": 205.024,+ "peakRssMiB": 101.5234375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64"+ }+ ]+}diff --git a/docs/research/2026-10-09-exact-resume-pools.md b/docs/research/2026-10-09-exact-resume-pools.mdnew file mode 100644index 000000000..02a531f8a--- /dev/null+++ b/docs/research/2026-10-09-exact-resume-pools.md@@ -0,0 +1,47 @@+# Complete exact transcript lookup++An explicit resume id used a full `readdir` for Pi and Claude, and a synchronous first-match walk for Codex. A failed later home or truncated walk could be reported as absence; a first match could hide a conflicting transcript. Resume after a crash, Stop capture and Pi Close read these facts in core.++The former-main golden is committed separately in `2cb987e24`. Its 18 observations cover default and moved homes, explicit Codex profiles, missing/unsupported ids, Pi custom ids and colliding workspace encodings. Linux, UTC, fixed time, private homes and abstract workspace realpaths are pinned. Host binaries and optional reader loading are forbidden. The initial recording exposed a random temporary-directory name inside Pi's encoded workspace; the corrected fixture uses a fixed abstract workspace and passed before production edits. The JSON artifact is not re-recorded for the move.++`engines/kit/exactTranscript.ts` streams a complete pool under a shared 4,096-operation/entry budget, at most 64 roots and 64 existing candidate files, and a depth bound. A shared two-second work deadline is checked between operations. Native calls themselves are not cancellable: these are work bounds and change detection, not a hard elapsed-time guarantee. Directory aliases are traversed once but each path's evidence is retained. File aliases count once. Missing locations, directory listings, selected and rejected candidates are revalidated; the final bounded metadata check has no native await and checks a selected file last. The check is not an atomic multi-file snapshot.++Claude retains exact filename authority and requires a readable regular file. Codex checks its declared first record's id before accepting a filename match. Pi keeps the existing id and workspace header checks, including the distinction between unwritten and unreadable conversations. Ambiguous, unreadable, oversized or changing pools hold the lookup. Subsequent calls gather fresh evidence. The optional history APIs and the registry's legacy synchronous repair remain separate work; the saved-home catalog still requires its own freshness and failure audit. This change does not claim that those remaining paths are complete.++Validation selects typecheck, architecture, unchanged exact-resume/session-store/repair/native goldens, affected repair/capture/Stop/binding specs, core/services and harnessd coverage, and serial resume coverage. Private bundled missing/stalled Pi lanes verify Close retains a live session on conflicting files and succeeds after evidence recovers. The touched machine crash-resume lanes and moved-home lane run privately. Assertion-failing wiring mutations and matched CPU/latency/RSS measurements precede independent review and automatic CI. No release.++The first focused run found that an older golden pins asynchronous `stat` timestamps for process-age tests, while the new final metadata check reads actual filesystem timestamps. Lookup now obtains actual inode metadata with `lstat`, resolving a final symlink explicitly; the golden and its artifact remain unchanged. Typecheck and all 210 focused assertions then passed. Routine final receipts, failures, review, CI waiting and merge timing are recorded in the PR. Work began with former-code recording at 16:02 UTC on October 9; implementation followed the committed golden at 16:04 UTC. The original request began October 8 at 23:26:41 UTC; publication remains zero.++Independent review of the first implementation found five control gaps: homes adopted during a read, unavailable or changing Pi workspace aliases treated as exclusions, Pi errors losing the retry code through Close/checkpoint, a header read from a different inode while an ancestor alias changed back, and a matching-name Codex child record with no conclusive id. The correction revalidates current homes and canonical workspace proofs, ties an opened header descriptor to its inspected version, preserves typed holds through checkpointing, and gathers Pi identity before writing the screen. Composed queued Close tests use real native files through capture and checkpoint, retain the same waiting plan for partial and duplicate records, preserve all existing checkpoint bytes, and finish without a new request when evidence recovers. These are safety corrections, not golden re-recordings. The golden fixtures map abstract workspaces to private real directories for canonical identity; the JSON artifacts and healthy answers remain unchanged.++The corrective focused run passed all 369 tests; typecheck independently rejected an inferred test fixture array type. That annotation was fixed before final acceptance. No failed or partial run is represented as a passing gate.++The next independent review caught a separate directory-listing alias race: a root or ancestor could point at another directory only while `opendir` opened it, then return before target metadata was checked. The lookup now retains symlink metadata throughout each directory/candidate path and through chained relative or absolute targets, under the same operation/deadline budget and an alias-depth bound. Final synchronous revalidation checks those links before accepting the pool. Three directory-redirection regressions cover root, ancestor and chained-target aliases. The ordinary shared ancestors do not use directory-content stamps, so unrelated activity in the temporary directory is not evidence about this lookup.++The alias correction passed typecheck and 371 of 372 focused tests; the remaining test had assumed enumeration alone consumed every budget slot. Its assertion now checks that the shared bound is respected and the iterator closes, including the slots spent inspecting this private path. Final acceptance follows the main integration containing #1120; no healthy golden artifact changed.++Final review found that lexical normalization of `bridge/../home` could skip a symlink that the filesystem follows before consuming the parent component. The proof now follows link components in filesystem order, with a fourth directory-redirection regression and a successful retry for each alias shape. The earlier integrated head passed all local acceptance (1,942 core, 265 harnessd plus one existing skip, 374 focused tests and 28 private e2e cases); that evidence is limited to its source. The mutation run stopped when the old inspection-error mutation no longer broke the new outer alias guard; it was updated to break the current alias-inspection admission, and the new relative-target regression has its own mutation. Final corrected-source verification follows.++Independent review approved production `fb3e02387` against main `a847441e5` with no remaining blockers. The final production run passed 1,942 core tests, 375 focused tests, 28 private bundled e2e cases and 57 private tmux tests (15 installed-vendor rows excluded). The harnessd gate failed one existing test because its polling reader parsed an incomplete appended JSON line; it now uses that suite's established complete-line reader. This was a test fixture race, not a passing gate. The selected final gates are rerun after that test-only correction.++All 26 fault variants subsequently assertion-failed after a green baseline. The added descriptor test replaces and restores an ordinary ancestor directory around both opens: it proves the descriptor check independently of the alias check, which had also caught the earlier fixture. The production source remains exactly the independently approved implementation; these final changes add regression coverage and fix the observed JSONL fixture race. E2e/tmux evidence still covers identical production source and test lanes.++## Matched runtime cost and final local acceptance++The [raw comparison](2026-10-09-exact-resume-cost.json) records three interleaved fresh processes per source/workload, ten lookups each, on Node 22.23.2 and macOS x64. Former main is `a847441e566cf9c34c960bbd43a5ec8b3ff83e10`; current source is `fa431e3586a7fce896c3a5f8d3f3c6c67d69e6ea`. The former checkout's complete CLI/Store trees were verified identical to that main. Private fixture setup and imports are excluded from lookup CPU/latency; process peak RSS includes them. The embedded driver reproduces all cases. Measurements ran without other local validation from 17:03:05 to 17:03:28 UTC. They are reference measurements, not Linux measurements or numerical performance gates.++| Workload | Median lookup, former → current (ms) | Median CPU per 10 lookups (ms) | Median process peak RSS (MiB) | Current result |+|---|---:|---:|---:|---|+| One Claude transcript | 0.17 → 0.89 | 2.56 → 11.84 | 96.46 → 96.18 | exact |+| One Codex transcript | 0.12 → 1.08 | 1.82 → 15.13 | 93.68 → 95.11 | exact |+| One Pi transcript | 0.40 → 1.05 | 5.30 → 14.04 | 93.02 → 95.54 | exact |+| Codex plus 1,000 unrelated files | 1.03 → 5.79 | 10.96 → 113.03 | 93.48 → 105.40 | exact |+| Two conflicting Codex transcripts | 0.12 → 1.79 | 1.85 → 23.85 | 95.79 → 94.07 | held |+| Unreadable later Claude home | 0.14 → 0.91 | 2.04 → 14.04 | 94.55 → 96.20 | held |+| Codex plus 4,200 unrelated files | 4.10 → 12.29 | 43.08 → 199.83 | 92.88 → 104.07 | held |++Every healthy lookup returned the exact transcript. Every current ambiguous, unavailable or over-limit lookup held; former code returned an unsafe exact result in those cases. The complete-pool checks add measured work: about 0.7–1.0 ms for these single-transcript cases and 4.8 ms with 1,000 unrelated files. This is an explicit cost of fresh complete evidence, not a claim of faster lookup or constant cost.++Final local evidence: typecheck, 377 focused tests, 1,942 core/services tests and 265 harnessd tests with one existing skip passed (`20261009T165856.912427Z-45762`); core/services and harnessd retained required 100% coverage. The unchanged production and lane source passed all 28 private e2e and 57 private tmux cases, excluding 15 installed-vendor rows (`20261009T165253.657816Z-98926`). That receipt also records the subsequently corrected harnessd JSONL failure; it is not described as an all-green receipt. The first serial run passed 356 assertions but missed the already-landed composed Hermes Stop tests in its scope and reached 99.78% branches. Including those existing tests produced 413 passes and 100% statements, branches, functions and lines (`20261009T170140.831767Z-64765`), run alone. All 26 broken-wiring variants assertion-failed.++Independent read-only review approved production `fb3e02387` and final test-only head `fa431e358` against `a847441e5`, with no remaining blockers. Final report review and CI/merge timing are recorded in the PR. Implementation ran after the 16:04 golden through the last production correction at 16:50; test-only work ended at 16:58. Validation and review overlapped that work; final deterministic gates ran 16:58–16:59, complete serial resume 17:01–17:02, and cost 17:03. The original request began October 8 at 23:26:41 UTC. Publication remains zero.