Skip to content

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

Hold incomplete native locations and retry discovery (#1118)

Dee902ab6038d39
diff --git a/cli/e2e/eagerIdentity.e2e.ts b/cli/e2e/eagerIdentity.e2e.ts
index aaf9a5a00..a95fa9cd5 100644
--- a/cli/e2e/eagerIdentity.e2e.ts
+++ b/cli/e2e/eagerIdentity.e2e.ts
@@ -1,6 +1,6 @@
/** Real core and process discovery with optional native modules absent or unable to finish loading. */
import { execFileSync } from 'node:child_process'
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, rmdirSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterAll, afterEach, beforeAll, expect, it, onTestFailed } from 'vitest'
@@ -64,11 +64,16 @@ console.log('fixture-${engine}-ready'); setInterval(() => {}, 1000);
const copilot = await create('copilot')
await until('Copilot binding from its lock with no optional reader', async () => (await rows()).find(row => row.id === copilot.id)?.sessionId === first || null, 30_000, 100)
const pid = Number(readFileSync(join(d.root, 'copilot.pid'), 'utf8'))
+ const unknown = join(d.env.COPILOT_HOME, 'session-state', '99999999-1111-4222-8333-444444444444', `inuse.${pid}.lock`)
+ mkdirSync(unknown, { recursive: true })
const folder = join(d.env.COPILOT_HOME, 'session-state', next); mkdirSync(folder, { recursive: true })
writeFileSync(join(folder, 'events.jsonl'), JSON.stringify({ type: 'session.start', data: { context: { cwd } } }) + '\n')
const lock = join(folder, `inuse.${pid}.lock`); writeFileSync(lock, '')
const newer = new Date(Date.now() + 2000); utimesSync(lock, newer, newer)
- await until('Copilot in-process resume without a hook or reader', async () => (await rows()).find(row => row.id === copilot.id)?.sessionId === next || null, 30_000, 100)
+ // A competing native location that cannot be read must retain the old binding,
+ // without stopping discovery of the Cursor siblings below.
+ await until('Copilot binding held for its incomplete lock pool', () => d.log().includes('binding held · Conversation identity is held: a native identity location is not a regular file'), 30_000, 100)
+ expect((await rows()).find(row => row.id === copilot.id)?.sessionId).toBe(first)
// The two Copilot bindings already occupy reader slots. Three more pending Cursor sessions
// saturate the four-slot pool before the final Cursor is asked to locate its transcript.
const cursorId = 'cccccccc-1111-4222-8333-444444444444'
@@ -86,12 +91,24 @@ console.log('fixture-${engine}-ready'); setInterval(() => {}, 1000);
await until('the binding is visible before optional attachment completes', async () =>
(await rows()).find(row => row.id === cursor.id)?.sessionId === sessionId || null, 5000, 100)
}
- const transcript = join(d.env.CURSOR_HOME, 'projects', 'p', 'agent-transcripts', cursorId, `${cursorId}.jsonl`)
- mkdirSync(dirname(transcript), { recursive: true }); writeFileSync(transcript, '{}\n')
+ const heldCursorId = 'dddddddd-1111-4222-8333-444444444444'
+ const transcript = join(d.env.CURSOR_HOME, 'projects', 'p', 'agent-transcripts', heldCursorId, `${heldCursorId}.jsonl`)
+ // The first candidate's native read fails while a sibling's transcript is ready.
+ // Neither optional readers nor this failed location may own the polling loop.
+ mkdirSync(transcript, { recursive: true })
+ const siblingId = cursorId
+ const siblingTranscript = join(d.env.CURSOR_HOME, 'projects', 'p', 'agent-transcripts', siblingId, `${siblingId}.jsonl`)
+ mkdirSync(dirname(siblingTranscript), { recursive: true }); writeFileSync(siblingTranscript, '{}\n')
+ await until('the pending Cursor native read to hold', () => d.log().includes(`transcript ${heldCursorId} held`), 15_000, 100)
+ await until('the sibling transcript to publish while another lookup is held', () =>
+ readFileSync(join(d.dataDir, 'registry.json'), 'utf8').includes(siblingTranscript), 15_000, 100)
+ rmdirSync(transcript); writeFileSync(transcript, '{}\n')
await until('Cursor location committed while its optional reader is unavailable', () => {
const registry = JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8'))
return JSON.stringify(registry).includes(transcript) || null
}, 15_000, 100)
+ rmdirSync(unknown)
+ await until('Copilot in-process resume after its native pool recovers', async () => (await rows()).find(row => row.id === copilot.id)?.sessionId === next || null, 30_000, 100)
expect((await fetch(`http://127.0.0.1:${d.port}/api/health`)).ok).toBe(true)
expect(d.coresStarted()).toBe(1)
}, 120_000)
diff --git a/cli/scripts/handoff-2026-10-08/location-cost.ts b/cli/scripts/handoff-2026-10-08/location-cost.ts
new file mode 100644
index 000000000..14cfeb9b5
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/location-cost.ts
@@ -0,0 +1,49 @@
+/** Same private native pool on both production trees. No host engine, process or daemon. */
+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { performance } from 'node:perf_hooks'
+import { CURSOR_TRANSCRIPT } from '../../src/engines/cursor/contract.js'
+import { GROK_TRANSCRIPT } from '../../src/engines/grok/contract.js'
+import { COPILOT_PROCESS_SESSION } from '../../src/engines/copilot/contract.js'
+import { locateProcessSession, locateTranscript } from '../../src/engines/kit/sessionLocation.js'
+const root = mkdtempSync(join(tmpdir(), 'native-location-cost-'))
+const workload = process.argv[2] ?? 'transcript'
+const id = (n: number) => `aaaaaaaa-1111-4222-8333-${String(n).padStart(12, '0')}`
+const file = (path: string, text = '{}\n') => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); return path }
+try {
+ const count = workload === 'limit' ? 4200 : 160
+ for (let i = 0; i < count; i++) {
+ if (workload === 'process') {
+ mkdirSync(join(root, 'session-state', id(i)), { recursive: true })
+ const path = file(join(root, 'session-state', id(i), 'inuse.4242.lock'))
+ utimesSync(path, 1000 + i, 1000 + i)
+ } else if (workload === 'grok-sidecars') {
+ const group = join(root, 'sessions', `hash-${String(i).padStart(5, '0')}`)
+ file(join(group, id(1), 'updates.jsonl'))
+ file(join(group, '.cwd'), (i === count - 1 ? '/workspace' : `/elsewhere-${i}`).padEnd(60 * 1024, ' '))
+ } else mkdirSync(join(root, 'projects', `project-${String(i).padStart(5, '0')}`), { recursive: true })
+ }
+ if (workload === 'transcript') file(join(root, 'projects', 'project-00159', 'agent-transcripts', id(1), `${id(1)}.jsonl`))
+ const latenciesMs: number[] = [], outcomes: Record<string, number> = {}
+ const cpu = process.cpuUsage()
+ for (let i = 0; i < 10; i++) {
+ const started = performance.now()
+ let outcome: string
+ try {
+ const found = workload === 'process' ? await locateProcessSession(COPILOT_PROCESS_SESSION, root, 4242)
+ : workload === 'grok-sidecars' ? await locateTranscript(GROK_TRANSCRIPT, root, id(1), { cwd: '/workspace' })
+ : await locateTranscript(CURSOR_TRANSCRIPT, root, id(1))
+ outcome = found ? 'exact' : 'absent'
+ } catch (error) {
+ if ((error as { code?: string }).code !== 'IDENTITY_UNAVAILABLE') throw error
+ outcome = 'held'
+ }
+ latenciesMs.push(Number((performance.now() - started).toFixed(2)))
+ outcomes[outcome] = (outcomes[outcome] ?? 0) + 1
+ }
+ const used = process.cpuUsage(cpu)
+ console.log(JSON.stringify({ workload, entries: count, iterations: 10, outcomes, latenciesMs,
+ cpuMs: (used.user + used.system) / 1000, peakRssMiB: process.resourceUsage().maxRSS / 1024,
+ node: process.version, platform: process.platform, arch: process.arch }))
+} finally { rmSync(root, { recursive: true, force: true }) }
diff --git a/cli/scripts/handoff-2026-10-08/mutate-native-locations.py b/cli/scripts/handoff-2026-10-08/mutate-native-locations.py
new file mode 100644
index 000000000..d39db8fe5
--- /dev/null
+++ b/cli/scripts/handoff-2026-10-08/mutate-native-locations.py
@@ -0,0 +1,64 @@
+"""Each broken native-control connection must fail an assertion in a disposable worktree."""
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+cli = Path(sys.argv[1]).resolve()
+location = 'src/engines/kit/sessionLocation.ts'
+spec = 'src/engines/kit/sessionLocation.spec.ts'
+polling = 'src/engines/kit/transcriptDiscovery.ts'
+poll_spec = 'src/engines/kit/transcriptDiscovery.spec.ts'
+golden = 'src/engines/nativeLocation.golden.spec.ts'
+mutations = [
+ ('unreadable metadata is absent', location, "if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null", 'return null', spec),
+ ('first transcript wins', location, ' selected ??= { path, info, workspace }', ' return path', spec),
+ ('selected Grok workspace not rechecked', location, 'if (selected.workspace) await verifyWorkspace(selected.workspace)', 'if (false) await verifyWorkspace(selected.workspace!)', spec),
+ ('selected Cursor path not revalidated', location, 'if (options.valid && !options.valid(selected.path))', 'if (false)', spec),
+ ('unreadable Cursor validation is rejection', 'src/lib/registry.ts', "if (strict) throw new IdentityReadUnavailable('the transcript path could not be validated')", 'if (false) throw new Error()', 'src/lib/nativeLocations.control.spec.ts'),
+ ('Copilot bind claim not revalidated', 'src/core/agents/bind.ts', "if (await processSessionOf('copilot', homes.copilot, observed.processIdentity.pid) !== next)", 'if (false)', 'src/lib/nativeLocations.control.spec.ts'),
+ ('Copilot repair claim not revalidated', 'src/lib/sessionRepair.ts', "if (await nativeProcessSession('copilot', env.COPILOT_HOME, opts!.pid!) !== locked)", 'if (false)', 'src/lib/nativeLocations.control.spec.ts'),
+ ('agy repair claim not revalidated', 'src/lib/sessionRepair.ts', "if (await nativeProcessSession('agy', env.AGY_HOME, pid) !== conversationId)", 'if (false)', 'src/lib/nativeLocations.control.spec.ts'),
+ ('shared listing loses its authority', location, "if (signature(await inspect(root)) !== proof.signature)", 'if (false)', spec),
+ ('new transcript ignored', location, "if (file.path !== selected?.path && fileIdentity(await fileInfo(file.path)) !== fileIdentity(file.info))", 'if (false)', spec),
+ ('tied process locks accepted', location, 'if (tied) throw', 'if (false) throw', spec),
+ ('selected process claim not rechecked', location, 'if (best && signature(await fileInfo(best.path)) !== signature(best.info))', 'if (false)', spec),
+ ('new process directories ignored', location, "if (signature(await inspect(root)) !== before) throw new IdentityReadUnavailable('the native session directories", "if (false) throw new IdentityReadUnavailable('the native session directories", spec),
+ ('first held lock wins', location, 'if (ids.size > 1)', 'if (false)', spec),
+ ('partial process output accepted', location, "if (Buffer.byteLength(out) > DESCRIPTOR_BYTES || (out && !out.endsWith('\\n')))", 'if (false)', spec),
+ ('new descriptors ignored', location, "if (names.sort().join('\\0') !== descriptors.map(entry => entry.name).sort().join('\\0'))", 'if (false)', spec),
+ ('initial lookup stays busy forever', polling, ' candidate.looking = false\n this.schedule()', ' candidate.looking = true\n this.schedule()', poll_spec),
+ ('failed candidate aborts its siblings', polling, ' } catch (error) { this.hold(id, candidate, error) }', ' } catch (error) { throw error }', poll_spec),
+ ('native read failure escapes binding', 'src/core/agents/bind.ts', ' return null\n }\n }\n const mayClaim', ' throw error\n }\n }\n const mayClaim', 'src/core/agents/bind.spec.ts'),
+ ('Cursor declaration disconnected', 'src/engines/cursor/contract.ts', "folder: 'agent-transcripts'", "folder: 'missing-transcripts'", golden),
+ ('Copilot process declaration disconnected', 'src/engines/copilot/contract.ts', "prefix: 'inuse.'", "prefix: 'missing.'", golden),
+]
+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}
+for name in ['TMUX', 'TMUX_PANE', 'RECORD_NATIVE_LOCATION_GOLDEN', 'RECORD_OTHER_ENGINES_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, target in mutations:
+ path = cli / relative
+ original = path.read_text()
+ assert original.count(before) == 1, (label, original.count(before))
+ try:
+ path.write_text(original.replace(before, after))
+ result = run([target])
+ output = result.stdout + result.stderr
+ if result.returncode == 0 or 'AssertionError' not in output:
+ print(output)
+ raise SystemExit(f'{label}: not caught by an assertion')
+ print(f'{label}: caught by assertion', flush=True)
+ finally:
+ path.write_text(original)
diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.ts
index 55510cb27..202e46042 100644
--- a/cli/src/core/agents/bind.spec.ts
+++ b/cli/src/core/agents/bind.spec.ts
@@ -354,6 +354,64 @@ describe('binding a running process to its session', () => {
} finally { reconciler.stop() }
})
+ it.each(['copilot-process', 'copilot-transcript', 'continuation', 'cursor-resume', 'grok-resume',
+ 'agy-resume', 'copilot-resume', 'claude-resume', 'codex-resume'] as const)(
+ 'isolates %s failure from readiness and retries the same live binding', async kind => {
+ const run = setup()
+ const engine = kind === 'continuation' ? 'claude' : kind.split('-')[0] as DiscoveredTerminalAgent['engine']
+ const alreadyBound = kind === 'continuation' || kind === 'copilot-process' || kind === 'copilot-transcript'
+ const rows = [agent({ engine, agentId: 'held', sessionId: alreadyBound ? 'previous' : '',
+ transcriptPath: alreadyBound ? '/t/previous.jsonl' : undefined, runtimes: [], active: true,
+ processIdentity: { pid: 42, executable: engine, startMarker: '2026-10-09T00:00:00Z' } }),
+ agent({ engine: 'codex', agentId: 'next', sessionId: '', runtimes: [], active: true,
+ processIdentity: { pid: 43, executable: 'codex', startMarker: '2026-10-09T00:00:00Z' } })]
+ for (const row of rows) run.byAgent.set(row.agentId, row)
+ vi.mocked(run.deps.registry.byProcess).mockImplementation((_, identity) => rows.find(row => row.processIdentity?.pid === identity.pid))
+ vi.mocked(findLiveSession).mockResolvedValue({ sessionId: 'sibling', transcriptPath: '/t/sibling.jsonl' })
+ vi.mocked(processSessionOf).mockResolvedValue('resumed')
+ const failure = new Error('native evidence unavailable')
+ if (kind === 'copilot-process') vi.mocked(processSessionOf).mockRejectedValueOnce(failure)
+ else if (kind === 'continuation') vi.mocked(continuationOf).mockRejectedValueOnce(failure)
+ else if (kind === 'claude-resume' || kind === 'codex-resume') vi.mocked(findResumedTranscript).mockRejectedValueOnce(failure)
+ else vi.mocked(transcriptOf).mockRejectedValueOnce(failure)
+ vi.mocked(run.deps.registry.register).mockImplementation(request => {
+ const entry = rows.find(row => row.processIdentity?.pid === request.processIdentity?.pid)!
+ Object.assign(entry, { sessionId: request.sessionId, transcriptPath: request.transcriptPath })
+ return { entry, ...meta({ isNew: true }) } as never
+ })
+ const held = observed({ engine, processIdentity: rows[0]!.processIdentity!, resumeSessionId: alreadyBound ? null : 'resumed' })
+ const onProbeStatus = vi.fn(), onRemoved = vi.fn(), onDormant = vi.fn()
+ const reconciler = new TerminalAgentReconciler({
+ current: () => rows, backends: [], backendOrder: ['tmux'], onProbeStatus, onRemoved, onDormant,
+ onDiscovered: run.binding.bindObservedAgent, onObserved: run.binding.bindObservedAgent,
+ probe: async () => ({ processTableAvailable: true, targets: [], ambiguousPlacements: new Set(),
+ agents: [held, observed({ engine: 'codex', processIdentity: rows[1]!.processIdentity! })] }),
+ })
+ try {
+ await expect(reconciler.start(60_000)).resolves.toBeUndefined()
+ expect(rows[0]!.sessionId).toBe(alreadyBound ? 'previous' : '')
+ expect(rows[1]!.sessionId).toBe('sibling')
+ expect(onProbeStatus).toHaveBeenCalledWith({ ready: true, error: null })
+ expect(onRemoved).not.toHaveBeenCalled(); expect(onDormant).not.toHaveBeenCalled()
+ expect(run.deps.stoppedAgents.save).toHaveBeenCalledExactlyOnceWith(rows[1])
+ expect(console.log).toHaveBeenCalledWith('[discovery] held binding held · native evidence unavailable')
+ vi.mocked(continuationOf).mockResolvedValue({ sessionId: 'resumed', transcriptPath: '/t/resumed.jsonl' })
+ await run.binding.bindObservedAgent(held)
+ expect(rows[0]!.sessionId).toBe('resumed')
+ } finally { reconciler.stop() }
+ })
+
+ it('discards a rejected native read after the session has changed ownership', async () => {
+ const run = setup(), row = agent({ sessionId: '' })
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(row)
+ let reject!: (error: Error) => void
+ vi.mocked(findResumedTranscript).mockReturnValueOnce(new Promise((_, no) => { reject = no }))
+ const pending = run.binding.bindObservedAgent(observed({ resumeSessionId: 'resumed' }))
+ row.sessionId = 'replacement'; reject(new Error('obsolete lookup failed')); await pending
+ expect(run.deps.registry.register).not.toHaveBeenCalled()
+ expect(console.log).not.toHaveBeenCalled()
+ })
+
it.each([new Error('reader unavailable'), 'reader unavailable'])('contains an optional attachment failure after binding', async error => {
const log = vi.spyOn(console, 'error').mockImplementation(() => {})
const run = setup({ attachSession: vi.fn(async () => { throw error }) })
@@ -399,7 +457,7 @@ describe('binding a running process to its session', () => {
const entry = agent({ engine, transcriptPath: '/t/s1.jsonl' })
vi.mocked(run.deps.registry.byProcess).mockReturnValue(entry)
let answer!: () => void
- if (engine === 'copilot') vi.mocked(processSessionOf).mockReturnValueOnce(new Promise(resolve => { answer = () => resolve('s2') }))
+ if (engine === 'copilot') vi.mocked(processSessionOf).mockResolvedValue('s2').mockReturnValueOnce(new Promise(resolve => { answer = () => resolve('s2') }))
else vi.mocked(continuationOf).mockReturnValueOnce(new Promise(resolve => { answer = () => resolve({ sessionId: 's2', transcriptPath: '/t/s2.jsonl' }) }))
const pending = run.binding.bindObservedAgent(observed({ engine }))
entry.sessionId = 'newer'
@@ -410,7 +468,7 @@ describe('binding a running process to its session', () => {
it('does not take a Copilot resume target that was stopped during its transcript lookup', async () => {
const run = setup()
vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ engine: 'copilot' }))
- vi.mocked(processSessionOf).mockResolvedValueOnce('s2')
+ vi.mocked(processSessionOf).mockResolvedValue('s2')
let answer!: (path: string | null) => void
vi.mocked(transcriptOf).mockReturnValueOnce(new Promise(resolve => { answer = resolve }))
const pending = run.binding.bindObservedAgent(observed({ engine: 'copilot' }))
@@ -420,6 +478,16 @@ describe('binding a running process to its session', () => {
expect(run.deps.registry.register).not.toHaveBeenCalled()
})
+ it.each(['s3', null])('holds a Copilot conversation changed to %s during transcript lookup', async next => {
+ const run = setup(), row = agent({ engine: 'copilot' })
+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(row)
+ vi.mocked(processSessionOf).mockResolvedValueOnce('s2').mockResolvedValueOnce(next)
+ await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))
+ expect(run.deps.registry.register).not.toHaveBeenCalled()
+ expect(row.sessionId).toBe('s1')
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('process conversation changed during transcript lookup'))
+ })
+
describe('an agent that already has a session', () => {
it('follows Copilot to the session it /resumed into, and only to a new one', async () => {
const run = setup()
diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.ts
index e3623886a..cf5f92cb7 100644
--- a/cli/src/core/agents/bind.ts
+++ b/cli/src/core/agents/bind.ts
@@ -8,6 +8,7 @@
*/
import { stat } from 'node:fs/promises'
import { transcriptOf, processSessionOf } from '../../engines/identities.js'
+import { IdentityReadUnavailable } from '../../engines/kit/identityScan.js'
import { cursorDataDir } from '../../engines/cursor/contract.js'
import { continuationOf } from '../../engines/sessionFiles.js'
import { sessionStoreOf } from '../../engines/sessionStoreContracts.js'
@@ -222,6 +223,15 @@ export function createBinding({
const authority = paneReadIdentity(agent)
const current = () => !changing(agent.agentId) && !isRecentlyDeleted(agent.agentId)
&& paneReadIdentity(registry.byProcess(observed.engine, observed.processIdentity)) === authority
+ // Only native reads are contained here. A rejected lookup cannot end the serial
+ // discovery/readiness pass or bind an unwritten session as if evidence were absent.
+ const read = async <T>(work: () => Promise<T>): Promise<{ value: T } | null> => {
+ try { return { value: await work() } }
+ catch (error) {
+ if (current()) console.log(`[discovery] ${sid(agent.agentId)} binding held · ${error instanceof Error ? error.message : error}`)
+ return null
+ }
+ }
const mayClaim = (id: string): boolean => {
if (isRecentlyDeleted(id)) return false
const owner = registry.bySession(id)
@@ -240,9 +250,19 @@ export function createBinding({
if (agent.resumeOnly && agent.launch && agent.launch.state !== 'ready') return
if (agent.sessionId) {
if (observed.engine === 'copilot') {
- const next = await processSessionOf('copilot', homes.copilot, observed.processIdentity.pid)
+ const process = await read(() => processSessionOf('copilot', homes.copilot, observed.processIdentity.pid))
+ if (!process) return
+ const next = process.value
if (!next || next === agent.sessionId || isRecentlyDeleted(next)) return
- const transcript = await transcriptOf('copilot', homes.copilot, next)
+ const located = await read(async () => {
+ const path = await transcriptOf('copilot', homes.copilot, next)
+ if (await processSessionOf('copilot', homes.copilot, observed.processIdentity.pid) !== next) {
+ throw new IdentityReadUnavailable('the process conversation changed during transcript lookup')
+ }
+ return path
+ })
+ if (!located) return
+ const transcript = located.value
if (!current() || !mayClaim(next)) return
console.log(`[discovery] ${sid(agent.agentId)} switched copilot session ${sid(agent.sessionId)} → ${sid(next)} (/resume)`)
const rotated = registry.register({
@@ -268,7 +288,9 @@ export function createBinding({
// extra to ask. Its session store declares the marker (`continuation`), read in core with the kit.
const store = sessionStoreOf(observed.engine)
if (store?.continuation && agent.transcriptPath) {
- const continuation = await continuationOf(observed.engine, agent.transcriptPath)
+ const located = await read(() => continuationOf(observed.engine, agent.transcriptPath!))
+ if (!located) return
+ const continuation = located.value
if (!continuation || continuation.sessionId === agent.sessionId
|| registry.has(continuation.sessionId) || isRecentlyDeleted(continuation.sessionId)) return
if (!current()) return
@@ -296,11 +318,13 @@ export function createBinding({
let source = 'terminal-resume'
if (sessionId) {
if (!mayClaim(sessionId)) return
- transcriptPath = observed.engine === 'cursor' || observed.engine === 'grok' || observed.engine === 'agy' || observed.engine === 'copilot'
- ? await ownTranscript(observed.engine, sessionId, observed.cwd) ?? undefined
+ const located = await read(async () => observed.engine === 'cursor' || observed.engine === 'grok' || observed.engine === 'agy' || observed.engine === 'copilot'
+ ? await ownTranscript(observed.engine, sessionId!, observed.cwd) ?? undefined
: observed.engine === 'claude' || observed.engine === 'codex'
- ? await findResumedTranscript(observed.engine, sessionId, { codexHome: agent.codexHome ?? undefined }) ?? undefined
- : undefined
+ ? await findResumedTranscript(observed.engine, sessionId!, { codexHome: agent.codexHome ?? undefined }) ?? undefined
+ : undefined)
+ if (!located) return
+ transcriptPath = located.value
// The registry refuses a claude/codex session without its file, so a resume of a transcript this
// machine does not have is not a session — the hook that follows the user's next prompt will say.
if ((observed.engine === 'cursor' || observed.engine === 'grok' || observed.engine === 'claude' || observed.engine === 'codex')
@@ -315,16 +339,13 @@ export function createBinding({
if (!Number.isFinite(startedAtMs)) return
// agy cannot be found by directory — its repair reads the presence lock the process holds open.
//
- const found = await findLiveSession(observed.engine, observed.cwd, startedAtMs, {
+ const located = await read(() => findLiveSession(observed.engine, observed.cwd, startedAtMs, {
bornOnly: true,
pid: observed.processIdentity.pid,
codexHome: agent.codexHome ?? undefined,
- }).catch(error => {
- // A native store can be unreadable or exceed a safe identity bound. That holds this
- // process alone; rejecting onObserved would abort the serial discovery/readiness pass.
- console.log(`[discovery] ${sid(agent.agentId)} binding held · ${error instanceof Error ? error.message : error}`)
- return null
- })
+ }))
+ if (!located) return
+ const found = located.value
if (!found || registry.has(found.sessionId) || isRecentlyDeleted(found.sessionId)) return
sessionId = found.sessionId
transcriptPath = found.transcriptPath
diff --git a/cli/src/core/engines/cursorDiscovery.spec.ts b/cli/src/core/engines/cursorDiscovery.spec.ts
index a2f48703a..8c2b79fe4 100644
--- a/cli/src/core/engines/cursorDiscovery.spec.ts
+++ b/cli/src/core/engines/cursorDiscovery.spec.ts
@@ -3,10 +3,10 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
import { createCursorDiscovery, type CursorDiscovery } from './cursorDiscovery.js'
-import { validTranscriptPath } from '../../lib/registry.js'
+import { inspectTranscriptPath } from '../../lib/registry.js'
vi.mock('../../engines/inProcess.js', () => ({ engineNow: () => { throw new Error('optional engine unavailable') } }))
-vi.mock('../../lib/registry.js', () => ({ validTranscriptPath: vi.fn(() => true) }))
+vi.mock('../../lib/registry.js', () => ({ inspectTranscriptPath: vi.fn(() => true) }))
const root = mkdtempSync(join(tmpdir(), 'core-cursor-discovery-'))
let discovery: CursorDiscovery
@@ -21,6 +21,7 @@ it('uses the declared data layout and registry validation without loading an eng
await discovery.start()
await discovery.add(id)
expect(found).toHaveBeenCalledExactlyOnceWith(id, path)
- expect(validTranscriptPath).toHaveBeenCalledExactlyOnceWith('cursor', path)
+ expect(inspectTranscriptPath).toHaveBeenCalledTimes(2)
+ expect(inspectTranscriptPath).toHaveBeenLastCalledWith('cursor', path)
discovery.remove(id)
})
diff --git a/cli/src/core/engines/cursorDiscovery.ts b/cli/src/core/engines/cursorDiscovery.ts
index 5c4652e95..c594329a4 100644
--- a/cli/src/core/engines/cursorDiscovery.ts
+++ b/cli/src/core/engines/cursorDiscovery.ts
@@ -1,11 +1,11 @@
/** Transcript discovery is session control, present even when Cursor's optional readers cannot load. */
import { CURSOR_TRANSCRIPT, CURSOR_TRANSCRIPT_POLL_MS } from '../../engines/cursor/contract.js'
import { TranscriptDiscovery } from '../../engines/kit/transcriptDiscovery.js'
-import { validTranscriptPath } from '../../lib/registry.js'
+import { inspectTranscriptPath } from '../../lib/registry.js'
export type CursorDiscovery = Pick<TranscriptDiscovery, 'start' | 'add' | 'remove' | 'stop'>
export function createCursorDiscovery(cursorHome: string, onFound: (sessionId: string, transcriptPath: string) => void): CursorDiscovery {
return new TranscriptDiscovery(cursorHome, CURSOR_TRANSCRIPT, onFound,
- path => validTranscriptPath('cursor', path), CURSOR_TRANSCRIPT_POLL_MS)
+ path => inspectTranscriptPath('cursor', path), CURSOR_TRANSCRIPT_POLL_MS)
}
diff --git a/cli/src/engines/__fixtures__/native-location.golden.json b/cli/src/engines/__fixtures__/native-location.golden.json
new file mode 100644
index 000000000..dd1c6bf95
--- /dev/null
+++ b/cli/src/engines/__fixtures__/native-location.golden.json
@@ -0,0 +1,35 @@
+{
+ "cursor:existing": "<root>/cursor/projects/project/agent-transcripts/aaaaaaaa-1111-4222-8333-000000000001/aaaaaaaa-1111-4222-8333-000000000001.jsonl",
+ "cursor:missing": null,
+ "cursor:invalid": null,
+ "cursor:validation-rejected": null,
+ "cursor:groups": "<root>/cursor/projects/project/agent-transcripts/aaaaaaaa-1111-4222-8333-000000000001/aaaaaaaa-1111-4222-8333-000000000001.jsonl",
+ "copilot:existing": "<root>/copilot/session-state/aaaaaaaa-1111-4222-8333-000000000003/events.jsonl",
+ "copilot:missing": null,
+ "copilot:invalid": null,
+ "agy:existing": "<root>/agy/brain/aaaaaaaa-1111-4222-8333-000000000003/.system_generated/logs/transcript_full.jsonl",
+ "agy:missing": null,
+ "agy:invalid": null,
+ "grok:encoded": "<root>/grok/sessions/%2Fwork%2Fencoded/aaaaaaaa-1111-4222-8333-000000000005/updates.jsonl",
+ "grok:hashed": "<root>/grok/sessions/hashed-workspace/aaaaaaaa-1111-4222-8333-000000000006/updates.jsonl",
+ "grok:other-workspace": null,
+ "grok:missing": null,
+ "grok:no-workspace": null,
+ "copilot:newest-lock": "aaaaaaaa-1111-4222-8333-000000000012",
+ "copilot:no-lock": null,
+ "copilot:invalid-pid": null,
+ "agy:held-lock": "aaaaaaaa-1111-4222-8333-000000000013",
+ "agy:no-lock": null,
+ "agy:invalid-pid": null,
+ "discovery:found": [
+ [
+ "aaaaaaaa-1111-4222-8333-000000000021",
+ "<root>/pending/projects/project/agent-transcripts/aaaaaaaa-1111-4222-8333-000000000021/aaaaaaaa-1111-4222-8333-000000000021.jsonl"
+ ],
+ [
+ "aaaaaaaa-1111-4222-8333-000000000022",
+ "<root>/pending/projects/project/agent-transcripts/aaaaaaaa-1111-4222-8333-000000000022/aaaaaaaa-1111-4222-8333-000000000022.jsonl"
+ ]
+ ],
+ "discovery:stopped": false
+}
diff --git a/cli/src/engines/cursor/discovery.ts b/cli/src/engines/cursor/discovery.ts
index 303ff3311..c50064fe7 100644
--- a/cli/src/engines/cursor/discovery.ts
+++ b/cli/src/engines/cursor/discovery.ts
@@ -1,5 +1,5 @@
/** Compatibility entry for optional Cursor consumers; session control uses the eager kit directly. */
-import { validTranscriptPath } from '../../lib/registry.js'
+import { inspectTranscriptPath } from '../../lib/registry.js'
import { TranscriptDiscovery } from '../kit/transcriptDiscovery.js'
import { locateTranscript } from '../kit/sessionLocation.js'
import { CURSOR_TRANSCRIPT, CURSOR_TRANSCRIPT_POLL_MS } from './contract.js'
@@ -7,10 +7,10 @@ export { CURSOR_TRANSCRIPT_POLL_MS } from './contract.js'
export class CursorTranscriptDiscovery extends TranscriptDiscovery {
constructor(home: string, onFound: (sessionId: string, path: string) => void, pollMs = CURSOR_TRANSCRIPT_POLL_MS) {
- super(home, CURSOR_TRANSCRIPT, onFound, path => validTranscriptPath('cursor', path), pollMs)
+ super(home, CURSOR_TRANSCRIPT, onFound, path => inspectTranscriptPath('cursor', path), pollMs)
}
}
export function findCursorTranscript(home: string, id: string): Promise<string | null> {
- return locateTranscript(CURSOR_TRANSCRIPT, home, id, { valid: path => validTranscriptPath('cursor', path) })
+ return locateTranscript(CURSOR_TRANSCRIPT, home, id, { valid: path => inspectTranscriptPath('cursor', path) })
}
diff --git a/cli/src/engines/identities.ts b/cli/src/engines/identities.ts
index 30cc1ddf8..aa16e36e1 100644
--- a/cli/src/engines/identities.ts
+++ b/cli/src/engines/identities.ts
@@ -4,7 +4,7 @@ import { GROK_TRANSCRIPT } from './grok/contract.js'
import { AGY_PROCESS_SESSION, AGY_TRANSCRIPT } from './agy/contract.js'
import { COPILOT_PROCESS_SESSION, COPILOT_TRANSCRIPT } from './copilot/contract.js'
import { locateProcessSession, locateTranscript } from './kit/sessionLocation.js'
-import { validTranscriptPath } from '../lib/registry.js'
+import { inspectTranscriptPath } from '../lib/registry.js'
import { env } from '../config/env.js'
import { readProcessEnv } from '../lib/processEnv.js'
import type { ProcessIdentity } from '../lib/terminalTypes.js'
@@ -17,7 +17,7 @@ export type LocatedEngine = keyof typeof transcripts
export function transcriptOf(engine: LocatedEngine, home: string, id: string, cwd?: string): Promise<string | null> {
return locateTranscript(transcripts[engine], home, id, { cwd,
- ...(engine === 'cursor' ? { valid: (path: string) => validTranscriptPath(engine, path) } : {}),
+ ...(engine === 'cursor' ? { valid: (path: string) => inspectTranscriptPath(engine, path) } : {}),
})
}
export function processSessionOf(engine: 'agy' | 'copilot', home: string, pid: number): Promise<string | null> {
diff --git a/cli/src/engines/kit/sessionLocation.spec.ts b/cli/src/engines/kit/sessionLocation.spec.ts
new file mode 100644
index 000000000..c562d82b2
--- /dev/null
+++ b/cli/src/engines/kit/sessionLocation.spec.ts
@@ -0,0 +1,276 @@
+import { execFile } from 'node:child_process'
+import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, unlinkSync, 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, expect, it, vi } from 'vitest'
+import { CURSOR_TRANSCRIPT } from '../cursor/contract.js'
+import { GROK_TRANSCRIPT } from '../grok/contract.js'
+import { COPILOT_PROCESS_SESSION, COPILOT_TRANSCRIPT } from '../copilot/contract.js'
+import { AGY_PROCESS_SESSION } from '../agy/contract.js'
+import { locateProcessSession, locateTranscript, transcriptGroups } from './sessionLocation.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), readlink: vi.fn(actual.readlink) }
+})
+vi.mock('node:child_process', async original => {
+ const actual = await original<typeof import('node:child_process')>()
+ const { promisify } = await import('node:util')
+ const execFile = vi.fn(() => { throw new Error('Unexpected host process probe') })
+ Object.defineProperty(execFile, promisify.custom, { value: (...args: unknown[]) => new Promise((resolve, reject) => {
+ Reflect.apply(execFile, undefined, [...args, (error: unknown, stdout: string, stderr: string) =>
+ error ? reject(error) : resolve({ stdout, stderr })])
+ }) })
+ return { ...actual, execFile }
+})
+const A = 'aaaaaaaa-1111-4222-8333-444444444444', B = 'bbbbbbbb-1111-4222-8333-444444444444'
+let root: string
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+let actual: typeof fs
+const permission = () => Object.assign(new Error('private fixture denied'), { code: 'EACCES' })
+function file(path: string, text = ''): string { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); return path }
+const cursor = (project = 'p', id = A) => file(join(root, 'projects', project, 'agent-transcripts', id, `${id}.jsonl`), '{}\n')
+const lock = (id = A, time = 1000) => {
+ const path = file(join(root, 'session-state', id, 'inuse.4242.lock'))
+ utimesSync(path, time / 1000, time / 1000); return path
+}
+const lookup = () => locateTranscript(CURSOR_TRANSCRIPT, root, A)
+const copilot = () => locateProcessSession(COPILOT_PROCESS_SESSION, root, 4242)
+const agy = () => locateProcessSession(AGY_PROCESS_SESSION, root, 4242)
+function descriptors(...paths: string[]): void {
+ const folder = join(root, 'proc', '4242', 'fd'); mkdirSync(folder, { recursive: true })
+ paths.forEach((path, index) => symlinkSync(path, join(folder, String(index))))
+}
+function lsof(stdout: string, error: unknown = null): void {
+ vi.mocked(execFile).mockImplementation(((...args: unknown[]) => {
+ const callback = args.at(-1) as (error: unknown, stdout: string, stderr: string) => void
+ callback(error, stdout, ''); return {}
+ }) as typeof execFile)
+}
+beforeEach(async () => {
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'native-location-')))
+ actual = await vi.importActual<typeof fs>('node:fs/promises')
+ vi.mocked(fs.open).mockReset().mockImplementation(actual.open)
+ const mapped = (path: unknown) => String(path).startsWith('/proc/') ? join(root, 'proc', String(path).slice(6)) : path
+ vi.mocked(fs.opendir).mockReset().mockImplementation(((path: unknown, ...args: unknown[]) =>
+ Reflect.apply(actual.opendir, actual, [mapped(path), ...args])) as typeof fs.opendir)
+ vi.mocked(fs.stat).mockReset().mockImplementation(actual.stat)
+ vi.mocked(fs.readlink).mockReset().mockImplementation(((path: unknown, ...args: unknown[]) =>
+ Reflect.apply(actual.readlink, actual, [mapped(path), ...args])) as typeof fs.readlink)
+ vi.mocked(execFile).mockReset().mockImplementation(() => { throw new Error('Unexpected host process probe') })
+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })
+})
+afterEach(() => { Object.defineProperty(process, 'platform', platform); vi.restoreAllMocks(); rmSync(root, { recursive: true, force: true }) })
+
+it('keeps verified missing stores and invalid IDs distinct from unreadable stores', async () => {
+ await expect(lookup()).resolves.toBeNull()
+ vi.mocked(fs.opendir).mockClear()
+ await expect(locateTranscript(CURSOR_TRANSCRIPT, root, '../escape')).resolves.toBeNull()
+ expect(fs.opendir).not.toHaveBeenCalled()
+ cursor(); vi.mocked(fs.opendir).mockRejectedValueOnce(permission())
+ await expect(lookup()).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+})
+it('holds duplicate transcripts instead of accepting the first project', async () => {
+ cursor('first'); cursor('second')
+ await expect(lookup()).rejects.toThrow('more than one transcript')
+})
+it('allows two project links to name the same native file', async () => {
+ cursor('p'); symlinkSync(join(root, 'projects', 'p'), join(root, 'projects', 'alias'))
+ await expect(lookup()).resolves.toMatch(/\/(p|alias)\/agent-transcripts\//)
+})
+it('holds an unreadable competitor after finding a usable transcript', async () => {
+ cursor('first'); const second = cursor('second')
+ vi.mocked(fs.stat).mockImplementation(((path, ...args) => String(path) === second
+ ? Promise.reject(permission()) : Reflect.apply(actual.stat, actual, [path, ...args])) as typeof fs.stat)
+ await expect(lookup()).rejects.toThrow('could not be inspected')
+})
+it('holds a selected transcript that disappears before publication', async () => {
+ const path = cursor(); let reads = 0
+ vi.mocked(fs.stat).mockImplementation(((name, ...args) => {
+ if (String(name) === path && ++reads === 2) unlinkSync(path)
+ return Reflect.apply(actual.stat, actual, [name, ...args])
+ }) as typeof fs.stat)
+ await expect(lookup()).rejects.toThrow('selected transcript changed')
+})
+it('bounds directory buffering and supplied group probes', async () => {
+ const close = vi.fn()
+ vi.mocked(fs.opendir).mockResolvedValueOnce({ async *[Symbol.asyncIterator]() {
+ try { for (let i = 0; i < 5000; i++) yield { name: String(i), isDirectory: () => true } }
+ finally { close() }
+ } } as never)
+ await expect(transcriptGroups(root, CURSOR_TRANSCRIPT)).rejects.toThrow('directory entry limit')
+ expect(close).toHaveBeenCalledOnce()
+ expect(fs.opendir).toHaveBeenCalledWith(join(root, 'projects'), { bufferSize: 32 })
+ vi.mocked(fs.stat).mockClear()
+ await expect(locateTranscript(CURSOR_TRANSCRIPT, root, A, { groups: Array(4097).fill('p') })).rejects.toThrow('probe limit')
+ expect(fs.stat).not.toHaveBeenCalled()
+})
+it('holds a nonregular direct transcript instead of declaring it absent', async () => {
+ mkdirSync(join(root, 'session-state', A, 'events.jsonl'), { recursive: true })
+ await expect(locateTranscript(COPILOT_TRANSCRIPT, root, A)).rejects.toThrow('not a regular file')
+})
+it.each(['missing', 'relative', 'oversized'])('holds a Grok candidate with a %s workspace sidecar', async mode => {
+ file(join(root, 'sessions', 'hash', A, 'updates.jsonl'))
+ if (mode !== 'missing') file(join(root, 'sessions', 'hash', '.cwd'), mode === 'relative' ? 'relative' : '/' + 'x'.repeat(65536))
+ await expect(locateTranscript(GROK_TRANSCRIPT, root, A, { cwd: '/workspace' })).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+})
+it('does not let an encoded Grok candidate hide an unreadable hashed competitor', async () => {
+ file(join(root, 'sessions', encodeURIComponent('/workspace'), A, 'updates.jsonl'))
+ file(join(root, 'sessions', 'hash', A, 'updates.jsonl'))
+ await expect(locateTranscript(GROK_TRANSCRIPT, root, A, { cwd: '/workspace' })).rejects.toThrow('sidecar could not be read')
+})
+it('excludes a verified other workspace and preserves registry path rejection', async () => {
+ file(join(root, 'sessions', 'hash', A, 'updates.jsonl')); file(join(root, 'sessions', 'hash', '.cwd'), '/elsewhere')
+ await expect(locateTranscript(GROK_TRANSCRIPT, root, A, { cwd: '/workspace' })).resolves.toBeNull()
+ cursor(); await expect(locateTranscript(CURSOR_TRANSCRIPT, root, A, { valid: () => false })).resolves.toBeNull()
+})
+it('checks the selected Grok workspace after later sidecars and transcript evidence', async () => {
+ file(join(root, 'sessions', 'a', A, 'updates.jsonl'))
+ const selected = file(join(root, 'sessions', 'a', '.cwd'), '/workspace')
+ file(join(root, 'sessions', 'b', A, 'updates.jsonl'))
+ const other = file(join(root, 'sessions', 'b', '.cwd'), '/elsewhere')
+ const groups = await transcriptGroups(root, GROK_TRANSCRIPT); groups.sort()
+ let reads = 0
+ vi.mocked(fs.open).mockImplementation(((path, ...args) => {
+ // Each bounded read opens twice. Change the selected evidence during the other sidecar's recheck.
+ if (String(path) === other && ++reads === 3) writeFileSync(selected, '/changed')
+ return Reflect.apply(actual.open, actual, [path, ...args])
+ }) as typeof fs.open)
+ await expect(locateTranscript(GROK_TRANSCRIPT, root, A, { cwd: '/workspace', groups })).rejects.toThrow('sidecar changed')
+})
+it('revalidates the selected registry path after all asynchronous reads', async () => {
+ cursor()
+ const valid = vi.fn().mockReturnValueOnce(true).mockReturnValueOnce(false)
+ await expect(locateTranscript(CURSOR_TRANSCRIPT, root, A, { valid })).rejects.toThrow('selected transcript path changed')
+})
+it('holds equally new process locks instead of guessing by directory order', async () => {
+ lock(A); lock(B)
+ await expect(copilot()).rejects.toThrow('newest process lock is ambiguous')
+})
+it('does not let an unreadable process claim make a sibling newest', async () => {
+ lock(A); const unknown = lock(B, 2000)
+ vi.mocked(fs.stat).mockImplementation(((path, ...args) => String(path) === unknown
+ ? Promise.reject(permission()) : Reflect.apply(actual.stat, actual, [path, ...args])) as typeof fs.stat)
+ await expect(copilot()).rejects.toThrow('could not be inspected')
+})
+it('rechecks the selected process claim after the other claims', async () => {
+ const selected = lock(A, 3000), other = lock(B, 1000); let otherReads = 0
+ vi.mocked(fs.stat).mockImplementation(((path, ...args) => {
+ if (String(path) === other && ++otherReads === 2) writeFileSync(selected, 'changed')
+ return Reflect.apply(actual.stat, actual, [path, ...args])
+ }) as typeof fs.stat)
+ await expect(copilot()).rejects.toThrow('process lock changed')
+})
+it('bounds process-lock enumeration before selecting from a partial pool', async () => {
+ lock()
+ vi.mocked(fs.opendir).mockResolvedValueOnce({ async *[Symbol.asyncIterator]() {
+ for (let i = 0; i < 5000; i++) yield { name: 'irrelevant', isDirectory: () => false }
+ } } as never)
+ await expect(copilot()).rejects.toThrow('directory entry limit')
+})
+it('accepts repeated descriptors for one conversation, but holds two distinct locks', async () => {
+ const first = join(root, 'presence', `${A}.lock`)
+ descriptors(first, first)
+ await expect(agy()).resolves.toBe(A)
+ symlinkSync(join(root, 'presence', `${B}.lock`), join(root, 'proc', '4242', 'fd', 'third'))
+ await expect(agy()).rejects.toThrow('more than one conversation lock')
+})
+it('holds unavailable or partially readable process descriptors', async () => {
+ await expect(agy()).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ descriptors(join(root, 'presence', `${A}.lock`), '/dev/null')
+ vi.mocked(fs.readlink).mockRejectedValueOnce(permission())
+ await expect(agy()).rejects.toThrow('descriptor could not be read')
+})
+it('ignores unrelated descriptors only after reading the complete pool', async () => {
+ descriptors('/dev/null', join(root, 'presence', 'invalid.lock'))
+ await expect(agy()).resolves.toBeNull()
+ expect(execFile).not.toHaveBeenCalled()
+})
+it.each(['error', 'partial', 'oversized', 'entries'])('holds %s lsof output instead of using its readable prefix', async mode => {
+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })
+ const valid = `p4242\nn${join(root, 'presence', `${A}.lock`)}\n`
+ lsof(mode === 'partial' ? valid.trimEnd() : mode === 'oversized' ? valid + 'x'.repeat(256 * 1024) + '\n'
+ : mode === 'entries' ? valid + '\n'.repeat(4096) : valid, mode === 'error' ? Object.assign(new Error('probe failed'), { stdout: valid }) : null)
+ await expect(agy()).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+ expect(execFile).toHaveBeenCalledWith('lsof', ['-n', '-P', '-w', '-p', '4242', '-Fn'],
+ expect.objectContaining({ timeout: 4000, killSignal: 'SIGKILL', maxBuffer: 256 * 1024 }), expect.any(Function))
+})
+it('uses a completed Darwin descriptor probe without running a host binary', async () => {
+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })
+ lsof(`p4242\nn${join(root, 'presence', `${A}.lock`)}\n`)
+ await expect(agy()).resolves.toBe(A)
+})
+
+it('allows ordinary transcript appends while retaining the same file identity', async () => {
+ const path = cursor(); let reads = 0
+ vi.mocked(fs.stat).mockImplementation(((name, ...args) => {
+ if (String(name) === path && ++reads === 2) writeFileSync(path, '{}\n{}\n')
+ return Reflect.apply(actual.stat, actual, [name, ...args])
+ }) as typeof fs.stat)
+ await expect(lookup()).resolves.toBe(path)
+})
+it('holds a competing transcript that appears during the rest of the lookup', async () => {
+ cursor('first'); mkdirSync(join(root, 'projects', 'other'), { recursive: true })
+ const appearing = join(root, 'projects', 'other', 'agent-transcripts', A, `${A}.jsonl`)
+ let reads = 0
+ vi.mocked(fs.stat).mockImplementation(((name, ...args) => {
+ if (String(name) === appearing && ++reads === 2) file(appearing)
+ return Reflect.apply(actual.stat, actual, [name, ...args])
+ }) as typeof fs.stat)
+ await expect(lookup()).rejects.toThrow('transcript candidate changed')
+})
+it('does not use a shared directory listing after its root changes', async () => {
+ cursor('first')
+ const groups = await transcriptGroups(root, CURSOR_TRANSCRIPT)
+ cursor('new')
+ await expect(locateTranscript(CURSOR_TRANSCRIPT, root, A, { groups })).rejects.toThrow('directory list changed')
+})
+it('holds a new process session directory appearing while old claims are rechecked', async () => {
+ const selected = lock(A, 3000), other = lock(B, 1000); let reads = 0
+ vi.mocked(fs.stat).mockImplementation(((name, ...args) => {
+ if (String(name) === other && ++reads === 2) lock('cccccccc-1111-4222-8333-444444444444', 9000)
+ return Reflect.apply(actual.stat, actual, [name, ...args])
+ }) as typeof fs.stat)
+ await expect(copilot()).rejects.toThrow('session directories changed')
+ expect(selected).toContain(A)
+})
+it('rechecks a held conversation descriptor after inspecting unrelated descriptors', async () => {
+ const held = join(root, 'presence', `${A}.lock`)
+ descriptors(held, '/dev/null'); let reads = 0
+ const fd = join(root, 'proc', '4242', 'fd', '0')
+ vi.mocked(fs.readlink).mockImplementation(((name, ...args) => {
+ const mapped = join(root, 'proc', String(name).slice(6))
+ if (String(name).endsWith('/1') && ++reads === 2) {
+ unlinkSync(fd); symlinkSync(join(root, 'presence', `${B}.lock`), fd)
+ }
+ return Reflect.apply(actual.readlink, actual, [mapped, ...args])
+ }) as typeof fs.readlink)
+ await expect(agy()).rejects.toThrow('descriptor changed')
+})
+it('holds a descriptor pool that grows before publication', async () => {
+ descriptors(join(root, 'presence', `${A}.lock`)); let opens = 0
+ vi.mocked(fs.opendir).mockImplementation(((name, ...args) => {
+ if (++opens === 2) symlinkSync(join(root, 'presence', `${B}.lock`), join(root, 'proc', '4242', 'fd', '1'))
+ return Reflect.apply(actual.opendir, actual, [join(root, 'proc', String(name).slice(6)), ...args])
+ }) as typeof fs.opendir)
+ await expect(agy()).rejects.toThrow('descriptor list changed')
+})
+it('holds a deleted lock that the process still has open', async () => {
+ descriptors(join(root, 'presence', `${A}.lock (deleted)`))
+ await expect(agy()).rejects.toThrow('deleted conversation lock')
+})
+it('holds changing Darwin descriptor evidence', async () => {
+ Object.defineProperty(process, 'platform', { ...platform, value: 'darwin' })
+ let reads = 0
+ vi.mocked(execFile).mockImplementation(((...args: unknown[]) => {
+ const callback = args.at(-1) as (error: unknown, stdout: string, stderr: string) => void
+ callback(null, `p4242\nn${join(root, 'presence', `${++reads === 1 ? A : B}.lock`)}\n`, ''); return {}
+ }) as typeof execFile)
+ await expect(agy()).rejects.toThrow('descriptors changed')
+})
+
+it('does not allow a supplied subset to hide another project', async () => {
+ cursor('first'); cursor('second')
+ await expect(locateTranscript(CURSOR_TRANSCRIPT, root, A, { groups: ['first'] })).rejects.toThrow('more than one transcript')
+})
diff --git a/cli/src/engines/kit/sessionLocation.ts b/cli/src/engines/kit/sessionLocation.ts
index 2a083fa17..25d0d981d 100644
--- a/cli/src/engines/kit/sessionLocation.ts
+++ b/cli/src/engines/kit/sessionLocation.ts
@@ -1,8 +1,11 @@
/** Filesystem evidence for binding, declared by each engine and available before optional readers load. */
import { execFile } from 'node:child_process'
-import { access, readdir, readFile, readlink, stat } from 'fs/promises'
-import { basename, join, sep } from 'node:path'
+import { createHash } from 'node:crypto'
+import type { Stats } from 'node:fs'
+import { readlink, stat } from 'node:fs/promises'
+import { basename, isAbsolute, join, sep } from 'node:path'
import { promisify } from 'node:util'
+import { identityEntries, identityFile, identityScanBudget, IdentityReadUnavailable } from './identityScan.js'
export type TranscriptLocation = { id: RegExp; root: string } & (
| { kind: 'direct'; file: readonly string[] }
@@ -15,15 +18,47 @@ export type ProcessSessionLocation = { id: RegExp; root: string; suffix: string
| { kind: 'open-lock'; timeoutMs: number }
)
-async function isFile(path: string): Promise<boolean> {
- try { return (await stat(path)).isFile() } catch { return false }
+async function inspect(path: string): Promise<Stats | null> {
+ try { return await stat(path) }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw new IdentityReadUnavailable('a native location could not be inspected')
+ }
+}
+async function fileInfo(path: string): Promise<Stats | null> {
+ const info = await inspect(path)
+ if (info && !info.isFile()) throw new IdentityReadUnavailable('a native identity location is not a regular file')
+ return info
+}
+const signature = (info: Stats | null) => info && `${info.dev}:${info.ino}:${info.size}:${info.mtimeMs}:${info.ctimeMs}`
+const fileIdentity = (info: Stats | null) => info && `${info.dev}:${info.ino}`
+const digest = (text: string) => createHash('sha256').update(text).digest('hex')
+type WorkspaceProof = { path: string; digest: string }
+async function verifyWorkspace(proof: WorkspaceProof): Promise<void> {
+ const current = await identityFile(proof.path).catch(() => { throw new IdentityReadUnavailable('a workspace sidecar became unavailable during lookup') })
+ if (digest(current) !== proof.digest) throw new IdentityReadUnavailable('a workspace sidecar changed during lookup')
}
+// Evidence belongs to this one listing, not a cache reused by later polls.
+const groupProofs = new WeakMap<readonly string[], { root: string; signature: string | null }>()
+/** A complete bounded listing. An unreadable directory is not an empty store. */
export async function transcriptGroups(home: string, rule: TranscriptLocation): Promise<string[]> {
- return readdir(join(home, rule.root)).catch(() => [])
+ const root = join(home, rule.root), groups: string[] = []
+ const before = signature(await inspect(root))
+ for await (const entry of identityEntries(root, identityScanBudget())) {
+ if (entry.isDirectory()) groups.push(entry.name)
+ else if (entry.isSymbolicLink()) {
+ const info = await inspect(join(root, entry.name))
+ if (!info) throw new IdentityReadUnavailable('a native directory link disappeared')
+ if (info.isDirectory()) groups.push(entry.name)
+ }
+ }
+ if (signature(await inspect(root)) !== before) throw new IdentityReadUnavailable('the native directory list changed during lookup')
+ groupProofs.set(groups, { root, signature: before })
+ return groups
}
-/** One known id, never a guess by newest transcript. A grouped lookup may share its listing across a sweep. */
+/** One known id in a complete pool. Two different files cannot both be its authoritative transcript. */
export async function locateTranscript(rule: TranscriptLocation, home: string, id: string,
options: { cwd?: string; groups?: readonly string[]; valid?: (path: string) => boolean } = {},
): Promise<string | null> {
@@ -31,68 +66,160 @@ export async function locateTranscript(rule: TranscriptLocation, home: string, i
const root = join(home, rule.root)
if (rule.kind === 'direct') {
const path = join(root, id, ...rule.file)
- return await isFile(path) ? path : null
+ return await fileInfo(path) ? path : null
}
- if (rule.kind === 'cwd') {
- if (!options.cwd) return null
- const direct = join(root, encodeURIComponent(options.cwd), id, rule.file)
- if (await isFile(direct)) return direct
- const groups = await readdir(root, { withFileTypes: true }).catch(() => [])
- for (const group of groups) {
- if (!group.isDirectory()) continue
- const directory = join(root, group.name)
- const cwd = await readFile(join(directory, rule.sidecar), 'utf8').catch(() => '')
- if (cwd.trim() !== options.cwd) continue
- const path = join(directory, id, rule.file)
- if (await isFile(path)) return path
+ if (rule.kind === 'cwd' && !options.cwd) return null
+ if (options.groups && options.groups.length > 4096) throw new IdentityReadUnavailable('the native location probe limit was reached')
+ const shared = options.groups && groupProofs.get(options.groups)
+ const groups = shared?.root === root ? options.groups! : await transcriptGroups(home, rule)
+ const proof = groupProofs.get(groups)!
+ const files: { path: string; info: Stats | null }[] = []
+ // Keep fixed-size digests, not up to 64 KiB of retained text for every project.
+ const sidecars: WorkspaceProof[] = []
+ let selected: { path: string; info: Stats; workspace?: WorkspaceProof } | null = null
+ for (const group of groups) {
+ const directory = join(root, group)
+ const path = rule.kind === 'projects'
+ ? join(directory, rule.folder, id, `${id}${rule.suffix}`) : join(directory, id, rule.file)
+ const info = await fileInfo(path)
+ files.push({ path, info })
+ if (!info) continue
+ let workspace: WorkspaceProof | undefined
+ if (rule.kind === 'cwd' && group !== encodeURIComponent(options.cwd!)) {
+ let cwd: string
+ try {
+ const sidecar = join(directory, rule.sidecar), text = await identityFile(sidecar)
+ workspace = { path: sidecar, digest: digest(text) }
+ sidecars.push(workspace); cwd = text.trim()
+ }
+ catch (error) {
+ if (error instanceof IdentityReadUnavailable) throw error
+ throw new IdentityReadUnavailable('the native workspace sidecar could not be read')
+ }
+ if (!isAbsolute(cwd)) throw new IdentityReadUnavailable('the native workspace sidecar is invalid')
+ if (cwd !== options.cwd) continue
}
- return null
- }
- for (const group of options.groups ?? await transcriptGroups(home, rule)) {
- const path = join(root, group, rule.folder, id, `${id}${rule.suffix}`)
// Only an existing candidate pays for the registry's synchronous realpath validation.
- if (!await access(path).then(() => true, () => false)) continue
- if (!options.valid || options.valid(path)) return path
+ if (options.valid && !options.valid(path)) continue
+ if (selected && (selected.info.dev !== info.dev || selected.info.ino !== info.ino)) {
+ throw new IdentityReadUnavailable('more than one transcript matches the conversation')
+ }
+ selected ??= { path, info, workspace }
}
- return null
+ // Negative candidates matter too: a competing file may appear while later projects are read.
+ for (const file of files) {
+ if (file.path !== selected?.path && fileIdentity(await fileInfo(file.path)) !== fileIdentity(file.info)) {
+ throw new IdentityReadUnavailable('a transcript candidate changed during lookup')
+ }
+ }
+ for (const sidecar of sidecars) {
+ if (sidecar !== selected?.workspace) await verifyWorkspace(sidecar)
+ }
+ if (signature(await inspect(root)) !== proof.signature) throw new IdentityReadUnavailable('the native directory list changed during lookup')
+ if (!selected) return null
+ // Appending conversation records does not change the identity of its file.
+ if (fileIdentity(await fileInfo(selected.path)) !== fileIdentity(selected.info)) {
+ throw new IdentityReadUnavailable('the selected transcript changed during lookup')
+ }
+ // The selected workspace must survive every other native await, including other sidecars.
+ if (selected.workspace) await verifyWorkspace(selected.workspace)
+ if (options.valid && !options.valid(selected.path)) throw new IdentityReadUnavailable('the selected transcript path changed during lookup')
+ return selected.path
}
const execFileAsync = promisify(execFile)
+const DESCRIPTOR_BYTES = 256 * 1024
-/** Native process evidence: the newest session lock, or a lock descriptor the process still holds. */
+/** Native process evidence is useful only when every relevant claim could be inspected. */
export async function locateProcessSession(rule: ProcessSessionLocation, home: string, pid: number): Promise<string | null> {
if (!Number.isSafeInteger(pid) || pid <= 0) return null
const root = join(home, rule.root)
if (rule.kind === 'newest-lock') {
- const entries = await readdir(root, { withFileTypes: true }).catch(() => [])
- let best: { id: string; time: number } | null = null
- for (const entry of entries) {
- if (!entry.isDirectory() || !rule.id.test(entry.name)) continue
- const info = await stat(join(root, entry.name, `${rule.prefix}${pid}${rule.suffix}`)).catch(() => null)
- if (info && (!best || info.mtimeMs > best.time)) best = { id: entry.name, time: info.mtimeMs }
+ const before = signature(await inspect(root))
+ const claims: { path: string; id: string; info: Stats | null }[] = []
+ let best: typeof claims[number] | null = null
+ let tied = false
+ for await (const entry of identityEntries(root, identityScanBudget())) {
+ if (!rule.id.test(entry.name)) continue
+ if (entry.isSymbolicLink()) throw new IdentityReadUnavailable('a native session directory is a symbolic link')
+ if (!entry.isDirectory()) continue
+ const path = join(root, entry.name, `${rule.prefix}${pid}${rule.suffix}`)
+ const claim = { path, id: entry.name, info: await fileInfo(path) }
+ claims.push(claim)
+ if (!claim.info) continue
+ if (!best || claim.info.mtimeMs > best.info!.mtimeMs) { best = claim; tied = false }
+ else if (claim.info.mtimeMs === best.info!.mtimeMs) tied = true
+ }
+ if (tied) throw new IdentityReadUnavailable('the newest process lock is ambiguous')
+ // A current claim is checked last so no later native await can make its answer stale.
+ for (const claim of claims.filter(claim => claim !== best)) {
+ if (signature(await fileInfo(claim.path)) !== signature(claim.info)) {
+ throw new IdentityReadUnavailable('a process lock changed during lookup')
+ }
+ }
+ if (signature(await inspect(root)) !== before) throw new IdentityReadUnavailable('the native session directories changed during lookup')
+ if (best && signature(await fileInfo(best.path)) !== signature(best.info)) {
+ throw new IdentityReadUnavailable('a process lock changed during lookup')
}
return best?.id ?? null
}
let paths: string[]
if (process.platform === 'linux') {
- const directory = `/proc/${pid}/fd`
- const entries = await readdir(directory).catch(() => [])
- paths = []
- for (const entry of entries) {
- const path = await readlink(join(directory, entry)).catch(() => '')
- if (path) paths.push(path)
+ const directory = `/proc/${pid}/fd`, budget = identityScanBudget()
+ const descriptors: { name: string; path: string }[] = []
+ const read = async (name: string): Promise<string> => {
+ try {
+ const path = await readlink(join(directory, name))
+ if (path) return path
+ } catch { /* A disappearing descriptor cannot prove a complete pool. */ }
+ throw new IdentityReadUnavailable('a process descriptor could not be read')
+ }
+ for await (const entry of identityEntries(directory, budget, false)) {
+ descriptors.push({ name: entry.name, path: await read(entry.name) })
+ }
+ const claimed = descriptors.filter(entry => entry.path.startsWith(root + sep) && entry.path.endsWith(rule.suffix))
+ for (const entry of descriptors.filter(entry => !claimed.includes(entry))) {
+ if (await read(entry.name) !== entry.path) throw new IdentityReadUnavailable('a process descriptor changed during lookup')
}
+ const names: string[] = []
+ for await (const entry of identityEntries(directory, budget, false)) names.push(entry.name)
+ if (names.sort().join('\0') !== descriptors.map(entry => entry.name).sort().join('\0')) {
+ throw new IdentityReadUnavailable('the process descriptor list changed during lookup')
+ }
+ // Recheck actual conversation descriptors last, after the complete pool is known.
+ for (const entry of claimed) {
+ if (await read(entry.name) !== entry.path) throw new IdentityReadUnavailable('a process descriptor changed during lookup')
+ }
+ paths = descriptors.map(entry => entry.path)
} else {
- const out = await execFileAsync('lsof', ['-w', '-p', String(pid), '-Fn'], { timeout: rule.timeoutMs })
- .then(result => result.stdout).catch((error: { stdout?: string }) => error.stdout ?? '')
- paths = out.split('\n').filter(line => line.startsWith('n')).map(line => line.slice(1))
+ const probe = async (): Promise<string[]> => {
+ let out: string
+ try {
+ out = (await execFileAsync('lsof', ['-n', '-P', '-w', '-p', String(pid), '-Fn'], {
+ encoding: 'utf8', timeout: rule.timeoutMs, killSignal: 'SIGKILL', maxBuffer: DESCRIPTOR_BYTES,
+ })).stdout
+ } catch { throw new IdentityReadUnavailable('the process descriptor probe did not complete') }
+ if (Buffer.byteLength(out) > DESCRIPTOR_BYTES || (out && !out.endsWith('\n'))) {
+ throw new IdentityReadUnavailable('the process descriptor output is incomplete')
+ }
+ const lines = out.split('\n')
+ if (lines.length > 4096) throw new IdentityReadUnavailable('the process descriptor entry limit was reached')
+ return lines.filter(line => line.startsWith('n')).map(line => line.slice(1)).sort()
+ }
+ paths = await probe()
+ if ((await probe()).join('\0') !== paths.join('\0')) throw new IdentityReadUnavailable('the process descriptors changed during lookup')
}
+ const ids = new Set<string>()
for (const path of paths) {
+ if (path.startsWith(root + sep) && path.endsWith(`${rule.suffix} (deleted)`)) {
+ throw new IdentityReadUnavailable('the process holds a deleted conversation lock')
+ }
if (!path.startsWith(root + sep) || !path.endsWith(rule.suffix)) continue
const id = basename(path, rule.suffix)
- if (rule.id.test(id)) return id
+ if (rule.id.test(id)) ids.add(id)
}
- return null
+ if (ids.size > 1) throw new IdentityReadUnavailable('the process holds more than one conversation lock')
+ return ids.values().next().value ?? null
}
/** A cwd in the opening records, with its envelope and field path declared by the engine. */
diff --git a/cli/src/engines/kit/transcriptDiscovery.spec.ts b/cli/src/engines/kit/transcriptDiscovery.spec.ts
index 6201323b1..4191e5d53 100644
--- a/cli/src/engines/kit/transcriptDiscovery.spec.ts
+++ b/cli/src/engines/kit/transcriptDiscovery.spec.ts
@@ -1,17 +1,18 @@
-import { afterEach, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { TranscriptDiscovery } from './transcriptDiscovery.js'
import { locateTranscript, transcriptGroups } from './sessionLocation.js'
import { CURSOR_TRANSCRIPT } from '../cursor/contract.js'
vi.mock('./sessionLocation.js', () => ({ locateTranscript: vi.fn(), transcriptGroups: vi.fn(async () => ['p']) }))
const id = 'aaaaaaaa-1111-4222-8333-444444444444'
const runs: TranscriptDiscovery[] = []
+beforeEach(() => { vi.spyOn(console, 'error').mockImplementation(() => {}) })
const fresh = () => {
const found = vi.fn()
const discovery = new TranscriptDiscovery('/fixture', CURSOR_TRANSCRIPT, found, () => true, 10)
runs.push(discovery)
return { discovery, found }
}
-afterEach(async () => { for (const run of runs.splice(0)) await run.stop(); vi.resetAllMocks(); vi.useRealTimers() })
+afterEach(async () => { for (const run of runs.splice(0)) await run.stop(); vi.resetAllMocks(); vi.restoreAllMocks(); vi.useRealTimers() })
it.each(['remove', 'stop'] as const)('revokes an initial lookup when %s happens before its answer', async action => {
let answer!: (path: string | null) => void
@@ -55,3 +56,67 @@ it('revokes a sweep after stop and a new start, even if the same session is pend
expect(found).toHaveBeenCalledExactlyOnceWith(id, '/fixture/new.jsonl')
expect(discovery.isPolling).toBe(false)
})
+
+
+it('retries an initial native read failure instead of leaving the candidate marked looking', async () => {
+ vi.useFakeTimers()
+ vi.mocked(transcriptGroups).mockResolvedValue(['p'])
+ vi.mocked(locateTranscript).mockRejectedValueOnce(new Error('unreadable candidate')).mockResolvedValue('/fixture/recovered.jsonl')
+ const { discovery, found } = fresh()
+ await discovery.start(); await expect(discovery.add(id)).resolves.toBeUndefined()
+ expect(found).not.toHaveBeenCalled(); expect(discovery.isPolling).toBe(true)
+ await vi.advanceTimersByTimeAsync(10)
+ expect(found).toHaveBeenCalledExactlyOnceWith(id, '/fixture/recovered.jsonl')
+ expect(discovery.isPolling).toBe(false)
+})
+it('holds only the failed sweep candidate and still publishes its sibling', async () => {
+ vi.useFakeTimers()
+ const sibling = 'bbbbbbbb-1111-4222-8333-444444444444'
+ vi.mocked(transcriptGroups).mockResolvedValue(['p'])
+ vi.mocked(locateTranscript).mockResolvedValueOnce(null).mockResolvedValueOnce(null)
+ .mockRejectedValueOnce(new Error('read unavailable')).mockResolvedValueOnce('/fixture/sibling.jsonl')
+ .mockResolvedValue('/fixture/recovered.jsonl')
+ const { discovery, found } = fresh()
+ await discovery.start(); await discovery.add(id); await discovery.add(sibling)
+ await vi.advanceTimersByTimeAsync(10)
+ expect(found).toHaveBeenCalledExactlyOnceWith(sibling, '/fixture/sibling.jsonl')
+ await vi.advanceTimersByTimeAsync(10)
+ expect(found).toHaveBeenLastCalledWith(id, '/fixture/recovered.jsonl')
+ expect(discovery.isPolling).toBe(false)
+})
+it('retains pending work across a failed group listing and reports a repeated hold once', async () => {
+ vi.useFakeTimers()
+ vi.mocked(locateTranscript).mockResolvedValueOnce(null).mockResolvedValue('/fixture/recovered.jsonl')
+ vi.mocked(transcriptGroups).mockRejectedValueOnce('directory unavailable').mockRejectedValueOnce('directory unavailable').mockResolvedValue(['p'])
+ const { discovery, found } = fresh()
+ await discovery.start(); await discovery.add(id)
+ await vi.advanceTimersByTimeAsync(20)
+ expect(found).not.toHaveBeenCalled(); expect(console.error).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(10)
+ expect(found).toHaveBeenCalledExactlyOnceWith(id, '/fixture/recovered.jsonl')
+})
+it.each(['remove', 'stop', 'replace'] as const)('does not revive a rejected lookup after %s', async action => {
+ vi.useFakeTimers()
+ let reject!: (error: Error) => void
+ vi.mocked(locateTranscript).mockReturnValueOnce(new Promise((_, no) => { reject = no })).mockResolvedValue('/fixture/new.jsonl')
+ const { discovery, found } = fresh()
+ await discovery.start(); const adding = discovery.add(id)
+ if (action === 'remove') discovery.remove(id)
+ else if (action === 'stop') await discovery.stop()
+ else await discovery.add(id)
+ reject(new Error('old lookup failed')); await adding
+ await vi.advanceTimersByTimeAsync(20)
+ expect(found).toHaveBeenCalledTimes(action === 'replace' ? 1 : 0)
+ expect(console.error).not.toHaveBeenCalled(); expect(discovery.isPolling).toBe(false)
+})
+it('retains a transcript whose publication throws, then retries it', async () => {
+ vi.useFakeTimers()
+ vi.mocked(transcriptGroups).mockResolvedValue(['p'])
+ vi.mocked(locateTranscript).mockResolvedValue('/fixture/found.jsonl')
+ const { discovery, found } = fresh()
+ found.mockImplementationOnce(() => { throw new Error('publication unavailable') })
+ await discovery.start(); await discovery.add(id)
+ expect(discovery.isPolling).toBe(true)
+ await vi.advanceTimersByTimeAsync(10)
+ expect(found).toHaveBeenCalledTimes(2); expect(discovery.isPolling).toBe(false)
+})
diff --git a/cli/src/engines/kit/transcriptDiscovery.ts b/cli/src/engines/kit/transcriptDiscovery.ts
index bb8cbf78c..dfea51a16 100644
--- a/cli/src/engines/kit/transcriptDiscovery.ts
+++ b/cli/src/engines/kit/transcriptDiscovery.ts
@@ -6,7 +6,7 @@ import { locateTranscript, transcriptGroups, type TranscriptLocation } from './s
* Every lookup carries its own candidate identity: remove, replacement and stop revoke it immediately.
*/
export class TranscriptDiscovery {
- private readonly pending = new Map<string, { looking: boolean }>()
+ private readonly pending = new Map<string, { looking: boolean; detail?: string }>()
private timer: NodeJS.Timeout | null = null
private started = false
private sweeping = false
@@ -28,14 +28,29 @@ export class TranscriptDiscovery {
if (!this.rule.id.test(id)) return
const candidate = { looking: true }
this.pending.set(id, candidate)
- const found = await locateTranscript(this.rule, this.home, id, { valid: this.valid })
+ try {
+ const found = await locateTranscript(this.rule, this.home, id, { valid: this.valid })
+ if (found && this.pending.get(id) === candidate) this.publish(id, candidate, found)
+ } catch (error) { this.hold(id, candidate, error) }
+ finally {
+ candidate.looking = false
+ this.schedule()
+ }
+ }
+
+ private hold(id: string, candidate: { looking: boolean; detail?: string }, error: unknown): void {
if (this.pending.get(id) !== candidate) return
- candidate.looking = false
- if (found) {
- this.pending.delete(id)
- if (!this.pending.size) this.clearTimer()
- this.onFound(id, found)
- } else this.schedule()
+ const detail = error instanceof Error ? error.message : String(error)
+ if (candidate.detail === detail) return
+ candidate.detail = detail
+ console.error(`[discovery] transcript ${id} held · ${detail}`)
+ }
+
+ private publish(id: string, candidate: { looking: boolean }, found: string): void {
+ // A failed publication keeps the pending intent. The callback may also remove or replace it.
+ this.onFound(id, found)
+ if (this.pending.get(id) === candidate) this.pending.delete(id)
+ if (!this.pending.size) this.clearTimer()
}
remove(id: string): void {
@@ -68,13 +83,20 @@ export class TranscriptDiscovery {
this.sweeping = true
const candidates = [...this.pending].filter(([, candidate]) => !candidate.looking)
try {
- const groups = await transcriptGroups(this.home, this.rule)
+ let groups: string[] | undefined
+ try { if (this.rule.kind !== 'direct') groups = await transcriptGroups(this.home, this.rule) }
+ catch (error) {
+ for (const [id, candidate] of candidates) this.hold(id, candidate, error)
+ return
+ }
for (const [id, candidate] of candidates) {
if (this.pending.get(id) !== candidate) continue
- const found = await locateTranscript(this.rule, this.home, id, { groups, valid: this.valid })
- if (!found || this.pending.get(id) !== candidate) continue
- this.pending.delete(id)
- this.onFound(id, found)
+ candidate.looking = true
+ try {
+ const found = await locateTranscript(this.rule, this.home, id, { groups, valid: this.valid })
+ if (found && this.pending.get(id) === candidate) this.publish(id, candidate, found)
+ } catch (error) { this.hold(id, candidate, error) }
+ finally { candidate.looking = false }
}
} finally {
this.sweeping = false
diff --git a/cli/src/engines/nativeLocation.golden.spec.ts b/cli/src/engines/nativeLocation.golden.spec.ts
new file mode 100644
index 000000000..f9040271a
--- /dev/null
+++ b/cli/src/engines/nativeLocation.golden.spec.ts
@@ -0,0 +1,133 @@
+/** Native location answers before bounded discovery. Linux, UTC, a fixed clock and private files;
+ * no host binary, process descriptor or engine home is consulted. Record before changing the wiring. */
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterAll, beforeAll, expect, it, vi } from 'vitest'
+
+const fixture = vi.hoisted(() => ({ root: '' }))
+vi.mock('node:fs/promises', async original => {
+ const fs = await original<typeof import('node:fs/promises')>()
+ const mapped = (path: unknown) => String(path).startsWith('/proc/')
+ ? join(fixture.root, 'proc', String(path).slice('/proc/'.length)) : path
+ return { ...fs,
+ readdir: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.readdir, fs, [mapped(path), ...args]),
+ opendir: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.opendir, fs, [mapped(path), ...args]),
+ readlink: (path: unknown, ...args: unknown[]) => Reflect.apply(fs.readlink, fs, [mapped(path), ...args]),
+ }
+})
+vi.mock('node:child_process', async original => ({ ...await original<object>(),
+ execFile: () => { throw new Error('This golden must never run a host binary') },
+}))
+const GOLDEN = fileURLToPath(new URL('./__fixtures__/native-location.golden.json', import.meta.url))
+const RECORD = process.env.RECORD_NATIVE_LOCATION_GOLDEN === '1'
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+const at = Date.parse('2026-10-09T12:00:00Z')
+const id = (n: number) => `aaaaaaaa-1111-4222-8333-${String(n).padStart(12, '0')}`
+const captured: Record<string, unknown> = {}
+let expected: Record<string, unknown>
+let locate: typeof import('./kit/sessionLocation.js')
+let contracts: {
+ cursor: typeof import('./cursor/contract.js')['CURSOR_TRANSCRIPT']
+ grok: typeof import('./grok/contract.js')['GROK_TRANSCRIPT']
+ copilot: typeof import('./copilot/contract.js')['COPILOT_TRANSCRIPT']
+ copilotProcess: typeof import('./copilot/contract.js')['COPILOT_PROCESS_SESSION']
+ agy: typeof import('./agy/contract.js')['AGY_TRANSCRIPT']
+ agyProcess: typeof import('./agy/contract.js')['AGY_PROCESS_SESSION']
+}
+const home = (engine: string) => join(fixture.root, engine)
+function file(path: string, body = '', time = at): string {
+ mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, body)
+ utimesSync(path, time / 1000, time / 1000)
+ return path
+}
+async function check(key: string, work: Promise<unknown> | unknown): Promise<void> {
+ captured[key] = JSON.parse(JSON.stringify(await work ?? null).split(fixture.root).join('<root>'))
+ if (!RECORD) expect({ key, value: captured[key] }).toEqual({ key, value: expected[key] })
+}
+beforeAll(async () => {
+ fixture.root = realpathSync(mkdtempSync(join(tmpdir(), 'native-location-golden-')))
+ for (const [name, value] of Object.entries({ HOME: join(fixture.root, 'home'), TZ: 'UTC',
+ ADAPTER_DATA_DIR: join(fixture.root, 'data'), ADAPTER_RUNTIME_DIR: join(fixture.root, 'runtime'),
+ CURSOR_HOME: home('cursor'), CURSOR_CONFIG_DIR: home('cursor'), CURSOR_DATA_DIR: home('cursor'),
+ COPILOT_HOME: home('copilot'), GROK_HOME: home('grok'), AGY_HOME: home('agy'), AGY_CONFIG_DIR: home('agy'),
+ })) vi.stubEnv(name, value)
+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })
+ vi.useFakeTimers({ toFake: ['Date'], now: at })
+ vi.resetModules()
+ locate = await import('./kit/sessionLocation.js')
+ contracts = {
+ cursor: (await import('./cursor/contract.js')).CURSOR_TRANSCRIPT,
+ grok: (await import('./grok/contract.js')).GROK_TRANSCRIPT,
+ copilot: (await import('./copilot/contract.js')).COPILOT_TRANSCRIPT,
+ copilotProcess: (await import('./copilot/contract.js')).COPILOT_PROCESS_SESSION,
+ agy: (await import('./agy/contract.js')).AGY_TRANSCRIPT,
+ agyProcess: (await import('./agy/contract.js')).AGY_PROCESS_SESSION,
+ }
+ expected = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8'))
+})
+afterAll(() => {
+ if (RECORD) writeFileSync(GOLDEN, JSON.stringify(captured, null, 2) + '\n')
+ Object.defineProperty(process, 'platform', platform); vi.useRealTimers(); vi.unstubAllEnvs()
+ rmSync(fixture.root, { recursive: true, force: true })
+})
+
+it('records exact transcript locations through each native declaration', async () => {
+ const cursor = file(join(home('cursor'), 'projects', 'project', 'agent-transcripts', id(1), `${id(1)}.jsonl`), '{}\n')
+ for (const [name, session] of [['existing', id(1)], ['missing', id(2)], ['invalid', '../escape']]) {
+ await check(`cursor:${name}`, locate.locateTranscript(contracts.cursor, home('cursor'), session))
+ }
+ await check('cursor:validation-rejected', locate.locateTranscript(contracts.cursor, home('cursor'), id(1), { valid: () => false }))
+ await check('cursor:groups', locate.locateTranscript(contracts.cursor, home('cursor'), id(1), { groups: ['project'], valid: path => path === cursor }))
+ for (const [engine, rule, path] of [
+ ['copilot', contracts.copilot, join(home('copilot'), 'session-state', id(3), 'events.jsonl')],
+ ['agy', contracts.agy, join(home('agy'), 'brain', id(3), '.system_generated', 'logs', 'transcript_full.jsonl')],
+ ] as const) {
+ file(path, '{}\n')
+ await check(`${engine}:existing`, locate.locateTranscript(rule, home(engine), id(3)))
+ await check(`${engine}:missing`, locate.locateTranscript(rule, home(engine), id(4)))
+ await check(`${engine}:invalid`, locate.locateTranscript(rule, home(engine), '../escape'))
+ }
+ file(join(home('grok'), 'sessions', encodeURIComponent('/work/encoded'), id(5), 'updates.jsonl'), '{}\n')
+ file(join(home('grok'), 'sessions', 'hashed-workspace', '.cwd'), '/work/hashed\n')
+ file(join(home('grok'), 'sessions', 'hashed-workspace', id(6), 'updates.jsonl'), '{}\n')
+ for (const [name, session, cwd] of [['encoded', id(5), '/work/encoded'], ['hashed', id(6), '/work/hashed'],
+ ['other-workspace', id(6), '/work/elsewhere'], ['missing', id(7), '/work/encoded'], ['no-workspace', id(5), undefined]] as const) {
+ await check(`grok:${name}`, locate.locateTranscript(contracts.grok, home('grok'), session, { cwd }))
+ }
+})
+
+it('records complete native process evidence without consulting host processes', async () => {
+ const pid = 4242
+ file(join(home('copilot'), 'session-state', id(11), `inuse.${pid}.lock`), '', at - 1000)
+ file(join(home('copilot'), 'session-state', id(12), `inuse.${pid}.lock`))
+ await check('copilot:newest-lock', locate.locateProcessSession(contracts.copilotProcess, home('copilot'), pid))
+ await check('copilot:no-lock', locate.locateProcessSession(contracts.copilotProcess, home('copilot'), 5000))
+ await check('copilot:invalid-pid', locate.locateProcessSession(contracts.copilotProcess, home('copilot'), 0))
+ const lock = file(join(home('agy'), 'presence', `${id(13)}.lock`))
+ const fd = join(fixture.root, 'proc', String(pid), 'fd'); mkdirSync(fd, { recursive: true })
+ symlinkSync(lock, join(fd, '3'))
+ symlinkSync(join(fixture.root, 'unrelated.lock'), join(fd, '4'))
+ mkdirSync(join(fixture.root, 'proc', '5000', 'fd'), { recursive: true })
+ await check('agy:held-lock', locate.locateProcessSession(contracts.agyProcess, home('agy'), pid))
+ await check('agy:no-lock', locate.locateProcessSession(contracts.agyProcess, home('agy'), 5000))
+ await check('agy:invalid-pid', locate.locateProcessSession(contracts.agyProcess, home('agy'), 0))
+})
+
+it('records pending transcript completion and cancellation through the eager discovery class', async () => {
+ const { TranscriptDiscovery } = await import('./kit/transcriptDiscovery.js')
+ const found: unknown[] = []
+ const discovery = new TranscriptDiscovery(home('pending'), contracts.cursor, (session, path) => { found.push([session, path]) }, () => true, 10)
+ const path = (n: number) => join(home('pending'), 'projects', 'project', 'agent-transcripts', id(n), `${id(n)}.jsonl`)
+ try {
+ file(path(21), '{}\n')
+ await discovery.start(); await discovery.add(id(21)); await discovery.add(id(22)); await discovery.add(id(23))
+ discovery.remove(id(23)); file(path(22), '{}\n'); file(path(23), '{}\n')
+ await vi.waitFor(() => expect(found).toHaveLength(2), { timeout: 3000 })
+ await discovery.stop()
+ await check('discovery:found', found)
+ await check('discovery:stopped', discovery.isPolling)
+ } finally { await discovery.stop() }
+})
+it('has exactly the recorded observations', () => { if (!RECORD) expect(Object.keys(captured).sort()).toEqual(Object.keys(expected).sort()) })
diff --git a/cli/src/engines/otherIdentity.golden.spec.ts b/cli/src/engines/otherIdentity.golden.spec.ts
index 3d2529e9b..ce25cbcd8 100644
--- a/cli/src/engines/otherIdentity.golden.spec.ts
+++ b/cli/src/engines/otherIdentity.golden.spec.ts
@@ -30,6 +30,12 @@ const descriptors = vi.hoisted(() => new Map<string, string[]>())
vi.mock('fs/promises', async (original) => {
const fs = await original<typeof import('node:fs/promises')>()
return { ...fs,
+ // Keep a streamed descriptor listing private as well as the former readdir path.
+ opendir: async (path: string, ...args: unknown[]) => /^\/proc\/\d+\/fd$/.test(String(path))
+ ? { async *[Symbol.asyncIterator]() {
+ for (const [index] of (descriptors.get(String(path)) ?? []).entries()) yield { name: String(index) }
+ } }
+ : Reflect.apply(fs.opendir, fs, [path, ...args]),
readdir: async (path: string, ...args: unknown[]) => /^\/proc\/\d+\/fd$/.test(String(path))
? (descriptors.get(String(path)) ?? []).map((_, index) => String(index))
: Reflect.apply(fs.readdir, fs, [path, ...args]),
diff --git a/cli/src/lib/nativeLocations.control.spec.ts b/cli/src/lib/nativeLocations.control.spec.ts
new file mode 100644
index 000000000..76039ba26
--- /dev/null
+++ b/cli/src/lib/nativeLocations.control.spec.ts
@@ -0,0 +1,128 @@
+/** Real control callers and private native files; no real process, home, engine or daemon. */
+import { execFile } from 'node:child_process'
+import * as sync from 'node:fs'
+import * as fs from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import type { BindDeps } from '../core/agents/bind.js'
+import type { DiscoveredTerminalAgent } from './terminalAgentDiscovery.js'
+import type { RegisteredSession } from './registry.js'
+
+vi.mock('node:fs', async original => {
+ const actual = await original<typeof sync>()
+ return { ...actual, realpathSync: vi.fn(actual.realpathSync), statSync: vi.fn(actual.statSync) }
+})
+vi.mock('node:fs/promises', async original => {
+ const actual = await original<typeof fs>()
+ return { ...actual, stat: vi.fn(actual.stat), opendir: vi.fn(actual.opendir), readlink: vi.fn(actual.readlink) }
+})
+vi.mock('node:child_process', async original => ({ ...await original<object>(),
+ execFile: vi.fn(() => { throw new Error('Unexpected host process probe') }),
+}))
+vi.mock('../engines/inProcess.js', () => ({ loadEngine: () => { throw new Error('Unexpected optional engine load') } }))
+
+const A = 'aaaaaaaa-1111-4222-8333-444444444444', B = 'bbbbbbbb-1111-4222-8333-444444444444'
+const platform = Object.getOwnPropertyDescriptor(process, 'platform')!
+let root: string, actual: typeof fs, actualSync: typeof sync
+const file = (path: string, text = '{}\n') => { sync.mkdirSync(dirname(path), { recursive: true }); sync.writeFileSync(path, text); return path }
+const denied = () => Object.assign(new Error('private fixture denied'), { code: 'EACCES' })
+const copilotLock = (id: string, time: number) => {
+ const path = file(join(root, 'copilot', 'session-state', id, 'inuse.4242.lock'))
+ sync.utimesSync(path, time, time); return path
+}
+beforeEach(async () => {
+ actual = await vi.importActual<typeof fs>('node:fs/promises')
+ actualSync = await vi.importActual<typeof sync>('node:fs')
+ vi.mocked(sync.realpathSync).mockReset().mockImplementation(actualSync.realpathSync)
+ vi.mocked(sync.statSync).mockReset().mockImplementation(actualSync.statSync)
+ root = actualSync.realpathSync(sync.mkdtempSync(join(tmpdir(), 'native-control-')))
+ const map = (path: unknown) => String(path).startsWith('/proc/') ? join(root, 'proc', String(path).slice(6)) : path
+ vi.mocked(fs.opendir).mockReset().mockImplementation(((path, ...args) => Reflect.apply(actual.opendir, actual, [map(path), ...args])) as typeof fs.opendir)
+ vi.mocked(fs.readlink).mockReset().mockImplementation(((path, ...args) => Reflect.apply(actual.readlink, actual, [map(path), ...args])) as typeof fs.readlink)
+ vi.mocked(fs.stat).mockReset().mockImplementation(actual.stat)
+ for (const name of ['HOME', 'ADAPTER_DATA_DIR', 'ADAPTER_RUNTIME_DIR', 'HARNESS_AUTH_DIR', 'HARNESS_HOOK_ROUTES_DIR',
+ 'CLAUDE_CONFIG_DIR', 'CLAUDE_PROJECTS_DIR', 'CODEX_HOME', 'GROK_HOME', 'HERMES_HOME', 'PI_HOME', 'MUSE_HOME',
+ 'COMMANDCODE_HOME', 'AMP_SESSIONS_DIR', 'OPENCODE_DATA_DIR', 'KILO_DATA_DIR', 'DEVIN_HOME',
+ 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME']) vi.stubEnv(name, join(root, name.toLowerCase()))
+ for (const [name, directory] of Object.entries({ COPILOT_HOME: 'copilot', AGY_HOME: 'agy', AGY_CONFIG_DIR: 'agy',
+ CURSOR_HOME: 'cursor', CURSOR_DATA_DIR: 'cursor', CURSOR_CONFIG_DIR: 'cursor' })) vi.stubEnv(name, join(root, directory))
+ Object.defineProperty(process, 'platform', { ...platform, value: 'linux' })
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.resetModules()
+})
+afterEach(() => {
+ expect(execFile).not.toHaveBeenCalled()
+ vi.clearAllMocks(); vi.restoreAllMocks(); vi.unstubAllEnvs()
+ Object.defineProperty(process, 'platform', platform); sync.rmSync(root, { recursive: true, force: true })
+})
+
+it.each(['copilot', 'agy'] as const)('repair revalidates %s ownership after transcript lookup', async engine => {
+ const home = join(root, engine)
+ const path = engine === 'copilot' ? file(join(home, 'session-state', A, 'events.jsonl'))
+ : file(join(home, 'brain', A, '.system_generated', 'logs', 'transcript_full.jsonl'))
+ const descriptor = join(root, 'proc', '4242', 'fd', '0')
+ if (engine === 'copilot') { copilotLock(A, 3000); copilotLock(B, 1000) }
+ else { sync.mkdirSync(dirname(descriptor), { recursive: true }); sync.symlinkSync(join(home, 'presence', `${A}.lock`), descriptor) }
+ let changed = false
+ vi.mocked(fs.stat).mockImplementation(((name, ...args) => {
+ if (String(name) === path && !changed) {
+ changed = true
+ if (engine === 'copilot') copilotLock(B, 5000)
+ else { sync.unlinkSync(descriptor); sync.symlinkSync(join(home, 'presence', `${B}.lock`), descriptor) }
+ }
+ return Reflect.apply(actual.stat, actual, [name, ...args])
+ }) as typeof fs.stat)
+ const repair = await import('./sessionRepair.js')
+ await expect(repair.findLiveSession(engine, root, 1000, { pid: 4242 })).rejects.toThrow('process conversation changed')
+ await expect(repair.findLiveSession(engine, root, 1000, { pid: 4242 })).resolves.toEqual({ sessionId: B, transcriptPath: undefined })
+})
+
+it('Copilot binding retains its previous conversation when native ownership moves during transcript lookup', async () => {
+ copilotLock(A, 3000); copilotLock(B, 1000)
+ const path = file(join(root, 'copilot', 'session-state', A, 'events.jsonl'))
+ let changed = false
+ vi.mocked(fs.stat).mockImplementation(((name, ...args) => {
+ if (String(name) === path && !changed) { changed = true; copilotLock(B, 5000) }
+ return Reflect.apply(actual.stat, actual, [name, ...args])
+ }) as typeof fs.stat)
+ const row = { engine: 'copilot', agentId: 'private-agent', sessionId: 'previous', registeredAt: 0, runtimes: [],
+ processIdentity: { pid: 4242, executable: 'copilot', startMarker: '2026-10-09T00:00:00Z' } } as unknown as RegisteredSession
+ const register = vi.fn(() => null)
+ const deps = { registry: { byProcess: () => row, bySession: () => undefined, register },
+ homes: { copilot: join(root, 'copilot') } } as unknown as BindDeps
+ const observed: DiscoveredTerminalAgent = { engine: 'copilot', cwd: root, runtimes: [], primaryRuntimeKey: '',
+ args: 'copilot', resumeSessionId: null, processIdentity: row.processIdentity! }
+ const binding = (await import('../core/agents/bind.js')).createBinding(deps)
+ await binding.bindObservedAgent(observed)
+ expect(register).not.toHaveBeenCalled(); expect(row.sessionId).toBe('previous')
+ expect(console.log).toHaveBeenCalledWith(expect.stringContaining('process conversation changed'))
+ await binding.bindObservedAgent(observed)
+ expect(register).toHaveBeenCalledWith(expect.objectContaining({ sessionId: B, transcriptPath: undefined }))
+})
+
+it.each(['path', 'root', 'stat'] as const)('holds a Cursor pool when %s validation is unavailable beside a readable competitor', async failure => {
+ const home = join(root, 'cursor')
+ const unknown = file(join(home, 'projects', 'a', 'agent-transcripts', A, `${A}.jsonl`))
+ file(join(home, 'projects', 'b', 'agent-transcripts', A, `${A}.jsonl`))
+ if (failure === 'stat') vi.mocked(sync.statSync).mockImplementation(((path, ...args) => {
+ if (String(path) === unknown) throw denied()
+ return Reflect.apply(actualSync.statSync, actualSync, [path, ...args])
+ }) as typeof sync.statSync)
+ else vi.mocked(sync.realpathSync).mockImplementation(((path, ...args) => {
+ if (String(path) === (failure === 'root' ? join(home, 'projects') : unknown)) throw denied()
+ return Reflect.apply(actualSync.realpathSync, actualSync, [path, ...args])
+ }) as typeof sync.realpathSync)
+ const { transcriptOf } = await import('../engines/identities.js')
+ await expect(transcriptOf('cursor', home, A)).rejects.toMatchObject({ code: 'IDENTITY_UNAVAILABLE' })
+})
+
+it('still excludes a proven foreign Cursor file', async () => {
+ const home = join(root, 'cursor')
+ const foreign = file(join(root, 'foreign', 'agent-transcripts', A, `${A}.jsonl`))
+ const alias = join(home, 'projects', 'a', 'agent-transcripts', A, `${A}.jsonl`)
+ sync.mkdirSync(dirname(alias), { recursive: true }); sync.symlinkSync(foreign, alias)
+ const expected = file(join(home, 'projects', 'b', 'agent-transcripts', A, `${A}.jsonl`))
+ const { transcriptOf } = await import('../engines/identities.js')
+ await expect(transcriptOf('cursor', home, A)).resolves.toBe(expected)
+})
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 4e34557ae..f03fe3f46 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -39,6 +39,7 @@ import { randomUUID } from 'crypto'
import { join, basename, dirname, relative, isAbsolute } from 'path'
import { machineNames } from './machineNames.js'
import { cursorDataDir } from '../engines/cursor/contract.js'
+import { IdentityReadUnavailable } from '../engines/kit/identityScan.js'
import { env } from '../config/env.js'
import { sessionFolderOf, sessionRoots } from './engineHomes.js'
import { findSessionFileOf, sessionMetaOf } from '../engines/sessionFiles.js'
@@ -965,12 +966,24 @@ function transcriptRoots(engine: AgentEngine, root: (() => string) | 'store', co
}
export function validTranscriptPath(engine: AgentEngine, filePath: string, codexHome?: string, allowMissing = false): boolean {
+ return checkTranscriptPath(engine, filePath, codexHome, allowMissing, false)
+}
+
+/** Existing control candidates: an unreadable path cannot be excluded from a complete identity pool. */
+export function inspectTranscriptPath(engine: AgentEngine, filePath: string): boolean {
+ return checkTranscriptPath(engine, filePath, undefined, false, true)
+}
+
+function checkTranscriptPath(engine: AgentEngine, filePath: string, codexHome: string | undefined, allowMissing: boolean, strict: boolean): boolean {
const rootFor = TRANSCRIPT_ROOT[engine]
if (!rootFor) return false
try {
const missing = allowMissing && !existsSync(filePath)
const actual = missing ? join(realpathSync(dirname(filePath)), basename(filePath)) : realpathSync(filePath)
- const within = (root: string): boolean => { try { return isWithin(realpathSync(root), actual) } catch { return false } }
+ const within = (root: string): boolean => {
+ try { return isWithin(realpathSync(root), actual) }
+ catch (error) { if (strict) throw error; return false }
+ }
const st = statSync(missing ? dirname(actual) : actual)
if (!(missing ? st.isDirectory() : st.isFile()) || !transcriptRoots(engine, rootFor, codexHome).some(within)) return false
if (engine === 'cursor') {
@@ -980,6 +993,7 @@ export function validTranscriptPath(engine: AgentEngine, filePath: string, codex
const uid = typeof process.getuid === 'function' ? process.getuid() : null
return uid === null || st.uid === uid
} catch {
+ if (strict) throw new IdentityReadUnavailable('the transcript path could not be validated')
return false
}
}
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index 6a141d82c..a9f7c83e9 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -463,6 +463,9 @@ export async function findLiveSession(
const locked = opts?.pid ? await nativeProcessSession('copilot', env.COPILOT_HOME, opts.pid) : null
if (locked) {
const transcriptPath = await transcriptOf('copilot', env.COPILOT_HOME, locked)
+ if (await nativeProcessSession('copilot', env.COPILOT_HOME, opts!.pid!) !== locked) {
+ throw new IdentityReadUnavailable('the process conversation changed during transcript lookup')
+ }
return { sessionId: locked, transcriptPath: transcriptPath ?? undefined }
}
return copilotDirectoryScan(cwd, startedAtMs, opts)
@@ -487,6 +490,9 @@ async function agySession(pid: number): Promise<RepairedSession | null> {
const conversationId = await nativeProcessSession('agy', env.AGY_HOME, pid)
if (!conversationId) return null
const transcriptPath = await transcriptOf('agy', env.AGY_HOME, conversationId)
+ if (await nativeProcessSession('agy', env.AGY_HOME, pid) !== conversationId) {
+ throw new IdentityReadUnavailable('the process conversation changed during transcript lookup')
+ }
// A conversation with no transcript is one agy has opened but not written to; registry derives the
// path anyway, so bind it and let the watcher pick the file up when it appears.
return { sessionId: conversationId, transcriptPath: transcriptPath ?? undefined }
diff --git a/docs/research/2026-10-09-daemon-core-completion.md b/docs/research/2026-10-09-daemon-core-completion.md
index 20f5e3527..9dd91c8fb 100644
--- a/docs/research/2026-10-09-daemon-core-completion.md
+++ b/docs/research/2026-10-09-daemon-core-completion.md
@@ -13,7 +13,7 @@ This is the remaining completion scope as of October 9, after the six extraction
- [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).
+- [x] Bounded repair pools and native headers hold incomplete evidence; Stop/Close preserve intent (#1114, merged as `138ae6766` at 13:59:26 UTC).
## Remaining blockers
diff --git a/docs/research/2026-10-09-daemon-separation-progress.md b/docs/research/2026-10-09-daemon-separation-progress.md
index 6f45544c2..e134718ef 100644
--- a/docs/research/2026-10-09-daemon-separation-progress.md
+++ b/docs/research/2026-10-09-daemon-separation-progress.md
@@ -204,3 +204,7 @@ handling, and the OpenCode v2 Close checkpoint audit. The precise gaps are recor
[OpenCode control](2026-10-09-opencode-control.md). Remaining shared-control work includes bounded identity
scans, Cursor pending-task persistence, agy turn backstop/control facts, input verification declarations,
and the final unavailable-service/readiness audit. Line counts do not establish any of those properties.
+
+## Native locations and retry isolation
+
+[PR #1118](https://github.com/autonomous-ai/openharness/pull/1118) bounds exact Cursor/Grok locations and Copilot/agy process claims, rejects incomplete or changing evidence, and retains/retries failed bindings and pending transcript discovery without blocking siblings. The [implementation, independent review corrections, validation and measured cost](2026-10-09-native-location-discovery.md) are recorded separately. Former-code golden artifacts remain unchanged and all 21 broken-wiring variants assertion-fail. Native identity as a whole remains open in the completion checklist: exact resume/legacy records, saved-home catalogs, Hermes pools and shared visible hold state still need completion.
diff --git a/docs/research/2026-10-09-native-location-cost.json b/docs/research/2026-10-09-native-location-cost.json
new file mode 100644
index 000000000..1e8d0170e
--- /dev/null
+++ b/docs/research/2026-10-09-native-location-cost.json
@@ -0,0 +1,656 @@
+{
+ "baseline": "138ae6766febff6f094f1401705e4e4eb7f6ef9f",
+ "candidate": "b65769a31314b19513188c1dd4b73a3392e539d7",
+ "method": "Three interleaved processes per source/workload, ten lookups per process, same private 160-entry corpus (4200 at directory bound; Grok uses 160 sidecars of 60 KiB each), Node toolchain and warm filesystem cache. Lookup latency/CPU excludes import/setup; peak RSS includes them. No real engine, home, process probe or daemon. Reference measurements, not performance thresholds.",
+ "elapsedSeconds": 19.2,
+ "samples": [
+ {
+ "workload": "transcript",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 6.69,
+ 5.69,
+ 5.94,
+ 6.13,
+ 5.53,
+ 5.33,
+ 5.58,
+ 5.61,
+ 5.44,
+ 5.44
+ ],
+ "cpuMs": 77.419,
+ "peakRssMiB": 85.3671875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "transcript",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 14.15,
+ 12.32,
+ 12.45,
+ 11.21,
+ 11.72,
+ 11.86,
+ 11.15,
+ 11.22,
+ 11.57,
+ 10.62
+ ],
+ "cpuMs": 161.125,
+ "peakRssMiB": 90.20703125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "transcript",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 14.02,
+ 12.45,
+ 12.08,
+ 10.87,
+ 11.35,
+ 10.89,
+ 10.47,
+ 10.9,
+ 11.06,
+ 10.52
+ ],
+ "cpuMs": 156.288,
+ "peakRssMiB": 87.1953125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "transcript",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 7.43,
+ 5.75,
+ 5.78,
+ 5.89,
+ 5.43,
+ 5.21,
+ 5.71,
+ 5.5,
+ 5.08,
+ 5.01
+ ],
+ "cpuMs": 76.944,
+ "peakRssMiB": 85.1015625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "transcript",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 6.43,
+ 5.74,
+ 5.95,
+ 5.84,
+ 5.81,
+ 5.42,
+ 5.76,
+ 5.6,
+ 5.5,
+ 5.31
+ ],
+ "cpuMs": 77.93,
+ "peakRssMiB": 86.5625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "transcript",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 14.47,
+ 12.85,
+ 12.06,
+ 13.41,
+ 11.28,
+ 11.09,
+ 11.11,
+ 10.98,
+ 11.12,
+ 10.72
+ ],
+ "cpuMs": 162.784,
+ "peakRssMiB": 89.41015625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 3
+ },
+ {
+ "workload": "process",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 4.6,
+ 3.79,
+ 4.08,
+ 4.19,
+ 4.25,
+ 3.49,
+ 3.6,
+ 3.43,
+ 3.98,
+ 4.12
+ ],
+ "cpuMs": 50.544,
+ "peakRssMiB": 88.08203125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "process",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 10.59,
+ 8.82,
+ 8.04,
+ 9.23,
+ 7.68,
+ 7.9,
+ 7.52,
+ 8.11,
+ 7.32,
+ 7.73
+ ],
+ "cpuMs": 109.573,
+ "peakRssMiB": 83.61328125,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "process",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 12.29,
+ 9.19,
+ 8.49,
+ 8.44,
+ 7.89,
+ 8.04,
+ 7.3,
+ 7.56,
+ 7.14,
+ 8.2
+ ],
+ "cpuMs": 111.241,
+ "peakRssMiB": 84.22265625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "process",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 5.1,
+ 3.75,
+ 4.01,
+ 4.35,
+ 4.32,
+ 3.56,
+ 3.5,
+ 3.58,
+ 3.97,
+ 4.16
+ ],
+ "cpuMs": 51.851,
+ "peakRssMiB": 85.4609375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "process",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 4.48,
+ 3.96,
+ 4.44,
+ 4.22,
+ 4.36,
+ 3.58,
+ 3.51,
+ 3.38,
+ 3.96,
+ 3.99
+ ],
+ "cpuMs": 51.023,
+ "peakRssMiB": 86.796875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "process",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 11,
+ 9.15,
+ 8.1,
+ 8.37,
+ 9.15,
+ 7.93,
+ 8.24,
+ 7.93,
+ 7.64,
+ 7.71
+ ],
+ "cpuMs": 112.047,
+ "peakRssMiB": 83.2734375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 3
+ },
+ {
+ "workload": "limit",
+ "entries": 4200,
+ "iterations": 10,
+ "outcomes": {
+ "absent": 10
+ },
+ "latenciesMs": [
+ 140,
+ 121.08,
+ 121.08,
+ 120.21,
+ 122.27,
+ 119.48,
+ 117.99,
+ 117.11,
+ 124.77,
+ 126.58
+ ],
+ "cpuMs": 1448.156,
+ "peakRssMiB": 99.34765625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "limit",
+ "entries": 4200,
+ "iterations": 10,
+ "outcomes": {
+ "held": 10
+ },
+ "latenciesMs": [
+ 12.96,
+ 10.15,
+ 8.99,
+ 8.98,
+ 8.6,
+ 8.54,
+ 8.01,
+ 8.6,
+ 11.12,
+ 9.97
+ ],
+ "cpuMs": 131.252,
+ "peakRssMiB": 92.546875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "limit",
+ "entries": 4200,
+ "iterations": 10,
+ "outcomes": {
+ "held": 10
+ },
+ "latenciesMs": [
+ 13.64,
+ 9.97,
+ 9.04,
+ 8.85,
+ 8.33,
+ 8.47,
+ 8.27,
+ 8.34,
+ 11.11,
+ 10.01
+ ],
+ "cpuMs": 131.174,
+ "peakRssMiB": 97.16015625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "limit",
+ "entries": 4200,
+ "iterations": 10,
+ "outcomes": {
+ "absent": 10
+ },
+ "latenciesMs": [
+ 138.99,
+ 120.7,
+ 123.9,
+ 120.88,
+ 119,
+ 122.33,
+ 120.39,
+ 118.71,
+ 119.25,
+ 127.16
+ ],
+ "cpuMs": 1448.008,
+ "peakRssMiB": 96.7265625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "limit",
+ "entries": 4200,
+ "iterations": 10,
+ "outcomes": {
+ "absent": 10
+ },
+ "latenciesMs": [
+ 138.87,
+ 118.62,
+ 117.78,
+ 131.24,
+ 118.77,
+ 118.27,
+ 120.05,
+ 117.15,
+ 118.17,
+ 126.87
+ ],
+ "cpuMs": 1444.428,
+ "peakRssMiB": 96.99609375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "limit",
+ "entries": 4200,
+ "iterations": 10,
+ "outcomes": {
+ "held": 10
+ },
+ "latenciesMs": [
+ 12.94,
+ 9.04,
+ 9.11,
+ 8.71,
+ 8.23,
+ 8.63,
+ 8.23,
+ 8.39,
+ 11.23,
+ 10.44
+ ],
+ "cpuMs": 129.796,
+ "peakRssMiB": 93.90625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 3
+ },
+ {
+ "workload": "grok-sidecars",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 33.34,
+ 32.29,
+ 34.48,
+ 33.18,
+ 34.56,
+ 30.53,
+ 28.45,
+ 29.89,
+ 31.81,
+ 28.58
+ ],
+ "cpuMs": 373.933,
+ "peakRssMiB": 103.04296875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 1
+ },
+ {
+ "workload": "grok-sidecars",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 131.26,
+ 123.75,
+ 121.27,
+ 117.47,
+ 123.65,
+ 119.33,
+ 124.53,
+ 117.49,
+ 117.62,
+ 114.63
+ ],
+ "cpuMs": 1411.79,
+ "peakRssMiB": 104.85546875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 1
+ },
+ {
+ "workload": "grok-sidecars",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 129.77,
+ 123.82,
+ 121.32,
+ 120.79,
+ 130.88,
+ 119.08,
+ 116.53,
+ 116.93,
+ 115.64,
+ 116.1
+ ],
+ "cpuMs": 1415.866,
+ "peakRssMiB": 106.15234375,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 2
+ },
+ {
+ "workload": "grok-sidecars",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 31.19,
+ 29.51,
+ 28.81,
+ 28.25,
+ 32.06,
+ 29.04,
+ 28.06,
+ 32.23,
+ 31.83,
+ 30.15
+ ],
+ "cpuMs": 351.898,
+ "peakRssMiB": 94.48046875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 2
+ },
+ {
+ "workload": "grok-sidecars",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 31.15,
+ 28.4,
+ 27.71,
+ 27.66,
+ 28.41,
+ 28.1,
+ 28.11,
+ 30.93,
+ 31.81,
+ 27.53
+ ],
+ "cpuMs": 339.905,
+ "peakRssMiB": 98.34765625,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "baseline",
+ "sample": 3
+ },
+ {
+ "workload": "grok-sidecars",
+ "entries": 160,
+ "iterations": 10,
+ "outcomes": {
+ "exact": 10
+ },
+ "latenciesMs": [
+ 130.96,
+ 123.96,
+ 122.15,
+ 119.85,
+ 135.24,
+ 131.75,
+ 134.24,
+ 129.13,
+ 127.71,
+ 151.96
+ ],
+ "cpuMs": 1513.03,
+ "peakRssMiB": 109.546875,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "x64",
+ "source": "candidate",
+ "sample": 3
+ }
+ ]
+}
diff --git a/docs/research/2026-10-09-native-location-discovery.md b/docs/research/2026-10-09-native-location-discovery.md
new file mode 100644
index 000000000..1b171e07f
--- /dev/null
+++ b/docs/research/2026-10-09-native-location-discovery.md
@@ -0,0 +1,50 @@
+# Native location completeness and discovery retry
+
+The former native location implementation was recorded in `1121bf7fd` before production edits. A separate fixture-only commit, `1f82cef1b`, maps streamed Linux descriptor enumeration in the existing identity golden to the same private evidence as its previous listing. The new 24-observation artifact pins Linux, UTC, clock, native declarations and private filesystem/process fixtures; no host binary runs. Recording again against merged main `138ae6766` left it unchanged. Artifact SHA-256: `0efe2ce638b5d65f34cace39a8d686e3e758aea55bf04cc5d61f371ea265809a`.
+
+The existing locators could interpret read errors as absence, stop at the first matching transcript or descriptor, and accept the readable prefix of a failed process probe. Transcript discovery could leave its initial lookup permanently marked busy after rejection; one failed candidate could also abort the remaining sweep. Bound Copilot, continuation and argv-resume lookup failures could escape the serial binding pass.
+
+## Behavior
+
+Native directory enumeration now streams under an entry budget. Exact transcript lookup checks the complete project pool, distinguishes inode aliases from conflicting files, bounds workspace sidecars, and rejects a changed directory listing or candidate. Ordinary transcript appends keep the same file identity. A shared listing carries evidence for that one sweep and is checked before publication; caller-supplied subsets cannot hide competitors.
+
+Copilot requires a complete lock pool and a unique newest claim. Every claim, including absence, is rechecked; the selected claim is read last. Linux descriptor enumeration shares one budget across its initial and verification listings, checks descriptor changes, and refuses conflicting or deleted conversation locks. Darwin's process probe has a four-second deadline and 256 KiB output bound per invocation; two complete matching replies are required. A failed probe's partial stdout is never authority.
+
+Native reads are contained separately from registry publication in core binding. A rejected read preserves the current row and allows the next session and readiness to continue. Transcript discovery retains pending intent through lookup, listing and publication failures; one candidate's failure cannot abort its siblings. Remove, replacement and stop still revoke late completions. Repeated identical polling reasons are logged once per candidate.
+
+## Validation plan and scope
+
+Run types, architecture, core/services and master coverage at their per-file 100% gates, affected native/repair/Stop/Close specs and unchanged goldens. Run the affected resume coverage lane alone. Extend both private bundled eager-identity lanes: optional native modules missing and stalled, a held Copilot lock pool, a failed Cursor transcript lookup, sibling publication, and recovery. The mutation script deliberately breaks native declarations, completeness and retry wiring; every break must fail an assertion after a green baseline. Measure CPU, RSS and latency with the same private native corpus on former and candidate production. Exact-head independent review and automatic CI precede merge. No release.
+
+The initial affected run passed 127 tests and types; the directory/descriptor race follow-up passed 135 tests and types. Final gate results, mutation outcomes, runtime cost, review and merge evidence are recorded in the PR and appended after completion. Initial recording passed its test but the validation wrapper correctly reported `source_changed` because recording created the artifact; verification with recording disabled passed. The later recording against merged main passed without changing the artifact.
+
+This is part of the [completion checklist](2026-10-09-daemon-core-completion.md), not completion of its whole native-identity group. The legacy saved-home catalog, exact-ID traversal in `sessionRepair`/compatibility session records, complete Hermes pools, and shared visible binding-hold state remain separate named blockers. This change does not claim atomic filesystem snapshots or a cancellable filesystem API; it rejects observed incompleteness and changed evidence within bounded lookup work.
+
+Timing starts with baseline preparation at approximately 13:55 UTC on October 9. Implementation and its focused validation overlap; final validation, independent review/CI waiting and merge are recorded separately. Publication remains zero.
+
+## Independent review corrections
+
+The review of `94f7a2270` against `138ae6766` withheld approval for three concrete races. Grok now validates the selected workspace sidecar after every other native await; Copilot binding and Copilot/agy repair revalidate the complete process claim after transcript lookup; Cursor control paths use strict path validation so an inspection error cannot silently exclude a competing candidate. A known foreign path is still a verified rejection. Fixed-size sidecar digests also prevent retaining up to 64 KiB of text for every workspace.
+
+Private real-file regressions change a selected Grok sidecar during a later sidecar read, switch Copilot/agy native claims during the real caller's transcript lookup, and fail Cursor realpath/stat validation beside a readable competing file. The affected 265-test run passed; typecheck found a new fixture missing required discovery fields, corrected before final gates. Final validation adds the private real-tmux contract and stand-in engine rows (installed vendor smoke rows excluded) and a Grok sidecar workload to the matched cost comparison. No golden artifact was changed.
+
+Independent review approved production head `7a962068f2dc8a3fce8ae3ec0a19bd79e087ba44` against `138ae6766febff6f094f1401705e4e4eb7f6ef9f`. All 21 deliberate wiring mutations failed assertions after a green baseline. At that source, types, 439 affected/architecture tests, master coverage, both bundled native lanes, and 57 private tmux cases passed; 15 installed vendor smoke rows were excluded. Core's 1,942 assertions passed but its gate correctly failed on one uncovered ownership-fence return. The existing deferred Copilot fixture now keeps the native claim stable through the added revalidation so it reaches that fence; production code is unchanged. Only core coverage and types need repeating for that fixture correction.
+
+## Matched runtime cost
+
+Node 22.23.2 on the same Intel macOS machine, three interleaved processes per source/workload, ten lookups per process. Former production is `138ae6766`; candidate is `b65769a31` (production unchanged from the independently approved `7a962068f`). Import and fixture setup are excluded from lookup CPU/latency; process peak RSS includes both. These are reference measurements, not thresholds. The [machine-readable report](2026-10-09-native-location-cost.json) retains every sample.
+
+| Workload | Median lookup, former → current | Median CPU per 10 lookups | Median peak RSS |
+|---|---:|---:|---:|
+| 160 Cursor projects | 5.65 → 11.25 ms | 77.42 → 161.12 ms | 85.37 → 89.41 MiB |
+| 160 Copilot process locks | 3.99 → 8.07 ms | 51.02 → 111.24 ms | 86.80 → 83.61 MiB |
+| 4,200 projects, no match | 120.55 → 8.98 ms | 1448.01 → 131.17 ms | 97.00 → 93.91 MiB |
+| 160 Grok sidecars, 60 KiB each | 30.02 → 122.90 ms | 351.90 → 1415.87 ms | 98.35 → 106.15 MiB |
+
+The complete second inspection approximately doubles ordinary Cursor/Copilot lookup cost on this corpus. The deliberately large Grok sidecars cost about four times as much: bounded complete reads, file replacement checks and final workspace validation replace unchecked reads. Fixed-size digests prevent retaining all those sidecar contents. This stress corpus is not a typical workspace path size. At the directory limit, former code reported absence after scanning 4,200 projects; current code holds with its reason after the bounded scan.
+
+Final local evidence: 1,942 core tests at 100% statements/branches/functions/lines per covered file; 265 master tests and one existing skip at 100%; 439 affected/architecture cases; two bundled native outage/recovery lanes; 57 private tmux cases and 15 explicitly excluded installed-vendor smoke rows; 313 serial resume tests at 100%; types; all 21 mutants assertion-caught. The failed coverage receipt remains failed; the passing core-only correction is recorded separately.
+
+Main advanced to `a18b55e3b` through Desktop-only #1117/#1116. The conflict-free integration changed no CLI source, fixture, dependency or toolchain input. The passing coverage/types/resume receipts can be reused for the final documentation commit with their declared CLI+Store/toolchain scopes; no equivalent full suite is repeated.
+
+Timing: baseline preparation began about 13:55 UTC; implementation and review corrections ended at 14:35, with a test-only coverage correction at 14:39. Local validation finished at 14:41:28, then matched measurement ran 14:42:38–14:42:57. Independent review overlapped those phases. Final automatic CI waiting and merge are recorded in the PR; publication is zero.