The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Keep native session identity in the eager core (#1104)
Dee67ae6473ebce
diff --git a/cli/e2e/eagerIdentity.e2e.ts b/cli/e2e/eagerIdentity.e2e.tsnew file mode 100644index 000000000..aaf9a5a00--- /dev/null+++ b/cli/e2e/eagerIdentity.e2e.ts@@ -0,0 +1,97 @@+/** 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 { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { afterAll, afterEach, beforeAll, expect, it, onTestFailed } from 'vitest'+import { readLeanBundle } from '../src/harnessd/leanBundle.js'+import { LocalClient } from './harness/client.js'+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'+import { withLean } from './harness/release.js'++let scratch = '', bundle = ''+let daemon: IsolatedDaemon | undefined+let client: LocalClient | undefined+beforeAll(() => {+ scratch = mkdtempSync(join(tmpdir(), 'eager-identity-'))+ bundle = join(scratch, 'build', 'cli.js')+ execFileSync(process.execPath, ['build-bundle.mjs'], { cwd: CLI_ROOT,+ env: { ...process.env, BUNDLE_OUT_DIR: dirname(bundle) }, stdio: 'pipe' })+}, 120_000)+afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })+afterAll(() => { if (scratch) rmSync(scratch, { recursive: true, force: true }) })++it.each(['missing', 'stalled'] as const)('binds, follows Copilot resume and locates a Cursor transcript with %s optional modules', async mode => {+ const lean = readLeanBundle(readFileSync(bundle))!+ const files = Object.fromEntries([...lean.files].map(([name, value]) => [name, value.toString('utf8')]))+ for (const marker of ['CopilotNormalizer', 'CursorNormalizer']) {+ const chunks = Object.keys(files).filter(name => name.startsWith('core-inProcess-') && files[name]!.includes(marker))+ expect(chunks, marker).toHaveLength(1)+ if (mode === 'missing') delete files[chunks[0]!]+ else files[chunks[0]!] = `console.error('[fixture] ${marker} stalled'); await new Promise(() => {});\n`+ }+ const script = join(scratch, mode, 'cli.js')+ mkdirSync(dirname(script), { recursive: true })+ writeFileSync(script, withLean(readFileSync(bundle, 'utf8'), files), { mode: 0o755 })+ const d = daemon = await IsolatedDaemon.create({ scriptPath: script, env: { HARNESS_CONNECTIONS_PORT: '0' } })+ onTestFailed(() => console.log(d.log()))+ const first = 'aaaaaaaa-1111-4222-8333-444444444444', next = 'bbbbbbbb-1111-4222-8333-444444444444'+ d.env.COPILOT_HOME = join(d.root, 'copilot')+ d.env.CURSOR_HOME = join(d.root, 'cursor')+ const cwd = join(d.projectsDir, 'native'); mkdirSync(cwd)+ for (const engine of ['copilot', 'cursor'] as const) {+ const path = join(d.root, 'bin', engine)+ d.env[`${engine.toUpperCase()}_PATH`] = path+ writeFileSync(path, `#!${process.execPath}+const fs = require('node:fs'), path = require('node:path');+if (process.argv.includes('--version') || process.argv.includes('--help')) { console.log('1.0.0 --force'); process.exit(0) }+process.title = ${JSON.stringify(engine)}.padEnd(120);+fs.writeFileSync(${JSON.stringify(join(d.root, `${engine}.pid`))}, String(process.pid));+${engine === 'copilot' ? `const folder = path.join(process.env.COPILOT_HOME, 'session-state', '${first}');+fs.mkdirSync(folder, { recursive: true }); fs.writeFileSync(path.join(folder, 'inuse.' + process.pid + '.lock'), '');+fs.writeFileSync(path.join(folder, 'events.jsonl'), JSON.stringify({type:'session.start', data:{context:{cwd:process.cwd()}}}) + '\\n');` : ''}+console.log('fixture-${engine}-ready'); setInterval(() => {}, 1000);+`, { mode: 0o755 })+ }+ await d.start()+ const c = client = await LocalClient.connect(d)+ const rows = async () => (await c.request('agents_list', {})).agents as Array<Record<string, any>>+ const create = async (engine: string) => {+ const response = await c.request('agent_create', { engine, cwd, bypassPermission: true }, 60_000)+ expect(response.error, JSON.stringify(response)).toBeUndefined()+ return response.agent as Record<string, any>+ }+ 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 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)+ // 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'+ for (const id of ['dddddddd', 'eeeeeeee', 'ffffffff', 'cccccccc']) {+ const cursor = await create('cursor')+ const pane = String(cursor.terminal?.runtimes?.[0]?.paneId ?? cursor.tmuxPane)+ await until('the private Cursor process', async () => (await d.capture(pane)).includes('fixture-cursor-ready') || null, 15_000, 100)+ const callerPid = Number(readFileSync(join(d.root, 'cursor.pid'), 'utf8'))+ const sessionId = `${id}-1111-4222-8333-444444444444`+ const hook = await fetch(`http://127.0.0.1:${d.port}/api/hook/session-start`, { method: 'POST',+ headers: { 'content-type': 'application/json', 'x-harness-hook-token': d.hookCredential() },+ body: JSON.stringify({ engine: 'cursor', sessionId, cwd, tmuxPane: pane, callerPid, hookEvent: 'SessionStart' }),+ })+ expect(hook.status).toBe(200)+ 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')+ 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)+ 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/mutate-eager-identity.py b/cli/scripts/handoff-2026-10-08/mutate-eager-identity.pynew file mode 100644index 000000000..bab597c2f--- /dev/null+++ b/cli/scripts/handoff-2026-10-08/mutate-eager-identity.py@@ -0,0 +1,58 @@+"""Break one eager location wire at a time. Only assertion failures count, never setup or timeouts."""+import os+from pathlib import Path+import subprocess+import sys++cli = Path(sys.argv[1]).resolve()+golden = 'src/engines/otherIdentity.golden.spec.ts'+bind = 'src/core/agents/bind.spec.ts'+discovery = 'src/engines/kit/transcriptDiscovery.spec.ts'+profile = 'src/lib/terminalAgentDiscovery.hermesHome.spec.ts'+attach = 'src/core/transcripts/attach.spec.ts'+mutations = [+ ('Cursor layout lost', 'src/engines/cursor/contract.ts', "root: 'projects'", "root: 'wrong-projects'", golden),+ ('Grok hashed cwd lost', 'src/engines/grok/contract.ts', "sidecar: '.cwd'", "sidecar: '.wrong-cwd'", golden),+ ('Agy transcript lost', 'src/engines/agy/contract.ts', "file: ['.system_generated', 'logs', 'transcript_full.jsonl']", "file: ['.system_generated', 'logs', 'wrong.jsonl']", golden),+ ('Copilot resume lock lost', 'src/engines/copilot/contract.ts', "prefix: 'inuse.'", "prefix: 'wrong.'", golden),+ ('binding bypasses native transcript', 'src/core/agents/bind.ts', "transcriptOf(engine, engine === 'cursor' ? cursorDataDir() : homes[engine], sessionId, cwd)", "Promise.resolve(null)", golden),+ ('removed lookup publishes', 'src/engines/kit/transcriptDiscovery.ts', "if (this.pending.get(id) !== candidate) return", "if (false) return", discovery),+ ('old sweep publishes', 'src/engines/kit/transcriptDiscovery.ts', "if (!found || this.pending.get(id) !== candidate) continue", "if (!found) continue", discovery),+ ('profile fact lost', 'src/engines/hermes/contract.ts', "variable: 'HERMES_HOME'", "variable: 'UNDECLARED_HOME'", profile),+ ('SQLite binding unavailable', 'src/lib/sqliteRead.ts', 'const Database = builtinSqlite()', "return { ok: false, reason: 'transient' }; const Database = builtinSqlite()", golden),+ ('changed binding fence lost', 'src/core/agents/bind.ts', 'paneReadIdentity(registry.byProcess(observed.engine, observed.processIdentity)) === authority', 'true', bind),+ ('binding publication waits on reader', 'src/core/agents/bind.ts', ' stoppedAgents.save(entry)', ' await attachSession(entry); stoppedAgents.save(entry)', bind),+ ('target claim not rechecked', 'src/core/agents/bind.ts', 'if (!current() || !mayClaim(sessionId)) return', 'if (!current()) return', bind),+ ('changed path joins obsolete reader', 'src/lib/attachTracker.ts', 'if (!reset && pending.identity === identity)', 'if (!reset)', attach),+ ('newer reader keeps obsolete retry', 'src/core/transcripts/readerLoads.ts', ' held.delete(sessionId)\n let loading', ' // broken: old retry retained\n let loading', attach),+ ('missing reader starts a tail', 'src/core/transcripts/attach.ts', 'its reader is unavailable or still loading`)\n return true', 'its reader is unavailable or still loading`)\n // broken: interpretation proceeds', attach),+ ('binding waits on optional attachment', 'src/core/agents/bind.ts', 'followRegistered(result.entry, result)', 'await handleRegistered(result.entry, result)', bind),+]+env = {**os.environ, 'TZ': 'UTC', 'TMPDIR': '/tmp'}+env.pop('TMUX', None)+env.pop('TMUX_PANE', None)+env.pop('RECORD_OTHER_ENGINES_GOLDEN', 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([golden, bind, discovery, profile, attach])+if baseline.returncode:+ print(baseline.stdout + baseline.stderr)+ raise SystemExit('baseline failed; no mutants ran')+print('unchanged baseline passed', flush=True)+for label, relative, before, after, spec in mutations:+ path = cli / relative+ original = path.read_text()+ assert original.count(before) == 1, (label, original.count(before))+ try:+ path.write_text(original.replace(before, after))+ result = run([spec])+ output = result.stdout + result.stderr+ if result.returncode == 0 or 'AssertionError' not in output:+ print(output)+ raise SystemExit(f'{label}: not caught by an assertion')+ print(f'{label}: caught by assertion', flush=True)+ finally:+ path.write_text(original)diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 0f0bff233..d513dfa1e 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -443,6 +443,14 @@ describe('the daemon\'s shape', () => {}}, WALK_TIMEOUT_MS)+ it('transcript location, native process evidence and profile discovery have no lazy implementation dependency', () => {+ for (const entry of ['core/agents/bind.ts', 'core/engines/cursorDiscovery.ts', 'engines/identities.ts',+ 'engines/kit/sessionLocation.ts', 'engines/kit/transcriptDiscovery.ts', 'lib/terminalAgentDiscovery.ts', 'lib/sqliteRead.ts']) {+ const imports = importsFor(entry, readFileSync(join(SRC, entry), 'utf8'))+ expect(imports.filter(one => one.dynamic || /inProcess\.js$/.test(one.from)), entry).toEqual([])+ }+ })+it('the gateway reaches the core only through core/api.ts: never a core module, the registry, cli.ts or the socket', () => {// It speaks to the core through GatewayPort and GatewayEvents alone, so that it can run in a process of// its own (step 10, R2) without taking any of the core with it.diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.tsindex e0d29c4eb..e0e56c275 100644--- a/cli/src/core/agents/bind.spec.ts+++ b/cli/src/core/agents/bind.spec.ts@@ -2,10 +2,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { findAgyTranscript } from '../../engines/agy/session.js'-import { copilotSessionForPid, findCopilotTranscript } from '../../engines/copilot/session.js'-import { findCursorTranscript } from '../../engines/cursor/discovery.js'-import { findGrokTranscript } from '../../engines/grok/session.js'+import { transcriptOf, processSessionOf } from '../../engines/identities.js'import { loadEngine } from '../../engines/inProcess.js'import { continuationOf } from '../../engines/sessionFiles.js'import { isRecentlyDeleted } from '../../lib/deletedSessions.js'@@ -14,12 +11,9 @@ import { findLiveSession, findResumedTranscript } from '../../lib/sessionRepair.import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'import { createBinding, statBirthMs, type BindDeps, type RegisteredMeta } from './bind.js'-vi.mock('../../engines/agy/session.js', () => ({ findAgyTranscript: vi.fn(async () => '/t/agy.jsonl') }))-vi.mock('../../engines/copilot/session.js', () => ({ copilotSessionForPid: vi.fn(async () => null), findCopilotTranscript: vi.fn(async () => '/t/copilot.jsonl') }))-vi.mock('../../engines/cursor/discovery.js', async (real) => ({ ...await real<object>(), findCursorTranscript: vi.fn(async () => '/t/cursor.jsonl') }))-vi.mock('../../engines/cursor/home.js', async (real) => ({ ...await real<object>(), cursorDataDir: () => '/cursor' }))-vi.mock('../../engines/grok/session.js', () => ({ findGrokTranscript: vi.fn(async () => '/t/grok.jsonl') }))-// The other engines' finders are their own code, loaded when asked; a test may say one could not be.+vi.mock('../../engines/identities.js', () => ({ transcriptOf: vi.fn(), processSessionOf: vi.fn() }))+vi.mock('../../engines/cursor/contract.js', async (real) => ({ ...await real<object>(), cursorDataDir: () => '/cursor' }))+// The optional loader may be unavailable; identity must still be usable.vi.mock('../../engines/inProcess.js', async (real) => {const actual = await real<typeof import('../../engines/inProcess.js')>()return { ...actual, loadEngine: vi.fn(actual.loadEngine) }@@ -35,11 +29,9 @@ const dirs: string[] = []/** Every engine lookup back to its default answer, calls forgotten, before each test. */function resetLookups() {- vi.mocked(findAgyTranscript).mockReset().mockResolvedValue('/t/agy.jsonl')- vi.mocked(copilotSessionForPid).mockReset().mockResolvedValue(null)- vi.mocked(findCopilotTranscript).mockReset().mockResolvedValue('/t/copilot.jsonl')- vi.mocked(findCursorTranscript).mockReset().mockResolvedValue('/t/cursor.jsonl')- vi.mocked(findGrokTranscript).mockReset().mockResolvedValue('/t/grok.jsonl')+ vi.mocked(transcriptOf).mockReset().mockImplementation(async engine => `/t/${engine}.jsonl`)+ vi.mocked(processSessionOf).mockReset().mockResolvedValue(null)+ vi.mocked(loadEngine).mockClear()vi.mocked(isRecentlyDeleted).mockReset().mockReturnValue(false)vi.mocked(continuationOf).mockReset().mockResolvedValue(null)vi.mocked(findLiveSession).mockReset().mockResolvedValue(null)@@ -58,7 +50,7 @@ function setup(over: Partial<BindDeps> = {}) {registry: {inheritName: vi.fn(),unbindSession: vi.fn(() => true),- byAgent: vi.fn((agentId: string) => byAgent.get(agentId)),+ byAgent: vi.fn((agentId: string) => byAgent.get(agentId) ?? vi.mocked(deps.registry.register).mock.results.at(-1)?.value?.entry),byProcess: vi.fn(() => undefined),register: vi.fn(() => null),has: vi.fn(() => false),@@ -80,6 +72,11 @@ function setup(over: Partial<BindDeps> = {}) {return { deps, byAgent, bySession, binding: createBinding(deps) }}+function registered(run: ReturnType<typeof setup>, entry: RegisteredSession, meta: RegisteredMeta): Promise<void> {+ run.byAgent.set(entry.agentId, entry)+ return run.binding.handleRegistered(entry, meta)+}+describe('binding a registered session to its agent', () => {beforeEach(() => { vi.spyOn(console, 'log').mockImplementation(() => {}) })afterEach(() => {@@ -91,7 +88,7 @@ describe('binding a registered session to its agent', () => {const run = setup()const entry = agent({ boundAt: Date.parse('2026-10-04T10:00:00Z') })run.byAgent.set('a1', entry)- await run.binding.handleRegistered(entry, meta({ isNew: true }))+ await registered(run, entry, meta({ isNew: true }))expect(run.deps.attachSession).toHaveBeenCalledWith(entry, true, false, false)expect(run.deps.stoppedAgents.save).toHaveBeenCalledWith(entry)expect(run.deps.syncRecapPool).toHaveBeenCalled()@@ -109,21 +106,68 @@ describe('binding a registered session to its agent', () => {const entry = agent({ boundAt: Date.parse('2026-10-04T10:00:00Z'), resumeOnly: true })run.byAgent.set('a1', entry)vi.mocked(run.deps.stoppedAgents.save).mockImplementationOnce(() => { throw Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' }) })- await run.binding.handleRegistered(entry, meta({ isNew: true }))+ await registered(run, entry, meta({ isNew: true }))expect(error).toHaveBeenCalledWith('[agent] a1 could not save the record it resumes from: ENOSPC: no space left on device')expect(run.deps.stoppedAgents.finishResume).toHaveBeenCalledWith('a1')expect(run.deps.announceSession).toHaveBeenCalledWith(entry)expect(run.deps.clients.send).toHaveBeenCalledWith(expect.objectContaining({ type: 'session_synced' }))vi.mocked(run.deps.stoppedAgents.save).mockImplementationOnce(() => { throw 'disk gone' })- await run.binding.handleRegistered(entry, meta({ isNew: true }))+ await registered(run, entry, meta({ isNew: true }))expect(error).toHaveBeenLastCalledWith('[agent] a1 could not save the record it resumes from: disk gone')})+ it('completes a resumed binding while its optional attachment stays pending', async () => {+ const run = setup({ attachSession: vi.fn(() => new Promise<boolean>(() => {})) })+ const entry = agent({ resumeOnly: true })+ void registered(run, entry, meta({ isNew: true }))+ expect(run.deps.stoppedAgents.save).toHaveBeenCalledWith(entry)+ expect(run.deps.stoppedAgents.finishResume).toHaveBeenCalledWith('a1')+ expect(run.deps.registry.inheritName).toHaveBeenCalledWith('a1', 's1')+ expect(run.deps.announceSession).toHaveBeenCalledWith(entry)+ expect(run.deps.clients.send).toHaveBeenCalledWith(expect.objectContaining({ type: 'session_synced' }))+ expect(run.deps.attachSession).toHaveBeenCalledOnce()+ })++ it.each([true, false])('ignores a superseded attachment completing with %s', async attached => {+ let finish!: (attached: boolean) => void+ const run = setup({ attachSession: vi.fn(() => new Promise<boolean>(resolve => { finish = resolve })) })+ const first = agent()+ const pending = registered(run, first, meta({ isNew: true }))+ vi.mocked(run.deps.attachSession).mockResolvedValueOnce(true)+ // Mutate the row as the real registry does while the first attachment is still reading.+ first.sessionId = 's2'+ await registered(run, first, meta({ isNew: true }))+ vi.mocked(run.deps.clients.send).mockClear()+ vi.mocked(run.deps.announceSession).mockClear()+ vi.mocked(run.deps.stoppedAgents.save).mockClear()+ vi.mocked(run.deps.registry.inheritName).mockClear()+ finish(attached); await pending+ expect(run.deps.clients.send).not.toHaveBeenCalled()+ expect(run.deps.announceSession).not.toHaveBeenCalled()+ expect(run.deps.stoppedAgents.save).not.toHaveBeenCalled()+ expect(run.deps.registry.inheritName).not.toHaveBeenCalled()+ expect(run.deps.registry.unbindSession).not.toHaveBeenCalled()+ })++ it('does not start an optional reader if the binding changes during the transcript birth read', async () => {+ const run = setup()+ const home = mkdtempSync(join(tmpdir(), 'binding-stat-')); dirs.push(home)+ const path = join(home, 'transcript.jsonl'); writeFileSync(path, '{}\n')+ const entry = agent({ transcriptPath: path })+ const pending = registered(run, entry, meta({ isNew: true }))+ entry.sessionId = 'replacement'+ await pending+ expect(run.deps.attachSession).not.toHaveBeenCalled()+ expect(run.deps.clients.send).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({+ type: 'session_synced', payload: expect.objectContaining({ sessionId: 's1' }),+ }))+ })+it('stops after the attach for a session it already had, and finishes a resume it was waiting for', async () => {const run = setup()const entry = agent({ resumeOnly: true } as Partial<RegisteredSession>)run.byAgent.set('a1', entry)- await run.binding.handleRegistered(entry, meta())+ await registered(run, entry, meta())expect(run.deps.stoppedAgents.finishResume).toHaveBeenCalledWith('a1')expect(run.deps.announceSession).not.toHaveBeenCalled()// Bound elsewhere by the time the attach finished: not this agent's session to archive.@@ -136,25 +180,25 @@ describe('binding a registered session to its agent', () => {it('unbinds a session whose pane is gone and re-announces its agent', async () => {const run = setup({ attachSession: vi.fn(async () => false) })const entry = agent()- await run.binding.handleRegistered(entry, meta({ isNew: true }))+ await registered(run, entry, meta({ isNew: true }))expect(run.deps.registry.unbindSession).toHaveBeenCalledWith('s1')expect(run.deps.announceSession).toHaveBeenCalledWith(entry)- expect(run.deps.syncRecapPool).not.toHaveBeenCalled()+ expect(run.deps.syncRecapPool).toHaveBeenCalled()})it('keeps the verified conversation when a native exit beats its pending startup attach', async () => {let finish!: (attached: boolean) => voidconst run = setup({ attachSession: vi.fn(() => new Promise<boolean>(resolve => { finish = resolve })) })const entry = agent({ processIdentity: { pid: 42, startMarker: '2026-10-06T10:00:00Z', executable: 'claude' } })- const pending = run.binding.handleRegistered(entry, meta({ isNew: true, hookEvent: 'SessionStart' }))+ const pending = registered(run, entry, meta({ isNew: true, hookEvent: 'SessionStart' }))await vi.waitFor(() => expect(run.deps.attachSession).toHaveBeenCalled())finish(false)await pendingexpect(run.deps.registry.unbindSession).not.toHaveBeenCalled()expect(entry.sessionId).toBe('s1')expect(run.deps.announceSession).toHaveBeenCalledWith(entry)- expect(run.deps.stoppedAgents.save).not.toHaveBeenCalled()- expect(run.deps.clients.send).not.toHaveBeenCalled()+ expect(run.deps.stoppedAgents.save).toHaveBeenCalledWith(entry)+ expect(run.deps.clients.send).toHaveBeenCalledWith(expect.objectContaining({ type: 'session_synced' }))})it('keeps the binding of an agent a stop or a restart owns: its pane reads as gone only because of it', async () => {@@ -164,18 +208,18 @@ describe('binding a registered session to its agent', () => {const changing = vi.fn((agentId: string) => agentId === 'a1')run.binding.whileChanging(changing)const entry = agent()- await run.binding.handleRegistered(entry, meta())+ await registered(run, entry, meta())expect(changing).toHaveBeenCalledWith('a1')expect(run.deps.registry.unbindSession).not.toHaveBeenCalled()expect(run.deps.announceSession).toHaveBeenCalledWith(entry)// An agent nothing owns is unbound as before.- await run.binding.handleRegistered(agent({ agentId: 'a2', sessionId: 's2' }), meta())+ await registered(run, agent({ agentId: 'a2', sessionId: 's2' }), meta())expect(run.deps.registry.unbindSession).toHaveBeenCalledWith('s2')})it('hands a rebound agent its name and recap, and lets the stale session go', async () => {const run = setup()- await run.binding.handleRegistered(agent({ sessionId: 's2' }), meta({ rebound: 's1' }))+ await registered(run, agent({ sessionId: 's2' }), meta({ rebound: 's1' }))expect(run.deps.registry.inheritName).toHaveBeenCalledWith('s1', 's2')expect(run.deps.mirror.inheritSummary).toHaveBeenCalledWith('s1', 's2')expect(run.deps.forgetSession).toHaveBeenCalledWith('s1', { force: true, keepAgent: true })@@ -184,7 +228,7 @@ describe('binding a registered session to its agent', () => {it('forgets an evicted session and an agent the bind emptied out', async () => {const run = setup()- await run.binding.handleRegistered(agent(), meta({ evicted: 's0', orphaned: { agentId: 'a0', sessionId: 's0' } }))+ await registered(run, agent(), meta({ evicted: 's0', orphaned: { agentId: 'a0', sessionId: 's0' } }))expect(vi.mocked(run.deps.forgetSession).mock.calls).toEqual([['s0', { force: true }],['a0', { force: true, agentId: 'a0' }],@@ -194,9 +238,9 @@ describe('binding a registered session to its agent', () => {it('gives a fork the recap of its source once its own session reports in', async () => {const run = setup()run.binding.pendingForkInherit.set('a1', 'source-s')- await run.binding.handleRegistered(agent({ sessionId: '' }), meta())+ await registered(run, agent({ sessionId: '' }), meta())expect(run.deps.mirror.inheritSummary).not.toHaveBeenCalled()- await run.binding.handleRegistered(agent(), meta())+ await registered(run, agent(), meta())expect(run.deps.mirror.inheritSummary).toHaveBeenCalledWith('source-s', 's1')expect(run.binding.pendingForkInherit.has('a1')).toBe(false)})@@ -204,7 +248,7 @@ describe('binding a registered session to its agent', () => {it('resets on a SessionStart, except for engines that announce one turn more than once', async () => {const run = setup()for (const engine of ['claude', 'cursor', 'agy', 'copilot']) {- await run.binding.handleRegistered(agent({ engine } as Partial<RegisteredSession>), meta({ hookEvent: 'SessionStart' }))+ await registered(run, agent({ engine } as Partial<RegisteredSession>), meta({ hookEvent: 'SessionStart' }))}expect(vi.mocked(run.deps.attachSession).mock.calls.map((call) => [call[0].engine, call[1], call[2]])).toEqual([['claude', true, false], ['cursor', false, true], ['agy', false, false], ['copilot', false, false],@@ -217,8 +261,8 @@ describe('binding a registered session to its agent', () => {dirs.push(dir)const born = join(dir, 'session.jsonl')writeFileSync(born, '{}\n')- await run.binding.handleRegistered(agent({ transcriptPath: born, registeredAt: Date.now() - 60_000 }), meta())- await run.binding.handleRegistered(agent({ transcriptPath: join(dir, 'missing.jsonl'), registeredAt: Date.now() - 60_000 }), meta())+ await registered(run, agent({ transcriptPath: born, registeredAt: Date.now() - 60_000 }), meta())+ await registered(run, agent({ transcriptPath: join(dir, 'missing.jsonl'), registeredAt: Date.now() - 60_000 }), meta())expect(vi.mocked(run.deps.attachSession).mock.calls.map((call) => call[3])).toEqual([true, false])})@@ -231,13 +275,13 @@ describe('binding a registered session to its agent', () => {// A resume keeps the row's original registeredAt, so the transcript reads as born after its agent.const resumed = agent({ transcriptPath: born, registeredAt: Date.now() - 60_000, resumeOnly: true } as Partial<RegisteredSession>)vi.mocked(run.deps.stoppedAgents.get).mockReturnValue(agent({ sessionId: 's1' }))- await run.binding.handleRegistered(resumed, meta())+ await registered(run, resumed, meta())expect(run.deps.stoppedAgents.get).toHaveBeenCalledWith('a1')// `/clear` after the resume: a session the stopped record does not hold.- await run.binding.handleRegistered({ ...resumed, sessionId: 's2' }, meta())+ await registered(run, { ...resumed, sessionId: 's2' }, meta())// A resumed row with no stopped record left to compare against.vi.mocked(run.deps.stoppedAgents.get).mockReturnValue(null)- await run.binding.handleRegistered(resumed, meta())+ await registered(run, resumed, meta())expect(vi.mocked(run.deps.attachSession).mock.calls.map((call) => call[3])).toEqual([false, true, true])})})@@ -263,27 +307,104 @@ describe('binding a running process to its session', () => {expect(run.deps.registry.register).not.toHaveBeenCalled()})+ it('does not wait for optional transcript attachment before completing binding', async () => {+ const run = setup({ attachSession: vi.fn(() => new Promise<boolean>(() => {})) })+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '' }))+ vi.mocked(run.deps.registry.register).mockReturnValue({ entry: agent(), ...meta({ isNew: true }) } as never)+ let done = false+ void run.binding.bindObservedAgent(observed({ resumeSessionId: 'resumed' })).then(() => { done = true })+ await vi.waitFor(() => expect(done).toBe(true), { timeout: 1000 })+ expect(run.deps.registry.register).toHaveBeenCalledOnce()+ expect(run.deps.attachSession).toHaveBeenCalledOnce()+ })++ 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 }) })+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '' }))+ vi.mocked(run.deps.registry.register).mockReturnValue({ entry: agent(), ...meta({ isNew: true }) } as never)+ await run.binding.bindObservedAgent(observed({ resumeSessionId: 'resumed' }))+ await vi.waitFor(() => expect(log).toHaveBeenCalledWith('[agent] a1 transcript attachment is unavailable: reader unavailable'))+ expect(run.deps.registry.register).toHaveBeenCalledOnce()+ expect(run.deps.registry.unbindSession).not.toHaveBeenCalled()+ })++ it.each(['binding', 'process', 'stop', 'changing'] as const)('discards a delayed lookup after %s changed its authority', async change => {+ const run = setup()+ const entry = agent({ sessionId: '', processIdentity: { pid: 42, startMarker: '2026-10-04T10:00:00Z', executable: 'cursor' } })+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(entry)+ let answer!: (path: string | null) => void+ vi.mocked(transcriptOf).mockReturnValueOnce(new Promise(resolve => { answer = resolve }))+ const pending = run.binding.bindObservedAgent(observed({ engine: 'cursor', resumeSessionId: 'resumed' }))+ if (change === 'binding') entry.sessionId = 'newer'+ if (change === 'process') vi.mocked(run.deps.registry.byProcess).mockReturnValue(undefined)+ if (change === 'stop') vi.mocked(isRecentlyDeleted).mockImplementation(id => id === entry.agentId)+ if (change === 'changing') run.binding.whileChanging(() => true)+ answer('/fixture/transcript.jsonl'); await pending+ expect(run.deps.registry.register).not.toHaveBeenCalled()+ })++ it.each(['newer owner', 'target stopped'] as const)('rechecks the target after resume evidence waits: %s', async change => {+ const run = setup()+ vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '' }))+ let answer!: (path: string | null) => void+ vi.mocked(transcriptOf).mockReturnValueOnce(new Promise(resolve => { answer = resolve }))+ const pending = run.binding.bindObservedAgent(observed({ engine: 'cursor', resumeSessionId: 'r' }))+ if (change === 'newer owner') run.bySession.set('r', agent({ agentId: 'newer', processIdentity: {+ pid: 43, startMarker: '2026-10-04T11:00:00Z', executable: 'cursor',+ } }))+ else vi.mocked(isRecentlyDeleted).mockImplementation(id => id === 'r')+ answer('/fixture/transcript.jsonl'); await pending+ expect(run.deps.registry.register).not.toHaveBeenCalled()+ })++ it.each(['copilot', 'claude'] as const)('rejects a delayed %s continuation after the receiving binding changes', async engine => {+ const run = setup()+ 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') }))+ 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'+ answer(); await pending+ expect(run.deps.registry.register).not.toHaveBeenCalled()+ })++ 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')+ let answer!: (path: string | null) => void+ vi.mocked(transcriptOf).mockReturnValueOnce(new Promise(resolve => { answer = resolve }))+ const pending = run.binding.bindObservedAgent(observed({ engine: 'copilot' }))+ await vi.waitFor(() => expect(answer).toBeTypeOf('function'))+ vi.mocked(isRecentlyDeleted).mockImplementation(id => id === 's2')+ answer('/fixture/transcript.jsonl'); await pending+ expect(run.deps.registry.register).not.toHaveBeenCalled()+ })+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()vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ engine: 'copilot' } as Partial<RegisteredSession>))await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))- vi.mocked(copilotSessionForPid).mockResolvedValueOnce('s1')+ vi.mocked(processSessionOf).mockResolvedValueOnce('s1')await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))- vi.mocked(copilotSessionForPid).mockResolvedValueOnce('deleted')+ vi.mocked(processSessionOf).mockResolvedValueOnce('deleted')vi.mocked(isRecentlyDeleted).mockReturnValueOnce(true)await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))expect(run.deps.registry.register).not.toHaveBeenCalled()- vi.mocked(copilotSessionForPid).mockResolvedValue('s2')+ vi.mocked(processSessionOf).mockResolvedValue('s2')const rotated = agent({ engine: 'copilot', sessionId: 's2' } as Partial<RegisteredSession>)vi.mocked(run.deps.registry.register).mockReturnValueOnce({ entry: rotated, ...meta({ isNew: true }) } as never)await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))- expect(copilotSessionForPid).toHaveBeenLastCalledWith('/copilot', 42)- expect(findCopilotTranscript).toHaveBeenLastCalledWith('/copilot', 's2')+ expect(processSessionOf).toHaveBeenLastCalledWith('copilot', '/copilot', 42)+ expect(transcriptOf).toHaveBeenLastCalledWith('copilot', '/copilot', 's2')expect(vi.mocked(run.deps.registry.register).mock.calls[0][0]).toMatchObject({ sessionId: 's2', transcriptPath: '/t/copilot.jsonl', source: 'copilot-resume' })expect(run.deps.attachSession).toHaveBeenCalledWith(rotated, true, false, false)// Not new to the registry, or no transcript yet: registered as it is, attached by its hook later.- vi.mocked(findCopilotTranscript).mockResolvedValueOnce(null)+ vi.mocked(transcriptOf).mockResolvedValueOnce(null)vi.mocked(run.deps.registry.register).mockReturnValueOnce({ entry: rotated, ...meta() } as never)await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))expect(vi.mocked(run.deps.registry.register).mock.calls[1][0]).toMatchObject({ transcriptPath: undefined })@@ -335,27 +456,27 @@ describe('binding a running process to its session', () => {expect(vi.mocked(run.deps.registry.register).mock.calls.map(([input]) => [input.engine, input.transcriptPath, input.source, input.hookEvent])).toEqual(Object.entries(expected).map(([engine, path]) => [engine, path, 'terminal-resume', 'TerminalResumeDiscovery']),)- expect(findCursorTranscript).toHaveBeenCalledWith('/cursor', 'cursor-resumed')- expect(findGrokTranscript).toHaveBeenCalledWith('/grok', '/work', 'grok-resumed')- expect(findAgyTranscript).toHaveBeenCalledWith('/agy', 'agy-resumed')+ expect(transcriptOf).toHaveBeenCalledWith('cursor', '/cursor', 'cursor-resumed', '/work')+ expect(transcriptOf).toHaveBeenCalledWith('grok', '/grok', 'grok-resumed', '/work')+ expect(transcriptOf).toHaveBeenCalledWith('agy', '/agy', 'agy-resumed', '/work')expect(findResumedTranscript).toHaveBeenCalledWith('codex', 'codex-resumed', { codexHome: undefined })})- it('finds nothing without the engine\'s code: bound without a transcript, or not at all, as when none is found', async () => {+ it('binds and follows Copilot resume while the optional loader cannot answer', async () => {const run = setup()vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '' }))- vi.mocked(loadEngine).mockResolvedValue(null)+ vi.mocked(loadEngine).mockImplementation(() => new Promise(() => {}))try {for (const engine of ['cursor', 'grok', 'agy', 'copilot']) {await run.binding.bindObservedAgent(observed({ engine, resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))}- expect(vi.mocked(run.deps.registry.register).mock.calls.map(([input]) => [input.engine, input.transcriptPath])).toEqual([['agy', undefined], ['copilot', undefined]])- // Nor is a Copilot /resume followed.+ expect(vi.mocked(run.deps.registry.register).mock.calls.map(([input]) => [input.engine, input.transcriptPath])).toEqual(['cursor', 'grok', 'agy', 'copilot'].map(engine => [engine, `/t/${engine}.jsonl`]))+ // Copilot can also switch conversation while optional interpretation is unavailable.vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ engine: 'copilot' } as Partial<RegisteredSession>))- vi.mocked(copilotSessionForPid).mockResolvedValue('s2')+ vi.mocked(processSessionOf).mockResolvedValue('s2')await run.binding.bindObservedAgent(observed({ engine: 'copilot' }))- expect(run.deps.registry.register).toHaveBeenCalledTimes(2)- expect([findCursorTranscript, findGrokTranscript, findAgyTranscript, findCopilotTranscript, copilotSessionForPid].map((find) => vi.mocked(find).mock.calls.length)).toEqual([0, 0, 0, 0, 0])+ expect(run.deps.registry.register).toHaveBeenCalledTimes(5)+ expect(loadEngine).not.toHaveBeenCalled()} finally { vi.mocked(loadEngine).mockReset() }// Claude Code and Codex find theirs with no engine code loaded.vi.mocked(loadEngine).mockClear()@@ -369,14 +490,14 @@ describe('binding a running process to its session', () => {it('needs a transcript for the engines whose sessions are files, and skips a deleted session', async () => {const run = setup()vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ sessionId: '', codexHome: '/codex' } as Partial<RegisteredSession>))- vi.mocked(findCursorTranscript).mockResolvedValueOnce(null)- vi.mocked(findGrokTranscript).mockResolvedValueOnce(null)+ vi.mocked(transcriptOf).mockResolvedValueOnce(null)+ vi.mocked(transcriptOf).mockResolvedValueOnce(null)vi.mocked(findResumedTranscript).mockResolvedValueOnce(null).mockResolvedValueOnce(null)for (const engine of ['cursor', 'grok', 'claude', 'codex']) {await run.binding.bindObservedAgent(observed({ engine, resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))}- vi.mocked(findAgyTranscript).mockResolvedValueOnce(null)- vi.mocked(findCopilotTranscript).mockResolvedValueOnce(null)+ vi.mocked(transcriptOf).mockResolvedValueOnce(null)+ vi.mocked(transcriptOf).mockResolvedValueOnce(null)await run.binding.bindObservedAgent(observed({ engine: 'agy', resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))await run.binding.bindObservedAgent(observed({ engine: 'copilot', resumeSessionId: 'r' } as Partial<DiscoveredTerminalAgent>))vi.mocked(isRecentlyDeleted).mockReturnValueOnce(true)diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.tsindex 3c7337ce9..82cb7155c 100644--- a/cli/src/core/agents/bind.ts+++ b/cli/src/core/agents/bind.ts@@ -7,10 +7,12 @@* Moved verbatim out of `runForeground` (the core boundary, step 10: docs/design/2026-10-03-harnessd.md).*/import { stat } from 'node:fs/promises'-import { loadEngine } from '../../engines/inProcess.js'+import { transcriptOf, processSessionOf } from '../../engines/identities.js'+import { cursorDataDir } from '../../engines/cursor/contract.js'import { continuationOf } from '../../engines/sessionFiles.js'import { sessionStoreOf } from '../../engines/sessionStoreContracts.js'import type { TurnRecaps } from '../turns/recaps.js'+import { paneReadIdentity } from '../transcripts/readIdentity.js'import type { AutonomousDeviceInput } from '../deviceInput.js'import { isRecentlyDeleted } from '../../lib/deletedSessions.js'import { transcriptIsFirstTurn } from '../../lib/firstTurnReplay.js'@@ -81,6 +83,9 @@ export function createBinding({let changing: (agentId: string) => boolean = () => falseconst handleRegistered = async (entry: RegisteredSession, meta: RegisteredMeta): Promise<void> => {+ const authority = paneReadIdentity(entry)+ const current = () => paneReadIdentity(registry.byAgent(entry.agentId)) === authority+ if (!current()) returnconst forkSource = pendingForkInherit.get(entry.agentId)if (forkSource && entry.sessionId) {pendingForkInherit.delete(entry.agentId)@@ -110,6 +115,31 @@ export function createBinding({})}+ // Registration is complete before any optional history reader runs. In particular a stalled+ // module cannot withhold a resumed agent's record, name or announcement. Capture this fact before+ // finishResume changes the stopped record used to decide whether history may be replayed below.+ const resumedConversation = !!entry.resumeOnly && stoppedAgents.get(entry.agentId)?.sessionId === entry.sessionId+ try {+ stoppedAgents.save(entry)+ } catch (error) {+ console.error(`[agent] ${sid(entry.agentId)} could not save the record it resumes from: ${error instanceof Error ? error.message : error}`)+ }+ if (entry.resumeOnly) stoppedAgents.finishResume(entry.agentId)+ syncRecapPool()+ if (meta.isNew) {+ registry.inheritName(entry.agentId, entry.sessionId)+ announceSession(entry)+ clients.send({+ type: 'session_synced',+ payload: {+ sessionId: entry.sessionId,+ agentId: entry.agentId,+ title: projectDisplayName(entry),+ createdAt: new Date(entry.boundAt ?? Date.now()).toISOString(),+ },+ })+ }+// agy is excluded for the same reason as cursor, arriving by a different road: it has no// session-start event at all. The closest thing is `PreInvocation`, which fires before EVERY model// round-trip — four to seven times in one measured turn — and each one re-folded the transcript and@@ -149,13 +179,16 @@ export function createBinding({// announced as running with nothing left to end it (found end to end: stop in the middle of a first// turn, resume, and the agent read as working for good). A new session started in the agent after// the resume is not this conversation, and is judged like any other.- const resumedConversation = !!entry.resumeOnly && stoppedAgents.get(entry.agentId)?.sessionId === entry.sessionIdconst bornAfterAgent = !resumedConversation && transcriptIsFirstTurn(entry,entry.transcriptPath ? await statBirthMs(entry.transcriptPath) : 0,{ rebound: !!meta.rebound, now: Date.now() },)+ if (!current()) returnconst attached = await attachSession(entry, reset, entry.engine === 'cursor', bornAfterAgent)+ // The registry mutates rows in place. This completion cannot unbind or re-announce a later+ // conversation, nor an agent that Stop has already retired.+ if (!current()) returnif (!attached) {// A terminal reads as gone while a stop or a restart ends its engine. A registration that comes in// then, such as the old engine's own SessionStart arriving late on a loaded machine, is still the@@ -171,50 +204,32 @@ export function createBinding({announceSession(entry)return}- const confirmed = registry.byAgent(entry.agentId)- if (confirmed?.sessionId === entry.sessionId) {- // The record a stop is resumed from, kept current. Best effort: the binding has happened, and a- // full disk must not stop the windows hearing of it below (found end to end, e2e/diskfull.e2e.ts).- try {- stoppedAgents.save(confirmed)- } catch (error) {- console.error(`[agent] ${sid(entry.agentId)} could not save the record it resumes from: ${error instanceof Error ? error.message : error}`)- }- if (confirmed.resumeOnly) stoppedAgents.finishResume(confirmed.agentId)- }- syncRecapPool()- if (!meta.isNew) return- registry.inheritName(entry.agentId, entry.sessionId)- announceSession(entry)- clients.send({- type: 'session_synced',- payload: {- sessionId: entry.sessionId,- agentId: entry.agentId,- title: projectDisplayName(entry),- createdAt: new Date(entry.boundAt ?? Date.now()).toISOString(),- },- })}const lastRepairAttempt = new Map<string, number>()const repairAttempts = new Map<string, number>()- /**- * The transcript of a session the process of one of these engines names, found by that engine's own code,- * loaded here (engines/inProcess.ts). One whose code could not be loaded finds nothing: the process is bound as- * when its transcript is not there, or not at all.- */- const ownTranscript = async (engine: 'cursor' | 'grok' | 'agy' | 'copilot', sessionId: string, cwd: string): Promise<string | null> => {- switch (engine) {- case 'cursor': { const cursor = await loadEngine('cursor'); return cursor && cursor.findCursorTranscript(cursor.cursorDataDir(), sessionId) }- case 'grok': { const grok = await loadEngine('grok'); return grok && grok.findGrokTranscript(homes.grok, cwd, sessionId) }- case 'agy': { const agy = await loadEngine('agy'); return agy && agy.findAgyTranscript(homes.agy, sessionId) }- case 'copilot': { const copilot = await loadEngine('copilot'); return copilot && copilot.findCopilotTranscript(homes.copilot, sessionId) }- }+ // Binding is committed before optional interpretation starts. A missing reader must not hold the+ // discovery pass (and therefore readiness) or prevent another process from being bound.+ const followRegistered = (entry: RegisteredSession, meta: RegisteredMeta): void => {+ void handleRegistered(entry, meta).catch(error => console.error(+ `[agent] ${sid(entry.agentId)} transcript attachment is unavailable: ${error instanceof Error ? error.message : error}`))}+ const ownTranscript = (engine: 'cursor' | 'grok' | 'agy' | 'copilot', sessionId: string, cwd: string): Promise<string | null> =>+ transcriptOf(engine, engine === 'cursor' ? cursorDataDir() : homes[engine], sessionId, cwd)const bindObservedAgent = async (observed: DiscoveredTerminalAgent): Promise<void> => {const agent = registry.byProcess(observed.engine, observed.processIdentity)if (!agent) return+ const authority = paneReadIdentity(agent)+ const current = () => !changing(agent.agentId) && !isRecentlyDeleted(agent.agentId)+ && paneReadIdentity(registry.byProcess(observed.engine, observed.processIdentity)) === authority+ const mayClaim = (id: string): boolean => {+ if (isRecentlyDeleted(id)) return false+ const owner = registry.bySession(id)+ if (!owner || owner.agentId === agent.agentId) return true+ const observedStarted = Date.parse(observed.processIdentity.startMarker)+ const ownerStarted = Date.parse(owner.processIdentity?.startMarker ?? '')+ return !Number.isFinite(ownerStarted) || (Number.isFinite(observedStarted) && observedStarted > ownerStarted)+ }// Copilot can change session WITHOUT changing process: `/resume` inside the CLI opens another one,// and the pane then shows a conversation the daemon is not streaming. Every other engine here@@ -225,16 +240,14 @@ export function createBinding({if (agent.resumeOnly && agent.launch && agent.launch.state !== 'ready') returnif (agent.sessionId) {if (observed.engine === 'copilot') {- // Copilot's own code reads its lock (engines/inProcess.ts): without it, a /resume is not followed.- const copilot = await loadEngine('copilot')- if (!copilot) return- const current = await copilot.copilotSessionForPid(homes.copilot, observed.processIdentity.pid)- if (!current || current === agent.sessionId || isRecentlyDeleted(current)) return- const transcript = await copilot.findCopilotTranscript(homes.copilot, current)- console.log(`[discovery] ${sid(agent.agentId)} switched copilot session ${sid(agent.sessionId)} → ${sid(current)} (/resume)`)+ const next = await processSessionOf('copilot', homes.copilot, observed.processIdentity.pid)+ if (!next || next === agent.sessionId || isRecentlyDeleted(next)) return+ const transcript = await transcriptOf('copilot', homes.copilot, next)+ if (!current() || !mayClaim(next)) return+ console.log(`[discovery] ${sid(agent.agentId)} switched copilot session ${sid(agent.sessionId)} → ${sid(next)} (/resume)`)const rotated = registry.register({engine: 'copilot',- sessionId: current,+ sessionId: next,transcriptPath: transcript ?? undefined,cwd: observed.cwd,source: 'copilot-resume',@@ -243,7 +256,7 @@ export function createBinding({processIdentity: observed.processIdentity,hookEvent: 'CopilotResume',})- if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)+ if (rotated?.isNew) followRegistered(rotated.entry, rotated)return}// Claude can also change session WITHOUT any hook firing: a long conversation's transcript@@ -258,6 +271,7 @@ export function createBinding({const continuation = await continuationOf(observed.engine, agent.transcriptPath)if (!continuation || continuation.sessionId === agent.sessionId|| registry.has(continuation.sessionId) || isRecentlyDeleted(continuation.sessionId)) return+ if (!current()) returnconsole.log(`[discovery] ${sid(agent.agentId)} ${observed.engine} session continued ${sid(agent.sessionId)} → ${sid(continuation.sessionId)}`)const rotated = registry.register({engine: observed.engine,@@ -270,7 +284,7 @@ export function createBinding({processIdentity: observed.processIdentity,hookEvent: `${store.label}Continuation`,})- if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)+ if (rotated?.isNew) followRegistered(rotated.entry, rotated)return}return@@ -281,13 +295,7 @@ export function createBinding({let hermesHome: string | undefinedlet source = 'terminal-resume'if (sessionId) {- if (isRecentlyDeleted(sessionId)) return- const owner = registry.bySession(sessionId)- if (owner && owner.agentId !== agent.agentId) {- const observedStarted = Date.parse(observed.processIdentity.startMarker)- const ownerStarted = Date.parse(owner.processIdentity?.startMarker ?? '')- if (Number.isFinite(ownerStarted) && (!Number.isFinite(observedStarted) || observedStarted <= ownerStarted)) return- }+ if (!mayClaim(sessionId)) returntranscriptPath = 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'@@ -321,6 +329,7 @@ export function createBinding({source = 'process-repair'}+ if (!current() || !mayClaim(sessionId)) returnconst previousOwner = registry.bySession(sessionId)const result = registry.register({engine: observed.engine,@@ -343,7 +352,7 @@ export function createBinding({}lastRepairAttempt.delete(agent.agentId)repairAttempts.delete(agent.agentId)- await handleRegistered(result.entry, result)+ followRegistered(result.entry, result)console.log(`[discovery] bound ${observed.engine} session ${sid(result.entry.sessionId)} via ${observed.primaryRuntimeKey}`)}return {diff --git a/cli/src/core/agents/forget.spec.ts b/cli/src/core/agents/forget.spec.tsindex 03bdf7c7a..7d95434f2 100644--- a/cli/src/core/agents/forget.spec.ts+++ b/cli/src/core/agents/forget.spec.ts@@ -18,6 +18,7 @@ function setup() {stoppedAgents: { save: vi.fn() },syncRecapPool: vi.fn(),normalizers: { forget: vi.fn() },+ forgetAttach: vi.fn(),turnStartedAt: new Map([['s1', 1], ['other', 2]]),neverFoldedHistory: new Set(['s1', 'other']),replayedFirstTurn: new Set(['s1', 'other']),@@ -42,6 +43,7 @@ function setup() {function expectLetGo(deps: ForgetDeps, sessionId: string, agentId: string) {expect(deps.syncRecapPool).toHaveBeenCalled()expect(deps.normalizers.forget).toHaveBeenCalledWith(sessionId)+ expect(deps.forgetAttach).toHaveBeenCalledWith(sessionId)expect(deps.turnStartedAt.has(sessionId)).toBe(false)expect(deps.neverFoldedHistory.has(sessionId)).toBe(false)expect(deps.replayedFirstTurn.has(sessionId)).toBe(false)diff --git a/cli/src/core/agents/forget.ts b/cli/src/core/agents/forget.tsindex e8ca38713..2ff165f6c 100644--- a/cli/src/core/agents/forget.ts+++ b/cli/src/core/agents/forget.ts@@ -28,6 +28,7 @@ export interface ForgetDeps {stoppedAgents: Pick<StoppedAgentStore, 'save'>syncRecapPool: () => voidnormalizers: Pick<SessionNormalizers, 'forget'>+ forgetAttach: (sessionId: string) => voidturnStartedAt: Map<string, number>/** Attach's two per-session marks (core/transcripts/attach.ts). */neverFoldedHistory: Set<string>@@ -50,7 +51,7 @@ export interface ForgetDeps {}export function createForgetSession({- registry, stoppedAgents, syncRecapPool, normalizers, turnStartedAt, neverFoldedHistory, replayedFirstTurn, relaunchMarks,+ registry, stoppedAgents, syncRecapPool, normalizers, forgetAttach, turnStartedAt, neverFoldedHistory, replayedFirstTurn, relaunchMarks,clearAgyIdleWatch, cursorDiscovery, cursorSubagents, runtimeProfiles, watcher, stopHeartbeat, teams, input,deviceInput, detachDsh, mirror, clients, dataDir, onRemoved,}: ForgetDeps) {@@ -78,6 +79,7 @@ export function createForgetSession({else registry.remove(sessionId)syncRecapPool()normalizers.forget(sessionId)+ forgetAttach(sessionId)turnStartedAt.delete(sessionId)neverFoldedHistory.delete(sessionId)// Both sets are per-session and must die with it: left behind they grow without bound in a daemondiff --git a/cli/src/core/engines/cursorDiscovery.spec.ts b/cli/src/core/engines/cursorDiscovery.spec.tsindex 3d22c96a6..a2f48703a 100644--- a/cli/src/core/engines/cursorDiscovery.spec.ts+++ b/cli/src/core/engines/cursorDiscovery.spec.ts@@ -1,81 +1,26 @@-import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'-import { engineNow, loadEngine } from '../../engines/inProcess.js'-import { createCursorDiscovery } from './cursorDiscovery.js'+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+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'-const made = vi.hoisted(() => ({ discoveries: [] as unknown[] }))-vi.mock('../../engines/cursor/discovery.js', () => ({- CursorTranscriptDiscovery: class {- readonly args: unknown[]- start = vi.fn(async () => {})- add = vi.fn(async () => {})- remove = vi.fn()- stop = vi.fn(async () => {})- constructor(...args: unknown[]) { this.args = args; made.discoveries.push(this) }- },- findCursorTranscript: vi.fn(),-}))-// Cursor's code is loaded by its session's attach before that attach hands the session here; a test may say it-// could not be, or that it is not loaded at all.-vi.mock('../../engines/inProcess.js', async (real) => {- const actual = await real<typeof import('../../engines/inProcess.js')>()- return { ...actual, engineNow: vi.fn(actual.engineNow) }-})-beforeAll(async () => { await loadEngine('cursor') })--type Discovery = { args: unknown[]; start: ReturnType<typeof vi.fn>; add: ReturnType<typeof vi.fn>; remove: ReturnType<typeof vi.fn>; stop: ReturnType<typeof vi.fn> }-const built = () => made.discoveries as Discovery[]--describe('Cursor\'s transcript discovery', () => {- afterEach(() => { made.discoveries.length = 0; vi.clearAllMocks() })-- it('builds nothing, and loads nothing, until an attach hands it a Cursor session', async () => {- const discovery = createCursorDiscovery('/cursor/data', vi.fn())- await discovery.start()- discovery.remove('s1')- await discovery.stop()- expect(built()).toEqual([])- expect(engineNow).not.toHaveBeenCalled()- })-- it('looks in the data folder named at the start, with the core\'s callback, once loaded', async () => {- const onFound = vi.fn()- const discovery = createCursorDiscovery('/cursor/data', onFound)- await discovery.start()- await discovery.add('s1')- const [one] = built()- expect(one.args).toEqual(['/cursor/data', onFound])- // Started as the core started it, before the session it was built for.- expect(one.start).toHaveBeenCalledOnce()- expect(one.start.mock.invocationCallOrder[0]).toBeLessThan(one.add.mock.invocationCallOrder[0])- expect(one.add).toHaveBeenCalledWith('s1')- await discovery.add('s2')- discovery.remove('s1')- await discovery.stop()- expect(built()).toHaveLength(1)- expect(one.add).toHaveBeenLastCalledWith('s2')- expect(one.remove).toHaveBeenCalledWith('s1')- expect(one.stop).toHaveBeenCalledOnce()- })+vi.mock('../../engines/inProcess.js', () => ({ engineNow: () => { throw new Error('optional engine unavailable') } }))+vi.mock('../../lib/registry.js', () => ({ validTranscriptPath: vi.fn(() => true) }))+const root = mkdtempSync(join(tmpdir(), 'core-cursor-discovery-'))+let discovery: CursorDiscovery- it('builds stopped when the core has not started it, and starts with the core', async () => {- const discovery = createCursorDiscovery('/cursor/data', vi.fn())- await discovery.add('s1')- const [one] = built()- expect(one.start).not.toHaveBeenCalled()- await discovery.start()- expect(one.start).toHaveBeenCalledOnce()- // A stop, then a session: built already, so nothing is started again until the core does.- await discovery.stop()- await discovery.add('s2')- expect(one.start).toHaveBeenCalledOnce()- })+afterEach(async () => { await discovery?.stop(); rmSync(root, { recursive: true, force: true }); vi.clearAllMocks() })- it('looks for nothing when Cursor\'s code could not be loaded', async () => {- vi.mocked(engineNow).mockReturnValueOnce(null)- const discovery = createCursorDiscovery('/cursor/data', vi.fn())- await discovery.start()- await expect(discovery.add('s1')).resolves.toBeUndefined()- expect(built()).toEqual([])- expect(engineNow).toHaveBeenCalledWith('cursor', 'a session\'s transcript was looked for')- })+it('uses the declared data layout and registry validation without loading an engine', async () => {+ const id = 'aaaaaaaa-1111-4222-8333-444444444444'+ const path = join(root, 'projects', 'p', 'agent-transcripts', id, `${id}.jsonl`)+ mkdirSync(join(path, '..'), { recursive: true }); writeFileSync(path, '{}\n')+ const found = vi.fn()+ discovery = createCursorDiscovery(root, found)+ await discovery.start()+ await discovery.add(id)+ expect(found).toHaveBeenCalledExactlyOnceWith(id, path)+ expect(validTranscriptPath).toHaveBeenCalledExactlyOnceWith('cursor', path)+ discovery.remove(id)})diff --git a/cli/src/core/engines/cursorDiscovery.ts b/cli/src/core/engines/cursorDiscovery.tsindex a432da808..5c4652e95 100644--- a/cli/src/core/engines/cursorDiscovery.ts+++ b/cli/src/core/engines/cursorDiscovery.ts@@ -1,34 +1,11 @@-/**- * Finding the transcript of a Cursor session that has not written one yet (engines/cursor/discovery.ts).- *- * Built on the first Cursor session an attach hands it, from Cursor's own code (engines/inProcess.ts), loaded by- * that attach before it gets here: no other engine's daemon ever builds it. Until then nothing is pending, so a- * start, a remove or a stop has nothing to act on but whether it is started. Without Cursor's code a session's- * transcript is not looked for, as for any session whose engine's code could not be loaded.- */-import type { CursorTranscriptDiscovery } from '../../engines/cursor/discovery.js'-import { engineNow } from '../../engines/inProcess.js'+/** 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'-export type CursorDiscovery = Pick<CursorTranscriptDiscovery, 'start' | 'add' | 'remove' | 'stop'>+export type CursorDiscovery = Pick<TranscriptDiscovery, 'start' | 'add' | 'remove' | 'stop'>-/** `cursorHome` is named when the core starts, as it always was: the folder does not move with Cursor's load. */export function createCursorDiscovery(cursorHome: string, onFound: (sessionId: string, transcriptPath: string) => void): CursorDiscovery {- let built: CursorTranscriptDiscovery | null = null- let started = false- const build = (): CursorTranscriptDiscovery | null => {- if (built) return built- const cursor = engineNow('cursor', 'a session\'s transcript was looked for')- if (!cursor) return null- built = new cursor.CursorTranscriptDiscovery(cursorHome, onFound)- // Started already, as the core starts it once at boot: the same state, then this session.- if (started) void built.start()- return built- }- return {- start: async () => { started = true; await built?.start() },- // Synchronously into Cursor's own `add`, so nothing changes about what a stop() in flight discards.- add: async (sessionId) => { await build()?.add(sessionId) },- remove: (sessionId) => built?.remove(sessionId),- stop: async () => { started = false; await built?.stop() },- }+ return new TranscriptDiscovery(cursorHome, CURSOR_TRANSCRIPT, onFound,+ path => validTranscriptPath('cursor', path), CURSOR_TRANSCRIPT_POLL_MS)}diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex fd326981e..cdf2bd287 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -1050,11 +1050,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {hookEvent: 'TranscriptDiscovered',})if (!result) return- void attachSession(result.entry, false, true).then((attached) => {- if (!attached) return- syncRecapPool()- syncSession(result.entry)- }).catch((err) => {+ // The file is authoritative now. Publishing its binding must not wait for an optional reader.+ syncRecapPool()+ syncSession(result.entry)+ void attachSession(result.entry, false, true).catch((err) => {console.error('[cursor-discovery] attach failed:', err instanceof Error ? err.message : err)})})@@ -1480,6 +1479,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Release a session's binding, or remove a process-owned agent everywhere (core/agents/forget.ts).const forgetSession = createForgetSession({+ forgetAttach: attach.forget,onRemoved: (agentId) => forgetRestartRevision(agentId),relaunchMarks,registry,diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.tsindex 122bbbe76..2cad5fba2 100644--- a/cli/src/core/transcripts/attach.spec.ts+++ b/cli/src/core/transcripts/attach.spec.ts@@ -1,5 +1,5 @@import { liveFor } from '../../engines/live.js'-import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'@@ -11,6 +11,7 @@ import { createSessionNormalizers } from './normalizers.js'import { createRelaunchMarks, type RelaunchMark } from './relaunch.js'import type { PreparedLive } from '../engines/liveSessions.js'import type { LiveFrame } from '../../engines/worker/liveProtocol.js'+import { TranscriptDiscovery } from '../../engines/kit/transcriptDiscovery.js'/*** The engines' own normalizers and readers are tested with each engine. Here each is a fake that@@ -143,6 +144,16 @@ function remoteSetup(open = false, over: Partial<AttachDeps> = {}) {return { ...p, remote, candidate, handle }}+afterEach(() => {+ vi.restoreAllMocks()+ vi.mocked(loadEngine).mockReset()+ vi.useRealTimers()+ fakes.made.length = 0+ fakes.copilotOpen.value = true+ bindings.clear()+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+})+describe('the order of an attach of another engine\'s session', () => {it('loads the engine\'s code, then folds, then starts the tail: no line can come before its normalizer', async () => {let loaded!: () => void@@ -165,34 +176,187 @@ describe('the order of an attach of another engine\'s session', () => {})})+it('starts core transcript discovery before an optional Cursor module can stall attachment', async () => {+ let release!: () => void+ vi.mocked(loadEngine).mockImplementationOnce(() => new Promise(resolve => { release = () => resolve(null) }))+ const run = setup()+ const attaching = run.attach.attachSession(session('cursor'))+ try {+ await vi.waitFor(() => expect(run.deps.cursorDiscovery.add).toHaveBeenCalledWith('cursor-s'))+ await vi.waitFor(() => expect(release).toBeTypeOf('function'))+ expect(run.deps.watcher.addSession).not.toHaveBeenCalled()+ } finally { release(); await attaching; vi.clearAllMocks() }+})++it('locates a fifth Cursor session while four optional readers occupy the entire attach pool', async () => {+ const releases: Array<() => void> = []+ vi.mocked(loadEngine).mockImplementationOnce(() => new Promise(resolve => { releases.push(() => resolve(null)) }))+ const run = setup({ concurrency: 4 })+ const pending = Array.from({ length: 4 }, (_, i) => run.attach.attachSession(session('copilot', undefined, { agentId: `a${i}`, sessionId: `s${i}` })))+ await vi.waitFor(() => expect(releases).toHaveLength(1))+ expect(run.attach.attaches.attaching()).toHaveLength(4)+ const fifth = run.attach.attachSession(session('cursor'))+ expect(run.attach.attaches.queued()).toBe(1)+ expect(run.deps.cursorDiscovery.add).toHaveBeenCalledWith('cursor-s')+ releases.forEach(release => release())+ await Promise.all([...pending, fifth])+})++it.each(['terminal probe', 'optional module'] as const)('does not restore a forgotten Cursor while its %s completes', async phase => {+ const run = setup()+ let release!: () => void+ if (phase === 'terminal probe') vi.mocked(run.deps.terminalGone).mockImplementationOnce(() => new Promise(resolve => { release = () => resolve(false) }))+ else vi.mocked(loadEngine).mockImplementationOnce(() => new Promise(resolve => { release = () => resolve(null) }))+ const s = session('cursor')+ const pending = run.attach.attachSession(s)+ await vi.waitFor(() => expect(release).toBeTypeOf('function'))+ expect(run.deps.cursorDiscovery.add).toHaveBeenCalledOnce()+ bindings.delete(s.agentId)+ vi.mocked(run.deps.cursorDiscovery.add).mockClear()+ release()+ expect(await pending).toBe(false)+ expect(run.deps.cursorDiscovery.add).not.toHaveBeenCalled()+ expect(run.normalizers.hasState(s.sessionId)).toBe(false)+ expect(run.deps.watcher.addSession).not.toHaveBeenCalled()+ expect(run.deps.emit).not.toHaveBeenCalled()+})++it('rejects a stale attach before scheduling its locator or taking a slot', async () => {+ const run = setup()+ const stale = session('cursor')+ bindings.delete(stale.agentId)+ expect(await run.attach.attachSession(stale)).toBe(false)+ expect(run.deps.cursorDiscovery.add).not.toHaveBeenCalled()+ expect(run.deps.terminalGone).not.toHaveBeenCalled()+})++it('discards a queued attach whose binding was forgotten while every reader slot was occupied', async () => {+ const run = setup({ concurrency: 1 })+ let release!: () => void+ vi.mocked(run.deps.terminalGone).mockImplementationOnce(() => new Promise(resolve => { release = () => resolve(true) }))+ const first = run.attach.attachSession(session('pi'))+ const stale = session('cursor')+ const pending = run.attach.attachSession(stale)+ bindings.delete(stale.agentId)+ release()+ await first+ expect(await pending).toBe(false)+ expect(run.deps.terminalGone).toHaveBeenCalledOnce()+})++it.each([new Error('unavailable'), 'unavailable'])('contains a failed core locator without rejecting the binding: %s', async error => {+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})+ const run = setup({ cursorDiscovery: { add: vi.fn(async () => { throw error }) } })+ expect(await run.attach.attachSession(session('cursor'))).toBe(true)+ expect(log).toHaveBeenCalledWith('[cursor-discovery] lookup failed: unavailable')+})++it.each(['terminal probe', 'optional module'] as const)('attaches a newly located Cursor file after its pathless %s was superseded', async phase => {+ const code = await loadEngine('cursor')+ const home = mkdtempSync(join(tmpdir(), 'attach-locator-')); dirs.push(home)+ const s = session('cursor')+ let replacement: Promise<boolean> | undefined, release!: () => void+ const discovery = new TranscriptDiscovery(home, { kind: 'direct', root: '', id: /^cursor-s$/, file: ['cursor.jsonl'] }, (_id, path) => {+ s.transcriptPath = path+ replacement = run.attach.attachSession(s, false, true)+ }, () => true, 10)+ const run = setup({ cursorDiscovery: discovery })+ if (phase === 'terminal probe') vi.mocked(run.deps.terminalGone).mockImplementationOnce(() => new Promise(resolve => { release = () => resolve(false) }))+ else vi.mocked(loadEngine).mockImplementationOnce(() => new Promise(resolve => { release = () => resolve(code) }))+ await discovery.start()+ try {+ const first = run.attach.attachSession(s)+ await vi.waitFor(() => expect(release).toBeTypeOf('function'))+ mkdirSync(join(home, s.sessionId))+ const path = join(home, s.sessionId, 'cursor.jsonl'); writeFileSync(path, '{}\n')+ await vi.waitFor(() => expect(replacement).toBeDefined())+ release()+ expect(await first).toBe(false)+ expect(await replacement).toBe(true)+ expect(run.deps.watcher.addSession).toHaveBeenCalledOnce()+ expect(run.deps.watcher.addSession).toHaveBeenCalledWith(expect.objectContaining({ transcriptPath: path }), {})+ } finally { await discovery.stop() }+})++it.each(['current', 'forget', 'rebind'] as const)('holds a stalled import without writes and fences its late retry: %s', async change => {+ const code = await loadEngine('cursor')+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ let finish!: () => void+ vi.mocked(loadEngine).mockImplementationOnce(() => new Promise(resolve => { finish = () => resolve(code) }))+ const run = setup({ readerLoadWaitMs: 20 })+ const s = session('cursor', transcript([{}]))+ const first = run.attach.attachSession(s)+ await vi.advanceTimersByTimeAsync(20)+ expect(await first).toBe(true)+ expect(run.normalizers.hasState(s.sessionId)).toBe(false)+ expect(run.deps.watcher.addSession).not.toHaveBeenCalled()+ if (change === 'forget') { bindings.delete(s.agentId); run.attach.forget(s.sessionId) }+ if (change === 'rebind') s.sessionId = 'another'+ finish()+ if (change === 'current') await vi.waitFor(() => expect(run.deps.watcher.addSession).toHaveBeenCalledOnce())+ else { await vi.advanceTimersByTimeAsync(0); expect(run.deps.watcher.addSession).not.toHaveBeenCalled() }+ vi.useRealTimers()+})++it.each([new Error('reader failed'), 'reader failed'])('contains a late reader retry failure: %s', async error => {+ const code = await loadEngine('cursor')+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ const log = vi.spyOn(console, 'error').mockImplementation(() => {})+ let finish!: () => void+ vi.mocked(loadEngine).mockImplementationOnce(() => new Promise(resolve => { finish = () => resolve(code) }))+ const run = setup({ readerLoadWaitMs: 20 })+ vi.mocked(run.deps.watcher.addSession).mockRejectedValueOnce(error)+ const pending = run.attach.attachSession(session('cursor', transcript([{}])))+ await vi.advanceTimersByTimeAsync(20); await pending+ finish()+ await vi.waitFor(() => expect(log).toHaveBeenCalledWith('[agent] cursor-a reader retry failed: reader failed'))+ vi.useRealTimers()+})++it.each(['terminal probe', 'import'] as const)('does not replay twice when a held loader resolves during a newer attach\'s %s', async phase => {+ const code = await loadEngine('cursor')+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ let loaded!: () => void, probed!: () => void+ vi.mocked(loadEngine).mockImplementationOnce(() => new Promise(resolve => { loaded = () => resolve(code) }))+ const run = setup({ readerLoadWaitMs: 20 })+ const event = started('once')+ const s = session('cursor', transcript([{ events: [event] }]))+ const first = run.attach.attachSession(s, false, true)+ await vi.advanceTimersByTimeAsync(20); expect(await first).toBe(true)+ if (phase === 'terminal probe') vi.mocked(run.deps.terminalGone).mockImplementationOnce(() => new Promise(resolve => { probed = () => resolve(false) }))+ const second = run.attach.attachSession(s, false, true)+ await vi.advanceTimersByTimeAsync(0)+ loaded()+ await vi.advanceTimersByTimeAsync(0)+ if (phase === 'terminal probe') probed()+ expect(await second).toBe(true)+ await vi.waitFor(() => expect(run.attach.attaches.attaching()).toEqual([]))+ expect(run.deps.watcher.addSession).toHaveBeenCalledOnce()+ expect(run.deps.emit).toHaveBeenCalledExactlyOnceWith(s.sessionId, [event])+ expect(made('cursor')).toHaveLength(1)+})+describe('attaching a session whose engine\'s code could not be loaded', () => {- it('follows it with no normalizer or reader, says so, and folds nothing', async () => {+ it('holds interpretation without a normalizer or tail, says why, and preserves the binding', async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})vi.mocked(loadEngine).mockResolvedValueOnce(null as never).mockResolvedValueOnce(null as never)const file = setup()const path = transcript([{ any: 'line' }])expect(await file.attach.attachSession(session('grok', path))).toBe(true)expect(file.normalizers.hasState('grok-s')).toBe(false)- expect(file.deps.watcher.addSession).toHaveBeenCalledWith(expect.objectContaining({ sessionId: 'grok-s', transcriptPath: path }), {})+ expect(file.deps.watcher.addSession).not.toHaveBeenCalled()+ expect(file.deps.runtimeProfiles.hydrate).not.toHaveBeenCalled()expect(file.deps.emit).not.toHaveBeenCalled()const store = setup()expect(await store.attach.attachSession(session('opencode'))).toBe(true)expect(store.normalizers.hasState('opencode-s')).toBe(false)- expect(warn).toHaveBeenCalledWith('[agent] grok-age attached without its engine\'s code · engine=grok · its transcript is not read')- expect(warn).toHaveBeenCalledWith('[agent] opencode attached without its engine\'s code · engine=opencode · its transcript is not read')+ expect(warn).toHaveBeenCalledWith('[agent] grok-age transcript held · engine=grok · its reader is unavailable or still loading')+ expect(warn).toHaveBeenCalledWith('[agent] opencode transcript held · engine=opencode · its reader is unavailable or still loading')warn.mockRestore()})})describe('attaching a session', () => {- afterEach(() => {- vi.restoreAllMocks()- vi.useRealTimers()- fakes.made.length = 0- fakes.copilotOpen.value = true- bindings.clear()- for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })- })it('installs worker state after hydration, keeps device/profile observations and reuses only a current binding', async () => {const p = remoteSetup(true), s = session('claude', '/private/transcript')diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.tsindex 6436ad266..07df35312 100644--- a/cli/src/core/transcripts/attach.ts+++ b/cli/src/core/transcripts/attach.ts@@ -9,7 +9,7 @@*/import type { LiveFor } from '../../engines/facets/live.js'import type { CursorTranscriptDiscovery } from '../../engines/cursor/discovery.js'-import { isOtherEngine, loadEngine, type InProcessModules } from '../../engines/inProcess.js'+import { isOtherEngine, type InProcessModules } from '../../engines/inProcess.js'import type { AgentEngine } from '../../engines/types.js'import { pollsQuestions, type QuestionWatcher } from '../../lib/questionController.js'import { attachTranscript, type AttachRead } from '../../lib/attachTranscript.js'@@ -28,6 +28,7 @@ import type { RelaunchMarks } from './relaunch.js'import { createSideReads } from './sideReads.js'import { paneReadIdentity } from './readIdentity.js'import type { LiveSessions, PreparedLive } from '../engines/liveSessions.js'+import { createReaderLoads } from './readerLoads.js'export interface AttachDeps {liveFor: LiveFor@@ -57,6 +58,8 @@ export interface AttachDeps {hermesDb: (session: RegisteredSession) => Promise<string>/** How many sessions attach at once. */concurrency: number+ /** The wait for optional code, before any reader has started writing. */+ readerLoadWaitMs?: number/** Where an engine's writing became live again after a relaunch (core/transcripts/relaunch.ts): the fold stops there. */relaunchMarks?: Pick<RelaunchMarks, 'read' | 'complete'>/** The most of a transcript an engine without its own reader from the end folds, from its end. */@@ -68,13 +71,14 @@ export interface AttachDeps {export function createAttach({liveFor, resolve, remoteLive, terminalGone, normalizers, watcher, cursorDiscovery, device, runtimeProfiles, captureTerminal, emit,announceTurnAborted, questionWatcher, terminalLabel, dbs, devinHome, hermesDb, concurrency, relaunchMarks,- wholeReadCapBytes = WHOLE_READ_CAP_BYTES, settled,+ wholeReadCapBytes = WHOLE_READ_CAP_BYTES, settled, readerLoadWaitMs,}: AttachDeps) {const {liveParsers, cursorNormalizers, opencodeReaders, kiloReaders, museNormalizers, ampNormalizers,grokNormalizers, agyNormalizers, copilotNormalizers, piNormalizers, hermesReaders, devinReaders, commandcodeNormalizers,} = normalizersconst sideRead = createSideReads()+ const readerLoads = createReaderLoads(readerLoadWaitMs)/*** Sessions that attached before their transcript existed, so nothing was folded and nothing has ever* been streamed for them.@@ -100,6 +104,7 @@ export function createAttach({const replayedFirstTurn = new Set<string>()const attachSessionNow = async (session: RegisteredSession,+ current: () => boolean,reset = false,replayCursorFromStart = false,/**@@ -123,15 +128,18 @@ export function createAttach({// and a probe in flight when the machine slept times out at the wake before its answer is read: the// session of an agent still at work was unbound that way two seconds after a laptop woke (round 29,// e2e/clockjump.e2e.ts). A terminal that really is gone is retired by the reconciler's confirmed scans.- if (await terminalGone(session)) return false- // The other engines' code is loaded in this process, and before anything below: the tail starts only at- // the end of an attach, so no line reaches its normalizer before it is there (core/transcripts/ingest.ts).- // Started as the session entered the registry (engines/inProcess.ts `preloadEngine`), so this rarely- // waits. Code that could not load attaches the session with no normalizer or reader: it is followed, and- // reads no events, as an engine with no normalizer does.- const other = isOtherEngine(session.engine) ? await loadEngine(session.engine) : null+ if (!current() || await terminalGone(session) || !current()) return false+ // Bound only the wait for optional code, before any interpretation writes. A late import gets one+ // fenced retry; a missing import holds the transcript intact until an update or restart fixes it.+ const other = isOtherEngine(session.engine) ? await readerLoads.read(+ session.engine, session.sessionId, paneReadIdentity(session), current, async stillHeld => {+ if (current()) await attachSession(session, true, replayCursorFromStart, replayFromStart, stillHeld).catch(error => console.error(+ `[agent] ${sid(session.agentId)} reader retry failed: ${error instanceof Error ? error.message : error}`))+ }) : null+ if (!current()) return falseif (isOtherEngine(session.engine) && !other) {- console.warn(`[agent] ${sid(session.agentId)} attached without its engine's code · engine=${session.engine} · its transcript is not read`)+ console.warn(`[agent] ${sid(session.agentId)} transcript held · engine=${session.engine} · its reader is unavailable or still loading`)+ return true}const engine = <Name extends keyof InProcessModules>(name: Name): InProcessModules[Name] | null =>session.engine === name ? other as InProcessModules[Name] | null : null@@ -148,7 +156,6 @@ export function createAttach({{ fromStart: replayFromStart || unseen || (session.engine === 'cursor' && replayCursorFromStart) },)}- else if (session.engine === 'cursor') await cursorDiscovery.add(session.sessionId)console.log(`[agent] ${sid(session.agentId)} re-attached · engine=${session.engine} · terminal=${terminalLabel(session)} · session=${sid(session.sessionId)}`)return true}@@ -463,9 +470,7 @@ export function createAttach({if (!handover.hold || !watcher.tails(session.sessionId, session.transcriptPath)) {await watcher.addSession({ ...session, transcriptPath: session.transcriptPath }, fromEnd ? { fromOffset: fromEnd.next } : {})}- } else if (session.engine === 'cursor') {- await cursorDiscovery.add(session.sessionId)- } else {+ } else if (session.engine !== 'cursor') {// No transcript to fold: whatever this session writes later is its FIRST content, so the re-attach// that brings the path must read the file whole rather than from its end.neverFoldedHistory.add(session.sessionId)@@ -534,19 +539,34 @@ export function createAttach({reset = false,replayCursorFromStart = false,replayFromStart = false,- ): Promise<boolean> =>- attaches.attach(session, reset, async () => {+ retryCurrent?: () => boolean,+ ): Promise<boolean> => {+ const authority = paneReadIdentity(session)+ const current = () => paneReadIdentity(resolve(session.agentId)) === authority+ if (!current()) return Promise.resolve(false)+ readerLoads.supersede(session.sessionId, authority)+ // Location is core control, outside the optional reader pool. Four stalled readers must not+ // prevent a fifth Cursor session finding its file. add records its candidate synchronously, so+ // forget's remove revokes it even while the first filesystem lookup is pending.+ if (session.engine === 'cursor' && !session.transcriptPath) {+ void cursorDiscovery.add(session.sessionId).catch(error => console.error(+ `[cursor-discovery] lookup failed: ${error instanceof Error ? error.message : error}`))+ }+ return attaches.attach(session, reset, async () => {+ // A normal attach may have taken the import's result while this retry waited for its slot.+ if (retryCurrent && !retryCurrent()) return false// A tail an attach holds (a Claude Code or Codex reset, see attachSessionNow) is released only// here, after the whole attach — the new normalizer installed and any open turn said to be open —// so delivery resumes into it, in order. Released on every exit, however the attach ends.const handover = { hold: null as TailHold | null, next: null as number | null }try {- return await attachSessionNow(session, reset, replayCursorFromStart, replayFromStart, handover)+ return await attachSessionNow(session, current, reset, replayCursorFromStart, replayFromStart, handover)} finally {handover.hold?.release(handover.next)}- })- return { attachSession, attaches, neverFoldedHistory, replayedFirstTurn }+ }, authority)+ }+ return { attachSession, attaches, neverFoldedHistory, replayedFirstTurn, forget: readerLoads.forget }}export type Attach = ReturnType<typeof createAttach>diff --git a/cli/src/core/transcripts/readerLoads.spec.ts b/cli/src/core/transcripts/readerLoads.spec.tsnew file mode 100644index 000000000..668650215--- /dev/null+++ b/cli/src/core/transcripts/readerLoads.spec.ts@@ -0,0 +1,53 @@+import { afterEach, expect, it, vi } from 'vitest'+import { loadEngine } from '../../engines/inProcess.js'+import { createReaderLoads } from './readerLoads.js'++vi.mock('../../engines/inProcess.js', () => ({ loadEngine: vi.fn() }))+afterEach(() => { vi.resetAllMocks(); vi.useRealTimers() })++function deferred() {+ let finish!: (module: any) => void+ const promise = new Promise<any>(resolve => { finish = resolve })+ return { promise, finish }+}++it('returns available or missing code without a delayed retry', async () => {+ vi.useFakeTimers()+ const readers = createReaderLoads(), retry = vi.fn(async () => {})+ vi.mocked(loadEngine).mockResolvedValueOnce({ marker: 'loaded' } as never).mockResolvedValueOnce(null)+ expect(await readers.read('cursor', 'c', 'c1', () => true, retry)).toEqual({ marker: 'loaded' })+ expect(await readers.read('grok', 'g', 'g1', () => true, retry)).toBeNull()+ expect(vi.getTimerCount()).toBe(0)+ expect(retry).not.toHaveBeenCalled()+})++it('bounds a stalled import and coalesces repeated attempts to one current retry per session', async () => {+ vi.useFakeTimers()+ const readers = createReaderLoads(20), code = deferred(), obsolete = vi.fn(async () => {}), retry = vi.fn(async () => {}), other = vi.fn(async () => {})+ vi.mocked(loadEngine).mockReturnValueOnce(code.promise).mockReturnValueOnce(new Promise(() => {}))+ const first = readers.read('cursor', 'c', 'c1', () => true, obsolete)+ await vi.advanceTimersByTimeAsync(20); expect(await first).toBeNull()+ const second = readers.read('cursor', 'c', 'c1', () => true, retry)+ const third = readers.read('grok', 'g', 'g1', () => true, other)+ await vi.advanceTimersByTimeAsync(20); await Promise.all([second, third])+ readers.supersede('c', 'c1') // Same authority retains the latest retry.+ code.finish({})+ await vi.advanceTimersByTimeAsync(0)+ expect(obsolete).not.toHaveBeenCalled()+ expect(retry).toHaveBeenCalledOnce()+ expect(other).not.toHaveBeenCalled()+ expect(loadEngine).toHaveBeenCalledTimes(2)+})++it.each(['forget', 'supersede', 'revoked before deadline', 'missing import'] as const)('does not retry after %s', async outcome => {+ vi.useFakeTimers()+ const readers = createReaderLoads(20), code = deferred(), retry = vi.fn(async () => {})+ vi.mocked(loadEngine).mockReturnValueOnce(code.promise)+ const reading = readers.read('cursor', 'c', 'c1', () => outcome !== 'revoked before deadline', retry)+ await vi.advanceTimersByTimeAsync(20); await reading+ if (outcome === 'forget') readers.forget('c')+ if (outcome === 'supersede') readers.supersede('c', 'c2')+ code.finish(outcome === 'missing import' ? null : {})+ await vi.advanceTimersByTimeAsync(0)+ expect(retry).not.toHaveBeenCalled()+})diff --git a/cli/src/core/transcripts/readerLoads.ts b/cli/src/core/transcripts/readerLoads.tsnew file mode 100644index 000000000..1ffa588b9--- /dev/null+++ b/cli/src/core/transcripts/readerLoads.ts@@ -0,0 +1,50 @@+import { loadEngine, type InProcessModules, type OtherEngine } from '../../engines/inProcess.js'++/** Only loading code is bounded here; a reader already folding history is never abandoned mid-write. */+const LOAD_WAIT_MS = 5_000+const LOADING = Symbol('reader still loading')++export function createReaderLoads(waitMs = LOAD_WAIT_MS) {+ const imports = new Map<OtherEngine, Promise<InProcessModules[OtherEngine] | null>>()+ const retrying = new Set<OtherEngine>()+ const held = new Map<string, { engine: OtherEngine; identity: string; retry: (stillHeld: () => boolean) => Promise<unknown> }>()+ return {+ async read(engine: OtherEngine, sessionId: string, identity: string, current: () => boolean,+ retry: (stillHeld: () => boolean) => Promise<unknown>) {+ // A newer attempt owns this import's result. A late callback from an earlier hold must not+ // force a second fold behind it (Cursor would replay its first turn twice).+ held.delete(sessionId)+ let loading = imports.get(engine)+ if (!loading) { loading = loadEngine(engine); imports.set(engine, loading) }+ let timer!: ReturnType<typeof setTimeout>+ const waiting = new Promise<typeof LOADING>(resolve => {+ timer = setTimeout(() => resolve(LOADING), waitMs)+ timer.unref()+ })+ let value: InProcessModules[OtherEngine] | null | typeof LOADING+ try { value = await Promise.race([loading, waiting]) }+ finally { clearTimeout(timer) }+ if (value !== LOADING) return value+ if (current()) held.set(sessionId, { engine, identity, retry })+ // One callback per shared import, regardless of how often hooks ask again. Forget/rebind+ // removes ownership from held; the callback itself never retains a per-session retry closure.+ if (!retrying.has(engine)) {+ retrying.add(engine)+ void loading.then(module => {+ retrying.delete(engine)+ for (const [id, pending] of held) {+ if (pending.engine !== engine) continue+ if (!module) { held.delete(id); continue }+ const stillHeld = () => held.get(id) === pending+ void pending.retry(stillHeld).finally(() => { if (stillHeld()) held.delete(id) })+ }+ })+ }+ return null+ },+ supersede(sessionId: string, identity: string): void {+ if (held.get(sessionId)?.identity !== identity) held.delete(sessionId)+ },+ forget(sessionId: string): void { held.delete(sessionId) },+ }+}diff --git a/cli/src/engines/__fixtures__/other-identity.golden.json b/cli/src/engines/__fixtures__/other-identity.golden.jsonindex 6ccfc9a51..3568d481d 100644--- a/cli/src/engines/__fixtures__/other-identity.golden.json+++ b/cli/src/engines/__fixtures__/other-identity.golden.json@@ -1808,6 +1808,32 @@}]],+ [+ "grok",+ "0b6f4f2e-6c1a-4c55-9a51-000000000036",+ [+ {+ "engine": "grok",+ "sessionId": "0b6f4f2e-6c1a-4c55-9a51-000000000036",+ "transcriptPath": "<root>/home/.grok/sessions/hashed-group/0b6f4f2e-6c1a-4c55-9a51-000000000036/updates.jsonl",+ "cwd": "/work/g",+ "source": "terminal-resume",+ "runtimes": [+ {+ "backend": "tmux",+ "paneId": "%1"+ }+ ],+ "primaryRuntimeKey": "tmux:%1",+ "processIdentity": {+ "pid": 4242,+ "startMarker": "Mon Oct 8 10:00:00 2026",+ "executable": "grok"+ },+ "hookEvent": "TerminalResumeDiscovery"+ }+ ]+ ],["grok","0b6f4f2e-6c1a-4c55-9a51-000000000039",@@ -2288,5 +2314,15 @@"let go",null]+ ],+ "pending cursor transcripts": [+ [+ "0b6f4f2e-6c1a-4c55-9a51-000000000061",+ "<root>/home/.cursor/projects/golden-existing/agent-transcripts/0b6f4f2e-6c1a-4c55-9a51-000000000061/0b6f4f2e-6c1a-4c55-9a51-000000000061.jsonl"+ ],+ [+ "0b6f4f2e-6c1a-4c55-9a51-000000000062",+ "<root>/home/.cursor/projects/golden-later/agent-transcripts/0b6f4f2e-6c1a-4c55-9a51-000000000062/0b6f4f2e-6c1a-4c55-9a51-000000000062.jsonl"+ ]]}diff --git a/cli/src/engines/agy/contract.ts b/cli/src/engines/agy/contract.tsindex 2a32029f6..2003ca470 100644--- a/cli/src/engines/agy/contract.ts+++ b/cli/src/engines/agy/contract.ts@@ -3,10 +3,18 @@* (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of agy's code.*/import { join } from 'node:path'+import type { ProcessSessionLocation, TranscriptLocation } from '../kit/sessionLocation.js'/** A conversation id: its folder's name. */export const CONVERSATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i+export const AGY_TRANSCRIPT: TranscriptLocation = {+ id: CONVERSATION_ID, kind: 'direct', root: 'brain', file: ['.system_generated', 'logs', 'transcript_full.jsonl'],+}+export const AGY_PROCESS_SESSION: ProcessSessionLocation = {+ id: CONVERSATION_ID, kind: 'open-lock', root: 'presence', suffix: '.lock', timeoutMs: 4_000,+}+/** `<AGY_HOME>/brain/<conversationId>/.system_generated/logs/transcript_full.jsonl`. */export function agyTranscriptPath(agyHome: string, conversationId: string): string | null {if (!CONVERSATION_ID.test(conversationId)) return nulldiff --git a/cli/src/engines/agy/session.ts b/cli/src/engines/agy/session.tsindex f70ccaba1..36e9d4c7f 100644--- a/cli/src/engines/agy/session.ts+++ b/cli/src/engines/agy/session.ts@@ -1,17 +1,10 @@-import { execFile } from 'child_process'-import { readdir, readlink, stat } from 'fs/promises'-import { basename, join, sep } from 'path'-import { promisify } from 'util'+import { readdir, stat } from 'fs/promises'+import { join } from 'path'+import { locateProcessSession, locateTranscript } from '../kit/sessionLocation.js'-const execFileAsync = promisify(execFile)--import { agyTranscriptPath, CONVERSATION_ID } from './contract.js'+import { AGY_PROCESS_SESSION, AGY_TRANSCRIPT, CONVERSATION_ID } from './contract.js'export { agyTranscriptPath } from './contract.js'-async function isFile(path: string): Promise<boolean> {- try { return (await stat(path)).isFile() } catch { return false }-}-/*** Resolve a live agy transcript.*@@ -19,8 +12,7 @@ async function isFile(path: string): Promise<boolean> {* one. The `_full` file is the one to tail — see the normalizer header for why.*/export async function findAgyTranscript(agyHome: string, conversationId: string): Promise<string | null> {- const path = agyTranscriptPath(agyHome, conversationId)- return path && await isFile(path) ? path : null+ return locateTranscript(AGY_TRANSCRIPT, agyHome, conversationId)}export interface AgyConversation {@@ -69,32 +61,5 @@ export async function listAgyConversations(agyHome: string): Promise<AgyConversa* into agy's own environment, so neither the file nor `/proc/<pid>/environ` can answer this.*/export async function agyConversationForPid(agyHome: string, pid: number): Promise<string | null> {- const marker = join(agyHome, 'presence') + sep- const paths = process.platform === 'linux' ? await linuxFdTargets(pid) : await lsofTargets(pid)- for (const path of paths) {- if (!path.startsWith(marker) || !path.endsWith('.lock')) continue- const id = basename(path, '.lock')- if (CONVERSATION_ID.test(id)) return id- }- return null-}--async function linuxFdTargets(pid: number): Promise<string[]> {- const dir = `/proc/${pid}/fd`- const entries = await readdir(dir).catch(() => [])- const targets: string[] = []- for (const entry of entries) {- const target = await readlink(join(dir, entry)).catch(() => '')- if (target) targets.push(target)- }- return targets-}--async function lsofTargets(pid: number): Promise<string[]> {- // -Fn prints one `n<path>` record per descriptor and nothing else; -w silences the warnings lsof- // emits for file systems it cannot stat, which would otherwise land on stderr on every poll.- const out = await execFileAsync('lsof', ['-w', '-p', String(pid), '-Fn'], { timeout: 4_000 })- .then((r) => r.stdout)- .catch((err: { stdout?: string }) => err.stdout ?? '')- return out.split('\n').filter((line) => line.startsWith('n')).map((line) => line.slice(1))+ return locateProcessSession(AGY_PROCESS_SESSION, agyHome, pid)}diff --git a/cli/src/engines/copilot/contract.ts b/cli/src/engines/copilot/contract.tsindex e4354a558..ad46f5c59 100644--- a/cli/src/engines/copilot/contract.ts+++ b/cli/src/engines/copilot/contract.ts@@ -3,10 +3,19 @@* (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of Copilot's code.*/import { join } from 'node:path'+import type { ProcessSessionLocation, TranscriptLocation } from '../kit/sessionLocation.js'/** A session id: its folder's name. */export const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i+export const COPILOT_TRANSCRIPT: TranscriptLocation = {+ id: SESSION_ID, kind: 'direct', root: 'session-state', file: ['events.jsonl'],+}+export const COPILOT_PROCESS_SESSION: ProcessSessionLocation = {+ id: SESSION_ID, kind: 'newest-lock', root: 'session-state', prefix: 'inuse.', suffix: '.lock',+}+export const COPILOT_CWD = { type: 'session.start', field: ['data', 'context', 'cwd'] } as const+/*** `<COPILOT_HOME>/session-state/<sessionId>/events.jsonl`.*diff --git a/cli/src/engines/copilot/session.ts b/cli/src/engines/copilot/session.tsindex 33963d304..a97ee0a2c 100644--- a/cli/src/engines/copilot/session.ts+++ b/cli/src/engines/copilot/session.ts@@ -1,16 +1,12 @@import { readdir, stat } from 'fs/promises'import { join } from 'path'+import { locateProcessSession, locateTranscript, recordCwd } from '../kit/sessionLocation.js'-import { copilotTranscriptPath, SESSION_ID } from './contract.js'+import { COPILOT_CWD, COPILOT_PROCESS_SESSION, COPILOT_TRANSCRIPT, SESSION_ID } from './contract.js'export { copilotTranscriptPath } from './contract.js'-async function isFile(path: string): Promise<boolean> {- try { return (await stat(path)).isFile() } catch { return false }-}-export async function findCopilotTranscript(copilotHome: string, sessionId: string): Promise<string | null> {- const path = copilotTranscriptPath(copilotHome, sessionId)- return path && await isFile(path) ? path : null+ return locateTranscript(COPILOT_TRANSCRIPT, copilotHome, sessionId)}export interface CopilotSessionFile {@@ -47,15 +43,7 @@ export async function listCopilotSessions(copilotHome: string): Promise<CopilotS* the only link between a session file and the pane that owns it.*/export function copilotSessionCwd(firstLines: string[]): string | null {- for (const line of firstLines) {- try {- const record = JSON.parse(line) as { type?: unknown; data?: { context?: { cwd?: unknown } } }- if (record?.type !== 'session.start') continue- const cwd = record.data?.context?.cwd- return typeof cwd === 'string' && cwd ? cwd : null- } catch { /* a partial write mid-flush; the next poll sees the whole line */ }- }- return null+ return recordCwd(firstLines, COPILOT_CWD)}/**@@ -71,14 +59,5 @@ export function copilotSessionCwd(firstLines: string[]): string | null {* is why a directory scan cannot find it and why the agent used to sit unbound after `/resume`.*/export async function copilotSessionForPid(copilotHome: string, pid: number): Promise<string | null> {- const root = join(copilotHome, 'session-state')- const entries = await readdir(root, { withFileTypes: true }).catch(() => [])- let best: { sessionId: string; mtimeMs: number } | null = null- for (const entry of entries) {- if (!entry.isDirectory() || !SESSION_ID.test(entry.name)) continue- const info = await stat(join(root, entry.name, `inuse.${pid}.lock`)).catch(() => null)- if (!info) continue- if (!best || info.mtimeMs > best.mtimeMs) best = { sessionId: entry.name, mtimeMs: info.mtimeMs }- }- return best?.sessionId ?? null+ return locateProcessSession(COPILOT_PROCESS_SESSION, copilotHome, pid)}diff --git a/cli/src/engines/cursor/contract.ts b/cli/src/engines/cursor/contract.tsindex 03b7de90f..e4ab8566c 100644--- a/cli/src/engines/cursor/contract.ts+++ b/cli/src/engines/cursor/contract.ts@@ -4,6 +4,12 @@*/import { join } from 'node:path'import { env } from '../../config/env.js'+import type { TranscriptLocation } from '../kit/sessionLocation.js'++export const CURSOR_TRANSCRIPT: TranscriptLocation = {+ id: /^[0-9a-f-]{16,}$/i, kind: 'projects', root: 'projects', folder: 'agent-transcripts', suffix: '.jsonl',+}+export const CURSOR_TRANSCRIPT_POLL_MS = 1000/** Cursor's hooks and chat databases follow its config root, which can differ from its data root. */export function cursorConfigDir(vars: NodeJS.ProcessEnv = process.env): string {diff --git a/cli/src/engines/cursor/discovery.spec.ts b/cli/src/engines/cursor/discovery.spec.tsindex fbe8e026a..01fe07710 100644--- a/cli/src/engines/cursor/discovery.spec.ts+++ b/cli/src/engines/cursor/discovery.spec.ts@@ -49,7 +49,7 @@ describe('CursorTranscriptDiscovery', () => {afterEach(() => {delete process.env.CURSOR_HOMErmSync(cursorHome, { recursive: true, force: true })- })+ }, 30_000)it('reports a transcript that already exists without polling', async () => {const { CursorTranscriptDiscovery } = await loadDiscovery()@@ -179,5 +179,7 @@ describe('CursorTranscriptDiscovery', () => {await discovery.stop()expect(Date.now() - started).toBeLessThan(2000)- })+ // Creating 3,000 fixture directories can exceed Vitest's default under concurrent builds. The+ // measured discovery deadline above stays two seconds and excludes only fixture construction.+ }, 30_000)})diff --git a/cli/src/engines/cursor/discovery.ts b/cli/src/engines/cursor/discovery.tsindex c24ea0683..303ff3311 100644--- a/cli/src/engines/cursor/discovery.ts+++ b/cli/src/engines/cursor/discovery.ts@@ -1,138 +1,16 @@-import { access, readdir } from 'node:fs/promises'-import { join } from 'node:path'+/** Compatibility entry for optional Cursor consumers; session control uses the eager kit directly. */import { validTranscriptPath } 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'+export { CURSOR_TRANSCRIPT_POLL_MS } from './contract.js'-const SESSION_RE = /^[0-9a-f-]{16,}$/i--/**- * How often a pending session is re-checked for a transcript that has since appeared. A Cursor- * session is pending only between its process turning up and its first transcript write, so this- * is a short-lived poll — and no poll runs at all while nothing is pending.- */-export const CURSOR_TRANSCRIPT_POLL_MS = 1000--/**- * Finds the transcript of a Cursor session whose process is already known but whose JSONL has not- * been written yet.- *- * This POLLS rather than watching `<CURSOR_HOME>/projects`. A recursive watcher over that tree was- * the daemon's single worst behaviour on macOS: one machine had 6,849 folders under it for 10- * transcripts, and libuv keeps every watched path in ONE FSEvents stream that it tears down and- * recreates on each add or remove — thousands of adds meant the event loop spent minutes inside- * FSEventStreamCreate, `FSEventStreamStart` began failing (surfaced by libuv as `EMFILE` to every- * handle at once, 2,700 errors a minute in the log), and the loopback API the desktop app relies on- * stopped answering: "This computer · Offline", `agent_create` timing out. A readdir of the project- * list plus one stat per pending session, once a second, finds the same file for no standing cost.- */-export class CursorTranscriptDiscovery {- private readonly pending = new Set<string>()- private timer: NodeJS.Timeout | null = null- private started = false- private sweeping = false- /** Bumped by stop(); an add() that started before the bump discards what it finds. */- private epoch = 0-- constructor(- private readonly cursorHome: string,- private readonly onFound: (sessionId: string, transcriptPath: string) => void,- private readonly pollMs: number = CURSOR_TRANSCRIPT_POLL_MS,- ) {}-- /** Whether a poll timer is live — true only while at least one session is pending. */- get isPolling(): boolean {- return this.timer !== null- }-- async start(): Promise<void> {- if (this.started) return- this.started = true- this.schedule()- }-- async add(sessionId: string): Promise<void> {- if (!SESSION_RE.test(sessionId)) return- const epoch = this.epoch- const found = await findCursorTranscript(this.cursorHome, sessionId)- // Re-checked after the await: a stop() that ran while the lookup was in flight owns this session- // now — neither a callback nor a pending entry may outlive it.- if (epoch !== this.epoch) return- if (found) {- this.onFound(sessionId, found)- return- }- this.pending.add(sessionId)- this.schedule()- }-- remove(sessionId: string): void {- this.pending.delete(sessionId)- if (this.pending.size === 0) this.clearTimer()- }-- async stop(): Promise<void> {- this.epoch++- this.pending.clear()- this.clearTimer()- this.started = false- }-- private schedule(): void {- if (!this.started || this.timer || this.pending.size === 0) return- this.timer = setInterval(() => { void this.sweep() }, this.pollMs)- // A pending session must never be what keeps the daemon alive through shutdown.- this.timer.unref()- }-- private clearTimer(): void {- if (!this.timer) return- clearInterval(this.timer)- this.timer = null- }-- private async sweep(): Promise<void> {- if (this.sweeping) return // a slow disk must not stack sweeps on top of each other- this.sweeping = true- try {- // One listing per sweep, shared by every pending session.- const projects = await listProjects(this.cursorHome)- for (const sessionId of [...this.pending]) {- const found = await transcriptAmong(this.cursorHome, projects, sessionId)- // Re-checked after the await: remove()/stop() may have run while the lookup was in flight.- if (!found || !this.pending.has(sessionId)) continue- this.pending.delete(sessionId)- this.onFound(sessionId, found)- }- } finally {- this.sweeping = false- if (this.pending.size === 0) this.clearTimer()- }- }-}--export async function findCursorTranscript(cursorHome: string, sessionId: string): Promise<string | null> {- if (!SESSION_RE.test(sessionId)) return null- return transcriptAmong(cursorHome, await listProjects(cursorHome), sessionId)-}--/** The project folders below `<cursorHome>/projects`; none when the tree does not exist yet. */-async function listProjects(cursorHome: string): Promise<string[]> {- try { return await readdir(join(cursorHome, 'projects')) } catch { return [] }-}--async function transcriptAmong(cursorHome: string, projects: string[], sessionId: string): Promise<string | null> {- const root = join(cursorHome, 'projects')- for (const project of projects) {- const candidate = join(root, project, 'agent-transcripts', sessionId, `${sessionId}.jsonl`)- // Existence is probed asynchronously first. validTranscriptPath resolves two realpaths- // SYNCHRONOUSLY, and paying that for every project folder — hundreds on a machine that has- // opened many repos — once a second is a visible event-loop hitch. Only a candidate that is- // actually there pays for the validation.- if (!(await exists(candidate))) continue- if (validTranscriptPath('cursor', candidate)) return candidate+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)}- return null}-async function exists(path: string): Promise<boolean> {- try { await access(path); return true } catch { return false }+export function findCursorTranscript(home: string, id: string): Promise<string | null> {+ return locateTranscript(CURSOR_TRANSCRIPT, home, id, { valid: path => validTranscriptPath('cursor', path) })}diff --git a/cli/src/engines/facets/discovery.ts b/cli/src/engines/facets/discovery.tsindex 660ea4a53..25b793ea0 100644--- a/cli/src/engines/facets/discovery.ts+++ b/cli/src/engines/facets/discovery.ts@@ -29,7 +29,7 @@ export interface DiscoveryContract {modelInArgv?: boolean/** The engine home a process carries in `variable` when launched under a profile, and the setting naming* this machine's default. */- profile?: { variable: string; setting: FolderSetting }+ profile?: { variable: string; setting: FolderSetting; trimTrailingSlashes?: boolean }/*** Transcripts kept by the folder the session began in, `<root>/<folder's directory name>/<id>`, never* moved: the directory name is the folder with every character `mangle` matches replaced by `with`, anddiff --git a/cli/src/engines/grok/contract.ts b/cli/src/engines/grok/contract.tsnew file mode 100644index 000000000..9f56b551c--- /dev/null+++ b/cli/src/engines/grok/contract.ts@@ -0,0 +1,7 @@+/** Grok's transcript layout, including the sidecar used when the encoded cwd would be too long. */+import type { TranscriptLocation } from '../kit/sessionLocation.js'++export const GROK_TRANSCRIPT: TranscriptLocation = {+ id: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,+ kind: 'cwd', root: 'sessions', file: 'updates.jsonl', sidecar: '.cwd',+}diff --git a/cli/src/engines/grok/session.ts b/cli/src/engines/grok/session.tsindex 0d9c0fc04..e4c6e8e98 100644--- a/cli/src/engines/grok/session.ts+++ b/cli/src/engines/grok/session.ts@@ -1,24 +1,7 @@-import { readFile, readdir, stat } from 'fs/promises'-import { join } from 'path'+import { GROK_TRANSCRIPT } from './contract.js'+import { locateTranscript } from '../kit/sessionLocation.js'-async function isFile(path: string): Promise<boolean> {- try { return (await stat(path)).isFile() } catch { return false }-}--/** Resolve Grok's `updates.jsonl`, including its hashed-directory fallback for very long cwd names. */-export async function findGrokTranscript(grokHome: string, cwd: string, sessionId: string): Promise<string | null> {- if (!cwd || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId)) return null- const root = join(grokHome, 'sessions')- const direct = join(root, encodeURIComponent(cwd), sessionId, 'updates.jsonl')- if (await isFile(direct)) return direct- const groups = await readdir(root, { withFileTypes: true }).catch(() => [])- for (const group of groups) {- if (!group.isDirectory()) continue- const dir = join(root, group.name)- const recorded = await readFile(join(dir, '.cwd'), 'utf8').catch(() => '')- if (recorded.trim() !== cwd) continue- const candidate = join(dir, sessionId, 'updates.jsonl')- if (await isFile(candidate)) return candidate- }- return null+/** Resolve the declared layout, including its hashed-directory fallback for long cwd names. */+export function findGrokTranscript(home: string, cwd: string, id: string): Promise<string | null> {+ return locateTranscript(GROK_TRANSCRIPT, home, id, { cwd })}diff --git a/cli/src/engines/hermes/contract.ts b/cli/src/engines/hermes/contract.tsindex 3c1dfb203..189afbf87 100644--- a/cli/src/engines/hermes/contract.ts+++ b/cli/src/engines/hermes/contract.ts@@ -6,6 +6,8 @@ import { join } from 'node:path'import type { StoreHomes } from '../kit/storeHomes.js'import type { StoreSourceRule } from '../kit/storeSource.js'+export const HERMES_PROFILE = { variable: 'HERMES_HOME', setting: 'HERMES_HOME', trimTrailingSlashes: true } as const+/** The store a Hermes home keeps its sessions in. */export function hermesDbPath(home: string): string {return join(home, 'state.db')diff --git a/cli/src/engines/hermes/home.ts b/cli/src/engines/hermes/home.tsindex 8aa04b7a6..b879ff294 100644--- a/cli/src/engines/hermes/home.ts+++ b/cli/src/engines/hermes/home.ts@@ -22,10 +22,11 @@*/import { readdirSync, realpathSync, statSync } from 'node:fs'-import { isAbsolute, join } from 'node:path'+import { join } from 'node:path'import { env } from '../../config/env.js'-import { HERMES_HISTORY_ID_RE, HERMES_HOMES, hermesDbPath } from './contract.js'+import { HERMES_HISTORY_ID_RE, HERMES_HOMES, HERMES_PROFILE, hermesDbPath } from './contract.js'import { forgetStoreHomes, listStoreHomes } from '../kit/storeHomes.js'+import { profileFromEnv } from '../kit/processFacts.js'import { sqliteReadAll } from '../../lib/sqliteRead.js'import type { AgentEngine } from '../types.js'@@ -117,7 +118,5 @@ export function hermesHomeFromEnv(defaultHome = env.HERMES_HOME,): string | null {if (engine !== 'hermes') return null- const home = processEnv.HERMES_HOME- if (!home || !isAbsolute(home) || home.length > 4096 || /[\x00-\x1f\x7f]/.test(home)) return null- return sameHermesHome(home, defaultHome) ? null : home+ return profileFromEnv(HERMES_PROFILE, processEnv, defaultHome)}diff --git a/cli/src/engines/hermes/homeProbe.ts b/cli/src/engines/hermes/homeProbe.tsindex 6ca48a127..cc54f3e90 100644--- a/cli/src/engines/hermes/homeProbe.ts+++ b/cli/src/engines/hermes/homeProbe.ts@@ -1,24 +1,2 @@-/**- * Which Hermes home a live `hermes` process was launched under, read off its environment.- *- * The free half of the answer `home.ts` documents: when the engine exports `HERMES_HOME` for a- * `hermes -p <name>` session, one cached `ps` names the home and the registry row is filled before any- * store is opened. When it does not, this says nothing (`null`) and the session-id lookup answers- * instead — which is why nothing here is load-bearing.- *- * Same three answers as `codexHomeProbe`: a path for a non-default home, `null` for the default or an- * engine that said nothing, and `undefined` when the process could not be read at all, which must- * never overwrite what the registry already knows.- */--import type { AgentEngine } from '../types.js'-import { readProcessEnv } from '../../lib/processEnv.js'-import type { ProcessIdentity } from '../../lib/registry.js'-import { hermesHomeFromEnv } from './home.js'--export async function probeHermesHome(identity: ProcessIdentity, engine: AgentEngine): Promise<string | null | undefined> {- if (engine !== 'hermes') return null- const processEnv = await readProcessEnv(identity)- if (!processEnv) return undefined- return hermesHomeFromEnv(engine, processEnv)-}+/** The eager core probe reads Hermes's declared profile from verified process evidence. */+export { probeHermesHome } from '../identities.js'diff --git a/cli/src/engines/identities.ts b/cli/src/engines/identities.tsnew file mode 100644index 000000000..30cc1ddf8--- /dev/null+++ b/cli/src/engines/identities.ts@@ -0,0 +1,32 @@+/** Eager location facts for session control. Optional engine interpretation is never consulted. */+import { CURSOR_TRANSCRIPT } from './cursor/contract.js'+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 { env } from '../config/env.js'+import { readProcessEnv } from '../lib/processEnv.js'+import type { ProcessIdentity } from '../lib/terminalTypes.js'+import { HERMES_PROFILE } from './hermes/contract.js'+import { profileFromEnv } from './kit/processFacts.js'+import type { AgentEngine } from './types.js'++const transcripts = { cursor: CURSOR_TRANSCRIPT, grok: GROK_TRANSCRIPT, agy: AGY_TRANSCRIPT, copilot: COPILOT_TRANSCRIPT }+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) } : {}),+ })+}+export function processSessionOf(engine: 'agy' | 'copilot', home: string, pid: number): Promise<string | null> {+ return locateProcessSession(engine === 'agy' ? AGY_PROCESS_SESSION : COPILOT_PROCESS_SESSION, home, pid)+}++/** Undefined is unreadable process evidence; it must preserve an existing home. */+export async function probeHermesHome(identity: ProcessIdentity, engine: AgentEngine): Promise<string | null | undefined> {+ if (engine !== 'hermes') return null+ const processEnv = await readProcessEnv(identity)+ return processEnv ? profileFromEnv(HERMES_PROFILE, processEnv, env.HERMES_HOME) : undefined+}diff --git a/cli/src/engines/kit/processFacts.ts b/cli/src/engines/kit/processFacts.tsindex 357220bd8..6c5cea635 100644--- a/cli/src/engines/kit/processFacts.ts+++ b/cli/src/engines/kit/processFacts.ts@@ -31,5 +31,6 @@ function canonical(path: string): string {export function profileFromEnv(profile: NonNullable<DiscoveryContract['profile']>, processEnv: Record<string, string>, defaultHome: string): string | null {const home = processEnv[profile.variable]if (!home || !isAbsolute(home) || home.length > 4096 || /[\x00-\x1f\x7f]/.test(home)) return null- return canonical(home) === canonical(defaultHome) ? null : home+ const compared = (path: string) => canonical(profile.trimTrailingSlashes ? path.replace(/\/+$/, '') : path)+ return compared(home) === compared(defaultHome) ? null : home}diff --git a/cli/src/engines/kit/sessionLocation.ts b/cli/src/engines/kit/sessionLocation.tsnew file mode 100644index 000000000..2a083fa17--- /dev/null+++ b/cli/src/engines/kit/sessionLocation.ts@@ -0,0 +1,110 @@+/** 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 { promisify } from 'node:util'++export type TranscriptLocation = { id: RegExp; root: string } & (+ | { kind: 'direct'; file: readonly string[] }+ | { kind: 'projects'; folder: string; suffix: string }+ | { kind: 'cwd'; file: string; sidecar: string }+)++export type ProcessSessionLocation = { id: RegExp; root: string; suffix: string } & (+ | { kind: 'newest-lock'; prefix: string }+ | { kind: 'open-lock'; timeoutMs: number }+)++async function isFile(path: string): Promise<boolean> {+ try { return (await stat(path)).isFile() } catch { return false }+}++export async function transcriptGroups(home: string, rule: TranscriptLocation): Promise<string[]> {+ return readdir(join(home, rule.root)).catch(() => [])+}++/** One known id, never a guess by newest transcript. A grouped lookup may share its listing across a sweep. */+export async function locateTranscript(rule: TranscriptLocation, home: string, id: string,+ options: { cwd?: string; groups?: readonly string[]; valid?: (path: string) => boolean } = {},+): Promise<string | null> {+ if (!rule.id.test(id)) return null+ const root = join(home, rule.root)+ if (rule.kind === 'direct') {+ const path = join(root, id, ...rule.file)+ return await isFile(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+ }+ 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+ }+ return null+}++const execFileAsync = promisify(execFile)++/** Native process evidence: the newest session lock, or a lock descriptor the process still holds. */+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 }+ }+ 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)+ }+ } 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))+ }+ for (const path of paths) {+ if (!path.startsWith(root + sep) || !path.endsWith(rule.suffix)) continue+ const id = basename(path, rule.suffix)+ if (rule.id.test(id)) return id+ }+ return null+}++/** A cwd in the opening records, with its envelope and field path declared by the engine. */+export function recordCwd(lines: readonly string[], rule: { type: string; field: readonly string[] }): string | null {+ for (const line of lines) {+ try {+ const record = JSON.parse(line)+ if (record?.type !== rule.type) continue+ let value: unknown = record+ for (const key of rule.field) value = value && typeof value === 'object' ? (value as Record<string, unknown>)[key] : undefined+ return typeof value === 'string' && value ? value : null+ } catch { /* an incomplete record is checked on the next scan */ }+ }+ return null+}diff --git a/cli/src/engines/kit/transcriptDiscovery.spec.ts b/cli/src/engines/kit/transcriptDiscovery.spec.tsnew file mode 100644index 000000000..6201323b1--- /dev/null+++ b/cli/src/engines/kit/transcriptDiscovery.spec.ts@@ -0,0 +1,57 @@+import { afterEach, 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[] = []+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() })++it.each(['remove', 'stop'] as const)('revokes an initial lookup when %s happens before its answer', async action => {+ let answer!: (path: string | null) => void+ vi.mocked(locateTranscript).mockReturnValueOnce(new Promise(resolve => { answer = resolve }))+ const { discovery, found } = fresh()+ await discovery.start()+ const adding = discovery.add(id)+ if (action === 'remove') discovery.remove(id); else await discovery.stop()+ answer('/fixture/old.jsonl'); await adding+ expect(found).not.toHaveBeenCalled()+ expect(discovery.isPolling).toBe(false)+})++it('cannot publish a removed lookup through a replacement candidate with the same id', async () => {+ let old!: (path: string | null) => void+ vi.mocked(locateTranscript).mockReturnValueOnce(new Promise(resolve => { old = resolve }))+ .mockResolvedValueOnce('/fixture/new.jsonl')+ const { discovery, found } = fresh()+ const adding = discovery.add(id)+ discovery.remove(id)+ await discovery.add(id)+ old('/fixture/old.jsonl'); await adding+ expect(found).toHaveBeenCalledExactlyOnceWith(id, '/fixture/new.jsonl')+})++it('revokes a sweep after stop and a new start, even if the same session is pending again', async () => {+ vi.useFakeTimers()+ let old!: (path: string | null) => void+ vi.mocked(transcriptGroups).mockResolvedValue(['p'])+ vi.mocked(locateTranscript).mockResolvedValueOnce(null)+ .mockReturnValueOnce(new Promise(resolve => { old = resolve })).mockResolvedValue(null)+ const { discovery, found } = fresh()+ await discovery.start(); await discovery.add(id)+ await vi.advanceTimersByTimeAsync(10)+ expect(locateTranscript).toHaveBeenCalledTimes(2)+ await discovery.stop(); await discovery.start(); await discovery.add(id)+ old('/fixture/old.jsonl'); await vi.advanceTimersByTimeAsync(0)+ expect(found).not.toHaveBeenCalled()+ vi.mocked(locateTranscript).mockResolvedValue('/fixture/new.jsonl')+ await vi.advanceTimersByTimeAsync(10)+ expect(found).toHaveBeenCalledExactlyOnceWith(id, '/fixture/new.jsonl')+ expect(discovery.isPolling).toBe(false)+})diff --git a/cli/src/engines/kit/transcriptDiscovery.ts b/cli/src/engines/kit/transcriptDiscovery.tsnew file mode 100644index 000000000..bb8cbf78c--- /dev/null+++ b/cli/src/engines/kit/transcriptDiscovery.ts@@ -0,0 +1,84 @@+import { locateTranscript, transcriptGroups, type TranscriptLocation } from './sessionLocation.js'++/**+ * Poll only while a known session has no transcript. A recursive watcher over the project tree once+ * stalled the macOS daemon with thousands of FSEvents registrations for a handful of transcripts.+ * 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 timer: NodeJS.Timeout | null = null+ private started = false+ private sweeping = false++ constructor(private readonly home: string, private readonly rule: TranscriptLocation,+ private readonly onFound: (id: string, path: string) => void,+ private readonly valid: (path: string) => boolean, private readonly pollMs: number,+ ) {}++ get isPolling(): boolean { return this.timer !== null }++ async start(): Promise<void> {+ if (this.started) return+ this.started = true+ this.schedule()+ }++ async add(id: string): Promise<void> {+ 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 })+ 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()+ }++ remove(id: string): void {+ this.pending.delete(id)+ if (!this.pending.size) this.clearTimer()+ }++ async stop(): Promise<void> {+ this.pending.clear()+ this.clearTimer()+ this.started = false+ }++ private schedule(): void {+ if (!this.started || this.timer || !this.pending.size) return+ this.timer = setInterval(() => {+ void this.sweep().catch(error => console.error('[discovery] transcript lookup failed', error))+ }, this.pollMs)+ this.timer.unref()+ }++ private clearTimer(): void {+ if (!this.timer) return+ clearInterval(this.timer)+ this.timer = null+ }++ private async sweep(): Promise<void> {+ if (this.sweeping) return+ this.sweeping = true+ const candidates = [...this.pending].filter(([, candidate]) => !candidate.looking)+ try {+ const groups = await transcriptGroups(this.home, this.rule)+ 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)+ }+ } finally {+ this.sweeping = false+ if (!this.pending.size) this.clearTimer()+ }+ }+}diff --git a/cli/src/engines/otherIdentity.golden.spec.ts b/cli/src/engines/otherIdentity.golden.spec.tsindex 5cf96a717..9453e4233 100644--- a/cli/src/engines/otherIdentity.golden.spec.ts+++ b/cli/src/engines/otherIdentity.golden.spec.ts@@ -24,6 +24,8 @@ import { fileURLToPath } from 'node:url'import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'import type { AgentEngine } from './types.js'+vi.mock('../lib/bootId.js', async (original) => ({ ...await original<object>(), currentBootId: () => 'linux:11111111-1111-4111-8111-111111111111' }))+const descriptors = vi.hoisted(() => new Map<string, string[]>())vi.mock('fs/promises', async (original) => {const fs = await original<typeof import('node:fs/promises')>()@@ -73,6 +75,7 @@ type Modules = {notify: typeof import('./kit/notifyHooks.js')home: typeof import('./cursor/home.js')hermes: typeof import('./hermes/contract.js')+ cursorDiscovery: typeof import('../core/engines/cursorDiscovery.js')}let m: Modules@@ -103,6 +106,7 @@ beforeAll(async () => {notify: await import('./kit/notifyHooks.js'),home: await import('./cursor/home.js'),hermes: await import('./hermes/contract.js'),+ cursorDiscovery: await import('../core/engines/cursorDiscovery.js'),}m.registry.registry.load()golden = RECORD ? {} : JSON.parse(readFileSync(GOLDEN, 'utf8')) as Record<string, unknown>@@ -195,7 +199,10 @@ describe('where the core finds the other engines\' conversations', () => {file(home('.grok', 'sessions', encodeURIComponent('/work/g'), UUID(32), 'updates.jsonl'), '{}\n')file(home('.gemini', 'antigravity-cli', 'brain', UUID(33), '.system_generated', 'logs', 'transcript_full.jsonl'), '{}\n')file(home('.copilot', 'session-state', UUID(34), 'events.jsonl'), '{}\n')+ file(home('.copilot', 'session-state', UUID(34), 'inuse.4242.lock'))file(home('.copilot', 'session-state', UUID(35), 'inuse.4242.lock'))+ file(home('.grok', 'sessions', 'hashed-group', '.cwd'), ' /work/g \n')+ file(home('.grok', 'sessions', 'hashed-group', UUID(36), 'updates.jsonl'), '{}\n')file(home('.copilot', 'session-state', UUID(35), 'events.jsonl'), '{}\n')const registered: unknown[] = []const agents = new Map<string, Record<string, unknown>>()@@ -215,7 +222,7 @@ describe('where the core finds the other engines\' conversations', () => {processIdentity: { pid: 4242, startMarker: 'Mon Oct 8 10:00:00 2026', executable: engine }, ...over,})const results: unknown[] = []- const ids: Record<string, string[]> = { cursor: [UUID(31), UUID(39)], grok: [UUID(32), UUID(39)], agy: [UUID(33), UUID(39)], copilot: [UUID(34), UUID(39)] }+ const ids: Record<string, string[]> = { cursor: [UUID(31), UUID(39)], grok: [UUID(32), UUID(36), UUID(39)], agy: [UUID(33), UUID(39)], copilot: [UUID(34), UUID(39)] }for (const [engine, sessions] of Object.entries(ids)) {for (const resumeSessionId of sessions) {agents.clear(); agents.set(engine, { agentId: `agent-${engine}`, engine, sessionId: '', registeredAt: 0 })@@ -284,6 +291,28 @@ describe('where the core finds the other engines\' conversations', () => {check('repair agy lock', results)}, 60_000)+ it('locates an existing and a later Cursor transcript through core discovery, and stops pending work', async () => {+ const { loadEngine } = await import('./inProcess.js')+ await loadEngine('cursor')+ const found: unknown[] = []+ const discovery = m.cursorDiscovery.createCursorDiscovery(home('.cursor'), (id, path) => { found.push([id, path]) })+ await discovery.start()+ try {+ const existing = UUID(61), later = UUID(62), removed = UUID(63)+ file(home('.cursor', 'projects', 'golden-existing', 'agent-transcripts', existing, `${existing}.jsonl`), '{}\n')+ await discovery.add(existing)+ await discovery.add(later)+ await discovery.add(removed)+ discovery.remove(removed)+ file(home('.cursor', 'projects', 'golden-later', 'agent-transcripts', later, `${later}.jsonl`), '{}\n')+ file(home('.cursor', 'projects', 'golden-removed', 'agent-transcripts', removed, `${removed}.jsonl`), '{}\n')+ await vi.waitFor(() => expect(found).toHaveLength(2), { timeout: 5000 })+ await discovery.add('../invalid')+ await discovery.stop()+ check('pending cursor transcripts', found)+ } finally { await discovery.stop() }+ })+it('has a recorded outcome for every case, and no other', () => {if (RECORD) returnexpect(Object.keys(recorded).sort()).toEqual(Object.keys(golden).sort())diff --git a/cli/src/leanEntry.spec.ts b/cli/src/leanEntry.spec.tsindex 570eea5ae..9ad3ccb7a 100644--- a/cli/src/leanEntry.spec.ts+++ b/cli/src/leanEntry.spec.ts@@ -90,16 +90,16 @@ describe('the lean bundle a release carries', () => {it.each([// Each a string its module alone holds: lib/questionPane.ts's, lib/hooks.ts's (its Amp plugin's), Amp's thread// export's (engines/amp/threadExport.ts), and the name the bundle keeps for Cursor's sub-agents' reader- // (engines/cursor/subagent.ts), Devin's switch reader (engines/devin/runtimeProfile.ts), agy's lock reader- // (engines/agy/session.ts), Cursor's discovery (engines/cursor/discovery.ts) and Hermes's adoption reader- // (lib/sessionSearch/externals/hermes.ts), which the core's own files only call.+ // (engines/cursor/subagent.ts), Devin's switch reader (engines/devin/runtimeProfile.ts), the compatibility+ // wrappers for agy's lock lookup and Cursor discovery, and Hermes's optional adoption reader. Core+ // identity and discovery use eager declarations/kit mechanics instead of those optional wrappers.['pane readers', 'Native screen reader must be injected'],['hook installers', 'Mirrors this Amp thread to the machine adapter'],['own code: Amp\'s', 'AMP_DISABLE_PLUGINS'],['own code: Cursor\'s', '"loadCursorReplayTaskLinks"'],['runtime profiles: Devin\'s', '"devinModelCommandResult"'],- ['identity: agy\'s', '"agyConversationForPid"'],- ['identity: Cursor\'s discovery', '"CursorTranscriptDiscovery"'],+ ['compatibility lookup: agy\'s', '"agyConversationForPid"'],+ ['compatibility wrapper: Cursor\'s discovery', '"CursorTranscriptDiscovery"'],['adoption: Hermes\'s reader', '"hermesProvider"'],])('leaves the other engines\' %s out of the core until it needs them', (_, marker) => {// engines/inProcess.ts imports them (docs/design/2026-10-08-other-engines-out-of-core.md): a file of the@@ -143,12 +143,13 @@ describe('the lean bundle a release carries', () => {for (const role of ['master', 'search', 'updater', 'engine-claude', 'engine-codex', ...SERVICE_HOSTS.edge.services]) expect(hasZod(loads(role)), role).toBe(false)})- it('brings the edge host no node:sqlite until it reads a store some engines keep a conversation in', () => {- // A native binding, synchronous and able to take a process down with it, in the host meant to be light.- // The handoff, the monitor and projects read such stores for opencode, kilo, hermes and devin alone, and- // `lib/sqliteRead.ts` imports the binding's loader (`lib/sqliteBuiltin.ts`) only at the first read.+ it('keeps SQLite read mechanics eager in core and its service consumers', () => {+ // Hook admission must not need a lazy code chunk. Loading the mechanics does not load Node's native+ // binding: builtinSqlite resolves that only at a database read, verified in a real process below.+ expect(hasSqlite(loads('core')), 'core admission can read its store without an import').toBe(true)+ expect(hasSqlite(loads('usage')), 'usage shares the same eager read mechanics').toBe(true)expect(hasSqlite(loads('search')), 'search, the native-sqlite host, still has it').toBe(true)- for (const role of SERVICE_HOSTS.edge.services) expect(hasSqlite(loads(role)), role).toBe(false)+ for (const role of ['master', 'updater']) expect(hasSqlite(loads(role)), role).toBe(false)})it('starts the edge host without node:sqlite, where search, whose index is SQLite, has it', async () => {diff --git a/cli/src/lib/attachTracker.spec.ts b/cli/src/lib/attachTracker.spec.tsindex 2eb23fb1d..0193d6b38 100644--- a/cli/src/lib/attachTracker.spec.ts+++ b/cli/src/lib/attachTracker.spec.ts@@ -37,6 +37,18 @@ describe('AttachTracker', () => {expect(order).toEqual(['reset'])})+ it('serializes a new identity instead of joining an obsolete attach of the same session', async () => {+ const tracker = new AttachTracker<Engine>()+ const first = deferred<boolean>()+ const start = vi.fn(async () => true)+ const a = tracker.attach(subject('s1'), false, () => first.promise, 'pathless')+ const b = tracker.attach(subject('s1'), false, start, 'located')+ expect(start).not.toHaveBeenCalled()+ first.resolve(false)+ expect(await Promise.all([a, b])).toEqual([false, true])+ expect(start).toHaveBeenCalledOnce()+ })+it('a reset still runs after the attach it waited on failed', async () => {const tracker = new AttachTracker<Engine>()const first = deferred<boolean>()diff --git a/cli/src/lib/attachTracker.ts b/cli/src/lib/attachTracker.tsindex cfbe50d80..ac7c0d471 100644--- a/cli/src/lib/attachTracker.ts+++ b/cli/src/lib/attachTracker.ts@@ -42,7 +42,7 @@ const DEFAULT_CONCURRENCY = 4export class AttachTracker<E> {/** Every attach that has been asked for and not finished — waiting for a slot or running. */- private readonly inFlight = new Map<string, { run: Promise<boolean>; subject: AttachSubject<E>; since: number | null }>()+ private readonly inFlight = new Map<string, { run: Promise<boolean>; subject: AttachSubject<E>; since: number | null; identity?: string }>()private readonly waiting: Array<() => void> = []private running = 0private readonly concurrency: number@@ -62,16 +62,18 @@ export class AttachTracker<E> {* returns THAT one's result and `start` is never called; a `reset` waits for it, then runs `start`.* Either way `start` runs only once a slot is free.*/- async attach(session: AttachSubject<E>, reset: boolean, start: () => Promise<boolean>): Promise<boolean> {+ async attach(session: AttachSubject<E>, reset: boolean, start: () => Promise<boolean>, identity?: string): Promise<boolean> {// A loop, not an if: two resets waiting on the same attach would otherwise both start at once.// The key is read once: `session` is the registry's live object and unbinding blanks its sessionId// mid-attach, so reading it again later would miss the entry and leave it behind for good.const key = session.sessionIdfor (let pending = this.inFlight.get(key); pending; pending = this.inFlight.get(key)) {- if (!reset) return pending.run+ // A path discovered during the first probe is a new attach, not a join of the obsolete one.+ // Still serialize it: interpretation that has started writing must finish before its replacement.+ if (!reset && pending.identity === identity) return pending.runawait pending.run.catch(() => false)}- const entry = { run: Promise.resolve(false), subject: session, since: null as number | null }+ const entry = { run: Promise.resolve(false), subject: session, since: null as number | null, identity }entry.run = this.runWhenFree(entry, start).finally(() => {if (this.inFlight.get(key) === entry) this.inFlight.delete(key)})diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex 7cafce0a9..e011c4281 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -26,7 +26,11 @@ import type { AgentEngine } from '../engines/types.js'import { HERMES_HOMES, hermesDbPath } from '../engines/hermes/contract.js'import { listStoreHomes } from '../engines/kit/storeHomes.js'import { loadEngine, type InProcessModules } from '../engines/inProcess.js'+import { transcriptOf, processSessionOf as nativeProcessSession } from '../engines/identities.js'+import { COPILOT_CWD } from '../engines/copilot/contract.js'+import { recordCwd } from '../engines/kit/sessionLocation.js'import { sqliteReadAll, type SqliteParam } from './sqliteRead.js'+import { sqlitePreflightMessage } from './sqliteAvailability.js'import { sessionRoots } from './engineHomes.js'import { argvTokens, engineProcessMatchScore, processRows, type ProcessRow } from './tmux.js'@@ -235,7 +239,6 @@ let missingSqliteReported = falseasync function reportMissingSqliteOnce(): Promise<void> {if (missingSqliteReported) returnmissingSqliteReported = true- const { sqlitePreflightMessage } = await import('./sqliteAvailability.js')console.warn(sqlitePreflightMessage() ?? '[preflight] no SQLite reader available')}@@ -276,12 +279,11 @@ async function copilotDirectoryScan(cwd: string,startedAtMs: number,opts: { bornOnly?: boolean } | undefined,- copilotSessionCwd: InProcessModules['copilot']['copilotSessionCwd'],): Promise<RepairedSession | null> {return fileEngineSession(join(env.COPILOT_HOME, 'session-state'), cwd, startedAtMs, async (path) => {if (basename(path) !== 'events.jsonl') return nullconst head = (await readFile(path, 'utf8').catch(() => '')).split('\n', 5)- const root = copilotSessionCwd(head)+ const root = recordCwd(head, COPILOT_CWD)return root ? { cwd: root, sessionId: basename(dirname(path)) } : null}, opts)}@@ -328,7 +330,7 @@ export async function findLiveSession(const real = await realpath(cwd).catch(() => cwd)const dirs = real === cwd ? [cwd] : [cwd, real]const dirList = placeholders(dirs.length)- // Muse's, Copilot's and agy's readers of their own files are their code, loaded where they are read+ // Muse's transcript interpretation still lives with its optional reader// (engines/inProcess.ts); Hermes's homes are declared (engines/hermes/contract.ts). An engine whose code could not be loaded has no repair answer: its process stays// unbound, as when nothing is found.switch (engine) {@@ -436,14 +438,12 @@ export async function findLiveSession(// The lock the process holds is the only thing a `/resume` leaves behind, and it is exact.// Fall through to the directory scan when there is no pid or no lock yet (a brand-new session// takes its lock only once Copilot creates it).- const copilot = await loadEngine('copilot')- if (!copilot) return null- const locked = opts?.pid ? await copilot.copilotSessionForPid(env.COPILOT_HOME, opts.pid) : null+ const locked = opts?.pid ? await nativeProcessSession('copilot', env.COPILOT_HOME, opts.pid) : nullif (locked) {- const transcriptPath = await copilot.findCopilotTranscript(env.COPILOT_HOME, locked)+ const transcriptPath = await transcriptOf('copilot', env.COPILOT_HOME, locked)return { sessionId: locked, transcriptPath: transcriptPath ?? undefined }}- return copilotDirectoryScan(cwd, startedAtMs, opts, copilot.copilotSessionCwd)+ return copilotDirectoryScan(cwd, startedAtMs, opts)}case 'agy':@@ -462,11 +462,9 @@ export async function findLiveSession(/** The conversation the given `agy` pid is holding, if its transcript exists yet. */async function agySession(pid: number): Promise<RepairedSession | null> {- const agy = await loadEngine('agy')- if (!agy) return null- const conversationId = await agy.agyConversationForPid(env.AGY_HOME, pid)+ const conversationId = await nativeProcessSession('agy', env.AGY_HOME, pid)if (!conversationId) return null- const transcriptPath = await agy.findAgyTranscript(env.AGY_HOME, conversationId)+ const transcriptPath = await transcriptOf('agy', env.AGY_HOME, conversationId)// 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/cli/src/lib/sqliteBuiltin.ts b/cli/src/lib/sqliteBuiltin.tsindex 1e52e8edf..6d5b3cbc9 100644--- a/cli/src/lib/sqliteBuiltin.ts+++ b/cli/src/lib/sqliteBuiltin.ts@@ -1,5 +1,5 @@-/** The native `node:sqlite` binding, apart from `sqliteRead.ts`, which imports it at its first read: the edge host- * loads it only to read a store opencode, kilo, hermes or devin keeps, never for Claude Code or Codex. */+/** The native SQLite read mechanism is eager: hook admission must not depend on a lazy code chunk.+ * The optional Node builtin is resolved without a bundler import, and older Node keeps its CLI fallback. */import { statSync } from 'node:fs'import { pathToFileURL } from 'node:url'import { idleWalStore, type SqliteParam, type SqliteReadResult, type SqliteRow } from './sqliteRead.js'diff --git a/cli/src/lib/sqliteRead.ts b/cli/src/lib/sqliteRead.tsindex ed663facd..a487b8c55 100644--- a/cli/src/lib/sqliteRead.ts+++ b/cli/src/lib/sqliteRead.ts@@ -4,7 +4,7 @@** Two ways in, tried in this order:*- * 1. `node:sqlite` (`sqliteBuiltin.ts`, imported at the first read) — built into the Node the installers ship (22.23, see `runtime/current-node`),+ * 1. `node:sqlite` (`sqliteBuiltin.ts`, eagerly available for hook admission) — built into the Node the installers ship (22.23, see `runtime/current-node`),* and into any Node ≥ 22.13 without a flag. In-process, parameterised, no JSON round-trip: the* query that hung the `sqlite3` CLI for good on one machine (an opencode session with a ~7.5 MB* row) finishes here in tens of milliseconds. The binding is SYNCHRONOUS — it blocks the event@@ -23,6 +23,7 @@import { execFile } from 'node:child_process'import { closeSync, existsSync, openSync, readSync } from 'node:fs'import { promisify } from 'node:util'+import { builtinSqlite, readBuiltin } from './sqliteBuiltin.js'const execFileAsync = promisify(execFile)@@ -153,8 +154,6 @@ export async function sqliteReadAll(params: SqliteParam[] = [],options: SqliteReadOptions = {},): Promise<SqliteReadResult> {- // At the first read, not with this module: the edge host's handoff, monitor and projects import this one.- const { builtinSqlite, readBuiltin } = await import('./sqliteBuiltin.js')const Database = builtinSqlite()if (Database) {return readBuiltin(Database, dbPath, sql, params, options.busyTimeoutMs ?? DEFAULT_BUSY_TIMEOUT_MS)diff --git a/cli/src/lib/terminalAgentDiscovery.hermesHome.spec.ts b/cli/src/lib/terminalAgentDiscovery.hermesHome.spec.tsindex 9aa81aa9b..cc1f65a26 100644--- a/cli/src/lib/terminalAgentDiscovery.hermesHome.spec.ts+++ b/cli/src/lib/terminalAgentDiscovery.hermesHome.spec.ts@@ -3,8 +3,7 @@ import type { ProcessRow } from './tmux.js'import type { TerminalBackend } from './terminalBackend.js'/**- * The Hermes home a process runs under rides the live discovery path, read by Hermes's own probe- * (engines/hermes/homeProbe.ts), loaded for a Hermes process alone (engines/inProcess.ts).+ * The Hermes home rides the live discovery path through eager process facts.* `engines/otherAdmission.golden.spec.ts` pins what it reads; this pins when it is asked.*/const processRows = vi.hoisted(() => vi.fn())@@ -39,16 +38,20 @@ beforeEach(() => {})describe('Hermes\'s home on the live terminal discovery path', () => {- it('is read by Hermes\'s code, loaded for its process alone', async () => {+ it('is read without the optional engine loader', async () => {expect(await homes()).toEqual({ hermes: '/home/u/.hermes/profiles/work', claude: null })- expect(vi.mocked(loadEngine).mock.calls).toEqual([['hermes']])+ expect(loadEngine).not.toHaveBeenCalled()+ })++ it('still discovers the home when Hermes interpretation cannot load', async () => {+ vi.mocked(loadEngine).mockImplementationOnce(() => new Promise(() => {}))+ expect(await homes()).toEqual({ hermes: '/home/u/.hermes/profiles/work', claude: null })+ expect(loadEngine).not.toHaveBeenCalled()})- it('is unknown without Hermes\'s code, which never overwrites what the registry knows', async () => {- const error = vi.spyOn(console, 'error').mockImplementation(() => {})- vi.mocked(loadEngine).mockResolvedValueOnce(null)+ it('preserves an unknown home when the process environment cannot be read', async () => {+ readProcessEnv.mockResolvedValue(null)expect(await homes()).toEqual({ hermes: undefined, claude: null })- error.mockRestore()})it('is not asked of a pane with no Hermes in it', async () => {diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.tsindex f93faab66..349a3d821 100644--- a/cli/src/lib/terminalAgentDiscovery.ts+++ b/cli/src/lib/terminalAgentDiscovery.ts@@ -9,7 +9,7 @@ import { probeGatewayRuntime } from './gatewayRuntime.js'import { gridAssignmentProcess, type GridAssignment, type GridAssignmentProcess } from './gridAssignmentWire.js'import { readProcessEnv } from './processEnv.js'import { probeProfileHome } from '../engines/discoveries.js'-import { loadEngine } from '../engines/inProcess.js'+import { probeHermesHome } from '../engines/identities.js'import { probeDsh } from '../dsh/probe.js'import type { TerminalBackend } from './terminalBackend.js'import {@@ -272,12 +272,8 @@ export async function probeTerminalAgents(}// And, for Codex, the profile it runs under — a fact about the process the row cannot otherwise learn.agent.codexHome = await probeProfileHome(agent.processIdentity, agent.engine)- // …and, for Hermes, the home — same cached read, and it beats looking the session up in every store. Read by- // Hermes's own code, loaded for a Hermes process alone (engines/inProcess.ts); without it the process could- // not be read, which never overwrites what the registry knows.- agent.hermesHome = agent.engine === 'hermes'- ? await (await loadEngine('hermes'))?.probeHermesHome(agent.processIdentity, agent.engine)- : null+ // Hermes's declared profile is read eagerly from the same verified process environment.+ agent.hermesHome = await probeHermesHome(agent.processIdentity, agent.engine)// And the DSH it was created as — same read, so a pane the daemon did not create is labelled too.agent.dsh = await probeDsh(agent.processIdentity)}))diff --git a/cli/src/services/handoffProcess.spec.ts b/cli/src/services/handoffProcess.spec.tsindex d6e72f8bd..b5dc139a4 100644--- a/cli/src/services/handoffProcess.spec.ts+++ b/cli/src/services/handoffProcess.spec.ts@@ -99,7 +99,7 @@ describe('the handoff in the edge host', () => {expect(Object.keys(vi.mocked(runServiceProcess).mock.calls.at(-1)![0].requests)).toEqual([...HANDOFF_REQUESTS])})- it('loads the SQLite binding only for an engine that keeps its conversation in a store, and hands that one over', async () => {+ it('reads SQLite only for a store-backed conversation and hands that one over', async () => {const ws = mkdtempSync(join(tmpdir(), 'handoff-store-'))try {execFileSync('git', ['init', '-q'], { cwd: ws })@@ -111,14 +111,15 @@ describe('the handoff in the edge host', () => {value: query === 'resolve' ? Object.values(agents).find((agent) => agent.agentId === payload.id) ?? null: query === 'recentAsks' || query === 'recaps' ? [] : null,}))- // Claude Code and Codex keep a transcript file: nothing to read from a store, and the binding stays out.+ // The eager SQLite module does not open a database for a file-backed conversation.expect(core.transcripts.databaseHistory(agents.claude as never)).toBeUndefined()expect(core.transcripts.databaseHistory({ ...agents.claude, engine: 'codex' } as never)).toBeUndefined()const prepare = startHandoff(core).agent_handoff_prepare!const asker = { local: true, owner: true }await prepare({ agentId: 'claude-1', changeId: 'c'.repeat(32), targetEngine: 'codex' }, asker)- expect(binding.loads).toBe(0)- // OpenCode: read through the binding, loaded for that read, and the turn it holds handed over.+ expect(binding.loads).toBe(1)+ expect(binding.reads).toEqual([])+ // OpenCode reads through the same binding and hands over the turn the store holds.const handed = await prepare({ agentId: 'opencode-1', changeId: 'a'.repeat(32), targetEngine: 'claude' }, asker) as { file: string | null }expect(binding.loads).toBe(1)expect(binding.reads).toEqual([{ path: join(env.OPENCODE_DATA_DIR, 'opencode.db'), sql: expect.stringContaining('FROM message m'), params: ['ses_handoff1'] }])diff --git a/docs/research/2026-10-09-eager-identity.md b/docs/research/2026-10-09-eager-identity.mdnew file mode 100644index 000000000..0bbfb31b2--- /dev/null+++ b/docs/research/2026-10-09-eager-identity.md@@ -0,0 +1,17 @@+# Eager identity and transcript location++The owner requires session control to survive missing optional engine modules. The former main implementation still loads engine modules to locate Cursor, Grok, Agy and Copilot transcripts, follow Copilot's in-process resume, discover a Hermes profile, and poll a pending Cursor transcript. These filesystem and process facts belong to the eager core; interpretation remains optional.++Before changing implementation, `otherIdentity.golden.spec.ts` was recorded from main `3a68988a7848adaa6ea329a597cb4cfa82b17fb6`. It retains the existing identity outcomes and adds the Grok hashed-directory fallback, competing Copilot locks and core Cursor discovery of existing and later transcripts. The fixture also carries the previously recorded Hermes ID cases. Linux platform, boot identity, time, UTC, disposable homes and controlled descriptor evidence are pinned. Host Node paths are placeholders. Recording passed all nine cases; the fixture is committed separately before the move.++A lookup must remain available when an optional engine module is absent. A delayed lookup must also respect removal and stop; moving code is not sufficient evidence of that authority boundary. Engine declarations now feed eager kit mechanics. Binding uses the same layouts and PID lock evidence without asking an optional reader. Hermes profile probing and SQLite access are eager too. This keeps the recorded identity outcomes unchanged.++The move exposed lifecycle requirements beyond a mechanical extraction. Binding publishes its name, resume record and client announcement before optional interpretation. Reads retain copied process/binding authority and recheck a resume target's tombstone and newest owner before registration. Cursor location starts outside the optional reader queue; removal, stop and replacement revoke pending lookups. Its discovered path is published immediately.++Attachments serialize by immutable binding identity as well as session id, so a discovered path does not join an obsolete pathless attach. Only the wait for loading code has a five-second bound. Missing or stalled code holds interpretation, logs the reason and makes no normalizer, tail or runtime-profile writes; the binding remains available. A shared import that eventually resolves schedules one current retry per session. Forget removes retry ownership. A newer attach also revokes an earlier hold; any retry already queued checks that ownership again before starting, preventing a recovery from folding the same Cursor first turn twice. Reads that already began interpreting history are never abandoned by this deadline.++Independent review required regression tests for delayed binding publication, stale completion, an exhausted attachment pool, forgotten locator work, a competing resume owner, and a file discovered during the first probe or module load. Tests cover the real attachment tracker and locator together, plus late loader recovery and cleanup. The private-daemon lane removes or stalls optional Cursor/Copilot chunks and exercises PID-based binding, in-process resume and pending transcript discovery. Mutation checks deliberately disconnect both declaration wiring and lifetime checks; only assertion failures count.++The large Cursor-tree test retains its existing two-second discovery assertion. Fixture construction and cleanup each have a thirty-second test bound after concurrent builds exhausted Vitest's default fixture deadline; the isolated original case passed. Routine receipts retain the failed runs as well as the corrected validation.++This is one follow-up, not the end of the audit. Muse/Pi repair, bounded native identity reads, eager OpenCode launch, turn-closing/Stop facts, Cursor task cleanup and submission declarations remain separate work.