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 native session identity on incomplete evidence (#1114)
Dee138ae6766feb
diff --git a/cli/e2e/enginehomes.e2e.ts b/cli/e2e/enginehomes.e2e.tsindex 795c69c60..4ad4aee0e 100644--- a/cli/e2e/enginehomes.e2e.ts+++ b/cli/e2e/enginehomes.e2e.ts@@ -7,7 +7,7 @@* without the profile. An agent must still bind, take turns and come back after a restart.*/import { execFileSync } from 'node:child_process'-import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'+import { mkdirSync, readFileSync, readdirSync, renameSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { pathToFileURL } from 'node:url'import { afterEach, describe, expect, it, onTestFailed } from 'vitest'@@ -345,6 +345,55 @@ describe('the person\'s engines keeping their data elsewhere', () => {client.close()}, 300_000)+ it('an incomplete native identity holds binding, Stop and Close while readiness and a sibling continue', async () => {+ const d = await IsolatedDaemon.create({ env: { HOOK_INSTALL_ENGINES: 'codex' } }); daemon = d+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`))+ await d.start()+ let client = await LocalClient.connect(d)+ const opened = await client.request('agent_create', { engine: 'terminal', cwd: d.projectsDir }, 60_000)+ expect(opened.error, JSON.stringify(opened)).toBeUndefined()+ const tile = await until('the private terminal tile', async () => {+ const now = await row(client, opened.agent.id); return now?.tmuxPane ? now : null+ })+ client.close()+ await d.stop()+ // Start only in this fixture's private pane while discovery is stopped. No hook can+ // bind before the engine's own record is made incomplete, as during a crashed write.+ await type(d, tile.tmuxPane, 'claude')+ const records = join(d.engineConfig.claudeProjectsDir, '..', 'sessions')+ const path = await until('the private engine process record', () => {+ try { const files = readdirSync(records); return files.length === 1 ? join(records, files[0]) : null }+ catch { return null }+ })+ const complete = readFileSync(path, 'utf8')+ const native = JSON.parse(complete)+ writeFileSync(path, '{')+ await d.start()+ client = await LocalClient.connect(d)+ await until('the binding hold with its reason', () => d.log().includes('binding held · Conversation identity is held: the process record is incomplete'))+ const held = await row(client, tile.id)+ expect(held?.engine).toBe('claude')+ expect(held?.sessionId).toBeFalsy()+ expect(held?.status).toBe('active')+ const sibling = await client.request('agent_create', { engine: 'codex', cwd: d.projectsDir, bypassPermission: true }, 90_000)+ expect(sibling.error, JSON.stringify(sibling)).toBeUndefined()+ await until('the independent sibling to bind', async () => (await row(client, sibling.agent.id))?.sessionId, 45_000)+ const stopped = await client.request('agent_delete', { agentId: tile.id }, 60_000)+ expect(stopped.error, JSON.stringify(stopped)).toBeTruthy()+ const closed = await client.request('agent_close', { agentId: tile.id, sessionId: held!.sessionId,+ createdAt: held!.createdAt, mode: 'now' }, 60_000)+ expect(closed).toMatchObject({ error: 'IDENTITY_UNAVAILABLE', detail: expect.stringContaining('process record is incomplete') })+ expect(IsolatedDaemon.alive(native.pid)).toBe(true)+ expect((await row(client, tile.id))?.status).toBe('active')+ writeFileSync(path + '.complete', complete)+ renameSync(path + '.complete', path)+ await until('the same live process to bind after its record becomes complete', async () => {+ const now = await row(client, tile.id)+ return now?.status === 'active' && now.sessionId === native.sessionId+ }, 60_000, 250)+ client.close()+ }, 240_000)+// A Codex agent in a moved CODEX_HOME, restarted, then stopped and opened again. Its rollout was held to the// daemon's own CODEX_HOME before the relaunch (portableHistory.ts) and refused as outside the profile: the// restart failed after Codex had already been stopped, and the reopen said RESUME_PREPARATION_FAILED. Anddiff --git a/cli/scripts/handoff-2026-10-08/identity-cost.ts b/cli/scripts/handoff-2026-10-08/identity-cost.tsnew file mode 100644index 000000000..38436e365--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/identity-cost.ts@@ -0,0 +1,46 @@+/** Run unchanged against both source trees with node --import tsx. Private native fixtures only. */+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { performance } from 'node:perf_hooks'++const root = mkdtempSync(join(tmpdir(), 'identity-cost-'))+const workload = process.argv[2] ?? 'pool'+if (!['pool', 'process', 'limit', 'homes'].includes(workload)) throw new Error('Unknown workload')+const home = join(root, 'claude')+const cwd = join(root, 'workspace')+mkdirSync(cwd)+Object.assign(process.env, { HOME: join(root, 'home'), ADAPTER_DATA_DIR: join(root, 'data'),+ CLAUDE_PROJECTS_DIR: join(home, 'projects'), CLAUDE_CONFIG_DIR: home, CODEX_HOME: join(root, 'codex'),+ HARNESS_CONNECTIONS_PORT: '0', TZ: 'UTC' })+const put = (path: string, text: string) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text) }+const started = Math.floor(Date.now() / 1000) * 1000+const id = '11111111-2222-4333-8444-555555555555'+const count = workload === 'limit' ? 420 : 160+for (let i = 0; i < count; i++) put(join(home, 'projects', `project-${i % 10}`, `${i === 0 ? id : `other-${i}`}.jsonl`),+ JSON.stringify({ cwd: i === 0 ? cwd : join(root, `other-${i}`), isSidechain: false }) + '\n' + 'x'.repeat(8192))+if ((workload === 'process' || workload === 'homes')) put(join(home, 'sessions', '77.json'), JSON.stringify({ pid: 77,+ procStart: new Date(started).toISOString(), cwd, sessionId: id }))+if (workload === 'homes') put(join(root, 'data', 'engine-homes.json'), JSON.stringify({+ claude: Array.from({ length: 63 }, (_, i) => join(root, `missing-home-${i}`)),+}))+try {+ const { findLiveSession } = await import('../../src/lib/sessionRepair.js')+ const cpu = process.cpuUsage()+ const latencies: number[] = []+ const outcomes: Record<string, number> = {}+ for (let i = 0; i < 10; i++) {+ const begin = performance.now()+ let outcome: string+ try {+ const found = await findLiveSession('claude', cwd, started, (workload === 'process' || workload === 'homes') ? { pid: 77 } : { bornOnly: true })+ outcome = found?.sessionId === id ? 'exact' : found ? 'other' : 'absent'+ } catch (error) { outcome = (error as { code?: string }).code === 'IDENTITY_UNAVAILABLE' ? 'held' : 'error' }+ latencies.push(Math.round((performance.now() - begin) * 100) / 100)+ outcomes[outcome] = (outcomes[outcome] ?? 0) + 1+ }+ const used = process.cpuUsage(cpu)+ console.log(JSON.stringify({ workload, files: count, iterations: 10, outcomes, latenciesMs: latencies,+ 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-bounded-identity.py b/cli/scripts/handoff-2026-10-08/mutate-bounded-identity.pynew file mode 100644index 000000000..248d59f21--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/mutate-bounded-identity.py@@ -0,0 +1,62 @@+"""Break actual native-identity wiring in a disposable worktree; assertions must catch every change."""+import os+from pathlib import Path+import subprocess+import sys++cli = Path(sys.argv[1]).resolve()+bounds = 'src/lib/sessionRepair.bounds.spec.ts'+repair = 'src/lib/sessionRepair.ts'+scan = 'src/engines/kit/identityScan.ts'+golden = 'src/engines/repairIdentity.golden.spec.ts'+close = 'src/lib/closeAgentService.spec.ts'+mutations = [+ ('truncated file pool', repair, "if (out.length >= MAX_FILES) throw new IdentityReadUnavailable('the transcript count limit was reached')", 'if (out.length >= MAX_FILES) continue', bounds),+ ('truncated depth', repair, "if (depth >= MAX_DEPTH) throw new IdentityReadUnavailable('the transcript depth limit was reached')", 'if (depth >= MAX_DEPTH) continue', bounds),+ ('directory buffer bound', scan, 'for await (const entry of directory) {\n if (budget.remaining-- <= 0)', 'for await (const entry of directory) {\n if (budget.remaining-- < -1)', bounds),+ ('unreadable tree treated as absent', scan, "if (missingOkay && (error as NodeJS.ErrnoException).code === 'ENOENT') return", 'return', bounds),+ ('partial header treated as absent', repair, 'if (!cwd || (sidechain && side === undefined && malformed))', 'if (false)', bounds),+ ('permissive Codex reader', repair, 'findSessionFileOf, sessionIdentityMetaOf }', 'findSessionFileOf, sessionMetaOf as sessionIdentityMetaOf }', bounds),+ ('Copilot missing identity ignored', repair, 'if (!root || !isAbsolute(root)) throw new IdentityReadUnavailable(head.complete', 'if (false) throw new IdentityReadUnavailable(head.complete', bounds),+ ('invalid process start accepted', repair, "|| !Number.isFinite(Date.parse(record[rule.start]))", '', bounds),+ ('first home wins', repair, ' result = found\n', ' return found\n', bounds),+ ('authoritative claim read too early', repair, 'const recheck = [...records.filter(record => record.file !== selected), ...records.filter(record => record.file === selected)]', 'const recheck = records', bounds),+ ('home adoption ignored during lookup', repair, "if (repairRoots(engine, opts?.codexHome).join('\\0') !== sessions.join('\\0'))", 'if (false)', bounds),+ ('unbounded known homes', repair, 'if (roots.length > 64)', 'if (false)', bounds),+ ('process claim not rechecked', repair, 'if (await read(file) !== text)', 'if (false)', bounds),+ ('replaced inode accepted', scan, 'const now = await current.stat()', 'const now = before', bounds),+ ('whole-file byte limit ignored', scan, 'if (bytes.length > maxBytes)', 'if (false)', bounds),+ ('Close hold becomes failed', 'src/lib/closeAgentService.ts', "state: result.error === 'IDENTITY_UNAVAILABLE' ? 'waiting' : 'failed'", "state: 'failed'", close),+ ('Muse declaration disconnected', 'src/engines/muse/contract.ts', "'workspace_root'", "'missing_workspace'", golden),+ ('Pi native header disconnected', repair, 'const head = await readPiHead(join(directory, file))', 'const head = null', golden),+]+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}+for name in ['TMUX', 'TMUX_PANE', 'RECORD_REPAIR_IDENTITY_GOLDEN',+ 'RECORD_OTHER_ENGINES_GOLDEN', 'RECORD_SESSION_STORE_GOLDEN']:+ env.pop(name, None)+++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=180)+++baseline = run(list(dict.fromkeys(item[4] for item in mutations)))+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, spec 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([spec])+ 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/scripts/handoff-2026-10-08/mutate-repair-identity.py b/cli/scripts/handoff-2026-10-08/mutate-repair-identity.pyindex ed9db0de1..7fbe576db 100644--- a/cli/scripts/handoff-2026-10-08/mutate-repair-identity.py+++ b/cli/scripts/handoff-2026-10-08/mutate-repair-identity.py@@ -25,7 +25,7 @@ mutations = [('Pi core header disconnected', 'src/lib/sessionRepair.ts', 'const head = await readPiHead(join(directory, file))', 'const head = null', golden),('Muse core identity disconnected', 'src/lib/sessionRepair.ts', 'const identity = await museSessionIdentity(path, root => sameDir(root, cwd))', 'const identity = null', golden),('Muse waits on optional code', 'src/lib/sessionRepair.ts', 'const identity = await museSessionIdentity', "await (await import('../engines/inProcess.js')).loadEngine('muse')\n const identity = await museSessionIdentity", eager),- ('Read bound mistaken for absence', 'src/engines/kit/sessionIdentity.ts', "throw new Error('The conversation identity exceeds the bounded read; discovery is held.')", 'return null', bounded),+ ('Read bound mistaken for absence', 'src/engines/kit/sessionIdentity.ts', "throw new IdentityReadUnavailable('the run identity exceeds the bounded read')", 'return null', bounded),('One hold aborts discovery', 'src/core/agents/bind.ts', 'binding held · ${error instanceof Error ? error.message : error}`)\n return null', 'binding held · ${error instanceof Error ? error.message : error}`)\n throw error', bind),('Stop capture erased by live snapshot', 'src/lib/stoppedAgents.ts', 'session = { ...session, transcriptPath: previous.transcriptPath }', 'session = { ...session, transcriptPath: null }', stop),('Saved path crosses a conversation', 'src/lib/stoppedAgents.ts', 'session.sessionId === previous.sessionId && session.engine === previous.engine', 'session.engine === previous.engine', saved),diff --git a/cli/src/engines/kit/identityScan.ts b/cli/src/engines/kit/identityScan.tsnew file mode 100644index 000000000..bb8fba69a--- /dev/null+++ b/cli/src/engines/kit/identityScan.ts@@ -0,0 +1,92 @@+/** Bounded native evidence. An unfinished lookup cannot prove that a conversation is unique. */+import { constants, type Dirent } 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}.`) }+}++/** 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> {+ 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')+ const length = Math.min(before.size, maxBytes)+ const bytes = Buffer.alloc(length)+ let read = 0+ while (read < length) {+ const next = await handle.read(bytes, read, length - read, read)+ if (!next.bytesRead) throw new IdentityReadUnavailable('the native record ended during the read')+ read += next.bytesRead+ }+ const after = await handle.stat()+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs) {+ throw new IdentityReadUnavailable('the native record changed during the read')+ }+ // Atomic rename leaves the old descriptor perfectly readable. Reopen the path without+ // waiting for a writer and verify that it still names the record we just read.+ const current = await open(path, constants.O_RDONLY | constants.O_NONBLOCK).catch(() => {+ throw new IdentityReadUnavailable('the native record disappeared during the read')+ })+ try {+ const now = await current.stat()+ if (now.dev !== before.dev || now.ino !== before.ino || now.size !== before.size+ || now.mtimeMs !== before.mtimeMs || now.ctimeMs !== before.ctimeMs) {+ throw new IdentityReadUnavailable('the native record was replaced during the read')+ }+ } finally { await current.close() }+ return bytes+ } finally { await handle.close() }+}++/** opendir bounds the directory buffer too; readdir followed by slice would still read the whole tree. */+export async function* identityEntries(path: string, budget: { remaining: number }, missingOkay = true): AsyncGenerator<Dirent> {+ // An empty or missing directory still costs a filesystem operation.+ if (budget.remaining-- <= 0) throw new IdentityReadUnavailable('the directory entry limit was reached')+ let directory+ try { directory = await opendir(path, { bufferSize: 32 }) }+ catch (error) {+ if (missingOkay && (error as NodeJS.ErrnoException).code === 'ENOENT') return+ throw new IdentityReadUnavailable('a session directory could not be read')+ }+ try {+ // The iterator closes the directory on completion, exceptions and early return.+ for await (const entry of directory) {+ if (budget.remaining-- <= 0) throw new IdentityReadUnavailable('the directory entry limit was reached')+ yield entry+ }+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ throw new IdentityReadUnavailable('a session directory could not be read completely')+ }+}++/** Small whole-file identity, never a prefix that could omit a conflicting field. */+export async function identityFile(path: string, maxBytes = 64 * 1024): Promise<string> {+ let bytes: Buffer+ try { bytes = await identityBytes(path, maxBytes + 1) }+ catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') throw error+ throw new IdentityReadUnavailable('the native record could not be read')+ }+ if (bytes.length > maxBytes) throw new IdentityReadUnavailable('the native record exceeds the read limit')+ return bytes.toString('utf8')+}++/** 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 => {+ if (error instanceof IdentityReadUnavailable) throw error+ throw new IdentityReadUnavailable('the native header could not be read')+ })+ const complete = bytes.length <= maxBytes+ const head = bytes.subarray(0, maxBytes).toString('utf8').split('\n')+ if (!complete) head.pop()+ return { lines: head.slice(0, lines), complete: complete && head.length <= lines }+}diff --git a/cli/src/engines/kit/sessionIdentity.spec.ts b/cli/src/engines/kit/sessionIdentity.spec.tsindex 29ed3ca78..add266cf0 100644--- a/cli/src/engines/kit/sessionIdentity.spec.ts+++ b/cli/src/engines/kit/sessionIdentity.spec.ts@@ -25,11 +25,11 @@ it('expands a head for later identity and accepts a complete final line without})it('holds when a run marker lies beyond the bound, instead of ruling out a competing conversation', async () => {const path = pathFor(header + ' '.repeat(200) + '\n' + run)- await expect(readRunIdentity(rule, path, async () => true)).rejects.toThrow('discovery is held')+ await expect(readRunIdentity(rule, path, async () => true)).rejects.toThrow('identity is held')})it('holds when even the first line exceeds the bound', async () => {const path = pathFor(JSON.stringify({ padding: 'x'.repeat(200), header: { cwd: '/work' } }) + '\n' + run)- await expect(readRunIdentity(rule, path, async () => true)).rejects.toThrow('discovery is held')+ await expect(readRunIdentity(rule, path, async () => true)).rejects.toThrow('identity is held')})it('a file from another workspace cannot hold this workspace on a late marker', async () => {const matches = vi.fn(async () => false)@@ -37,12 +37,15 @@ it('a file from another workspace cannot hold this workspace on a late marker',await expect(readRunIdentity(rule, path, matches)).resolves.toBeNull()expect(matches).toHaveBeenCalledExactlyOnceWith('/work')})-it.each(['', 'bad\n', 'null\n', '[]\n', '{"header":[]}\n', header + '{"run":{"kind":"task"}}'])('refuses a complete file without identity: %j', async text => {- await expect(readRunIdentity(rule, pathFor(text), async () => true)).resolves.toBeNull()+it.each(['', 'bad\n', 'null\n', '[]\n', '{"header":[]}\n', header + '{"run":'])('holds an incomplete or invalid identity: %j', async text => {+ await expect(readRunIdentity(rule, pathFor(text), async () => true)).rejects.toThrow('identity is held')+})+it('excludes a complete background task with a valid workspace header', async () => {+ await expect(readRunIdentity(rule, pathFor(header + '{"run":{"kind":"task"}}'), async () => true)).resolves.toBeNull()})it('keeps native I/O failure distinct from an absent run', async () => {const path = pathFor(''); rmSync(path)- await expect(readRunIdentity(rule, path, async () => true)).rejects.toMatchObject({ code: 'ENOENT' })+ await expect(readRunIdentity(rule, path, async () => true)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })await expect(readPiHead(path)).resolves.toBe(UNSETTLED)mkdirSync(path)await expect(readPiHead(path)).resolves.toBe(UNSETTLED)diff --git a/cli/src/engines/kit/sessionIdentity.ts b/cli/src/engines/kit/sessionIdentity.tsindex d8746d2cc..c791edd9b 100644--- a/cli/src/engines/kit/sessionIdentity.ts+++ b/cli/src/engines/kit/sessionIdentity.ts@@ -1,6 +1,6 @@/** Small native identity records needed by session control, independent of optional readers. */-import { resolve } from 'node:path'-import { headBytes } from './continuation.js'+import { isAbsolute, resolve } from 'node:path'+import { identityBytes, IdentityReadUnavailable } from './identityScan.js'export const UNSETTLED: unique symbol = Symbol('unsettled')type Field = readonly string[]@@ -59,18 +59,27 @@ export async function readSessionHeader(rule: SessionHeader, read: (bytes: numbe* if relevant evidence lies beyond it, the caller holds the lookup instead of guessing a sibling. */export async function readRunIdentity(rule: RunIdentity, path: string, matches: (cwd: string) => Promise<boolean>): Promise<{ cwd: string } | null> {for (const bytes of rule.bytes) {- const head = await headBytes(path, bytes + 1)+ const head = await identityBytes(path, bytes + 1).catch(error => {+ if (error instanceof IdentityReadUnavailable) throw error+ throw new IdentityReadUnavailable('the workspace identity could not be read')+ })const complete = head.length <= bytesconst lines = head.subarray(0, bytes).toString('utf8').split('\n')if (!complete) lines.pop()if (!lines.length) continueconst cwd = valueAt(parsed(lines[0]!), rule.cwd)- if (typeof cwd !== 'string' || !cwd || !await matches(cwd)) return null+ if (typeof cwd !== 'string' || !isAbsolute(cwd)) throw new IdentityReadUnavailable('the workspace header is incomplete or invalid')+ if (!await matches(cwd)) return null+ let malformed = falsefor (const line of lines) {const record = parsed(line)+ if (line.trim() && record === null) malformed = trueif (rule.run.every(part => valueAt(record, part.field) === part.value)) return { cwd }}- if (complete) return null+ if (complete) {+ if (malformed) throw new IdentityReadUnavailable('the run identity is incomplete or invalid')+ return null+ }}- throw new Error('The conversation identity exceeds the bounded read; discovery is held.')+ throw new IdentityReadUnavailable('the run identity exceeds the bounded read')}diff --git a/cli/src/engines/kit/sessionRecords.ts b/cli/src/engines/kit/sessionRecords.tsindex 9147d4f8e..3fb7b9419 100644--- a/cli/src/engines/kit/sessionRecords.ts+++ b/cli/src/engines/kit/sessionRecords.ts@@ -5,8 +5,9 @@* path, so every read is bounded.*/import { closeSync, existsSync, openSync, readdirSync, readSync } from 'node:fs'-import { join } from 'node:path'+import { isAbsolute, join } from 'node:path'import type { SessionStoreContract } from '../facets/sessionStore.js'+import { identityHead, IdentityReadUnavailable } from './identityScan.js'type JsonObject = Record<string, unknown>@@ -61,6 +62,39 @@ function valueAt(value: unknown, path: readonly string[]): unknown {return at}+function firstRecordMeta(firstLine: string, first: NonNullable<SessionStoreContract['first']>): SessionMeta | null {+ const record = object(JSON.parse(firstLine))+ if (record?.type !== first.type || !object(valueAt(record, first.id.slice(0, -1)))) return null+ const id = valueAt(record, first.id)+ const cwd = valueAt(record, first.cwd)+ const child = valueAt(record, first.child)+ const parent = valueAt(record, first.parent)+ return {+ id: typeof id === 'string' ? id : '',+ isSubagent: child !== undefined && child !== null,+ parentThreadId: typeof parent === 'string' && parent ? parent : null,+ cwd: typeof cwd === 'string' ? cwd : null,+ }+}++/** 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> {+ try {+ const head = await identityHead(file, Number.MAX_SAFE_INTEGER, first.maxBytes)+ 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)+ if (!meta || (!meta.isSubagent && (!meta.id || !meta.cwd || !isAbsolute(meta.cwd)))) {+ throw new IdentityReadUnavailable('the rollout header is incomplete or invalid')+ }+ return meta+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ throw new IdentityReadUnavailable('the rollout header could not be read completely')+ }+}+/** Read only the first record (the first line with anything on it, within the declared bound). Null for a* file that does not open with the declared record, or cannot be read or parsed. */export function readFirstRecord(file: string, first: NonNullable<SessionStoreContract['first']>): SessionMeta | null {@@ -71,18 +105,7 @@ export function readFirstRecord(file: string, first: NonNullable<SessionStoreConconst bytes = readSync(fd, buffer, 0, buffer.length, 0)const firstLine = buffer.subarray(0, bytes).toString('utf8').split('\n').find((line) => line.trim())if (!firstLine) return null- const record = object(JSON.parse(firstLine))- if (record?.type !== first.type || !object(valueAt(record, first.id.slice(0, -1)))) return null- const id = valueAt(record, first.id)- const cwd = valueAt(record, first.cwd)- const child = valueAt(record, first.child)- const parent = valueAt(record, first.parent)- return {- id: typeof id === 'string' ? id : '',- isSubagent: child !== undefined && child !== null,- parentThreadId: typeof parent === 'string' && parent ? parent : null,- cwd: typeof cwd === 'string' ? cwd : null,- }+ return firstRecordMeta(firstLine, first)} catch {return null} finally {diff --git a/cli/src/engines/otherIdentity.golden.spec.ts b/cli/src/engines/otherIdentity.golden.spec.tsindex 9453e4233..3d2529e9b 100644--- a/cli/src/engines/otherIdentity.golden.spec.ts+++ b/cli/src/engines/otherIdentity.golden.spec.ts@@ -56,11 +56,13 @@ function check(key: string, value: unknown): void {recorded[key] = resultif (!RECORD) expect({ key, result }).toEqual({ key, result: golden[key] })}+const writtenFiles: string[] = []let fileTime = T0/** A file, written, whose modification time is the next tick of a fixed clock: a scan's newest-first order is set. */function file(path: string, text = ''): string {mkdirSync(join(path, '..'), { recursive: true })writeFileSync(path, text)+ writtenFiles.push(path)fileTime += 1000utimesSync(path, fileTime / 1000, fileTime / 1000)return path@@ -240,6 +242,8 @@ describe('where the core finds the other engines\' conversations', () => {it('repairs a live process\'s session: by folder, by store, by its lock, and a resumed Pi conversation', async () => {const since = T0+ // Resolver/binding fixtures model older conversations; repair gets a fresh corpus below.+ for (const path of writtenFiles) utimesSync(path, (T0 - 60_000) / 1000, (T0 - 60_000) / 1000)// Pi, Command Code and Amp name the folder on their first line; Muse its workspace, once a run has opened.file(home('.pi', 'agent', 'sessions', '--work-r--', `2026_${UUID(41)}.jsonl`), `${JSON.stringify({ type: 'session', id: UUID(41), cwd: '/work/r' })}\n`)file(home('.commandcode', 'projects', 'work-r', `${UUID(42)}.jsonl`), `${JSON.stringify({ cwd: '/work/r', sessionId: UUID(42) })}\n`)diff --git a/cli/src/engines/repairIdentities.ts b/cli/src/engines/repairIdentities.tsindex c2cacf536..87439905a 100644--- a/cli/src/engines/repairIdentities.ts+++ b/cli/src/engines/repairIdentities.ts@@ -1,10 +1,10 @@/** Native repair facts available while optional history readers are missing or loading. */import { MUSE_IDENTITY } from './muse/contract.js'import { PI_FOLDER, PI_HEADER } from './pi/contract.js'-import { headBytes } from './kit/continuation.js'+import { identityBytes } from './kit/identityScan.js'import { readRunIdentity, readSessionHeader, sessionFolder, UNSETTLED } from './kit/sessionIdentity.js'export const museSessionIdentity = (path: string, matches: (cwd: string) => Promise<boolean>) => readRunIdentity(MUSE_IDENTITY, path, matches)export const piSessionFolder = (cwd: string): string => sessionFolder(PI_FOLDER, cwd)export const readPiHead = (path: string) => readSessionHeader(PI_HEADER,- async bytes => (await headBytes(path, bytes)).toString('utf8')).catch(() => UNSETTLED)+ async bytes => (await identityBytes(path, bytes)).toString('utf8')).catch(() => UNSETTLED)diff --git a/cli/src/engines/repairIdentity.golden.spec.ts b/cli/src/engines/repairIdentity.golden.spec.tsindex e0bb06c87..7fbfdb52c 100644--- a/cli/src/engines/repairIdentity.golden.spec.ts+++ b/cli/src/engines/repairIdentity.golden.spec.ts@@ -39,7 +39,20 @@ async function check(key: string, run: () => unknown | Promise<unknown>): Promistry { value = await run() } catch (error) { value = { error: (error as Error).message } }if (typeof value === 'symbol') value = '<unsettled>'captured[key] = JSON.parse(JSON.stringify(value ?? null).split(clock.root).join('<root>'))- if (!RECORD) expect({ key, value: captured[key] }).toEqual({ key, value: expected[key] })+ if (!RECORD) {+ // Explicit safety corrections only: keep the former nulls in the artifact, but do not+ // let an incomplete identity remove a possible competitor from a discovery pool.+ const held: Record<string, string> = {+ 'muse:malformed': 'the workspace header is incomplete or invalid',+ 'muse:noWorkspace': 'the workspace header is incomplete or invalid',+ 'muse:wrongEnvelope': 'the workspace header is incomplete or invalid',+ 'muse:incomplete': 'the run identity is incomplete or invalid',+ }+ const reason = held[key]+ if (reason) expect(expected[key], `${key} · former answer`).toBeNull()+ expect({ key, value: captured[key] }).toEqual({ key,+ value: reason ? { error: `Conversation identity is held: ${reason}.` } : expected[key] })+ }}beforeAll(async () => {@@ -86,6 +99,8 @@ it('records which Muse files identify a conversation', async () => {const cwd = `/work/muse/${name}`file(join(root, name, 'session.jsonl'), body(cwd))await check(`muse:${name}`, () => repair.findLiveSession('muse', cwd, clock.time, { bornOnly: true }))+ // A malformed header must not affect later cases; keep spoken for the final age check.+ if (name !== 'spoken') rmSync(join(root, name), { recursive: true, force: true })}file(join(root, 'parent', 'subagent', 'session.jsonl'), lines(header('/work/muse/child'), event('run', 'started')))await check('muse:subagent', () => repair.findLiveSession('muse', '/work/muse/child', clock.time))diff --git a/cli/src/engines/sessionFiles.ts b/cli/src/engines/sessionFiles.tsindex bbd0f9481..ed8b52ab7 100644--- a/cli/src/engines/sessionFiles.ts+++ b/cli/src/engines/sessionFiles.ts@@ -6,7 +6,7 @@*/import { sessionRoots } from '../lib/engineHomes.js'import { continuedIn } from './kit/continuation.js'-import { findSessionFile, readFirstRecord, type SessionMeta } from './kit/sessionRecords.js'+import { findSessionFile, readFirstRecord, readIdentityFirstRecord, type SessionMeta } from './kit/sessionRecords.js'import { sessionStoreOf } from './sessionStoreContracts.js'import type { AgentEngine } from './types.js'@@ -19,6 +19,12 @@ export function sessionMetaOf(engine: AgentEngine | string, path: string): Sessireturn first ? readFirstRecord(path, first) : null}+/** 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> {+ const first = sessionStoreOf(engine)?.first+ return first ? readIdentityFirstRecord(path, first) : null+}+/*** One session file found by its id under `root`, else in each of the engine's sessions folders, without scanning* unbounded history: for an engine whose file name holds the id (`byId.layout: 'walk'`). The daemon's own folderdiff --git a/cli/src/engines/sessionStore.golden.spec.ts b/cli/src/engines/sessionStore.golden.spec.tsindex 0d57ccd23..919c1bcc0 100644--- a/cli/src/engines/sessionStore.golden.spec.ts+++ b/cli/src/engines/sessionStore.golden.spec.ts@@ -384,6 +384,8 @@ async function findCases(): Promise<Record<string, unknown>> {// ------------------------------------------------------------------------------------------- continuationasync function continuationCases(): Promise<Record<string, unknown>> {+ const owned: string[] = []+ const put = (path: string, text: string) => { owned.push(path); write(path, text) }const dir = join(root, 'claude/projects/-work-b')const marker = (id: unknown) => ({ type: 'continued-in', continuedInSessionId: id })const big = 'x'.repeat(300 * 1024)@@ -402,20 +404,23 @@ async function continuationCases(): Promise<Record<string, unknown>> {'empty': '','trailing blank lines': `${JSON.stringify(marker(C))}\n\n \n`,}- write(join(dir, 'a0a0a0a0-0000-4000-8000-a0a0a0a0a0a0.jsonl'), jsonl({ type: 'ai-title' }, { type: 'agent-name' }))+ put(join(dir, 'a0a0a0a0-0000-4000-8000-a0a0a0a0a0a0.jsonl'), jsonl({ type: 'ai-title' }, { type: 'agent-name' }))+ owned.push(join(dir, 'c0c0c0c0-0000-4000-8000-c0c0c0c0c0c0.jsonl'))mkdirSync(join(dir, 'c0c0c0c0-0000-4000-8000-c0c0c0c0c0c0.jsonl'), { recursive: true })- write(join(dir, 'd0d0d0d0-0000-4000-8000-d0d0d0d0d0d0.jsonl'), jsonl({ type: 'file-history-snapshot', big }, { type: 'user' }))- write(join(dir, 'e0e0e0e0-0000-4000-8000-e0e0e0e0e0e0.jsonl'), jsonl({ type: 'mode' }, '{"type":"assistant","x":"\\"user\\""}'))+ put(join(dir, 'd0d0d0d0-0000-4000-8000-d0d0d0d0d0d0.jsonl'), jsonl({ type: 'file-history-snapshot', big }, { type: 'user' }))+ put(join(dir, 'e0e0e0e0-0000-4000-8000-e0e0e0e0e0e0.jsonl'), jsonl({ type: 'mode' }, '{"type":"assistant","x":"\\"user\\""}'))// Past the 256 KiB head and short of twice it, with no turn at all: taken for its length.- write(join(dir, 'f0f0f0f0-0000-4000-8000-f0f0f0f0f0f0.jsonl'), jsonl({ type: 'file-history-snapshot', big }))+ put(join(dir, 'f0f0f0f0-0000-4000-8000-f0f0f0f0f0f0.jsonl'), jsonl({ type: 'file-history-snapshot', big }))const cases: Record<string, unknown> = {}for (const [name, text] of Object.entries(files)) {const path = join(dir, `${name.replace(/[^a-z]+/g, '-')}.jsonl`)- write(path, text)+ put(path, text)cases[name] = await attempt(() => m.stores.continuationOf('claude', path))}cases['missing file'] = await attempt(() => m.stores.continuationOf('claude', join(dir, 'nope.jsonl')))cases['codex'] = await attempt(() => m.stores.continuationOf('codex', join(dir, 'continued-with-a-turn.jsonl')))+ // Continuation bodies are not discovery headers. Do not carry these fixtures into the Linux pass.+ for (const path of owned) rmSync(path, { recursive: true, force: true })return cases}@@ -592,7 +597,21 @@ describe('core finds sessions where it did before Claude Code and Codex declaredexpect(Object.keys(actual), platform).toEqual(Object.keys(golden))for (const [section, cases] of Object.entries(golden)) {expect(Object.keys(actual[section]!).sort(), `${platform} · ${section}`).toEqual(Object.keys(cases).sort())- for (const [key, value] of Object.entries(cases)) expect(actual[section]![key], `${platform} · ${section} · ${key}`).toEqual(value)+ for (const [key, value] of Object.entries(cases)) {+ // Safety correction: an existing unusable process record is not proof of absence. Keep+ // the former artifact intact, assert its exact old answer, and name every changed case.+ const held = new Map<string, string>(['default homes', 'moved homes'].flatMap(home => [+ ...['no id', 'no start', 'unreadable'].map(name => [+ `process record · ${home} · ${name}`, 'the process record is incomplete or invalid',+ ] as const),+ [`process record · ${home} · no transcript`, 'the process names a conversation whose transcript is unavailable'] as const,+ [`process record · ${home} · another folder`, 'the current process record names a different working directory'] as const,+ ]))+ const reason = section === 'find' ? held.get(key) : undefined+ if (reason) expect(value, `${platform} · ${key} · former refusal`).toBeNull()+ expect(actual[section]![key], `${platform} · ${section} · ${key}`)+ .toEqual(reason ? { threw: `Conversation identity is held: ${reason}.` } : value)+ }}}}, 120_000)diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.tsindex 5439a5527..43f5cb1af 100644--- a/cli/src/lib/closeAgentService.spec.ts+++ b/cli/src/lib/closeAgentService.spec.ts@@ -6,6 +6,7 @@ import { mkdirSync, readFileSync, readdirSync, 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'let row: RegisteredSessionlet service: CloseAgentService@@ -65,6 +66,21 @@ it('checkpoint failure retains the session and reports the failure', async () =>expect(await service.request(request())).toMatchObject({ error: 'HISTORY_NOT_SAVED', detail: 'Disk full' })expect(registry.byAgent(row.agentId)).toBe(row)})+it('a queued Close preserves its intent and reason while native identity is unavailable, then retries', async () => {+ vi.mocked(deps.stop).mockRejectedValueOnce(new IdentityReadUnavailable('the process record is incomplete'))+ await expect(service.request(request('after_task'))).resolves.toEqual({ deferred: true })+ const plan = row.closePlan!+ await service.tick()+ time += 5_000+ await service.tick()+ expect(registry.byAgent(row.agentId)?.closePlan).toEqual({ ...plan,+ state: 'waiting', detail: 'Conversation identity is held: the process record is incomplete.' })+ expect(deps.checkpoint).not.toHaveBeenCalled()+ await service.tick()+ expect(deps.stop).toHaveBeenCalledTimes(2)+ expect(deps.checkpoint).toHaveBeenCalledOnce()+ expect(registry.byAgent(row.agentId)).toBeUndefined()+})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/closeAgentService.ts b/cli/src/lib/closeAgentService.tsindex 3a7e70282..017a83524 100644--- a/cli/src/lib/closeAgentService.ts+++ b/cli/src/lib/closeAgentService.ts@@ -216,7 +216,10 @@ export class CloseAgentService {if (result.error && result.error !== 'SESSION_NOT_IDLE') {const latest = this.deps.registry.byAgent(s.agentId)if (latest?.closePlan?.id === plan.id) {- const changed = this.deps.registry.setClosePlan(s.agentId, { ...plan, state: 'failed',+ // Native identity can be between writes. Preserve the queued intent and reason+ // so the next idle tick retries before any checkpoint or process mutation.+ const changed = this.deps.registry.setClosePlan(s.agentId, { ...plan,+ state: result.error === 'IDENTITY_UNAVAILABLE' ? 'waiting' : 'failed',detail: result.detail ?? 'Could not save and close this session. Open it to try again.' })if (changed) this.deps.changed(changed)}diff --git a/cli/src/lib/sessionRepair.bounds.spec.ts b/cli/src/lib/sessionRepair.bounds.spec.tsnew file mode 100644index 000000000..125c9c791--- /dev/null+++ b/cli/src/lib/sessionRepair.bounds.spec.ts@@ -0,0 +1,391 @@+import { execFile, execFileSync } from 'node:child_process'+import { constants } from 'node:buffer'+import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, truncateSync, utimesSync, writeFileSync } 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'+import { identityBytes, identityEntries, identityScanBudget } from '../engines/kit/identityScan.js'+import type { RegisteredSession } from './registry.js'+import type { StopAgentServiceDeps } from './stopAgentService.js'++vi.mock('node:fs/promises', async original => {+ const actual = await original<typeof import('node:fs/promises')>()+ return { ...actual, open: vi.fn(actual.open), opendir: vi.fn(actual.opendir), stat: vi.fn(actual.stat),+ readdir: vi.fn(actual.readdir), readlink: vi.fn(actual.readlink) }+})+vi.mock('node:child_process', async original => {+ const actual = await original<typeof import('node:child_process')>()+ return { ...actual, execFile: vi.fn(actual.execFile) }+})+vi.mock('./tmux.js', async original => ({ ...await original<object>(), processRows: vi.fn() }))+vi.mock('./deleteAgentFallback.js', () => ({ checkPidRuntime: vi.fn(), terminateDeletedAgent: vi.fn() }))++const START = Date.parse('2026-10-09T00:00:00Z')+const CWD = '/workspace'+const SID = '11111111-2222-4333-8444-555555555555'+const OTHER = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'+let root: string+let repair: typeof import('./sessionRepair.js')+const body = (cwd = CWD) => JSON.stringify({ cwd, isSidechain: false }) + '\n'+function file(path: string, text: string, time = START): string {+ mkdirSync(dirname(path), { recursive: true })+ writeFileSync(path, text)+ utimesSync(path, time / 1000, time / 1000)+ return path+}+const transcript = (name = SID, cwd = CWD, time = START) => file(join(root, 'claude', 'projects', 'work', `${name}.jsonl`), body(cwd), time)+const record = (text: string, home = join(root, 'claude')) => file(join(home, 'sessions', '77.json'), text)+const validRecord = (id = SID) => JSON.stringify({ pid: 77, procStart: new Date(START).toISOString(), cwd: CWD, sessionId: id })++beforeEach(async () => {+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.open).mockReset().mockImplementation(actual.open)+ vi.mocked(fs.opendir).mockReset().mockImplementation(actual.opendir)+ vi.mocked(fs.stat).mockReset().mockImplementation(actual.stat)+ vi.mocked(fs.readdir).mockReset().mockImplementation(actual.readdir)+ vi.mocked(fs.readlink).mockReset().mockImplementation(actual.readlink)+ const processes = await vi.importActual<typeof import('node:child_process')>('node:child_process')+ vi.mocked(execFile).mockReset().mockImplementation(processes.execFile)+ root = realpathSync(mkdtempSync(join(tmpdir(), 'identity-bounds-')))+ const homes = { HOME: join(root, 'home'), ADAPTER_DATA_DIR: join(root, 'data'),+ CLAUDE_PROJECTS_DIR: join(root, 'claude', 'projects'), CODEX_HOME: join(root, 'codex'),+ COPILOT_HOME: join(root, 'copilot'), GROK_HOME: join(root, 'grok'), PI_HOME: join(root, 'pi'), MUSE_HOME: join(root, 'muse') }+ for (const [name, value] of Object.entries(homes)) vi.stubEnv(name, value)+ vi.stubEnv('CLAUDE_CONFIG_DIR', '')+ vi.resetModules()+ repair = await import('./sessionRepair.js')+})+afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); rmSync(root, { recursive: true, force: true }) })+const scan = () => repair.findLiveSession('claude', CWD, START, { bornOnly: true })++describe('complete bounded evidence before choosing a conversation', () => {+ it('never makes a hidden second candidate unique by retaining only the newest 400 files', async () => {+ transcript('visible', CWD, START + 2000)+ transcript('hidden', CWD, START)+ for (let i = 0; i < 399; i++) transcript(`other-${i}`, '/elsewhere', START + 1000)+ await expect(scan()).rejects.toThrow('transcript count limit')+ })++ it('shares the file budget across moved homes', async () => {+ const moved = join(root, 'moved')+ for (let i = 0; i < 200; i++) transcript(`other-${i}`, '/elsewhere')+ for (let i = 0; i < 200; i++) file(join(moved, 'projects', 'work', `${i}.jsonl`), body('/elsewhere'))+ transcript('visible')+ const homes = await import('./engineHomes.js')+ homes.adoptEngineHomes({ CLAUDE_CONFIG_DIR: moved }, { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') })+ await expect(scan()).rejects.toThrow('transcript count limit')+ })++ it('holds a shallow candidate if an unknown deeper subtree cannot be inspected', async () => {+ transcript('visible')+ file(join(root, 'claude', 'projects', 'a', 'b', 'c', 'd', 'e', 'hidden.jsonl'), body())+ await expect(scan()).rejects.toThrow('depth limit')+ })++ it('excludes declared subagent folders before applying depth bounds', async () => {+ const path = transcript()+ file(join(root, 'claude', 'projects', 'work', 'subagents', 'a', 'b', 'c', 'd', 'child.jsonl'), body())+ await expect(scan()).resolves.toEqual({ sessionId: SID, transcriptPath: path })+ })++ it('holds on an unreadable subtree and recovers on a later complete scan', async () => {+ const path = transcript()+ const hidden = join(root, 'claude', 'projects', 'unknown'); mkdirSync(hidden)+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ vi.mocked(fs.opendir).mockImplementation(async (path, options) => {+ if (String(path) === hidden) throw Object.assign(new Error('fixture denied'), { code: 'EACCES' })+ return actual.opendir(path, options)+ })+ await expect(scan()).rejects.toThrow('directory could not be read')+ vi.mocked(fs.opendir).mockImplementation(actual.opendir)+ await expect(scan()).resolves.toEqual({ sessionId: SID, transcriptPath: path })+ })++ it('bounds directory iteration itself and closes its iterator on exhaustion', async () => {+ let reads = 0, closed = false+ const directory = { async *[Symbol.asyncIterator]() {+ try { while (true) { reads++; yield { name: `unrelated-${reads}` } } }+ finally { closed = true }+ } }+ vi.mocked(fs.opendir).mockResolvedValueOnce(directory as never)+ await expect((async () => { for await (const _entry of identityEntries('/fixture', identityScanBudget())) { /* consume */ } })())+ .rejects.toThrow('directory entry limit')+ expect(reads).toBe(4096)+ expect(closed).toBe(true)+ expect(fs.opendir).toHaveBeenLastCalledWith('/fixture', { bufferSize: 32 })+ })++ it.each(['read error', 'byte limit', 'line limit', 'unknown sidechain', 'empty', 'partial'])('does not choose a sibling when another header has %s', async mode => {+ transcript('sibling')+ const path = transcript('unknown')+ if (mode === 'empty') file(path, '')+ if (mode === 'partial') file(path, '{"cwd":"/workspace')+ if (mode === 'byte limit') file(path, ' '.repeat(256 * 1024) + body())+ if (mode === 'line limit') file(path, '{}\n'.repeat(20) + body())+ if (mode === 'unknown sidechain') file(path, JSON.stringify({ cwd: CWD }) + '\n' + '{}\n'.repeat(20) + '{"isSidechain":true}\n')+ if (mode === 'read error') {+ 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) === path) throw Object.assign(new Error('fixture denied'), { code: 'EACCES' })+ return actual.open(name, flags, mode)+ })+ }+ await expect(scan()).rejects.toThrow('Conversation identity is held')+ })++ it('can exclude a confirmed different cwd without reading its remaining history', async () => {+ const path = transcript()+ file(join(root, 'claude', 'projects', 'other.jsonl'), JSON.stringify({ cwd: '/elsewhere' }) + '\n' + 'x'.repeat(2 * 1024 * 1024))+ await expect(scan()).resolves.toEqual({ sessionId: SID, transcriptPath: path })+ })++ it.each(['claude', 'codex', 'codex-profile'])('rechecks %s home authority after an awaited native lookup', async mode => {+ const moved = join(root, 'new-home')+ const homes = await import('./engineHomes.js')+ const codex = mode !== 'claude'+ const header = (id: string) => JSON.stringify({ type: 'session_meta', payload: { id, cwd: CWD } }) + '\n'+ const own = codex ? file(join(root, 'codex', 'sessions', `rollout-${SID}.jsonl`), header(SID)) : transcript()+ const other = codex ? file(join(moved, 'sessions', `rollout-${OTHER}.jsonl`), header(OTHER))+ : file(join(moved, 'projects', 'work', `${OTHER}.jsonl`), body())+ if (codex) {+ // Both native OS paths are fixtures; never inspect an actual process's descriptors.+ vi.mocked(fs.readdir).mockResolvedValueOnce(['0', '1'] as never)+ vi.mocked(fs.readlink).mockResolvedValueOnce(own).mockResolvedValueOnce(other)+ vi.mocked(execFile).mockImplementationOnce(((...args: unknown[]) => {+ (args.at(-1) as (error: null, out: string, err: string) => void)(null, `n${own}\nn${other}\n`, '')+ return {}+ }) as never)+ }+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ let adopted = false+ vi.mocked(fs.open).mockImplementation(async (name, flags, mode) => {+ if (String(name) === own && !adopted) {+ adopted = true+ homes.adoptEngineHomes(codex ? { CODEX_HOME: moved } : { CLAUDE_CONFIG_DIR: moved },+ { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') })+ }+ return actual.open(name, flags, mode)+ })+ const result = codex ? repair.findLiveSession('codex', CWD, START,+ { pid: 77, ...(mode === 'codex-profile' ? { codexHome: join(root, 'codex') } : {}) }) : scan()+ if (mode === 'codex-profile') await expect(result).resolves.toEqual({ sessionId: SID, transcriptPath: own })+ else await expect(result).rejects.toThrow('known session homes changed')+ expect(adopted).toBe(true)+ })+})++describe('bounded native metadata', () => {+ it.each(['empty', 'partial', 'line limit'])('holds Copilot with a %s competing header', async mode => {+ const header = JSON.stringify({ type: 'session.start', data: { context: { cwd: CWD } } }) + '\n'+ file(join(root, 'copilot', 'session-state', SID, 'events.jsonl'), header)+ file(join(root, 'copilot', 'session-state', OTHER, 'events.jsonl'), mode === 'empty' ? ''+ : mode === 'partial' ? '{"type":"session.start","data":' : '{}\n'.repeat(5) + header)+ await expect(repair.findLiveSession('copilot', CWD, START)).rejects.toThrow('identity is held')+ })++ it.each(['empty', 'partial', 'oversized', 'read error'])('holds Codex with a %s competing rollout, including process-owned files', async mode => {+ const home = join(root, 'codex', 'sessions')+ const header = (id: string) => JSON.stringify({ type: 'session_meta', payload: { id, cwd: CWD } }) + '\n'+ const own = file(join(home, `rollout-${SID}.jsonl`), header(SID))+ const other = file(join(home, `rollout-${OTHER}.jsonl`), mode === 'empty' ? ''+ : mode === 'partial' ? '{"type":"session_meta","payload":' : ' '.repeat(128 * 1024) + header(OTHER))+ if (mode === 'read error') {+ 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) === other) throw Object.assign(new Error('fixture denied'), { code: 'EACCES' })+ return actual.open(name, flags, mode)+ })+ }+ await expect(repair.findLiveSession('codex', CWD, START)).rejects.toThrow('identity is held')+ await expect(repair.openFileSessionOf('codex', 77, home, CWD, async () => [own, other])).rejects.toThrow('identity is held')+ })++ it.each(['empty', 'workspace', 'run'])('holds Muse with a partly written %s identity beside a complete run', async mode => {+ const base = join(root, 'muse', 'sessions', '2026', '10', '09')+ const header = JSON.stringify({ payload: { record: { workspace_root: CWD } } }) + '\n'+ const run = JSON.stringify({ payload: { kind: 'run', event: { kind: 'started' } } }) + '\n'+ file(join(base, SID, 'session.jsonl'), header + run)+ file(join(base, OTHER, 'session.jsonl'), mode === 'empty' ? '' : mode === 'workspace' ? '{"payload":' : header + '{"payload":')+ await expect(repair.findLiveSession('muse', CWD, START)).rejects.toThrow('identity is held')+ })++ it('reads Copilot opening records without loading a history larger than a JS string', async () => {+ const path = file(join(root, 'copilot', 'session-state', SID, 'events.jsonl'),+ JSON.stringify({ type: 'session.start', data: { context: { cwd: CWD } } }) + '\n')+ truncateSync(path, constants.MAX_STRING_LENGTH + 4096)+ await expect(repair.findLiveSession('copilot', CWD, START)).resolves.toEqual({ sessionId: SID, transcriptPath: path })+ })++ it('holds Copilot when its first identity record exceeds the bounded prefix', async () => {+ file(join(root, 'copilot', 'session-state', SID, 'events.jsonl'), ' '.repeat(256 * 1024) + JSON.stringify({ type: 'session.start', data: { context: { cwd: CWD } } }))+ await expect(repair.findLiveSession('copilot', CWD, START)).rejects.toThrow('header exceeds the read limit')+ })++ it('rejects an oversized Grok sidecar instead of matching a truncated directory', async () => {+ const group = join(root, 'grok', 'sessions', 'hashed')+ file(join(group, SID, 'updates.jsonl'), '{}\n')+ file(join(group, '.cwd'), CWD + ' '.repeat(64 * 1024))+ await expect(repair.findLiveSession('grok', CWD, START)).rejects.toThrow('native record exceeds')+ })++ it.each(['missing', 'relative'])('holds a Grok hash folder with a %s working directory', async mode => {+ file(join(root, 'grok', 'sessions', encodeURIComponent(CWD), SID, 'updates.jsonl'), '{}\n')+ const group = join(root, 'grok', 'sessions', 'hashed')+ file(join(group, OTHER, 'updates.jsonl'), '{}\n')+ if (mode === 'relative') file(join(group, '.cwd'), 'relative')+ await expect(repair.findLiveSession('grok', CWD, START)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ })++ it('holds a native record removed between opening and verifying its path', async () => {+ const path = record(validRecord())+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ const handle = await actual.open(path, 'r')+ const original = handle.read.bind(handle)+ vi.spyOn(handle, 'read').mockImplementationOnce((async (...args: Parameters<typeof handle.read>) => {+ const result = await Reflect.apply(original, handle, args)+ rmSync(path)+ return result+ }) as typeof handle.read)+ vi.mocked(fs.open).mockResolvedValueOnce(handle)+ await expect(repair.processSessionOf('claude', 77, CWD, START)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })+ expect(handle.fd).toBe(-1)+ })++ it.each(['malformed', 'oversized', 'read error', 'missing transcript'])('does not fall back to a sibling after a %s process record', async mode => {+ transcript(OTHER)+ const path = record(mode === 'malformed' ? '{' : mode === 'oversized' ? validRecord() + ' '.repeat(64 * 1024) : validRecord())+ if (mode === 'read error') {+ 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) === path) throw Object.assign(new Error('fixture denied'), { code: 'EACCES' })+ return actual.open(name, flags, mode)+ })+ }+ await expect(repair.findLiveSession('claude', CWD, START, { pid: 77 })).rejects.toThrow('Conversation identity is held')+ })++ it.each(['unreadable', 'conflicting'])('does not accept the first home before checking a %s moved-home record', async mode => {+ transcript(); record(validRecord())+ const moved = join(root, 'moved')+ file(join(moved, 'projects', 'work', `${OTHER}.jsonl`), body())+ record(mode === 'unreadable' ? '{' : validRecord(OTHER), moved)+ const homes = await import('./engineHomes.js')+ homes.adoptEngineHomes({ CLAUDE_CONFIG_DIR: moved }, { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') })+ await expect(repair.processSessionOf('claude', 77, CWD, START)).rejects.toThrow('Conversation identity is held')+ })++ it.each([{ procStart: '' }, { procStart: 'garbage' }, { cwd: '' }, { cwd: 'relative' }, { cwd: '/another/workspace' }])(+ 'does not fall back after invalid or contradictory current process evidence %j', async fields => {+ transcript(OTHER)+ record(JSON.stringify({ ...JSON.parse(validRecord()), ...fields }))+ await expect(repair.findLiveSession('claude', CWD, START, { pid: 77 })).rejects.toThrow('identity is held')+ })++ it.each(['initial', 'validation'])('rechecks the authoritative claim after later homes in the %s pass', async pass => {+ transcript(); transcript(OTHER)+ const first = record(validRecord())+ const moved = join(root, 'moved')+ const later = record(JSON.stringify({ ...JSON.parse(validRecord()), pid: 88 }), moved)+ const homes = await import('./engineHomes.js')+ homes.adoptEngineHomes({ CLAUDE_CONFIG_DIR: moved }, { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') })+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ let reads = 0+ vi.mocked(fs.open).mockImplementation(async (name, flags, mode) => {+ if (String(name) === later && ++reads === (pass === 'initial' ? 1 : 3)) writeFileSync(first, validRecord(OTHER))+ return actual.open(name, flags, mode)+ })+ await expect(repair.processSessionOf('claude', 77, CWD, START)).rejects.toThrow('process records changed')+ })++ it.each(['scan', 'process'])('bounds %s probes even when every saved home is missing', async kind => {+ file(join(root, 'data', 'engine-homes.json'), JSON.stringify({+ claude: Array.from({ length: 65 }, (_, i) => join(root, `missing-${i}`)),+ }))+ await expect(kind === 'scan' ? scan() : repair.processSessionOf('claude', 77, CWD, START))+ .rejects.toThrow('known session-home limit')+ expect(fs.opendir).not.toHaveBeenCalled()+ expect(fs.open).not.toHaveBeenCalled()+ })++ it('holds when the saved home set changes while the authoritative record is rechecked', async () => {+ transcript(); const path = record(validRecord())+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ let reads = 0+ vi.mocked(fs.open).mockImplementation(async (name, flags, mode) => {+ if (String(name) === path && ++reads === 3) {+ file(join(root, 'data', 'engine-homes.json'), JSON.stringify({ claude: [join(root, 'new-home')] }))+ }+ return actual.open(name, flags, mode)+ })+ await expect(repair.processSessionOf('claude', 77, CWD, START)).rejects.toThrow('known session homes changed')+ })++ it('rejects an atomically replaced identity even when its old descriptor stays readable', async () => {+ const path = file(join(root, 'record'), 'before')+ const replacement = file(join(root, 'replacement'), 'after!')+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ const handle = await actual.open(path, 'r')+ let opened = false+ vi.mocked(fs.open).mockImplementation(async (name, flags, mode) => {+ if (String(name) === path) {+ if (!opened) { opened = true; return handle }+ renameSync(replacement, path)+ }+ return actual.open(name, flags, mode)+ })+ await expect(identityBytes(path, 64)).rejects.toThrow(/changed during|replaced during/)+ expect(handle.fd).toBe(-1)+ })++ it('rejects nonregular native records without waiting for a FIFO writer', async () => {+ const path = join(root, 'fifo')+ execFileSync('mkfifo', [path])+ await expect(identityBytes(path, 64)).rejects.toThrow('not a regular file')+ })++ it('rejects a file changing or ending during the read and closes the descriptor', async () => {+ const path = file(join(root, 'record'), 'complete')+ const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')+ for (const mode of ['changed', 'ended']) {+ const handle = await actual.open(path, 'r')+ const original = handle.read.bind(handle)+ vi.spyOn(handle, 'read').mockImplementationOnce((async (...args: Parameters<typeof handle.read>) => {+ if (mode === 'ended') return { bytesRead: 0, buffer: args[0] }+ const result = await Reflect.apply(original, handle, args)+ writeFileSync(path, 'changed and longer')+ return result+ }) as typeof handle.read)+ vi.mocked(fs.open).mockResolvedValueOnce(handle)+ await expect(identityBytes(path, 64)).rejects.toThrow(mode === 'changed' ? 'changed during' : 'ended during')+ expect(handle.fd).toBe(-1)+ }+ })+})++it.each(['Stop', 'checkpointed Stop'])('%s holds before saving, signalling or retiring when real native identity is incomplete', async action => {+ transcript(OTHER); record('{')+ const row = { agentId: 'fixture-agent', engine: 'claude', sessionId: '', cwd: CWD, registeredAt: 1,+ runtimes: [{ backend: 'tmux', paneId: '%77' }],+ processIdentity: { pid: 77, executable: 'claude', startMarker: new Date(START).toISOString() },+ } as RegisteredSession+ const tmux = await import('./tmux.js')+ vi.mocked(tmux.processRows).mockResolvedValue([{ ...row.processIdentity!, parentPid: 1, args: 'claude' }])+ const { AgentRestartCoordinator } = await import('./restartAgent.js')+ const { createStopAgentService } = await import('./stopAgentService.js')+ const { terminateDeletedAgent } = await import('./deleteAgentFallback.js')+ const checkpoint = vi.fn(), save = vi.fn()+ const deps: StopAgentServiceDeps = {+ registry: { resolve: () => row }, stoppedAgents: { save } as unknown as StopAgentServiceDeps['stoppedAgents'],+ restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(), tmuxBackend: { kill: vi.fn() },+ agentReconciler: { suppress: vi.fn(), holdRoute: vi.fn(), releaseRoute: vi.fn(), trigger: vi.fn() },+ forgetSession: vi.fn(), markDeleted: vi.fn(), clearDeleted: vi.fn(), stopNative: vi.fn(),+ }+ await expect(createStopAgentService(deps)(row.agentId, action === 'checkpointed Stop' ? { checkpoint } : {}))+ .rejects.toThrow('process record is incomplete')+ expect(save).not.toHaveBeenCalled(); expect(checkpoint).not.toHaveBeenCalled()+ expect(deps.stopNative).not.toHaveBeenCalled(); expect(terminateDeletedAgent).not.toHaveBeenCalled()+ expect(deps.tmuxBackend!.kill).not.toHaveBeenCalled(); expect(deps.forgetSession).not.toHaveBeenCalled()+ expect(deps.markDeleted).not.toHaveBeenCalled(); expect(deps.registry.resolve(row.agentId)).toBe(row)+ expect(deps.stopJobs.size).toBe(0)+})diff --git a/cli/src/lib/sessionRepair.metadata.spec.ts b/cli/src/lib/sessionRepair.metadata.spec.tsindex 2b3c7066c..6ecc1cc19 100644--- a/cli/src/lib/sessionRepair.metadata.spec.ts+++ b/cli/src/lib/sessionRepair.metadata.spec.ts@@ -13,7 +13,7 @@ vi.mock('fs/promises', async importOriginal => {const LIMIT = 256 * 1024const CWD = '/fixture/工作/📘'-const META = JSON.stringify({ type: 'session', cwd: CWD })+const META = JSON.stringify({ type: 'session', cwd: CWD, isSidechain: false })let directory: stringbeforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'repair-meta-')) })afterEach(() => {@@ -51,7 +51,7 @@ describe('bounded session metadata discovery', () => {it.each([19, 20])('keeps the 20-line limit with %i bookkeeping lines', async count => {const { read } = await fixture(Array(count).fill('{}').join('\n') + '\n' + META + '\n')if (count === 19) await expect(read()).resolves.toMatchObject({ sessionId: 'session-id' })- else await expect(read()).resolves.toBeNull()+ else await expect(read()).rejects.toThrow('header exceeds the read limit')})it.each([0, 1])('keeps the UTF-16 character boundary with metadata ending %i characters after the limit', async overflow => {@@ -61,7 +61,7 @@ describe('bounded session metadata discovery', () => {expect(Buffer.byteLength(text)).toBeGreaterThan(LIMIT)const { read } = await fixture(text)if (overflow === 0) await expect(read()).resolves.toMatchObject({ sessionId: 'session-id' })- else await expect(read()).resolves.toBeNull()+ else await expect(read()).rejects.toThrow('header exceeds the read limit')})it('keeps the first declared directory authoritative', async () => {@@ -85,7 +85,7 @@ describe('bounded session metadata discovery', () => {try {await expect(read()).resolves.toMatchObject({ sessionId: 'session-id' })expect(reads).toHaveBeenCalledTimes(1)- expect(reads.mock.calls[0].slice(1)).toEqual([0, LIMIT * 4, 0])+ expect(reads.mock.calls[0].slice(1)).toEqual([0, LIMIT * 4 + 1, 0])expect(handle.fd).toBe(-1)} finally { if (handle.fd !== -1) await handle.close() }})@@ -104,26 +104,26 @@ describe('bounded session metadata discovery', () => {} finally { if (handle.fd !== -1) await handle.close() }})- it('returns no binding and closes the handle after a read error', async () => {+ it('holds identity and closes the handle after a read error', async () => {const { path, read } = await fixture(META + '\n')const actual = await vi.importActual<typeof import('fs/promises')>('fs/promises')const handle = await actual.open(path, 'r')vi.spyOn(handle, 'read').mockRejectedValueOnce(new Error('fixture read failure'))vi.mocked(fs.open).mockResolvedValueOnce(handle)try {- await expect(read()).resolves.toBeNull()+ await expect(read()).rejects.toThrow('header could not be read')expect(handle.fd).toBe(-1)} finally { if (handle.fd !== -1) await handle.close() }})- it('stops and closes the handle if the file reaches EOF before its stated size', async () => {+ it('holds and closes the handle if the file reaches EOF before its stated size', async () => {const { path, read } = await fixture(META + '\n')const actual = await vi.importActual<typeof import('fs/promises')>('fs/promises')const handle = await actual.open(path, 'r')vi.spyOn(handle, 'read').mockResolvedValueOnce({ bytesRead: 0, buffer: Buffer.alloc(0) })vi.mocked(fs.open).mockResolvedValueOnce(handle)try {- await expect(read()).resolves.toBeNull()+ await expect(read()).rejects.toThrow('record ended during the read')expect(handle.fd).toBe(-1)} finally { if (handle.fd !== -1) await handle.close() }})diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.tsindex ef51da287..80f3bfeb8 100644--- a/cli/src/lib/sessionRepair.spec.ts+++ b/cli/src/lib/sessionRepair.spec.ts@@ -291,15 +291,15 @@ describe('session repair — Claude subagent transcripts, verifier cases', () =>.resolves.toEqual({ sessionId: 'fork-sess', transcriptPath: fork })})- it('reads only the opening for the flag: a sidechain record past the scanned lines does not hide a main session', async () => {+ it('holds when the opening does not settle the sidechain flag before the read limit', async () => {const root = join(tempRoot(), 'projects')const opening = Array.from({ length: 25 }, (_, i) => ({ type: 'x-mode', i }))- const file = write(root, 'proj/long-sess.jsonl',+ write(root, 'proj/long-sess.jsonl',lines({ type: 'summary' }, { type: 'user', cwd: CWD }, ...opening, { type: 'user', isSidechain: true, cwd: CWD }),STARTED_AT + 10_000)const { findLiveSession } = await load(root)await expect(findLiveSession('claude', CWD, STARTED_AT, { bornOnly: true }))- .resolves.toEqual({ sessionId: 'long-sess', transcriptPath: file })+ .rejects.toThrow('header exceeds the read limit')})it('takes the cwd from a later record when the flagged opening carries none', async () => {@@ -835,7 +835,10 @@ it.each(['bad pid', 'bad start', 'missing file', 'bad json', 'different pid', 'dif (mode === 'invalid id') record.sessionId = '../escape'mkdirSync(join(home, 'sessions'))if (mode !== 'missing file') writeFileSync(join(home, 'sessions', '77.json'), mode === 'bad json' ? '{' : JSON.stringify(record))- expect(await processSessionOf('claude', mode === 'bad pid' ? -1 : 77, CWD, mode === 'bad start' ? NaN : STARTED_AT)).toBeNull()+ const result = processSessionOf('claude', mode === 'bad pid' ? -1 : 77, CWD, mode === 'bad start' ? NaN : STARTED_AT)+ if (['bad json', 'different cwd', 'missing start', 'missing cwd', 'missing id', 'invalid id', 'missing history'].includes(mode)) {+ await expect(result).rejects.toThrow('Conversation identity is held')+ } else await expect(result).resolves.toBeNull()})/**diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex 80463cb3a..6a141d82c 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -15,12 +15,12 @@*/import { execFile } from 'child_process'-import { readdir, readFile, readlink, realpath, stat } from 'fs/promises'-import { basename, dirname, join, relative, sep } from 'path'+import { readdir, readlink, realpath, stat } from 'fs/promises'+import { basename, dirname, isAbsolute, join, sep } from 'path'import { env } from '../config/env.js'import type { SessionStoreContract } from '../engines/facets/sessionStore.js'-import { headBytes } from '../engines/kit/continuation.js'-import { findSessionFileOf, sessionMetaOf } from '../engines/sessionFiles.js'+import { identityBytes, identityEntries, identityFile, identityHead, identityScanBudget, IdentityReadUnavailable } from '../engines/kit/identityScan.js'+import { findSessionFileOf, sessionIdentityMetaOf } from '../engines/sessionFiles.js'import { sessionStoreOf } from '../engines/sessionStoreContracts.js'import type { AgentEngine } from '../engines/types.js'import { HERMES_HOMES, hermesDbPath } from '../engines/hermes/contract.js'@@ -49,6 +49,13 @@ const START_SLACK_MS = 5_000const MAX_DEPTH = 4const MAX_FILES = 400+/** Known empty homes still require native probes. Do not let a saved catalog bypass the walk bound. */+function repairRoots(engine: AgentEngine, profile?: string): string[] {+ const roots = sessionRoots(engine, profile)+ if (roots.length > 64) throw new IdentityReadUnavailable('the known session-home limit was reached')+ return roots+}+export interface RepairedSession {sessionId: string/** File-backed engines only; the DB-backed ones are read by session id. */@@ -59,22 +66,27 @@ export interface RepairedSession {interface TranscriptFile { path: string; mtimeMs: number; birthMs: number }-/** Every `.jsonl` under `root`, newest first, capped. Checkpoint/sidecar files are not transcripts. */-async function transcripts(root: string, depth = 0): Promise<TranscriptFile[]> {- if (depth > MAX_DEPTH) return []- let entries- try { entries = await readdir(root, { withFileTypes: true }) } catch { return [] }- const out: TranscriptFile[] = []- for (const entry of entries) {+/** Collect a complete bounded pool. Truncation must never make two conversations look like one. */+async function transcripts(root: string, budget: { remaining: number }, out: TranscriptFile[], excluded?: string, depth = 0): Promise<void> {+ for await (const entry of identityEntries(root, budget, depth === 0)) {const full = join(root, entry.name)- if (entry.isDirectory()) { out.push(...await transcripts(full, depth + 1)); continue }+ if (entry.isDirectory()) {+ if (entry.name === excluded) continue+ if (depth >= MAX_DEPTH) throw new IdentityReadUnavailable('the transcript depth limit was reached')+ await transcripts(full, budget, out, excluded, depth + 1)+ continue+ }if (!entry.name.endsWith('.jsonl') || entry.name.includes('.checkpoints.')) continue+ if (out.length >= MAX_FILES) throw new IdentityReadUnavailable('the transcript count limit was reached')try {const info = await stat(full)+ if (!info.isFile()) throw new IdentityReadUnavailable('a transcript is not a regular file')out.push({ path: full, mtimeMs: info.mtimeMs, birthMs: info.birthtimeMs || info.mtimeMs })- } catch { /* vanished mid-scan */ }+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ throw new IdentityReadUnavailable('a transcript could not be inspected')+ }}- return out.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, MAX_FILES)}/**@@ -93,24 +105,39 @@ const CWD_SCAN_CHARS = 256 * 1024* store declares it: `scan.sidechain`). One bounded read (256 KB — transcripts run to hundreds of MB) shared by* every file engine that declares its cwd in-file. Without a flag it stops at the first cwd, exactly as it always did.*/-async function readTranscriptHead(path: string, sidechain: string | null): Promise<{ cwd: string; side: boolean | undefined } | null> {+async function readTranscriptHead(path: string, sidechain: string | null, requestedCwd?: string): Promise<{ cwd: string; side: boolean | undefined } | null> {try {// Preserve the existing UTF-16 character budget, including non-ASCII paths. Four// UTF-8 bytes per code unit is sufficient even when the cutoff splits a surrogate// pair; a byte budget equal to the character budget would silently shrink the scan.- const head = (await headBytes(path, CWD_SCAN_CHARS * 4)).toString('utf-8').slice(0, CWD_SCAN_CHARS)+ const bytes = await identityBytes(path, CWD_SCAN_CHARS * 4 + 1)+ const text = bytes.subarray(0, CWD_SCAN_CHARS * 4).toString('utf-8')+ const head = text.slice(0, CWD_SCAN_CHARS)+ const complete = bytes.length <= CWD_SCAN_CHARS * 4 && text.length <= CWD_SCAN_CHARS+ && head.split('\n').length <= CWD_SCAN_LINESlet cwd = ''let side: boolean | undefined+ let malformed = falsefor (const line of head.split('\n', CWD_SCAN_LINES)) {if (!line.trim()) continuelet obj: Record<string, unknown>- try { obj = JSON.parse(line) as Record<string, unknown> } catch { continue }+ try { obj = JSON.parse(line) as Record<string, unknown> } catch { malformed = true; continue }+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) { malformed = true; continue }if (!cwd && typeof obj.cwd === 'string' && obj.cwd) cwd = obj.cwd+ if (cwd && !isAbsolute(cwd)) throw new IdentityReadUnavailable('the transcript working directory is invalid')if (sidechain && side === undefined && typeof obj[sidechain] === 'boolean') side = obj[sidechain] as boolean- if (cwd && (!sidechain || side !== undefined)) break+ if (cwd && requestedCwd && !await sameDir(cwd, requestedCwd)) return { cwd, side }+ if (side === true || (cwd && (!sidechain || side !== undefined))) return { cwd, side }+ }+ if (!complete) throw new IdentityReadUnavailable('the transcript header exceeds the read limit')+ if (!cwd || (sidechain && side === undefined && malformed)) {+ throw new IdentityReadUnavailable('the transcript header is incomplete or invalid')}return { cwd, side }- } catch { return null }+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ throw new IdentityReadUnavailable('a transcript header could not be read')+ }}async function readTranscriptMeta(path: string): Promise<TranscriptMeta | null> {@@ -132,19 +159,19 @@ async function readTranscriptMeta(path: string): Promise<TranscriptMeta | null>* `first`: the file's first record (engines/sessionFiles.ts), whose id is the session's (the file name only holds* it), and never a child's: a subagent's rollout must never become an agent of its own.*/-function scanMeta(engine: AgentEngine, scan: SessionStoreContract['scan']): (path: string) => Promise<TranscriptMeta | null> {+function scanMeta(engine: AgentEngine, scan: SessionStoreContract['scan'], cwd: string): (path: string) => Promise<TranscriptMeta | null> {if (scan.from === 'first') {return async (path) => {- const meta = sessionMetaOf(engine, path)+ const meta = await sessionIdentityMetaOf(engine, path)return meta && !meta.isSubagent ? { cwd: meta.cwd, sessionId: meta.id || undefined } : null}}return async (path) => {// Relative to the sessions folder it is under (the daemon's own, or a moved home's): that folder itself may// legitimately sit under a folder of the child's name.- const root = sessionRoots(engine).find((one) => !relative(one, path).startsWith('..'))- if (root !== undefined && relative(root, path).split(sep).includes(scan.childFolder)) return null- const head = await readTranscriptHead(path, scan.sidechain)+ // The bounded walk already excludes childFolder below each root. Reading the home+ // catalog again here would make every transcript reopen an unrelated configuration.+ const head = await readTranscriptHead(path, scan.sidechain, cwd)return head && head.side !== true && head.cwd ? { cwd: head.cwd } : null}}@@ -189,14 +216,18 @@ async function fileEngineSession(cwd: string,startedAtMs: number,readMeta: (path: string) => Promise<TranscriptMeta | null>,- opts?: { bornOnly?: boolean },+ opts?: { bornOnly?: boolean; excludedDirectory?: string },): Promise<RepairedSession | null> {const since = startedAtMs - START_SLACK_MSconst born: RepairedSession[] = []const wrote: RepairedSession[] = []// Several roots are one pool, newest first: one conversation in each of two homes is two agents, as in one.- const files = typeof root === 'string' ? await transcripts(root)- : (await Promise.all(root.map((one) => transcripts(one)))).flat().sort((a, b) => b.mtimeMs - a.mtimeMs)+ const files: TranscriptFile[] = []+ const budget = identityScanBudget()+ for (const directory of typeof root === 'string' ? [root] : root) {+ await transcripts(directory, budget, files, opts?.excludedDirectory)+ }+ files.sort((a, b) => b.mtimeMs - a.mtimeMs || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))for (const file of files) {if (file.mtimeMs < since) break // sorted newest-first: everything after is older stillconst meta = await readMeta(file.path)@@ -266,8 +297,10 @@ async function copilotDirectoryScan(): Promise<RepairedSession | null> {return fileEngineSession(join(env.COPILOT_HOME, 'session-state'), cwd, startedAtMs, async (path) => {if (basename(path) !== 'events.jsonl') return null- const head = (await readFile(path, 'utf8').catch(() => '')).split('\n', 5)- const root = recordCwd(head, COPILOT_CWD)+ const head = await identityHead(path, 5)+ const root = recordCwd(head.lines, COPILOT_CWD)+ if (!root || !isAbsolute(root)) throw new IdentityReadUnavailable(head.complete+ ? 'the session header is incomplete or invalid' : 'the session header exceeds the read limit')return root ? { cwd: root, sessionId: basename(dirname(path)) } : null}, opts)}@@ -289,14 +322,22 @@ async function storeSession(startedAtMs: number,opts?: { bornOnly?: boolean; pid?: number; codexHome?: string },): Promise<RepairedSession | null> {- const scan = scanMeta(engine, store.scan)+ const scan = scanMeta(engine, store.scan, cwd)if ('record' in store.live) {const exact = opts?.pid ? await processSessionOf(engine, opts.pid, cwd, startedAtMs) : null- return exact ?? fileEngineSession(sessionRoots(engine), cwd, startedAtMs, scan, opts)+ if (exact) return exact}- const sessions = sessionRoots(engine, opts?.codexHome)- if (opts?.pid) return openFileSessionOf(engine, opts.pid, sessions, cwd)- return fileEngineSession(sessions, cwd, startedAtMs, scan, opts)+ const sessions = repairRoots(engine, opts?.codexHome)+ const found = opts?.pid && 'open' in store.live+ ? await openFileSessionOf(engine, opts.pid, sessions, cwd)+ : await fileEngineSession(sessions, cwd, startedAtMs, scan,+ { ...opts, ...(store.scan.from === 'head' ? { excludedDirectory: store.scan.childFolder } : {}) })+ // The login shell may adopt another home during any native read. Its unseen candidates+ // invalidate this pool; an explicit profile remains independent of unrelated homes.+ if (repairRoots(engine, opts?.codexHome).join('\0') !== sessions.join('\0')) {+ throw new IdentityReadUnavailable('the known session homes changed during discovery')+ }+ return found}export async function findLiveSession(@@ -335,7 +376,7 @@ export async function findLiveSession(// being conversed in has opened a RUN.const identity = await museSessionIdentity(path, root => sameDir(root, cwd))return identity ? { ...identity, sessionId: basename(dirname(path)) } : null- }, opts)+ }, { ...opts, excludedDirectory: 'subagent' })}case 'amp':// The transcripts scanned here are the adapter's own — Amp keeps no conversation on disk, so its@@ -356,7 +397,11 @@ export async function findLiveSession(const group = dirname(sessionDir)let root = ''try { root = decodeURIComponent(basename(group)) } catch { /* hashed layout below */ }- if (!root.startsWith('/')) root = (await readFile(join(group, '.cwd'), 'utf8').catch(() => '')).trim()+ if (!root.startsWith('/')) root = (await identityFile(join(group, '.cwd')).catch(error => {+ if (error instanceof IdentityReadUnavailable) throw error+ throw new IdentityReadUnavailable('the session working directory is unavailable')+ })).trim()+ if (!isAbsolute(root)) throw new IdentityReadUnavailable('the session working directory is invalid')return root ? { cwd: root, sessionId: basename(sessionDir) } : null}, opts)case 'opencode':@@ -572,7 +617,7 @@ export async function openFileSessionOf(if (!live.open.file.test(path)) continueconst real = await realpath(path).catch(() => path)if (!roots.some((root) => real.startsWith(`${root}${sep}`))) continue- const meta = sessionMetaOf(engine, real)+ const meta = await sessionIdentityMetaOf(engine, real)if (!meta || meta.isSubagent || !meta.id || !meta.cwd || !await sameDir(meta.cwd, cwd)) continuefound.set(real, { sessionId: meta.id, transcriptPath: real })}@@ -590,28 +635,65 @@ export async function processSessionOf(engine: AgentEngine, pid: number, cwd: stif (!live || !('record' in live)) return nullif (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isFinite(startedAtMs)) return nullconst rule = live.record- for (const sessions of sessionRoots(engine)) {- const found = await processRecord(engine, rule, join(dirname(sessions), rule.folder, `${pid}${rule.suffix}`), pid, cwd, startedAtMs)- if (found) return found+ let result: RepairedSession | null = null+ let selected: string | undefined+ const roots = repairRoots(engine)+ const records: { file: string; text: string | null }[] = []+ const read = (file: string) => identityFile(file).catch(error => {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw error+ })+ for (const sessions of roots) {+ const file = join(dirname(sessions), rule.folder, `${pid}${rule.suffix}`)+ const text = await read(file)+ records.push({ file, text })+ if (text === null) continue+ const found = await processRecord(engine, rule, text, pid, cwd, startedAtMs)+ if (!found) continue+ if (result && (result.sessionId !== found.sessionId || result.transcriptPath !== found.transcriptPath)) {+ throw new IdentityReadUnavailable('current process records name different conversations')+ }+ result = found+ selected = file}- return null+ // A conversation can change inside the same process while another home is being read.+ // Recheck absent/stale claims too: a newly created claim invalidates the earlier pool.+ // Read the authoritative claim last: otherwise it can change while the later homes+ // are being rechecked. No asynchronous work follows that final native read.+ const recheck = [...records.filter(record => record.file !== selected), ...records.filter(record => record.file === selected)]+ for (const { file, text } of recheck) {+ if (await read(file) !== text) throw new IdentityReadUnavailable('the process records changed during discovery')+ }+ if (repairRoots(engine).join('\0') !== roots.join('\0')) throw new IdentityReadUnavailable('the known session homes changed during discovery')+ return result}type ProcessRecordRule = Extract<SessionStoreContract['live'], { record: unknown }>['record']-async function processRecord(engine: AgentEngine, rule: ProcessRecordRule, file: string, pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null> {+async function processRecord(engine: AgentEngine, rule: ProcessRecordRule, text: string, pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null> {try {- const record = JSON.parse(await readFile(file, 'utf8'))+ const record = JSON.parse(text)+ if (!record || typeof record !== 'object' || Array.isArray(record)+ || !Number.isSafeInteger(record[rule.pid]) || record[rule.pid] <= 0 || typeof record[rule.start] !== 'string'+ || !Number.isFinite(Date.parse(record[rule.start]))+ || typeof record[rule.cwd] !== 'string' || !isAbsolute(record[rule.cwd])+ || typeof record[rule.id] !== 'string' || !record[rule.id]) {+ throw new IdentityReadUnavailable('the process record is incomplete or invalid')+ }const start = record[rule.start]const folder = record[rule.cwd]const sessionId = record[rule.id]// Claude's procStart is UTC in current builds, while older builds used the host's local ps format.// Both represent the exact second, not the metadata file's modification time or a recycled PID.- if (record[rule.pid] !== pid || typeof start !== 'string'- || ![Date.parse(start), Date.parse(`${start} UTC`)].includes(startedAtMs)- || typeof folder !== 'string' || !await sameDir(folder, cwd)- || typeof sessionId !== 'string') return null+ if (record[rule.pid] !== pid || ![Date.parse(start), Date.parse(`${start} UTC`)].includes(startedAtMs)) return null+ if (!await sameDir(folder, cwd)) throw new IdentityReadUnavailable('the current process record names a different working directory')const transcriptPath = await findResumedTranscript(engine, sessionId)- return transcriptPath ? { sessionId, transcriptPath } : null- } catch { return null }+ if (!transcriptPath) throw new IdentityReadUnavailable('the process names a conversation whose transcript is unavailable')+ return { sessionId, transcriptPath }+ } catch (error) {+ if (error instanceof IdentityReadUnavailable) throw error+ if (error instanceof SyntaxError) throw new IdentityReadUnavailable('the process record is incomplete or invalid')+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null+ throw new IdentityReadUnavailable('the process record could not be read')+ }}diff --git a/docs/research/2026-10-09-bounded-identity-cost.json b/docs/research/2026-10-09-bounded-identity-cost.jsonnew file mode 100644index 000000000..bb381f6a2--- /dev/null+++ b/docs/research/2026-10-09-bounded-identity-cost.json@@ -0,0 +1,656 @@+{+ "baseline": "62cc1cc4343b05c7c800f614ba9254f7cadf7990",+ "candidate": "cc6470abef447662b6a790a7fc32e9b49b66efb0",+ "method": "Three interleaved processes per workload/source; ten lookups per process; identical private 160-file corpus (420 at count limit), 64 known homes for homes, Node toolchain; warm filesystem cache; setup and module import excluded from lookup CPU/latency, peak RSS includes both. Reference measurements, not performance thresholds.",+ "elapsedSeconds": 14.12,+ "samples": [+ {+ "workload": "pool",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 42.83,+ 41.22,+ 38.42,+ 38.09,+ 35.15,+ 36.34,+ 35.61,+ 35.51,+ 36.19,+ 35.23+ ],+ "cpuMs": 507.891,+ "peakRssMiB": 102.078125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 1+ },+ {+ "workload": "pool",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 65.63,+ 58.65,+ 57.12,+ 55.61,+ 56.91,+ 57.32,+ 55.91,+ 54.81,+ 64.86,+ 61.64+ ],+ "cpuMs": 832.962,+ "peakRssMiB": 100.83203125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 1+ },+ {+ "workload": "pool",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 65.37,+ 62.03,+ 61.6,+ 53.83,+ 54.85,+ 52.85,+ 52.09,+ 51.37,+ 49.74,+ 51.12+ ],+ "cpuMs": 785.203,+ "peakRssMiB": 104.265625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 2+ },+ {+ "workload": "pool",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 41.54,+ 41.46,+ 38.1,+ 37.88,+ 37.08,+ 35.54,+ 35.27,+ 35.46,+ 35.27,+ 35.59+ ],+ "cpuMs": 505.936,+ "peakRssMiB": 103.69921875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 2+ },+ {+ "workload": "pool",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 43.02,+ 40.27,+ 38.2,+ 38.54,+ 35.2,+ 35.37,+ 35.79,+ 35.83,+ 34.97,+ 35.93+ ],+ "cpuMs": 506.477,+ "peakRssMiB": 101.69921875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 3+ },+ {+ "workload": "pool",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 64.54,+ 57.93,+ 57.75,+ 54.38,+ 55.02,+ 53.13,+ 51.65,+ 52.69,+ 50.47,+ 50.77+ ],+ "cpuMs": 776.271,+ "peakRssMiB": 99.0078125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 3+ },+ {+ "workload": "process",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.44,+ 0.3,+ 0.33,+ 0.3,+ 0.38,+ 0.26,+ 0.35,+ 0.29,+ 0.44,+ 0.35+ ],+ "cpuMs": 5.075,+ "peakRssMiB": 94.8359375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 1+ },+ {+ "workload": "process",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 2.26,+ 0.8,+ 0.75,+ 0.7,+ 0.75,+ 0.67,+ 0.61,+ 0.58,+ 0.67,+ 0.66+ ],+ "cpuMs": 10.077,+ "peakRssMiB": 93.12890625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 1+ },+ {+ "workload": "process",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 2.32,+ 0.9,+ 0.85,+ 0.72,+ 0.71,+ 0.68,+ 0.66,+ 0.62,+ 0.67,+ 0.65+ ],+ "cpuMs": 10.416,+ "peakRssMiB": 92.42578125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 2+ },+ {+ "workload": "process",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.58,+ 0.39,+ 0.29,+ 0.25,+ 0.33,+ 0.25,+ 0.31,+ 0.31,+ 0.43,+ 0.36+ ],+ "cpuMs": 5.092,+ "peakRssMiB": 94.23046875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 2+ },+ {+ "workload": "process",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.45,+ 0.39,+ 0.31,+ 0.3,+ 0.34,+ 0.3,+ 0.35,+ 0.3,+ 0.49,+ 0.35+ ],+ "cpuMs": 5.226,+ "peakRssMiB": 94.48828125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 3+ },+ {+ "workload": "process",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 2.25,+ 0.84,+ 0.76,+ 0.72,+ 0.83,+ 0.66,+ 0.62,+ 0.57,+ 0.69,+ 0.65+ ],+ "cpuMs": 10.25,+ "peakRssMiB": 94.04296875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 3+ },+ {+ "workload": "limit",+ "files": 420,+ "iterations": 10,+ "outcomes": {+ "absent": 10+ },+ "latenciesMs": [+ 100.95,+ 90.74,+ 88.09,+ 88.3,+ 85.85,+ 84.2,+ 84.29,+ 82.46,+ 87.51,+ 79.82+ ],+ "cpuMs": 1211.107,+ "peakRssMiB": 105.80078125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 1+ },+ {+ "workload": "limit",+ "files": 420,+ "iterations": 10,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 15.52,+ 12.21,+ 11.77,+ 14.91,+ 11.66,+ 13.31,+ 12.37,+ 11.82,+ 13.43,+ 12.55+ ],+ "cpuMs": 180.386,+ "peakRssMiB": 103.80078125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 1+ },+ {+ "workload": "limit",+ "files": 420,+ "iterations": 10,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 14.58,+ 12.4,+ 11.44,+ 14.89,+ 11.73,+ 12.89,+ 13.34,+ 14.69,+ 14.32,+ 11.08+ ],+ "cpuMs": 183.586,+ "peakRssMiB": 105.33984375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 2+ },+ {+ "workload": "limit",+ "files": 420,+ "iterations": 10,+ "outcomes": {+ "absent": 10+ },+ "latenciesMs": [+ 104.01,+ 90.09,+ 88.6,+ 88.69,+ 84.94,+ 87.21,+ 91.75,+ 83.08,+ 80.14,+ 82.76+ ],+ "cpuMs": 1218.774,+ "peakRssMiB": 105.625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 2+ },+ {+ "workload": "limit",+ "files": 420,+ "iterations": 10,+ "outcomes": {+ "absent": 10+ },+ "latenciesMs": [+ 101.22,+ 90.35,+ 87.58,+ 88.96,+ 84.3,+ 84.57,+ 84,+ 85.05,+ 80.89,+ 80.87+ ],+ "cpuMs": 1205.955,+ "peakRssMiB": 105.17578125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 3+ },+ {+ "workload": "limit",+ "files": 420,+ "iterations": 10,+ "outcomes": {+ "held": 10+ },+ "latenciesMs": [+ 14.76,+ 12.04,+ 11.83,+ 14.43,+ 11.79,+ 13.41,+ 11.89,+ 14.01,+ 13.05,+ 10.43+ ],+ "cpuMs": 179.263,+ "peakRssMiB": 100.8046875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 3+ },+ {+ "workload": "homes",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.82,+ 0.53,+ 0.43,+ 0.38,+ 0.36,+ 0.36,+ 0.32,+ 0.4,+ 0.61,+ 0.9+ ],+ "cpuMs": 8.791,+ "peakRssMiB": 90.84765625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 1+ },+ {+ "workload": "homes",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 7.61,+ 5.93,+ 5.67,+ 5.42,+ 5.71,+ 4.96,+ 4.95,+ 6.39,+ 7.09,+ 5.16+ ],+ "cpuMs": 85.115,+ "peakRssMiB": 97.79296875,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 1+ },+ {+ "workload": "homes",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 7.72,+ 5.95,+ 5.29,+ 5.54,+ 5.88,+ 5.21,+ 4.73,+ 5,+ 7.99,+ 5.49+ ],+ "cpuMs": 84.759,+ "peakRssMiB": 96.9453125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 2+ },+ {+ "workload": "homes",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.67,+ 0.48,+ 0.43,+ 0.37,+ 0.34,+ 0.35,+ 0.35,+ 0.37,+ 1.03,+ 0.39+ ],+ "cpuMs": 8.396,+ "peakRssMiB": 91.84375,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 2+ },+ {+ "workload": "homes",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 1.85,+ 0.57,+ 0.52,+ 0.38,+ 0.38,+ 0.36,+ 0.31,+ 0.36,+ 0.53,+ 0.36+ ],+ "cpuMs": 7.706,+ "peakRssMiB": 91.30078125,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "baseline",+ "sample": 3+ },+ {+ "workload": "homes",+ "files": 160,+ "iterations": 10,+ "outcomes": {+ "exact": 10+ },+ "latenciesMs": [+ 7.81,+ 6.23,+ 5.23,+ 5.2,+ 5.68,+ 5.04,+ 4.63,+ 6.49,+ 6.79,+ 5.13+ ],+ "cpuMs": 84.471,+ "peakRssMiB": 98.28515625,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "x64",+ "source": "candidate",+ "sample": 3+ }+ ]+}diff --git a/docs/research/2026-10-09-bounded-identity.md b/docs/research/2026-10-09-bounded-identity.mdnew file mode 100644index 000000000..38bbeeb62--- /dev/null+++ b/docs/research/2026-10-09-bounded-identity.md@@ -0,0 +1,57 @@+# Bounded native identity discovery++Former-code baseline: main `b6e15e10c7dee075b8db098647bb5b4ffca56d83`. The repair-identity, other-identity and session-store goldens were re-recorded before implementation under `TZ=UTC TMPDIR=/tmp`, with their pinned platform, clock, homes and process fixtures. Recording passed in 28.0 seconds; verification with recording disabled passed in 27.6 seconds. All three artifacts are byte-for-byte identical to main. The subsequent launch-preparation merge changes none of these identity inputs.++Artifact SHA-256:++- `repair-identity.golden.json`: `0de8c0b227abaf0efc909cda0d4f627c3434dea2234659757e5dda5bc6c1b3c8`+- `other-identity.golden.json`: `deab341a2808e65e1a2fa23c67144d247850f39771ef09497a2e1024f7ce9eb6`+- `session-store.golden.json`: `dd3be450efddfae1c9336f82e0e71225fa741c17399297ed44ef0b24e95fc236`++The next safety change replaces truncated evidence with an explicit incomplete result. A directory scan that stops at a count or depth bound cannot prove a unique conversation. Native metadata reads must be bounded and a cut or unreadable record must not make another candidate look unique. Known excluded subagent directories remain excluded. Exact process evidence remains available independently of optional readers; discovery isolates an incomplete lookup so other sessions and readiness continue.++Validation preserves these former artifacts, adds incomplete-scan and large-file regressions, deliberately breaks the actual wiring, and runs types, architecture, core/master coverage, affected identity/Stop/resume tests and private bundled lifecycle lanes. Independent exact-head review and automatic CI precede merging. No release.++## Implementation boundary++File-backed live repair now streams directory entries with one entry/file budget across all known homes. An unfinished walk, unreadable candidate, missing or cut header, nonregular file, or changed identity record holds the lookup. Native header readers use bounded asynchronous I/O; Copilot no longer reads an entire transcript. Codex repair uses a strict first-record reader while registry/history compatibility readers retain their existing nullable API. Declared child directories and verified other workspaces remain excluded.++Claude process records must be complete and valid before a different PID/start can establish staleness. A current record contradicting the observed workspace holds. Every home's claim must agree, and the records are read again before publishing the pool, with the selected claim read last. The known-home set must still match. Missing directories consume the traversal budget and more than 64 known homes holds before native probes. Bounded reads reject short reads and changed descriptors and reopen the path to detect atomic replacement. Existing verified conversation bindings keep their fast path. Stop captures identity before saving or signalling; a deferred Close retains its waiting intent and reason when native identity is unavailable, then retries.++The former-code goldens shared unrelated fixture files between observations. A separate fixture-only commit isolates Muse cases (retaining the age-test file), ages previous resolver fixtures before the fresh repair corpus, and removes only continuation-owned files before the next platform pass. Recording and verification on former production code passed with all three JSON artifacts unchanged. The comparison names the intentional safety deltas: unusable/contradictory Claude process records and four incomplete Muse identities now hold instead of returning absence. All other recorded observations remain exact.++The new regressions include hidden competing candidates, shared budgets, partial headers, invalid/current-but-contradictory PID claims, atomic replacement, two-home revalidation, sparse histories larger than a JavaScript string, private FIFOs, Stop before mutations, deferred Close retry, and a private bundled daemon whose held process does not block readiness or its sibling.++## Remaining native-identity work++This change does not claim that every native lookup is bounded yet. Strict process-lock/descriptor enumeration in `kit/sessionLocation.ts`, complete Hermes store-home/database pools, exact-ID traversal, and containment/retry at every binding and transcript-discovery entry point remain separate follow-ups. Those changes must preserve the same distinction between verified absence and unavailable evidence. Discovery currently reports a binding hold in the daemon log; a shared visible hold state remains part of the broader durable-intent work.++The existing synchronous compatibility readers remain for registry/history callers, and the shared saved-home catalog still uses its legacy synchronous loader. Bounding that catalog read is a remaining prerequisite for a fully bounded native lookup path; the per-lookup home/probe cap here does not claim otherwise. Runtime cost is measured with the same private native corpus and Node toolchain on both trees using `cli/scripts/handoff-2026-10-08/identity-cost.ts`; line count is not an acceptance metric.++The [cost record](2026-10-09-bounded-identity-cost.json) compares the former production tree at `62cc1cc4343b05c7c800f614ba9254f7cadf7990` with the corrected implementation at `cc6470abef447662b6a790a7fc32e9b49b66efb0`. Three interleaved processes per source/workload perform ten lookups each. The corpus includes 160 ordinary files, 420 files for incomplete-pool behavior, and 64 known homes for empty-home probe cost. These measure a warm filesystem cache; process peak RSS includes setup and module import, while lookup latency/CPU exclude them. This is a reference measurement of the safety cost, not a new numerical acceptance threshold.++## Validation and measured cost++The final production change is `9d79c4607`; `40b30bbbd` only canonicalizes private test paths on macOS. Integration with main `576ae7246` changes Desktop and TUI only. No CLI/Store validation input or production behavior changed in that integration.++- Core/services: 1,930 tests, 100% per-file coverage (receipt `20261009T133531.927972Z-92550`).+- Master: 265 passed, one existing skip, 100% per-file coverage; types and 244 affected identity/architecture tests passed (receipt `20261009T133800.424067Z-8569`).+- Resume: 313 tests and 100% coverage, run alone (receipt `20261009T134355.238968Z-36854`, 48.5 seconds).+- Bundled private lifecycle: six selected tests passed, including incomplete native identity, manual start/resume, and Codex tmux-crash resume (receipt `20261009T133531.927972Z-92550`, 67.4 seconds). Twenty tests outside those selected lanes were skipped.+- All 18 deliberate wiring mutations failed by assertion after a passing unchanged baseline. All three former-code golden artifacts remain unchanged.+- Cost comparison: 24 interleaved processes, 14.2 seconds (receipt `20261009T134506.715167Z-47079`).++The initial final-production run exposed a macOS-only test fixture path mismatch and an unrelated existing master-test flake: its polling reader observed an incomplete JSON log append. The fixture correction, affected specs, types and full master coverage gate passed on rerun. Passing core and bundled e2e evidence is retained because the intervening correction changed only test paths. A mistyped resume receipt argument stopped the runner before tests; the corrected invocation passed.++Latency below pools all 30 lookups per source/workload. CPU is per ten lookups; RSS is process peak including imports and corpus setup.++| Workload | Former median / p95 ms | Candidate median / p95 ms | Former / candidate CPU ms | Former / candidate RSS MiB |+| --- | --- | --- | --- | --- |+| pool | 36.06 / 42.83 | 55.31 / 65.37 | 506–508 / 776–833 | 101.7–103.7 / 99.0–104.3 |+| process | 0.34 / 1.45 | 0.69 / 2.26 | 5–5 / 10–10 | 94.2–94.8 / 92.4–94.0 |+| limit | 86.53 / 101.22 | 12.72 / 14.91 | 1206–1219 / 179–184 | 105.2–105.8 / 100.8–105.3 |+| homes | 0.39 / 1.82 | 5.61 / 7.81 | 8–9 / 84–85 | 90.8–91.8 / 96.9–98.3 |++The 160-file pool and exact process lookups keep the same answer. The 420-file case changes from an unsafe absence to an explicit hold. The 64-home case checks every claim and revalidates the selected one instead of stopping at the first claim; that completeness accounts for the added work. These are local reference measurements, not guarantees or new performance gates.++For this follow-up, implementation and diagnosis ran from approximately 12:48 to 13:38 UTC on October 9; validation overlapped that work and finished at 13:45, including the final isolated resume lane and cost measurement. Independent review and CI waiting are tracked separately in the PR, followed by merge time. Publication is excluded: no release is authorized. The overall daemon-separation request began at 23:26 UTC on October 8; this follow-up is one part of that work, not its total duration.diff --git a/docs/research/2026-10-09-daemon-core-completion.md b/docs/research/2026-10-09-daemon-core-completion.mdnew file mode 100644index 000000000..20f5e3527--- /dev/null+++ b/docs/research/2026-10-09-daemon-core-completion.md@@ -0,0 +1,30 @@+# Daemon core completion checklist++This is the remaining completion scope as of October 9, after the six extraction phases in the [handoff](2026-10-08-daemon-separation-handoff.md). The architecture must be safe under unavailable dependencies and changing session ownership. Source size is a reference, not a gate. The [progress history](2026-10-09-daemon-separation-progress.md) records landed work and timing; individual PRs carry exact-head review and validation receipts. No release is authorized.++## Landed foundations++- [x] Crash resume preserves the interrupted turn boundary (#1072).+- [x] DSH preparation runs through Store and held boot launches (#1073).+- [x] Grid assignment and saved APIs use the models boundary without delaying discovery (#1076).+- [x] Usage and external sessions run in their services (#1078, #1081).+- [x] The legacy runtime profile manager is removed (#1088).+- [x] Same-millisecond pane labels cannot collide (#1091).+- [x] Capture ownership is checked after asynchronous reads (#1093).+- [x] Kilo, Hermes, native identity, Muse/Pi repair, OpenCode control and native hook declarations are eager where session control requires them (#1095, #1097, #1104, #1106, #1110, #1111).+- [x] Launch preparation gathers dependencies before local writes and commits under current ownership (#1113).+- [ ] Bounded repair pools and native headers hold incomplete evidence; Stop/Close preserve intent (#1114, reviewed and in final CI).++## 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.+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.+5. **Final architecture acceptance.** Exercise startup, discovery, binding, launch, resume, Stop, hook admission, turn closing and Close with required services absent, stalled, disconnected and recovered. Verify readiness remains independent, pending work survives without partial writes or archival, and stale completions cannot affect a replacement session. Run the relevant coverage gates, unchanged goldens and assertion-failing wiring mutations, affected private e2e/chaos lanes, and matched runtime-cost measurements. Obtain independent review and merge every completed change.++These groups are the completion bar, not a requirement for one PR per group. Update each with landed evidence; do not mark a group complete while its named cases remain open. Any additional blocker must identify a concrete violation of the stated architecture and its reproducer. Unrelated enhancements and cosmetic cleanup are outside this checklist. The six unreachable pane drivers retain the owner's existing decision and do not block completion. The interim search optimization was superseded by moving external sessions into the search process.++## Estimate and accounting++The working estimate given to the owner on October 9 is two to three more focused days, with moderate confidence; durable lifecycle intent and retargeting are the largest uncertainties. This is an estimate, not a claim that implementation or validation is complete. Track implementation, validation, independent review/CI waiting, merge and publication separately. The original request began October 8 at 23:26:41 UTC. Publication remains zero.diff --git a/docs/research/2026-10-09-daemon-separation-progress.md b/docs/research/2026-10-09-daemon-separation-progress.mdindex ac1308680..6f45544c2 100644--- a/docs/research/2026-10-09-daemon-separation-progress.md+++ b/docs/research/2026-10-09-daemon-separation-progress.md@@ -1,6 +1,6 @@# Daemon separation continuation, 2026-10-09-The architectural requirements and remaining order are in the [handoff](2026-10-08-daemon-separation-handoff.md). No release is authorized.+The architectural requirements and remaining order are in the [handoff](2026-10-08-daemon-separation-handoff.md). No release is authorized. The current remaining scope is the [completion checklist](2026-10-09-daemon-core-completion.md); the sections below are the historical implementation record.## Crash resume