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
Claude Code's and Codex's session stores: declared data the kit applies in core (c4) (#1057)
Deecb014edbc55d
diff --git a/cli/e2e/enginehomes.e2e.ts b/cli/e2e/enginehomes.e2e.tsindex db8fcb58d..795c69c60 100644--- a/cli/e2e/enginehomes.e2e.ts+++ b/cli/e2e/enginehomes.e2e.ts@@ -312,7 +312,7 @@ describe('the person\'s engines keeping their data elsewhere', () => {// other engine's hooks are installed here, as for a person whose moved home has none of the daemon's yet.// The process repair binds it from what the engine leaves for that in the home it writes in: Claude Code's// process record (`<home>/sessions/<pid>.json`), the rollout Codex holds open. It looked in the default- // folders alone (sessionRepair.ts `claudeProcessSession`, `findLiveSession`), and the tile never bound.+ // folders alone (sessionRepair.ts `processSessionOf`, `findLiveSession`), and the tile never bound.it.each([['claude', 'CLAUDE_CONFIG_DIR', 'codex'],['codex', 'CODEX_HOME', 'claude'],diff --git a/cli/scripts/resume-native-e2e.ts b/cli/scripts/resume-native-e2e.tsindex 848dd0027..b2ab71538 100644--- a/cli/scripts/resume-native-e2e.ts+++ b/cli/scripts/resume-native-e2e.ts@@ -51,7 +51,7 @@ const { AgentRestartCoordinator } = await import('../src/lib/restartAgent.js')const { resolvePaneEngineProcess, checkSessionRuntime, lookupPaneEngineProcess, tmuxPaneProcessTree } = await import('../src/lib/tmux.js')const { probeTerminalAgents } = await import('../src/lib/terminalAgentDiscovery.js')const { captureResumeIdentity } = await import('../src/lib/captureResumeIdentity.js')-const { claudeProcessSession } = await import('../src/lib/sessionRepair.js')+const { processSessionOf } = await import('../src/lib/sessionRepair.js')const { checkPidRuntime } = await import('../src/lib/deleteAgentFallback.js')const { startHookServer } = await import('../src/hookServer.js')const { BackendSocket } = await import('../src/backendSocket.js')@@ -274,7 +274,7 @@ try {assert.equal(unbound.sessionId, '')assert.equal((await captureResumeIdentity(unbound)).sessionId, sessionId)if (engine === 'claude') {- assert.equal((await claudeProcessSession(unbound.processIdentity!.pid, cwd,+ assert.equal((await processSessionOf('claude', unbound.processIdentity!.pid, cwd,Date.parse(unbound.processIdentity!.startMarker)))?.sessionId, sessionId,'Claude native process metadata identifies the conversation before Stop')}diff --git a/cli/src/agentHandoff.fork.integration.spec.ts b/cli/src/agentHandoff.fork.integration.spec.tsindex ed1611dbd..6bd82b986 100644--- a/cli/src/agentHandoff.fork.integration.spec.ts+++ b/cli/src/agentHandoff.fork.integration.spec.ts@@ -50,8 +50,9 @@ async function modules() {const discovery = await import('./lib/handoffDiscovery.js')const handoff = await import('./lib/agentHandoff.js')const stopped = await import('./lib/stoppedAgents.js')+ const stores = await import('./engines/sessionStores.js')registryModule.registry.load()- return { ...registryModule, ...repair, ...discovery, ...handoff, ...stopped }+ return { ...registryModule, ...repair, ...discovery, ...handoff, ...stopped, processSession: stores.processSessionOf }}type Mods = Awaited<ReturnType<typeof modules>>@@ -82,7 +83,7 @@ function forkOriginAsCliBuildsIt(source: RegisteredSession, sourceName: string)* The provider deps through cli.ts's own factory (`handoffProviderDeps`), with the real registry, stopped store,* transcript lookup, gate and session searches; only the mirror is faked, loudly, so any use of it shows.*/-function cliDeps(m: Mods, rows: RegisteredSession[], over: { findLiveSession?: Mods['findLiveSession']; claudeProcessSession?: Mods['claudeProcessSession'] } = {}) {+function cliDeps(m: Mods, rows: RegisteredSession[], over: { findLiveSession?: Mods['findLiveSession']; processSession?: Mods['processSession'] } = {}) {const stoppedDir = join(data, 'stopped-agents')const store = new m.StoppedAgentStore(stoppedDir)return m.handoffProviderDeps({@@ -105,7 +106,7 @@ function cliDeps(m: Mods, rows: RegisteredSession[], over: { findLiveSession?: M} as unknown as Parameters<Mods['handoffProviderDeps']>[0]['mirror'],databaseHistory: () => undefined,findLiveSession: over.findLiveSession ?? m.findLiveSession,- claudeProcessSession: over.claudeProcessSession ?? m.claudeProcessSession,+ processSession: over.processSession ?? m.processSession,isRecentlyDeleted: () => false,findResumedTranscript: m.findResumedTranscript,validTranscriptPath: m.validTranscriptPath,@@ -152,8 +153,8 @@ describe('fork record → registry → stopped copy → inheritance (real modulefor (const [label, row] of [['live', fork], ['restarted', restartedFork], ['stopped', stoppedFork]] as const) {rmSync(join(ws, '.harness'), { recursive: true, force: true })const findLiveSession = vi.fn(m.findLiveSession)- const claudeProcessSession = vi.fn(m.claudeProcessSession)- const result = await m.prepareAgentHandoff(cliDeps(m, [parent, row], { findLiveSession, claudeProcessSession }), { agentId: row.agentId, changeId: CHANGE, targetEngine: 'codex' })+ const claudeProcessSession = vi.fn(m.processSession)+ const result = await m.prepareAgentHandoff(cliDeps(m, [parent, row], { findLiveSession, processSession: claudeProcessSession }), { agentId: row.agentId, changeId: CHANGE, targetEngine: 'codex' })expect(result, label).toEqual({ file: `.harness/handoff/${row.agentId}-${CHANGE}.md`, gitRepo: false, cwd: ws, degraded: ['git'] })const md = handoffMd(row.agentId)expect(md, label).toContain('PRE-FORK ask: add a retry')@@ -235,8 +236,8 @@ describe('discovery through the real Claude process record (handoffDiscovery ↔const marker = startMarker()ownFile(Date.parse(marker) + 500)const findLiveSession = vi.fn(m.findLiveSession)- const claudeProcessSession = vi.fn(m.claudeProcessSession)- const result = await ask(m, cliDeps(m, [unbound(marker)], { findLiveSession, claudeProcessSession }))+ const claudeProcessSession = vi.fn(m.processSession)+ const result = await ask(m, cliDeps(m, [unbound(marker)], { findLiveSession, processSession: claudeProcessSession }))expect(claudeProcessSession).toHaveBeenCalledTimes(1)expect(findLiveSession).not.toHaveBeenCalled()expect(result).toEqual({ file: null, gitRepo: false, cwd: ws, degraded: ['transcript'] })@@ -250,8 +251,8 @@ describe('discovery through the real Claude process record (handoffDiscovery ↔processRecord(FOUND_SESSION, marker)for (const [label, row] of [['no marker', unbound(null)], ['no pid', unbound(marker, null)], ['no identity', unbound(null, null)]] as const) {const findLiveSession = vi.fn(m.findLiveSession)- const claudeProcessSession = vi.fn(m.claudeProcessSession)- expect(await ask(m, cliDeps(m, [row], { findLiveSession, claudeProcessSession })), label).toEqual({ file: null, gitRepo: false, cwd: ws, degraded: ['transcript'] })+ const claudeProcessSession = vi.fn(m.processSession)+ expect(await ask(m, cliDeps(m, [row], { findLiveSession, processSession: claudeProcessSession })), label).toEqual({ file: null, gitRepo: false, cwd: ws, degraded: ['transcript'] })expect(claudeProcessSession, label).not.toHaveBeenCalled()expect(findLiveSession, label).not.toHaveBeenCalled()}@@ -300,8 +301,8 @@ describe('discovery through the real Claude process record (handoffDiscovery ↔processRecord(FOUND_SESSION, marker)const fork = { ...unbound(marker), forkedFrom: { agentId: 'gone-parent', name: 'Gone' } } as RegisteredSessionconst findLiveSession = vi.fn(m.findLiveSession)- const claudeProcessSession = vi.fn(m.claudeProcessSession)- const result = await ask(m, cliDeps(m, [fork], { findLiveSession, claudeProcessSession }))+ const claudeProcessSession = vi.fn(m.processSession)+ const result = await ask(m, cliDeps(m, [fork], { findLiveSession, processSession: claudeProcessSession }))expect(findLiveSession).not.toHaveBeenCalled()expect(claudeProcessSession).not.toHaveBeenCalled()expect(result).toEqual({ file: null, gitRepo: false, cwd: ws, degraded: ['transcript'] })diff --git a/cli/src/agentHandoff.wire.spec.ts b/cli/src/agentHandoff.wire.spec.tsindex 3edf225df..1f52cb55b 100644--- a/cli/src/agentHandoff.wire.spec.ts+++ b/cli/src/agentHandoff.wire.spec.ts@@ -85,7 +85,7 @@ function wire(sessions: RegisteredSession[], over: Partial<HandoffDeps> = {}, famirror: { recentAsks: () => [], lastFullText: () => undefined, recent: () => [] },databaseHistory: () => undefined,findLiveSession: async () => null,- claudeProcessSession: async () => null,+ processSession: async () => null,isRecentlyDeleted: () => false,findResumedTranscript: async () => null,validTranscriptPath: (_engine, path) => existsSync(path),@@ -283,7 +283,7 @@ describe('agent_handoff_prepare, socket + real provider: a fork that has not ansit('W1: a legacy fork switched at once gets its parent\'s conversation up to the fork', async () => {const findLiveSession = vi.fn(async () => null)const claudeProcessSession = vi.fn(async () => null)- wire([parent(), fork()], {}, { findLiveSession, claudeProcessSession })+ wire([parent(), fork()], {}, { findLiveSession, processSession: claudeProcessSession })ask('r1', 'fork-1')expect(await reply('r1')).toEqual({ requestId: 'r1', agentId: 'fork-1', file: `.harness/handoff/fork-1-${CHANGE}.md`, gitRepo: false, cwd: ws, degraded: ['git'] })expect(md()).toContain('Fix the login bug')@@ -318,11 +318,11 @@ describe('agent_handoff_prepare, socket + real provider: a fork that has not ansit('W4: an unbound agent that is not a fork is handed the session the daemon found for it', async () => {const found = parentFile('found.jsonl', 'later ask')const claudeProcessSession = vi.fn(async () => ({ sessionId: 'sx', transcriptPath: found }))- wire([unbound('fork-1')], {}, { claudeProcessSession })+ wire([unbound('fork-1')], {}, { processSession: claudeProcessSession })ask('r1', 'fork-1')expect((await reply('r1')).file).toBe(`.harness/handoff/fork-1-${CHANGE}.md`)expect(claudeProcessSession).toHaveBeenCalledTimes(1)- expect(claudeProcessSession).toHaveBeenCalledWith(4242, ws, Date.parse('Fri Oct 2 16:58:26 2026'))+ expect(claudeProcessSession).toHaveBeenCalledWith('claude', 4242, ws, Date.parse('Fri Oct 2 16:58:26 2026'))expect(md()).toContain('Fix the login bug')})// Verifier additions (unit-INT-a3-r1): discovery refusals through the real provider and socket.@@ -330,7 +330,7 @@ describe('agent_handoff_prepare, socket + real provider: a fork that has not ansit('W5: a discovered session another agent holds is never handed over', async () => {const other = session({ agentId: 'other-1', sessionId: 'sx', transcriptPath: parentFile('other.jsonl', 'OTHER ask') })const claudeProcessSession = vi.fn(async () => ({ sessionId: 'sx', transcriptPath: other.transcriptPath! }))- wire([unbound('new-1'), other], {}, { claudeProcessSession })+ wire([unbound('new-1'), other], {}, { processSession: claudeProcessSession })ask('r1', 'new-1')expect(await reply('r1')).toEqual(nothing('new-1'))expect(claudeProcessSession).toHaveBeenCalledTimes(1)@@ -342,7 +342,7 @@ describe('agent_handoff_prepare, socket + real provider: a fork that has not ansmkdirSync(dir, { recursive: true })const sub = join(dir, 'agent-a.jsonl')writeFileSync(sub, readFileSync(parentFile('sub-seed.jsonl', 'SUBAGENT ask')))- wire([unbound('new-1')], {}, { claudeProcessSession: async () => ({ sessionId: 'agent-a', transcriptPath: sub }) })+ wire([unbound('new-1')], {}, { processSession: async () => ({ sessionId: 'agent-a', transcriptPath: sub }) })ask('r1', 'new-1')expect(await reply('r1')).toEqual(nothing('new-1'))expect(existsSync(join(ws, '.harness'))).toBe(false)@@ -350,7 +350,7 @@ describe('agent_handoff_prepare, socket + real provider: a fork that has not ansit('W7: a fork whose record is malformed is neither discovered nor inherited', async () => {const claudeProcessSession = vi.fn(async () => ({ sessionId: 'sx', transcriptPath: parentFile('found.jsonl', 'later ask') }))- wire([parent(), fork({ forkedFrom: 'parent-1', processIdentity: { pid: 4242, executable: 'claude', startMarker: 'Fri Oct 2 16:58:26 2026' } })], {}, { claudeProcessSession })+ wire([parent(), fork({ forkedFrom: 'parent-1', processIdentity: { pid: 4242, executable: 'claude', startMarker: 'Fri Oct 2 16:58:26 2026' } })], {}, { processSession: claudeProcessSession })ask('r1', 'fork-1')expect(await reply('r1')).toEqual(nothing('fork-1'))expect(claudeProcessSession).not.toHaveBeenCalled()@@ -358,7 +358,7 @@ describe('agent_handoff_prepare, socket + real provider: a fork that has not ansit('W8: a discovery that never answers does not hold the reply, and a later change reuses the search still running', async () => {const claudeProcessSession = vi.fn(() => new Promise<null>(() => {}))- wire([unbound('new-1')], { discoverMs: 50 }, { claudeProcessSession })+ wire([unbound('new-1')], { discoverMs: 50 }, { processSession: claudeProcessSession })ask('r1', 'new-1')expect(await reply('r1')).toEqual(nothing('new-1'))ask('r2', 'new-1', OTHER)@@ -370,7 +370,7 @@ describe('agent_handoff_prepare, socket + real provider: a fork that has not ansit('W9: a discovered session is never handed over while one stopped record cannot be read (ownership fails closed)', async () => {const claudeProcessSession = vi.fn(async () => ({ sessionId: 'sx', transcriptPath: parentFile('found.jsonl', 'later ask') }))const stopped = { ids: () => ['ok-1', 'bad-1'], get: (id: string) => { if (id === 'bad-1') throw new Error('Could not read the saved stopped harness.'); return { agentId: id, sessionId: 'other' } as unknown as RegisteredSession } }- wire([unbound('new-1')], {}, { claudeProcessSession, stopped })+ wire([unbound('new-1')], {}, { processSession: claudeProcessSession, stopped })ask('r1', 'new-1')expect(await reply('r1')).toEqual(nothing('new-1'))expect(claudeProcessSession).toHaveBeenCalledTimes(1)@@ -378,7 +378,7 @@ describe('agent_handoff_prepare, socket + real provider: a fork that has not ansit('W10: a Claude pane with no process identity is not searched for at all', async () => {const claudeProcessSession = vi.fn(async () => ({ sessionId: 'sx', transcriptPath: parentFile('found.jsonl', 'later ask') }))- wire([unbound('new-1', { processIdentity: null })], {}, { claudeProcessSession })+ wire([unbound('new-1', { processIdentity: null })], {}, { processSession: claudeProcessSession })ask('r1', 'new-1')expect(await reply('r1')).toEqual(nothing('new-1'))expect(claudeProcessSession).not.toHaveBeenCalled()diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 84701cca8..34d0ea94b 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -156,11 +156,12 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {'services/workspaces.ts → ../lib/registry.js': 'sessionDisplayTitle, a pure helper',}-/** Claude Code's and Codex's declared contracts that core reads in line, and the rollout reader the registry keeps- * until (c4): what a launch's or discovery's closure may reach of the two engines. */+/** Claude Code's and Codex's declared contracts that core reads in line: what a launch's, discovery's or session+ * repair's closure may reach of the two engines. */const LAUNCH_CONTRACTS = new Set(['engines/claude/launch.ts', 'engines/codex/launch.ts'])+const SESSION_STORES = new Set(['engines/claude/sessionStore.ts', 'engines/codex/sessionStore.ts'])const DECLARED = new Set(['engines/claude/hookContract.ts', 'engines/codex/hookContract.ts', 'engines/claude/discoveryContract.ts',- 'engines/codex/discoveryContract.ts', 'engines/codex/rollout.ts'])+ 'engines/codex/discoveryContract.ts', ...SESSION_STORES])/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */const EDGE: RegExp[] = [@@ -354,8 +355,7 @@ describe('the daemon\'s shape', () => {})it('discovery loads the engines\' declared contracts alone', () => {- // The pass and what it reads off a process, the grid's model, the start-up repair, and the registry, which- // still holds Codex's rollout reader for its load-time repair until (c4).+ // The pass and what it reads off a process, the grid's model, the start-up repair, and the registry.for (const entry of ['lib/tmux.ts', 'lib/terminalAgentDiscovery.ts', 'lib/gridAssignment.ts', 'lib/cwdRepair.ts', 'lib/registry.ts','engines/discoveries.ts', 'engines/kit/processFacts.ts', 'engines/kit/projectFolder.ts']) {expect([...closureOf(entry).keys()].filter(file => /^engines\/(claude|codex)\//.test(file) && !DECLARED.has(file) && !LAUNCH_CONTRACTS.has(file)), entry).toEqual([])@@ -364,17 +364,57 @@ describe('the daemon\'s shape', () => {.toEqual(['engines/claude/discoveryContract.ts', 'engines/codex/discoveryContract.ts'])})+ it('the registry\'s load, session repair, resume capture and the handoff load the engines\' declared session stores alone', () => {+ // Binding a session, finding it by its id, by its process or by a scan, and putting back a parent's: session+ // control, with no engine worker and none of the two engines' code (docs/design/2026-10-08-engine-launch.md, (c4)).+ const theirs = (entry: string): string[] => [...closureOf(entry).keys()]+ .filter(file => /^engines\/(claude|codex)\//.test(file) && !DECLARED.has(file) && !LAUNCH_CONTRACTS.has(file))+ for (const entry of ['lib/registry.ts', 'lib/handoffDiscovery.ts', 'lib/engineHomes.ts', 'engines/sessionFiles.ts',+ 'engines/sessionStoreContracts.ts', 'engines/kit/sessionRecords.ts', 'engines/kit/continuation.ts']) {+ expect(theirs(entry), entry).toEqual([])+ }+ // Pi's session reader still loads the readers of the two engines' transcripts (lib/transcriptReader.ts), and+ // session repair names Pi's folders with it: the other engines' batch takes that out. Nothing else of session+ // repair, resume capture or binding reaches their code.+ const PI_READER = 'lib/sessionSearch/externals/pi.ts'+ const notThroughPi = (entry: string): string[] => {+ const seen = new Set<string>()+ const pending = [join(SRC, entry)]+ while (pending.length > 0) {+ const path = pending.pop()!+ const file = relative(SRC, path)+ if (seen.has(file) || file === PI_READER) continue+ seen.add(file)+ pending.push(...parsedFile(path).imports)+ }+ return [...seen].filter(file => /^engines\/(claude|codex)\//.test(file) && !DECLARED.has(file) && !LAUNCH_CONTRACTS.has(file))+ }+ for (const entry of ['lib/sessionRepair.ts', 'lib/captureResumeIdentity.ts', 'engines/sessionStores.ts', 'core/agents/bind.ts']) {+ expect(notThroughPi(entry), entry).toEqual([])+ }+ expect(closureOf('lib/sessionRepair.ts').has(PI_READER), 'Pi\'s reader is out of session repair: drop this exception').toBe(true)+ // The stores alone, and what Codex's shares with its launch and hook contracts (the rollout layout, the child rule).+ expect([...closureOf('engines/sessionStoreContracts.ts').keys()].filter(file => /^engines\/(claude|codex)\//.test(file)).sort())+ .toEqual(['engines/claude/sessionStore.ts', 'engines/codex/hookContract.ts', 'engines/codex/launch.ts', 'engines/codex/sessionStore.ts'])+ // The kit's mechanics know no engine at all.+ for (const entry of ['engines/kit/sessionRecords.ts', 'engines/kit/continuation.ts']) {+ expect([...closureOf(entry).keys()].filter(file => /^engines\/(claude|codex)\//.test(file)), entry).toEqual([])+ }+ })+it('building a launch loads the engines\' declared launch contracts alone', () => {const contracts = new Set(['engines/claude/launch.ts', 'engines/codex/launch.ts'])- // The builders: the argv and its script, a relaunch's overrides, a harness's flags.+ // The builders: the argv and its script, a relaunch's overrides, a harness's flags. The homes they launch in+ // are read with the session stores' declarations (lib/engineHomes.ts), data as well.for (const entry of ['lib/engineLaunch.ts', 'lib/launchOverrides.ts', 'engines/launches.ts', 'engines/kit/launchArgs.ts','engines/kit/launchStartup.ts', 'dsh/adapters.ts', 'engines/launchPrep.ts', 'engines/kit/folderTrust.ts','engines/kit/resumeRepair.ts', 'dsh/runtime.ts', 'lib/apiInstructions.ts']) {- expect([...closureOf(entry).keys()].filter(file => /^engines\/(claude|codex)\//.test(file) && !contracts.has(file)), entry).toEqual([])+ expect([...closureOf(entry).keys()].filter(file => /^engines\/(claude|codex)\//.test(file) && !contracts.has(file)+ && !SESSION_STORES.has(file) && file !== 'engines/codex/hookContract.ts'), entry).toEqual([])}expect([...closureOf('lib/engineLaunch.ts').keys()].filter(file => contracts.has(file)).sort()).toEqual([...contracts].sort())// The launches themselves reach the registry too, whose hook admission reads the hook contracts and whose- // load-time repair still reads Codex rollouts (rollout.ts, a later step of the plan). Nothing else of the two.+ // load-time repair reads the declared session stores. Nothing else of the two.const declared = new Set([...contracts, ...DECLARED])for (const entry of ['core/agents/create.ts', 'core/agents/fork.ts', 'core/agents/restart.ts', 'core/agents/swap.ts','core/agents/launch.ts', 'core/agents/launches.ts', 'lib/resumeAgentService.ts']) {diff --git a/cli/src/core/agents/bind.spec.ts b/cli/src/core/agents/bind.spec.tsindex a1921688e..d96981c75 100644--- a/cli/src/core/agents/bind.spec.ts+++ b/cli/src/core/agents/bind.spec.ts@@ -6,9 +6,10 @@ 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 { continuationOf } from '../../engines/sessionFiles.js'import { isRecentlyDeleted } from '../../lib/deletedSessions.js'import type { RegisteredSession } from '../../lib/registry.js'-import { claudeContinuation, findLiveSession, findResumedTranscript } from '../../lib/sessionRepair.js'+import { findLiveSession, findResumedTranscript } from '../../lib/sessionRepair.js'import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'import { createBinding, statBirthMs, type BindDeps, type RegisteredMeta } from './bind.js'@@ -18,8 +19,8 @@ vi.mock('../../engines/cursor/discovery.js', async (real) => ({ ...await real<obvi.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') }))vi.mock('../../lib/deletedSessions.js', () => ({ isRecentlyDeleted: vi.fn(() => false) }))+vi.mock('../../engines/sessionFiles.js', () => ({ continuationOf: vi.fn(async () => null) }))vi.mock('../../lib/sessionRepair.js', () => ({- claudeContinuation: vi.fn(async () => null),findLiveSession: vi.fn(async () => null),findResumedTranscript: vi.fn(async () => '/t/resumed.jsonl'),}))@@ -34,7 +35,7 @@ function resetLookups() {vi.mocked(findCursorTranscript).mockReset().mockResolvedValue('/t/cursor.jsonl')vi.mocked(findGrokTranscript).mockReset().mockResolvedValue('/t/grok.jsonl')vi.mocked(isRecentlyDeleted).mockReset().mockReturnValue(false)- vi.mocked(claudeContinuation).mockReset().mockResolvedValue(null)+ vi.mocked(continuationOf).mockReset().mockResolvedValue(null)vi.mocked(findLiveSession).mockReset().mockResolvedValue(null)vi.mocked(findResumedTranscript).mockReset().mockResolvedValue('/t/resumed.jsonl')}@@ -288,16 +289,17 @@ describe('binding a running process to its session', () => {vi.mocked(run.deps.registry.byProcess).mockReturnValue(agent({ transcriptPath: '/t/s1.jsonl' }))await run.binding.bindObservedAgent(observed())for (const continuation of [{ sessionId: 's1' }, { sessionId: 'known' }, { sessionId: 'deleted' }]) {- vi.mocked(claudeContinuation).mockResolvedValueOnce({ ...continuation, transcriptPath: '/t/x.jsonl' } as never)+ vi.mocked(continuationOf).mockResolvedValueOnce({ ...continuation, transcriptPath: '/t/x.jsonl' } as never)}vi.mocked(run.deps.registry.has).mockImplementation((sessionId: string) => sessionId === 'known')vi.mocked(isRecentlyDeleted).mockImplementation((sessionId?: string) => sessionId === 'deleted')for (let i = 0; i < 3; i++) await run.binding.bindObservedAgent(observed())expect(run.deps.registry.register).not.toHaveBeenCalled()- vi.mocked(claudeContinuation).mockResolvedValue({ sessionId: 's2', transcriptPath: '/t/s2.jsonl' } as never)+ vi.mocked(continuationOf).mockResolvedValue({ sessionId: 's2', transcriptPath: '/t/s2.jsonl' } as never)vi.mocked(run.deps.registry.register).mockReturnValueOnce({ entry: agent({ sessionId: 's2' }), ...meta({ isNew: true }) } as never)await run.binding.bindObservedAgent(observed())- expect(vi.mocked(run.deps.registry.register).mock.calls[0][0]).toMatchObject({ sessionId: 's2', source: 'claude-continuation' })+ expect(vi.mocked(run.deps.registry.register).mock.calls[0][0]).toMatchObject({ engine: 'claude', sessionId: 's2', source: 'claude-continuation', hookEvent: 'ClaudeContinuation' })+ expect(continuationOf).toHaveBeenCalledWith('claude', '/t/s1.jsonl')expect(run.deps.attachSession).toHaveBeenCalledTimes(1)vi.mocked(run.deps.registry.register).mockReturnValueOnce(null)await run.binding.bindObservedAgent(observed())@@ -309,7 +311,7 @@ describe('binding a running process to its session', () => {vi.mocked(run.deps.registry.byProcess).mockReturnValueOnce(agent({ engine: 'pi' } as Partial<RegisteredSession>)).mockReturnValueOnce(agent())await run.binding.bindObservedAgent(observed({ engine: 'pi' }))await run.binding.bindObservedAgent(observed())- expect(claudeContinuation).not.toHaveBeenCalled()+ expect(continuationOf).not.toHaveBeenCalled()})})diff --git a/cli/src/core/agents/bind.ts b/cli/src/core/agents/bind.tsindex ca608f745..536930732 100644--- a/cli/src/core/agents/bind.ts+++ b/cli/src/core/agents/bind.ts@@ -12,6 +12,8 @@ import { copilotSessionForPid, findCopilotTranscript } from '../../engines/copilimport { findCursorTranscript } from '../../engines/cursor/discovery.js'import { cursorDataDir } from '../../engines/cursor/home.js'import { findGrokTranscript } from '../../engines/grok/session.js'+import { continuationOf } from '../../engines/sessionFiles.js'+import { sessionStoreOf } from '../../engines/sessionStoreContracts.js'import type { TurnRecaps } from '../turns/recaps.js'import type { AutonomousDeviceInput } from '../deviceInput.js'import { isRecentlyDeleted } from '../../lib/deletedSessions.js'@@ -19,7 +21,7 @@ import { transcriptIsFirstTurn } from '../../lib/firstTurnReplay.js'import { sid } from '../../lib/log.js'import { projectDisplayName, type registry, type RegisteredSession } from '../../lib/registry.js'import type { SessionInputController } from '../../lib/sessionInput.js'-import { claudeContinuation, findLiveSession, findResumedTranscript } from '../../lib/sessionRepair.js'+import { findLiveSession, findResumedTranscript } from '../../lib/sessionRepair.js'import type { StoppedAgentStore } from '../../lib/stoppedAgents.js'import type { DiscoveredTerminalAgent } from '../../lib/terminalAgentDiscovery.js'import type { SwarmPromptScopes } from '../../teams/promptScope.js'@@ -238,22 +240,23 @@ export function createBinding({// SessionStart/UserPromptSubmit ever reaches us for it — the agent is left bound to a transcript// that has gone quiet forever while the real conversation continues one file over. Checked on// the same cadence this reconciler already re-observes every live process, so it costs nothing- // extra to ask.- if (observed.engine === 'claude' && agent.transcriptPath) {- const continuation = await claudeContinuation(agent.transcriptPath)+ // extra to ask. Its session store declares the marker (`continuation`), read in core with the kit.+ const store = sessionStoreOf(observed.engine)+ if (store?.continuation && agent.transcriptPath) {+ const continuation = await continuationOf(observed.engine, agent.transcriptPath)if (!continuation || continuation.sessionId === agent.sessionId|| registry.has(continuation.sessionId) || isRecentlyDeleted(continuation.sessionId)) return- console.log(`[discovery] ${sid(agent.agentId)} claude session continued ${sid(agent.sessionId)} → ${sid(continuation.sessionId)}`)+ console.log(`[discovery] ${sid(agent.agentId)} ${observed.engine} session continued ${sid(agent.sessionId)} → ${sid(continuation.sessionId)}`)const rotated = registry.register({- engine: 'claude',+ engine: observed.engine,sessionId: continuation.sessionId,transcriptPath: continuation.transcriptPath,cwd: observed.cwd,- source: 'claude-continuation',+ source: `${observed.engine}-continuation`,runtimes: observed.runtimes,primaryRuntimeKey: observed.primaryRuntimeKey,processIdentity: observed.processIdentity,- hookEvent: 'ClaudeContinuation',+ hookEvent: `${store.label}Continuation`,})if (rotated?.isNew) await handleRegistered(rotated.entry, rotated)returndiff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex be9726375..3682ccfc3 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -30,6 +30,7 @@ import {import { setUpWithin } from '../../lib/setUpWithin.js'import { writeGridConfigDir } from '../../lib/gridConfigDir.js'import { buildGridEngineLaunch, describeGridLaunch, gridConflictingEnvToClear, type GridLaunchMachine, type GridWebSearchStatus } from '../../lib/gridLaunch.js'+import { profileEnvironment } from '../../lib/engineHomes.js'import { DEFAULT_HARNESS_PERMISSION, freshHarnessEnvironment } from '../../lib/harnessDefaults.js'import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'import { engineHooks } from '../../engines/hooks.js'@@ -291,7 +292,8 @@ export function createAgentCreator({// a freshly-minted pane id, and that collision clears on its own on the very next pane.prepareApiTools(cwd, engine)// Mutually exclusive with a grid (backendSocket.ts refuses the two together): a chosen Codex- // profile becomes the new session's CODEX_HOME, the same `-e` mechanism a grid's own env rides.+ // profile becomes the new session's CODEX_HOME (its session store's variable, lib/engineHomes.ts+ // `profileEnvironment`), the same `-e` mechanism a grid's own env rides.const result = await createAndRegisterPane({tmuxBackend,registry,@@ -299,7 +301,7 @@ export function createAgentCreator({cwd,sessionLabel: label,argv,- env: freshHarnessEnvironment(engine, mergedLaunchEnv(mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined), dshEnv),+ env: freshHarnessEnvironment(engine, mergedLaunchEnv(mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? profileEnvironment(engine, codexHome) : undefined), dshEnv),scmLaunchEnv(scmLaunchRecord)), !!grid || !!resumeSessionId,permissionMode ?? (bypassPermission ? DEFAULT_HARNESS_PERMISSION : 'ask')),grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.tsindex 0db87edb1..2efb667a2 100644--- a/cli/src/core/engines/hooks.spec.ts+++ b/cli/src/core/engines/hooks.spec.ts@@ -3,9 +3,7 @@ import * as hooks from '../../lib/hooks.js'import { engineHooks } from '../../engines/hooks.js'import type { RegisteredSession } from '../../lib/registry.js'import { processRows } from '../../lib/terminalAgentDiscovery.js'-import { dirname } from 'node:path'-import { env } from '../../config/env.js'-import { adoptEngineHomes, movedEngineHomes } from '../../lib/engineHomes.js'+import { adoptHomes, movedHomes } from '../../lib/engineHomes.js'import { createEngineHooks, installEngineHooks, installOpencodePluginBeforeSpawn, PROCESS_RECORD_WAIT_MS, type EngineHookDeps } from './hooks.js'import { loadEngine } from '../../engines/inProcess.js'@@ -17,8 +15,8 @@ vi.mock('../../engines/hooks.js', async (real) => {} }})vi.mock('../../lib/engineHomes.js', () => ({- adoptEngineHomes: vi.fn(() => ({ claude: null, codex: null })),- movedEngineHomes: vi.fn(() => ({ claude: [], codex: [] })),+ adoptHomes: vi.fn(() => ({ claude: null, codex: null })),+ movedHomes: vi.fn(() => []),}))// The other engines' installers load through the loader; a test may make that load fail.const loading = vi.hoisted(() => ({ fail: false }))@@ -342,7 +340,7 @@ describe('installing every engine\'s hooks', () => {})it('only the engines asked for (HOOK_INSTALL_ENGINES), the homes they moved included', async () => {- vi.mocked(movedEngineHomes).mockReturnValueOnce({ claude: ['/w/claude'], codex: ['/w/codex'] })+ vi.mocked(movedHomes).mockReturnValueOnce(['/w/claude']).mockReturnValueOnce(['/w/codex'])await installEngineHooks(4242, { only: new Set(['codex']), environment: {} })expect(engineHooks.codex.install).toHaveBeenCalledWith(4242)expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/w/codex')@@ -369,25 +367,26 @@ describe('installing every engine\'s hooks', () => {// lib/engineHomes.ts: with CLAUDE_CONFIG_DIR or CODEX_HOME in the person's profile, no agent ever bound.it('puts the hooks in every home adopted on an earlier boot, at every start', async () => {- vi.mocked(movedEngineHomes).mockReturnValueOnce({ claude: ['/w/claude'], codex: ['/w/codex'] })+ vi.mocked(movedHomes).mockReturnValueOnce(['/w/claude']).mockReturnValueOnce(['/w/codex'])await installEngineHooks(4242, { environment: {} })expect(engineHooks.claude.installIn).toHaveBeenCalledWith(4242, '/w/claude')expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/w/codex')+ expect(vi.mocked(movedHomes).mock.calls).toEqual([['claude'], ['codex']])})it('adopts the homes its own environment moves, then the login shell\'s once that is read, and installs there', async () => {const log = vi.spyOn(console, 'log').mockImplementation(() => {})const own = { CLAUDE_CONFIG_DIR: '/m/claude' }const shell = { CODEX_HOME: '/s/codex' }- vi.mocked(adoptEngineHomes)+ vi.mocked(adoptHomes).mockReturnValueOnce({ claude: '/m/claude', codex: null }).mockReturnValueOnce({ claude: null, codex: '/s/codex' })void installEngineHooks(4242, { environment: own, loginShell: Promise.resolve(shell) })- expect(adoptEngineHomes).toHaveBeenCalledWith(own, { claudeHome: dirname(env.CLAUDE_PROJECTS_DIR), codexHome: env.CODEX_HOME })+ expect(adoptHomes).toHaveBeenCalledWith(own)expect(engineHooks.claude.installIn).toHaveBeenCalledWith(4242, '/m/claude')expect(log).toHaveBeenCalledWith('[hooks] engines keep their data elsewhere here: Claude Code in /m/claude')await Promise.resolve()- expect(adoptEngineHomes).toHaveBeenLastCalledWith(shell, { claudeHome: dirname(env.CLAUDE_PROJECTS_DIR), codexHome: env.CODEX_HOME })+ expect(adoptHomes).toHaveBeenLastCalledWith(shell)expect(engineHooks.codex.installIn).toHaveBeenCalledWith(4242, '/s/codex')expect(log).toHaveBeenCalledWith('[hooks] engines keep their data elsewhere here: Codex in /s/codex')})@@ -395,7 +394,7 @@ describe('installing every engine\'s hooks', () => {it('reads the daemon\'s own environment when none is given, and logs nothing when nothing moved', async () => {const log = vi.spyOn(console, 'log').mockImplementation(() => {})await installEngineHooks(4242)- expect(adoptEngineHomes).toHaveBeenCalledWith(process.env, expect.anything())+ expect(adoptHomes).toHaveBeenCalledWith(process.env)expect(log).not.toHaveBeenCalled()})diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.tsindex 6ab8b3f89..b1e76144d 100644--- a/cli/src/core/engines/hooks.ts+++ b/cli/src/core/engines/hooks.ts@@ -4,11 +4,10 @@** Moved verbatim out of `runForeground` (the core boundary, step 12: docs/design/2026-10-03-harnessd.md).*/-import { dirname } from 'node:path'import { engineHooks } from '../../engines/hooks.js'-import { env } from '../../config/env.js'+import { sessionStoreContracts, type SessionStoreEngine } from '../../engines/sessionStoreContracts.js'import { chooseHookAgent, type HookServerHandlers } from '../../hookServer.js'-import { adoptEngineHomes, movedEngineHomes } from '../../lib/engineHomes.js'+import { adoptHomes, movedHomes } from '../../lib/engineHomes.js'import { loadEngine, type InProcessModules } from '../../engines/inProcess.js'import { sid } from '../../lib/log.js'import type { registry, RegisteredSession } from '../../lib/registry.js'@@ -232,22 +231,21 @@ export async function installEngineHooks(port: number, options: InstallEngineHooconsole.warn(`[hooks] ${vendor} install skipped · ${error instanceof Error ? error.message : error}`)}}- // The homes the person moved (lib/engineHomes.ts) get the hooks too: every one adopted before, those- // the daemon's own environment names, and those of the login shell every engine is launched through- // once it has been read. That read is never waited on (cli.ts), so an engine started in the first- // seconds of a daemon's very first start with a moved home may miss its first hook.- const installIn = (homes: { claude: Array<string | null>; codex: Array<string | null> }): void => {- for (const engine of Object.keys(homes) as Array<keyof typeof homes>) {- for (const home of homes[engine]) if (home) hookStep(engine, () => engineHooks[engine].installIn(port, home))- }+ // The homes the person moved (lib/engineHomes.ts, by each engine's declared session store) get the hooks+ // too: every one adopted before, those the daemon's own environment names, and those of the login shell+ // every engine is launched through once it has been read. That read is never waited on (cli.ts), so an+ // engine started in the first seconds of a daemon's very first start with a moved home may miss its first hook.+ const installIn = (homes: Array<[SessionStoreEngine, string]>): void => {+ for (const [engine, home] of homes) hookStep(engine, () => engineHooks[engine].installIn(port, home))}const adopt = (environment: NodeJS.ProcessEnv): void => {- const moved = adoptEngineHomes(environment, { claudeHome: dirname(env.CLAUDE_PROJECTS_DIR), codexHome: env.CODEX_HOME })- if (!moved.claude && !moved.codex) return- console.log(`[hooks] engines keep their data elsewhere here: ${[moved.claude && `Claude Code in ${moved.claude}`, moved.codex && `Codex in ${moved.codex}`].filter(Boolean).join(', ')}`)- installIn({ claude: [moved.claude], codex: [moved.codex] })+ const moved = (Object.entries(adoptHomes(environment)) as Array<[SessionStoreEngine, string | null]>)+ .filter((found): found is [SessionStoreEngine, string] => !!found[1])+ if (!moved.length) return+ console.log(`[hooks] engines keep their data elsewhere here: ${moved.map(([engine, home]) => `${sessionStoreContracts[engine].product} in ${home}`).join(', ')}`)+ installIn(moved)}- installIn(movedEngineHomes())+ installIn((Object.keys(sessionStoreContracts) as SessionStoreEngine[]).flatMap((engine) => movedHomes(engine).map((home): [SessionStoreEngine, string] => [engine, home])))adopt(options.environment ?? process.env)void options.loginShell?.then(adopt)for (const [engine, hooks] of Object.entries(engineHooks)) hookStep(engine, () => hooks.install(port))diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex ed3ddb233..73711919a 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -58,7 +58,8 @@ import { HERMES_SYSTEM_MANAGED_DIR } from '../lib/gridWebMcp.js'import { writeGridConfigDir } from '../lib/gridConfigDir.js'import { tmuxSupportsSessionEnv } from '../lib/tmuxVersion.js'import { clearDeleted, isRecentlyDeleted, markDeleted } from '../lib/deletedSessions.js'-import { claudeProcessSession, findLiveSession, findResumedTranscript } from '../lib/sessionRepair.js'+import { findLiveSession, findResumedTranscript } from '../lib/sessionRepair.js'+import { processSessionOf } from '../engines/sessionStores.js'import { handoffProviderDeps } from '../lib/handoffDiscovery.js'import { TmuxBackend } from '../lib/tmuxBackend.js'import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from '../lib/hostTheme.js'@@ -1178,7 +1179,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {mirror,databaseHistory,findLiveSession,- claudeProcessSession,+ processSession: processSessionOf,isRecentlyDeleted,findResumedTranscript,validTranscriptPath,diff --git a/cli/src/engines/README.md b/cli/src/engines/README.mdindex c084e55c4..35433e25e 100644--- a/cli/src/engines/README.md+++ b/cli/src/engines/README.md@@ -23,7 +23,9 @@ worker ([hooks](../../../docs/design/2026-10-08-engine-hooks.md)). So are their`codex/launch.ts`): Codex's pane startup probe and retry, its own-login provider, the harness context and envflags, folder trust and the resume repair, applied by `kit/launchStartup.ts`, `kit/launchArgs.ts`,`kit/folderTrust.ts` and `kit/resumeRepair.ts`, and what discovery reads off their processes and transcripts-(`claude/discoveryContract.ts`, `codex/discoveryContract.ts`, `kit/processFacts.ts`, `kit/projectFolder.ts`) ([launch](../../../docs/design/2026-10-08-engine-launch.md)). Claude Code and Codex history/last-turn reads,+(`claude/discoveryContract.ts`, `codex/discoveryContract.ts`, `kit/processFacts.ts`, `kit/projectFolder.ts`), and+where they keep their sessions, which the registry, session repair, Stop's capture and the handoff read+(`claude/sessionStore.ts`, `codex/sessionStore.ts`, `kit/sessionRecords.ts`, `kit/continuation.ts`) ([launch](../../../docs/design/2026-10-08-engine-launch.md)). Claude Code and Codex history/last-turn reads,live transcript parsing, runtime profiles/catalogs, screen interpretation, submission readings, model-control drivers, question navigation and Codex's app-server connection run on demand in supervised workers;the other facets still run in core. Explicit inline mode and older masters retain inline implementations. See[hooks](../../../docs/design/2026-10-08-engine-hooks.md),@@ -433,7 +435,7 @@ Only needed for the capabilities your agent actually has. Skip what does not app| File | What to add ||---|---|| `lib/sessionInput.ts` | How text is submitted, and how long to wait before deciding the submit failed. Muse writes its `started` record as soon as it accepts a prompt, so 6 seconds is enough; a slower agent needs a longer window. Claude Code and Codex declare theirs in `<engine>/submissionPolicy.ts` and read their composer in `<engine>/submission.ts`, in their worker |-| `lib/sessionRepair.ts` | Rebinding a pane to its session after a restart |+| `lib/sessionRepair.ts` | Rebinding a pane to its session after a restart. Claude Code and Codex declare their store in `<engine>/sessionStore.ts` instead, and `findLiveSession` applies it || `lib/oneshot.ts` | Running a single prompt outside an interactive session |## Stage E — the product surfacesdiff --git a/cli/src/engines/__fixtures__/session-store.golden.json b/cli/src/engines/__fixtures__/session-store.golden.jsonnew file mode 100644index 000000000..5a51ab2d2--- /dev/null+++ b/cli/src/engines/__fixtures__/session-store.golden.json@@ -0,0 +1,265 @@+{+"homes": {+ "none moved": {"moved":{"claude":[],"codex":[]},"claudeRoots":["<root>/claude/projects"],"codexRoots":["<root>/codex"],"codexSettingRoots":["<root>/codex"],"sessionCodexHome":["<root>/profile","<root>/codex","<root>/codex","<root>/codex","<root>/codex","<root>/codex"],"sessionClaudeHome":["<root>/claude","<root>/claude","<root>/claude","<root>/claude"],"saved":null},+ "moved": {"adopted":{"claude":"<root>/moved-claude","codex":"<root>/moved-codex"},"moved":{"claude":["<root>/moved-claude"],"codex":["<root>/moved-codex"]},"claudeRoots":["<root>/claude/projects","<root>/moved-claude/projects"],"codexRoots":["<root>/codex","<root>/moved-codex"],"codexSettingRoots":["<root>/codex","<root>/moved-codex"],"sessionCodexHome":["<root>/profile","<root>/moved-codex","<root>/moved-codex","<root>/codex","<root>/codex","<root>/codex"],"sessionClaudeHome":["<root>/moved-claude","<root>/claude","<root>/claude","<root>/claude"],"saved":"{\"claude\":[\"<root>/moved-claude\"],\"codex\":[\"<root>/moved-codex\"]}\n"},+ "moved again": {"adopted":{"claude":null,"codex":null},"moved":{"claude":["<root>/moved-claude"],"codex":["<root>/moved-codex"]},"claudeRoots":["<root>/claude/projects","<root>/moved-claude/projects"],"codexRoots":["<root>/codex","<root>/moved-codex"],"codexSettingRoots":["<root>/codex","<root>/moved-codex"],"sessionCodexHome":["<root>/profile","<root>/moved-codex","<root>/moved-codex","<root>/codex","<root>/codex","<root>/codex"],"sessionClaudeHome":["<root>/moved-claude","<root>/claude","<root>/claude","<root>/claude"],"saved":"{\"claude\":[\"<root>/moved-claude\"],\"codex\":[\"<root>/moved-codex\"]}\n"},+ "moved to the defaults, a relative path and a tilde": {"adopted":[{"claude":null,"codex":null},{"claude":null,"codex":null},{"claude":"<root>/moved-claude","codex":"<root>/moved-codex"}],"moved":{"claude":["<root>/moved-claude"],"codex":["<root>/moved-codex"]},"claudeRoots":["<root>/claude/projects","<root>/moved-claude/projects"],"codexRoots":["<root>/codex","<root>/moved-codex"],"codexSettingRoots":["<root>/codex","<root>/moved-codex"],"sessionCodexHome":["<root>/profile","<root>/moved-codex","<root>/moved-codex","<root>/codex","<root>/codex","<root>/codex"],"sessionClaudeHome":["<root>/moved-claude","<root>/claude","<root>/claude","<root>/claude"],"saved":"{\"claude\":[\"<root>/moved-claude\"],\"codex\":[\"<root>/moved-codex\"]}\n"},+ "remembered": {"moved":{"claude":["<root>/moved-claude"],"codex":["<root>/moved-codex"]},"claudeRoots":["<root>/claude/projects","<root>/moved-claude/projects"],"codexRoots":["<root>/codex","<root>/moved-codex"],"codexSettingRoots":["<root>/codex","<root>/moved-codex"],"sessionCodexHome":["<root>/profile","<root>/moved-codex","<root>/moved-codex","<root>/codex","<root>/codex","<root>/codex"],"sessionClaudeHome":["<root>/moved-claude","<root>/claude","<root>/claude","<root>/claude"],"saved":"{\"claude\":[\"<root>/moved-claude\"],\"codex\":[\"<root>/moved-codex\"]}\n"},+ "launch homes · no variables": {"codex":"<root>/codex","codexProfile":"<root>/profile","claude":"<home folder>"},+ "launch homes · moved": {"codex":"<root>/moved-codex","codexProfile":"<root>/profile","claude":"<root>/moved-claude"},+ "launch homes · relative": {"codex":"<root>/codex","codexProfile":"<root>/profile","claude":"<home folder>"},+ "launch homes · trailing slash": {"codex":"<root>/moved-codex","codexProfile":"<root>/profile","claude":"<root>/moved-claude"}+},+"transcripts": {+ "claude · claudeA": [true,true,true,true],+ "claude · claudeSub": [true,true,true,true],+ "claude · claudeOldSub": [true,true,true,true],+ "claude · claudeB": [true,true,true,true],+ "claude · claudeMoved": [true,true,true,true],+ "claude · claudeContinued": [true,true,true,true],+ "claude · linkIn": [true,true,true,true],+ "claude · missingClaude": [false,false,true,true],+ "codex · codexA": [true,false,true,false],+ "codex · codexChild": [true,false,true,false],+ "codex · codexB": [true,false,true,false],+ "codex · codexMoved": [true,false,true,false],+ "codex · codexProfile": [false,true,false,true],+ "codex · missingCodex": [false,false,true,false],+ "cursor · cursor": [true,true,true,true],+ "not moved · claudeMoved": [false,false],+ "not moved · codexMoved": [false,false],+ "keeps a file": {"claude":true,"codex":true,"cursor":true,"pi":true,"opencode":false,"kilo":false,"hermes":false,"devin":false,"terminal":false}+},+"find": {+ "resumed · default homes · claude · aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa": "<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",+ "resumed · default homes · claude · 12121212-7777-4777-8777-121212121212": null,+ "resumed · default homes · claude · not-hex": null,+ "resumed · default homes · claude · eeeeeeee-5555-4555-8555-eeeeeeeeeeee": null,+ "resumed · default homes · codex · aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa": "<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",+ "resumed · default homes · codex · dddddddd-4444-4444-8444-dddddddddddd": "<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-01-dddddddd-4444-4444-8444-dddddddddddd.jsonl",+ "resumed · default homes · codex · 12121212-7777-4777-8777-121212121212": null,+ "resumed · default homes · codex · ffffffff-6666-4666-8666-ffffffffffff": null,+ "resumed · default homes · codex · ffffffff-6666-4666-8666-ffffffffffff · profile": "<root>/profile/sessions/2026/10/08/rollout-2026-10-08T00-00-04-ffffffff-6666-4666-8666-ffffffffffff.jsonl",+ "resumed · default homes · codex · aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa · profile": null,+ "resumed · default homes · codex · short": null,+ "resumed · default homes · cursor · aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa": null,+ "resumed · default homes · opencode · aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa": null,+ "live · default homes · claude · /work/a": null,+ "live · default homes · claude · /work/b": null,+ "live · default homes · claude · /work/c": null,+ "live · default homes · claude · /linked-a": null,+ "live · default homes · claude · /work/a · bornOnly": null,+ "live · default homes · claude · /elsewhere": null,+ "live · default homes · codex · /work/a": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "live · default homes · codex · /work/b": {"sessionId":"bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-02-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl"},+ "live · default homes · codex · /work/c": null,+ "live · default homes · codex · /work/a · codexHome": {"sessionId":"ffffffff-6666-4666-8666-ffffffffffff","transcriptPath":"<root>/profile/sessions/2026/10/08/rollout-2026-10-08T00-00-04-ffffffff-6666-4666-8666-ffffffffffff.jsonl"},+ "live · default homes · codex · /work/a · pid": null,+ "live · default homes · claude · started later": null,+ "resumed · moved homes · claude · aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa": "<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",+ "resumed · moved homes · claude · 12121212-7777-4777-8777-121212121212": "<root>/moved-claude/projects/-work-c/12121212-7777-4777-8777-121212121212.jsonl",+ "resumed · moved homes · claude · not-hex": null,+ "resumed · moved homes · claude · eeeeeeee-5555-4555-8555-eeeeeeeeeeee": null,+ "resumed · moved homes · codex · aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa": "<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",+ "resumed · moved homes · codex · dddddddd-4444-4444-8444-dddddddddddd": "<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-01-dddddddd-4444-4444-8444-dddddddddddd.jsonl",+ "resumed · moved homes · codex · 12121212-7777-4777-8777-121212121212": "<root>/moved-codex/sessions/2026/10/08/rollout-2026-10-08T00-00-03-12121212-7777-4777-8777-121212121212.jsonl",+ "resumed · moved homes · codex · ffffffff-6666-4666-8666-ffffffffffff": null,+ "resumed · moved homes · codex · ffffffff-6666-4666-8666-ffffffffffff · profile": "<root>/profile/sessions/2026/10/08/rollout-2026-10-08T00-00-04-ffffffff-6666-4666-8666-ffffffffffff.jsonl",+ "resumed · moved homes · codex · aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa · profile": null,+ "resumed · moved homes · codex · short": null,+ "resumed · moved homes · cursor · aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa": null,+ "resumed · moved homes · opencode · aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa": null,+ "live · moved homes · claude · /work/a": null,+ "live · moved homes · claude · /work/b": null,+ "live · moved homes · claude · /work/c": {"sessionId":"12121212-7777-4777-8777-121212121212","transcriptPath":"<root>/moved-claude/projects/-work-c/12121212-7777-4777-8777-121212121212.jsonl"},+ "live · moved homes · claude · /linked-a": null,+ "live · moved homes · claude · /work/a · bornOnly": null,+ "live · moved homes · claude · /elsewhere": null,+ "live · moved homes · codex · /work/a": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "live · moved homes · codex · /work/b": {"sessionId":"bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-02-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl"},+ "live · moved homes · codex · /work/c": {"sessionId":"12121212-7777-4777-8777-121212121212","transcriptPath":"<root>/moved-codex/sessions/2026/10/08/rollout-2026-10-08T00-00-03-12121212-7777-4777-8777-121212121212.jsonl"},+ "live · moved homes · codex · /work/a · codexHome": {"sessionId":"ffffffff-6666-4666-8666-ffffffffffff","transcriptPath":"<root>/profile/sessions/2026/10/08/rollout-2026-10-08T00-00-04-ffffffff-6666-4666-8666-ffffffffffff.jsonl"},+ "live · moved homes · codex · /work/a · pid": null,+ "live · moved homes · claude · started later": null,+ "live · claude · a subagent below its folder": {"sessionId":"abababab-8888-4888-8888-abababababab","transcriptPath":"<root>/claude/projects/-work-d/abababab-8888-4888-8888-abababababab.jsonl"},+ "live · claude · a subagent by its first flag": {"sessionId":"cdcdcdcd-9999-4999-8999-cdcdcdcdcdcd","transcriptPath":"<root>/claude/projects/-work-e/cdcdcdcd-9999-4999-8999-cdcdcdcdcdcd.jsonl"},+ "live · claude · a moved home below a subagents folder": {"sessionId":"eeeeeeee-5555-4555-8555-eeeeeeeeeeee","transcriptPath":"<root>/subagents/home/projects/-work-f/eeeeeeee-5555-4555-8555-eeeeeeeeeeee.jsonl"},+ "process record · default homes · local start": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "process record · default homes · linked folder": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "process record · default homes · another start": null,+ "process record · default homes · utc start": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "process record · default homes · utc record, local start": null,+ "process record · default homes · another pid": null,+ "process record · default homes · another folder": null,+ "process record · default homes · no id": null,+ "process record · default homes · no transcript": null,+ "process record · default homes · no start": null,+ "process record · default homes · moved home": null,+ "process record · default homes · unreadable": null,+ "process record · default homes · no record": null,+ "process record · default homes · bad pid": null,+ "process record · default homes · bad start": null,+ "process record · default homes · codex": null,+ "live · default homes · claude · pid with a record": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "process record · moved homes · local start": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "process record · moved homes · linked folder": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "process record · moved homes · another start": null,+ "process record · moved homes · utc start": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "process record · moved homes · utc record, local start": null,+ "process record · moved homes · another pid": null,+ "process record · moved homes · another folder": null,+ "process record · moved homes · no id": null,+ "process record · moved homes · no transcript": null,+ "process record · moved homes · no start": null,+ "process record · moved homes · moved home": {"sessionId":"12121212-7777-4777-8777-121212121212","transcriptPath":"<root>/moved-claude/projects/-work-c/12121212-7777-4777-8777-121212121212.jsonl"},+ "process record · moved homes · unreadable": null,+ "process record · moved homes · no record": null,+ "process record · moved homes · bad pid": null,+ "process record · moved homes · bad start": null,+ "process record · moved homes · codex": null,+ "live · moved homes · claude · pid with a record": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "open files · its rollout · a": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "open files · its rollout · c": null,+ "open files · a sub-agent rollout · a": null,+ "open files · a sub-agent rollout · c": null,+ "open files · two rollouts · a": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "open files · two rollouts · c": null,+ "open files · the same rollout twice · a": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "open files · the same rollout twice · c": null,+ "open files · outside the sessions · a": null,+ "open files · outside the sessions · c": null,+ "open files · another folder · a": null,+ "open files · another folder · c": null,+ "open files · a moved home · a": null,+ "open files · a moved home · c": {"sessionId":"12121212-7777-4777-8777-121212121212","transcriptPath":"<root>/moved-codex/sessions/2026/10/08/rollout-2026-10-08T00-00-03-12121212-7777-4777-8777-121212121212.jsonl"},+ "open files · nothing · a": null,+ "open files · nothing · c": null,+ "open files · a rollout and another session-shaped file": {"sessionId":"bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb","transcriptPath":"<root>/held/rollout-held-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl"},+ "open files · one root": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},+ "open files · claude": null,+ "process files · own rollout": ["<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"],+ "process files · node launcher": ["/dev/null","<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-02-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl"],+ "process files · nodejs launcher": ["<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-02-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl"],+ "process files · not a launcher": ["/dev/null"],+ "process files · no process table": ["/dev/null"],+ "process files · two children": []+},+"continuation": {+ "continued, with a turn": {"sessionId":"cccccccc-3333-4333-8333-cccccccccccc","transcriptPath":"<root>/claude/projects/-work-b/cccccccc-3333-4333-8333-cccccccccccc.jsonl"},+ "continued, background": null,+ "continued, next missing": null,+ "continued, next is a folder": null,+ "continued, next is large": {"sessionId":"d0d0d0d0-0000-4000-8000-d0d0d0d0d0d0","transcriptPath":"<root>/claude/projects/-work-b/d0d0d0d0-0000-4000-8000-d0d0d0d0d0d0.jsonl"},+ "continued, next turn as assistant": {"sessionId":"e0e0e0e0-0000-4000-8000-e0e0e0e0e0e0","transcriptPath":"<root>/claude/projects/-work-b/e0e0e0e0-0000-4000-8000-e0e0e0e0e0e0.jsonl"},+ "continued, next is large without a turn": {"sessionId":"f0f0f0f0-0000-4000-8000-f0f0f0f0f0f0","transcriptPath":"<root>/claude/projects/-work-b/f0f0f0f0-0000-4000-8000-f0f0f0f0f0f0.jsonl"},+ "not the last line": null,+ "a marker without an id": null,+ "a marker with a number": null,+ "invalid JSON last": null,+ "empty": null,+ "trailing blank lines": {"sessionId":"cccccccc-3333-4333-8333-cccccccccccc","transcriptPath":"<root>/claude/projects/-work-b/cccccccc-3333-4333-8333-cccccccccccc.jsonl"},+ "missing file": null,+ "codex": null+},+"rollouts": {+ "meta · a conversation": {"id":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","isSubagent":false,"parentThreadId":null,"cwd":"/w"},+ "meta · a sub-agent of a parent": {"id":"dddddddd-4444-4444-8444-dddddddddddd","isSubagent":true,"parentThreadId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","cwd":"/w"},+ "meta · a sub-agent without a parent": {"id":"dddddddd-4444-4444-8444-dddddddddddd","isSubagent":true,"parentThreadId":null,"cwd":"/w"},+ "meta · a null sub-agent": {"id":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","isSubagent":false,"parentThreadId":null,"cwd":"/w"},+ "meta · an empty parent": {"id":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","isSubagent":true,"parentThreadId":null,"cwd":"/w"},+ "meta · no id, no cwd": {"id":"","isSubagent":false,"parentThreadId":null,"cwd":null},+ "meta · an id that is not text": {"id":"","isSubagent":false,"parentThreadId":null,"cwd":null},+ "meta · no payload": null,+ "meta · another record first": null,+ "meta · blank lines first": {"id":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","isSubagent":false,"parentThreadId":null,"cwd":"/w"},+ "meta · invalid JSON": null,+ "meta · empty": null,+ "meta · a first line past 128 KiB": null,+ "meta · a first line just under 128 KiB": {"id":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","isSubagent":false,"parentThreadId":null,"cwd":"/w"},+ "meta · a first line 512 bytes past 128 KiB": null,+ "meta · missing": null,+ "meta · claude": null,+ "find · nested": "<root>/walk/2026/10/rollout-x-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",+ "find · in a dotted folder": null,+ "find · not jsonl": null,+ "find · an id too short": null,+ "find · an id with a slash": null,+ "find · a missing root": null,+ "find · every home · default": ["<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl",null,null],+ "find · every home · moved": ["<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","<root>/moved-codex/sessions/2026/10/08/rollout-2026-10-08T00-00-03-12121212-7777-4777-8777-121212121212.jsonl",null],+ "find · claude": null+},+"registry": {+ "default homes · a codex parent overwritten by its sub-agent": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"08","codexHome":null,"bound":true}],"persisted":[{"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"08"}],"logged":["[registry] repaired Codex parent aaaaaaaa transcript after child hook overwrite"]},+ "default homes · a codex row overwritten by another parent's sub-agent": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "default homes · a codex parent whose own rollout is gone": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "default homes · a codex parent on a profile, overwritten": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":"<root>/profile","bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "default homes · a codex row with its own rollout": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"p","codexHome":null,"bound":true}],"persisted":[{"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"p"}],"logged":[]},+ "default homes · a codex row in a moved home": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "default homes · a codex row on a profile": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"ffffffff-6666-4666-8666-ffffffffffff","transcriptPath":"<root>/profile/sessions/2026/10/08/rollout-2026-10-08T00-00-04-ffffffff-6666-4666-8666-ffffffffffff.jsonl","projectDir":"p","codexHome":"<root>/profile","bound":true}],"persisted":[{"sessionId":"ffffffff-6666-4666-8666-ffffffffffff","transcriptPath":"<root>/profile/sessions/2026/10/08/rollout-2026-10-08T00-00-04-ffffffff-6666-4666-8666-ffffffffffff.jsonl","projectDir":"p"}],"logged":[]},+ "default homes · a codex row on a profile, with the default rollout": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":"<root>/profile","bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "default homes · a codex row without a transcript": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "default homes · a claude row": {"loaded":[{"agentId":"h1","engine":"claude","sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"p","codexHome":null,"bound":true}],"persisted":[{"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"p"}],"logged":[]},+ "default homes · a claude row in a moved home": {"loaded":[{"agentId":"h1","engine":"claude","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "default homes · a claude row outside its projects": {"loaded":[{"agentId":"h1","engine":"claude","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "default homes · a claude row without a transcript": {"loaded":[{"agentId":"h1","engine":"claude","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "default homes · a cursor row without a transcript": {"loaded":[{"agentId":"h1","engine":"cursor","sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":true}],"persisted":[{"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "default homes · an unbound row": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "moved homes · a codex parent overwritten by its sub-agent": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"08","codexHome":null,"bound":true}],"persisted":[{"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"08"}],"logged":["[registry] repaired Codex parent aaaaaaaa transcript after child hook overwrite"]},+ "moved homes · a codex row overwritten by another parent's sub-agent": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "moved homes · a codex parent whose own rollout is gone": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "moved homes · a codex parent on a profile, overwritten": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":"<root>/profile","bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "moved homes · a codex row with its own rollout": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"p","codexHome":null,"bound":true}],"persisted":[{"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"p"}],"logged":[]},+ "moved homes · a codex row in a moved home": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"12121212-7777-4777-8777-121212121212","transcriptPath":"<root>/moved-codex/sessions/2026/10/08/rollout-2026-10-08T00-00-03-12121212-7777-4777-8777-121212121212.jsonl","projectDir":"p","codexHome":null,"bound":true}],"persisted":[{"sessionId":"12121212-7777-4777-8777-121212121212","transcriptPath":"<root>/moved-codex/sessions/2026/10/08/rollout-2026-10-08T00-00-03-12121212-7777-4777-8777-121212121212.jsonl","projectDir":"p"}],"logged":[]},+ "moved homes · a codex row on a profile": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"ffffffff-6666-4666-8666-ffffffffffff","transcriptPath":"<root>/profile/sessions/2026/10/08/rollout-2026-10-08T00-00-04-ffffffff-6666-4666-8666-ffffffffffff.jsonl","projectDir":"p","codexHome":"<root>/profile","bound":true}],"persisted":[{"sessionId":"ffffffff-6666-4666-8666-ffffffffffff","transcriptPath":"<root>/profile/sessions/2026/10/08/rollout-2026-10-08T00-00-04-ffffffff-6666-4666-8666-ffffffffffff.jsonl","projectDir":"p"}],"logged":[]},+ "moved homes · a codex row on a profile, with the default rollout": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":"<root>/profile","bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "moved homes · a codex row without a transcript": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "moved homes · a claude row": {"loaded":[{"agentId":"h1","engine":"claude","sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"p","codexHome":null,"bound":true}],"persisted":[{"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","projectDir":"p"}],"logged":[]},+ "moved homes · a claude row in a moved home": {"loaded":[{"agentId":"h1","engine":"claude","sessionId":"12121212-7777-4777-8777-121212121212","transcriptPath":"<root>/moved-claude/projects/-work-c/12121212-7777-4777-8777-121212121212.jsonl","projectDir":"p","codexHome":null,"bound":true}],"persisted":[{"sessionId":"12121212-7777-4777-8777-121212121212","transcriptPath":"<root>/moved-claude/projects/-work-c/12121212-7777-4777-8777-121212121212.jsonl","projectDir":"p"}],"logged":[]},+ "moved homes · a claude row outside its projects": {"loaded":[{"agentId":"h1","engine":"claude","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "moved homes · a claude row without a transcript": {"loaded":[{"agentId":"h1","engine":"claude","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "moved homes · a cursor row without a transcript": {"loaded":[{"agentId":"h1","engine":"cursor","sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":true}],"persisted":[{"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":null,"projectDir":"p"}],"logged":[]},+ "moved homes · an unbound row": {"loaded":[{"agentId":"h1","engine":"codex","sessionId":"","transcriptPath":null,"projectDir":"p","codexHome":null,"bound":false}],"persisted":[{"sessionId":"","transcriptPath":null,"projectDir":"p"}],"logged":[]}+},+"capture": {+ "capture · claude, no transcript": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","source":null},+ "capture · claude, a stale transcript": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","source":null},+ "capture · claude, its transcript": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","source":null},+ "capture · claude, in a moved home": {"sessionId":"12121212-7777-4777-8777-121212121212","transcriptPath":"<root>/moved-claude/projects/-work-c/12121212-7777-4777-8777-121212121212.jsonl","source":null},+ "capture · claude, unknown": {"sessionId":"eeeeeeee-5555-4555-8555-eeeeeeeeeeee","transcriptPath":null,"source":null},+ "capture · codex, no transcript": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-00-aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl","source":null},+ "capture · codex, on a profile": {"sessionId":"ffffffff-6666-4666-8666-ffffffffffff","transcriptPath":"<root>/profile/sessions/2026/10/08/rollout-2026-10-08T00-00-04-ffffffff-6666-4666-8666-ffffffffffff.jsonl","source":null},+ "capture · codex, a sub-agent id": {"sessionId":"dddddddd-4444-4444-8444-dddddddddddd","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-01-dddddddd-4444-4444-8444-dddddddddddd.jsonl","source":null},+ "capture · opencode": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":null,"source":null},+ "capture · terminal": {"sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":null,"source":null},+ "capture · claude, unbound, no process": {"sessionId":"","transcriptPath":null,"source":null},+ "handoff · claude": {"found":{"engine":"claude","sessionId":"aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa","transcriptPath":"<root>/claude/projects/-work-a/aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa.jsonl"},"calls":[["processSession","claude",42,"<root>/work/a","<start>"]]},+ "handoff · codex": {"found":{"engine":"codex","sessionId":"bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-02-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl"},"calls":[["findLiveSession","codex","<root>/work/a","<start>",{"bornOnly":true,"pid":42,"codexHome":"<root>/profile"}]]},+ "handoff · pi": {"found":{"engine":"pi","sessionId":"bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-02-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl"},"calls":[["findLiveSession","pi","<root>/work/a","<start>",{"bornOnly":true,"pid":42}]]},+ "handoff · opencode": {"found":null,"calls":[]},+ "handoff · cursor": {"found":{"engine":"cursor","sessionId":"bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb","transcriptPath":"<root>/codex/sessions/2026/10/08/rollout-2026-10-08T00-00-02-bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb.jsonl"},"calls":[["findLiveSession","cursor","<root>/work/a","<start>",{"bornOnly":true,"pid":42}]]}+},+"linux": {+"homes": {++},+"transcripts": {++},+"find": {++},+"continuation": {++},+"rollouts": {++},+"registry": {++},+"capture": {++}+}+}diff --git a/cli/src/engines/claude/sessionStore.ts b/cli/src/engines/claude/sessionStore.tsnew file mode 100644index 000000000..140b74102--- /dev/null+++ b/cli/src/engines/claude/sessionStore.ts@@ -0,0 +1,39 @@+import type { SessionStoreContract } from '../facets/sessionStore.js'++/**+ * Where Claude Code keeps its sessions, declared: data only, which core applies with the kit+ * (engines/sessionStoreContracts.ts, lib/sessionRepair.ts, lib/engineHomes.ts). Copied from the former+ * lib/sessionRepair.ts and lib/engineHomes.ts.+ */+export const sessionStore: SessionStoreContract = {+ label: 'Claude',+ product: 'Claude Code',+ sessions: {+ // `<projects>/<encoded cwd>/<id>.jsonl`. A CLAUDE_CONFIG_DIR the person moves keeps its own `projects`.+ own: { setting: 'CLAUDE_PROJECTS_DIR' },+ moved: { variable: 'CLAUDE_CONFIG_DIR', folder: 'projects', ownHome: 'parent' },+ },+ // The cwd encoding is Claude's to define, so the project folders are listed rather than the name derived.+ byId: { layout: 'projects', suffix: '.jsonl' },+ /**+ * Claude opens with bookkeeping records (`leafUuid`, `mode`) that carry no cwd, so the opening lines are read.+ * Its subagents (the Task tool, background agents) write transcripts of their own in the same tree, which a+ * scan by folder cannot tell from a conversation: `<proj>/<parent>/subagents/agent-<id>.jsonl` (current) and+ * `<proj>/agent-<id>.jsonl` (older builds), both opening with `isSidechain: true` and the PARENT's id. Left in,+ * the youngest subagent file of a running parent was bound to the fork born next to it. Only the opening+ * record's flag counts: a main transcript can hold sidechain records later.+ */+ scan: { from: 'head', childFolder: 'subagents', sidechain: 'isSidechain' },+ /**+ * Native Claude publishes a pid-to-conversation record (`<home>/sessions/<pid>.json`) even before a hook binds+ * it, removed at exit. `procStart` is UTC in current Claude and the host's local `ps` form in older builds: the+ * exact second either way, never a recycled pid.+ */+ live: { record: { folder: 'sessions', suffix: '.json', pid: 'pid', start: 'procStart', cwd: 'cwd', id: 'sessionId' } },+ /**+ * Claude rolls a long conversation over to a new file on its own; the old file's last line names the next+ * session. The same marker is written for a background session, whose file holds two bookkeeping lines and+ * never a turn, so a continuation counts only once a turn is in it (or the file is too long to be those lines).+ */+ continuation: { type: 'continued-in', field: 'continuedInSessionId', suffix: '.jsonl', tailBytes: 4 * 1024, turns: ['user', 'assistant'], headBytes: 256 * 1024 },+}diff --git a/cli/src/engines/codex/rollout.ts b/cli/src/engines/codex/rollout.tsindex c0ad2497c..cec8774ec 100644--- a/cli/src/engines/codex/rollout.ts+++ b/cli/src/engines/codex/rollout.ts@@ -1,68 +1,19 @@-import { closeSync, openSync, readSync } from 'fs'-import { join } from 'path'-import { env } from '../../config/env.js'-import { codexHomeRoots } from '../../lib/engineHomes.js'-import { findSessionFile } from '../kit/resumeRepair.js'-import { launch } from './launch.js'+/**+ * Codex's rollouts, read as its session store declares them (engines/codex/sessionStore.ts): the names its own+ * code (the sub-agent reader, engines/codex/subagent.ts) has always used. Core reads them through the engine-neutral+ * finders (engines/sessionFiles.ts) and never loads this file.+ */+import { findSessionFileOf, sessionMetaOf, type SessionMeta } from '../sessionFiles.js'-type JsonObject = Record<string, unknown>--const MAX_META_BYTES = 128 * 1024--export interface CodexRolloutMeta {- id: string- isSubagent: boolean- parentThreadId: string | null- /** The directory the session was started in — the only field that identifies WHERE a rollout belongs. */- cwd: string | null-}--function object(value: unknown): JsonObject | null {- return value !== null && typeof value === 'object' && !Array.isArray(value)- ? value as JsonObject- : null-}+export type CodexRolloutMeta = SessionMeta/** Read only the first rollout record, which is Codex's session_meta line. */export function readCodexRolloutMeta(file: string): CodexRolloutMeta | null {- let fd: number | null = null- try {- fd = openSync(file, 'r')- const buffer = Buffer.alloc(MAX_META_BYTES)- const bytes = readSync(fd, buffer, 0, buffer.length, 0)- const firstLine = buffer.subarray(0, bytes).toString('utf8').split('\n').find((line) => line.trim())- if (!firstLine) return null- const record = object(JSON.parse(firstLine))- const payload = object(record?.payload)- if (record?.type !== 'session_meta' || !payload) return null- const source = object(payload.source)- const subagent = source?.subagent- const spawn = object(object(subagent)?.thread_spawn)- const parentThreadId = typeof spawn?.parent_thread_id === 'string' && spawn.parent_thread_id- ? spawn.parent_thread_id- : null- return {- id: typeof payload.id === 'string' ? payload.id : '',- isSubagent: subagent !== undefined && subagent !== null,- parentThreadId,- cwd: typeof payload.cwd === 'string' ? payload.cwd : null,- }- } catch {- return null- } finally {- if (fd !== null) {- try { closeSync(fd) } catch { /* best effort */ }- }- }+ return sessionMetaOf('codex', file)}/** Find one rollout by thread id without scanning unbounded user history: under `root`, else in every Codex- * home the person moved too (lib/engineHomes.ts). The daemon's own alone missed the sub-agents of a Codex- * in a moved home, and its Task cards closed with no tools and no totals. The lookup is the kit's, on the- * rule Codex's launch contract declares (`resumeRepair.sessions`), which resuming uses too. */+ * home the person moved too (lib/engineHomes.ts). */export function resolveCodexRollout(threadId: string, root?: string): string | null {- if (root === undefined) {- return codexHomeRoots(env.CODEX_HOME).reduce<string | null>((found, home) => found ?? resolveCodexRollout(threadId, join(home, 'sessions')), null)- }- return findSessionFile(threadId, root, launch.resumeRepair!.sessions)+ return findSessionFileOf('codex', threadId, root)}diff --git a/cli/src/engines/codex/sessionStore.ts b/cli/src/engines/codex/sessionStore.tsnew file mode 100644index 000000000..b8fd48788--- /dev/null+++ b/cli/src/engines/codex/sessionStore.ts@@ -0,0 +1,44 @@+import type { SessionStoreContract } from '../facets/sessionStore.js'+import { hooks } from './hookContract.js'+import { launch } from './launch.js'++const rollouts = launch.resumeRepair!.sessions++/**+ * Where Codex keeps its sessions, declared: data only, which core applies with the kit+ * (engines/sessionStoreContracts.ts, lib/sessionRepair.ts, lib/engineHomes.ts, the registry). Copied from the+ * former engines/codex/rollout.ts, lib/sessionRepair.ts and lib/engineHomes.ts. The rollout layout and the+ * child rule are the same declarations the resume repair and hook admission use.+ */+export const sessionStore: SessionStoreContract = {+ label: 'Codex',+ product: 'Codex',+ sessions: {+ // `<CODEX_HOME>/sessions/<yyyy>/<mm>/<dd>/rollout-<timestamp>-<id>.jsonl`. An agent's own profile is its only+ // home; else the daemon's and every CODEX_HOME the person moved.+ own: { setting: 'CODEX_HOME', folder: rollouts.folder },+ profile: true,+ moved: { variable: 'CODEX_HOME', folder: rollouts.folder, ownHome: 'setting' },+ // Codex moves a finished session's rollout here; it is still that home's.+ archived: 'archived_sessions',+ },+ byId: { layout: 'walk', suffix: rollouts.suffix, id: rollouts.id, walk: rollouts.walk },+ /**+ * The rollout's first record is the session's metadata: its id (the file name only holds it), the folder it+ * started in (the one field that says where a rollout belongs), and whether a parent delegated to it. Read+ * within 128 KiB.+ */+ first: {+ type: hooks.children!.type, id: ['payload', 'id'], cwd: ['payload', 'cwd'], child: hooks.children!.child,+ parent: [...hooks.children!.child, 'thread_spawn', 'parent_thread_id'], maxBytes: 128 * 1024,+ },+ scan: { from: 'first' },+ /**+ * October 6 parallel-create incident: the only rollout in a folder can belong to a sibling whose file opened+ * first, so a known Codex process names its own open rollout and is never matched by folder. npm's Node+ * launcher holds no rollout; its one native child does.+ */+ live: { open: { file: /rollout-[^/]*\.jsonl$/, launcher: /^node(?:js)?$/ } },+ // A sub-agent's hooks run from its parent's pane, and an older daemon let them overwrite the parent's binding.+ repairsOverwrittenParent: true,+}diff --git a/cli/src/engines/facets/sessionStore.ts b/cli/src/engines/facets/sessionStore.tsnew file mode 100644index 000000000..bd4f32a7f--- /dev/null+++ b/cli/src/engines/facets/sessionStore.ts@@ -0,0 +1,58 @@+import type { FolderSetting } from './hooks.js'++/**+ * Where an engine keeps its sessions, and how core reads them: as the registry loads, on the hook path and+ * in session repair. Declared data, applied in core by the kit (kit/sessionRecords.ts, kit/continuation.ts)+ * and lib/sessionRepair.ts. Binding a session never waits on an engine worker+ * (docs/design/2026-10-08-engine-launch.md, (c4)).+ */+export interface SessionStoreContract {+ /** How the daemon's log and its own hook events name the engine (`[registry] repaired Codex parent …`,+ * `ClaudeContinuation`). */+ label: string+ /** How the person knows it, in what the daemon tells them (`Claude Code in <home>`). */+ product: string+ /**+ * Where sessions are. The daemon's own folder is `own` (a setting naming it, with `folder` below it when the+ * setting names a home), unless the agent runs on a profile of its own (`profile`), which is then its only+ * one. Every home the person moves with `moved.variable` adds `moved.folder` below it; the daemon's own home+ * for that variable is `moved.ownHome` (the setting's folder, or the parent of `own`'s). A finished session+ * may move to `archived`, beside `own.folder` in the same home.+ */+ sessions: {+ own: { setting: FolderSetting; folder?: string }+ profile?: boolean+ moved: { variable: string; folder: string; ownHome: 'setting' | 'parent' }+ archived?: string+ }+ /** How one session's file is found by its id. `walk`: a file ending in `suffix` whose name holds the id, at any+ * depth, at most `walk` entries looked at, for an id `id` accepts. `projects`: `<id><suffix>` in any one folder+ * directly below a sessions folder. */+ byId: { layout: 'walk'; suffix: string; id: RegExp; walk: number } | { layout: 'projects'; suffix: string }+ /**+ * What a session file's first record says about it, read within `maxBytes`: its `type`, and where it keeps+ * the id, the folder, the field whose presence marks a session another one delegated to, and that one's parent.+ */+ first?: { type: string; id: readonly string[]; cwd: readonly string[]; child: readonly string[]; parent: readonly string[]; maxBytes: number }+ /**+ * How a scan of the store tells which folder a session belongs to. `first`: the first record above, a child+ * never counts. `head`: the first `cwd` in its opening lines, never a file below a `childFolder` segment or one+ * whose first `sidechain` flag is true.+ */+ scan: { from: 'first' } | { from: 'head'; childFolder: string; sidechain: string }+ /**+ * How a live process names its own session. `record`: a file of its own, `<folder>/<pid><suffix>` beside each+ * sessions folder, naming the pid, its start (UTC or the host's local form), the folder and the session. `open`:+ * the session file it holds open, named like `file`; behind a Node launcher (`launcher`), its one native child's.+ */+ live: { record: { folder: string; suffix: string; pid: string; start: string; cwd: string; id: string } }+ | { open: { file: RegExp; launcher: RegExp } }+ /**+ * A conversation continued in another file: the last record of the transcript (within `tailBytes`) has type+ * `type` and names the next session in `field`, `<id><suffix>` beside it. It is taken only once that file holds a+ * turn (a record of `turns`, within `headBytes`, or a file at least that long).+ */+ continuation?: { type: string; field: string; suffix: string; tailBytes: number; turns: readonly string[]; headBytes: number }+ /** A parent's binding, overwritten by its delegated session's hook, is put back as the registry loads. */+ repairsOverwrittenParent?: boolean+}diff --git a/cli/src/engines/kit/continuation.ts b/cli/src/engines/kit/continuation.tsnew file mode 100644index 000000000..0f82ab552--- /dev/null+++ b/cli/src/engines/kit/continuation.ts@@ -0,0 +1,99 @@+/**+ * A conversation continued in another file, as an engine's session store declares it (`continuation`). Moved+ * from lib/sessionRepair.ts (claudeContinuation), whose every answer this reproduces+ * (engines/sessionStore.golden.spec.ts). Cheap and bounded: it runs on every reconciler pass, so a continuation+ * that is real binds on the pass after its first turn lands.+ */+import { open, stat } from 'node:fs/promises'+import { dirname, join } from 'node:path'+import type { SessionStoreContract } from '../facets/sessionStore.js'++type Continuation = NonNullable<SessionStoreContract['continuation']>++/** The last `maxBytes` of a file, as text. */+async function tailBytes(path: string, maxBytes: number): Promise<string> {+ const handle = await open(path, 'r')+ try {+ const info = await handle.stat()+ const start = Math.max(0, info.size - maxBytes)+ const length = info.size - start+ if (length <= 0) return ''+ const buffer = Buffer.alloc(length)+ await handle.read(buffer, 0, length, start)+ return buffer.toString('utf-8')+ } finally {+ await handle.close()+ }+}++/** The first `maxBytes` of a file. */+export async function headBytes(path: string, maxBytes: number): Promise<Buffer> {+ const handle = await open(path, 'r')+ try {+ const length = Math.min((await handle.stat()).size, maxBytes)+ if (length <= 0) return Buffer.alloc(0)+ const buffer = Buffer.alloc(length)+ let read = 0+ while (read < length) {+ const { bytesRead } = await handle.read(buffer, read, length - read, read)+ if (!bytesRead) break+ read += bytesRead+ }+ return buffer.subarray(0, read)+ } finally {+ await handle.close()+ }+}++/**+ * Whether a transcript holds a conversation, rather than being the file opened for a session nobody has spoken+ * in yet: a record of the declared turn types in its head, or more file than the head (a continuation can open+ * on a bookkeeping record large enough to push the first turn past the bound, and what is ruled out is two+ * short lines). The bytes read are counted, not decoded characters.+ */+async function hasConversationTurn(rule: Continuation, path: string): Promise<boolean> {+ let head: Buffer+ try {+ head = await headBytes(path, rule.headBytes)+ } catch {+ return false+ }+ const quoted = rule.turns.map((type) => `"${type}"`)+ for (const line of head.toString('utf-8').split('\n')) {+ if (!line.trim() || !quoted.some((type) => line.includes(type))) continue+ try {+ const record = JSON.parse(line) as { type?: unknown }+ if (typeof record.type === 'string' && rule.turns.includes(record.type)) return true+ } catch { /* a line cut by the read bound, or one this version does not know */ }+ }+ return head.length >= rule.headBytes+}++/** The session a transcript's last record says the conversation continued in, once that file holds a turn. */+export async function continuedIn(rule: Continuation, transcriptPath: string): Promise<{ sessionId: string; transcriptPath: string } | null> {+ let tail: string+ try {+ tail = await tailBytes(transcriptPath, rule.tailBytes)+ } catch {+ return null+ }+ const lines = tail.split('\n').map((line) => line.trim()).filter(Boolean)+ const lastLine = lines[lines.length - 1]+ if (!lastLine) return null+ let record: Record<string, unknown>+ try {+ record = JSON.parse(lastLine) as Record<string, unknown>+ } catch {+ return null+ }+ const nextId = record.type === rule.type && typeof record[rule.field] === 'string' ? record[rule.field] as string : ''+ if (!nextId) return null+ const nextPath = join(dirname(transcriptPath), `${nextId}${rule.suffix}`)+ try {+ if (!(await stat(nextPath)).isFile()) return null+ } catch {+ return null+ }+ if (!await hasConversationTurn(rule, nextPath)) return null+ return { sessionId: nextId, transcriptPath: nextPath }+}diff --git a/cli/src/engines/kit/hookRules.spec.ts b/cli/src/engines/kit/hookRules.spec.tsindex 72ac75556..f2297baaa 100644--- a/cli/src/engines/kit/hookRules.spec.ts+++ b/cli/src/engines/kit/hookRules.spec.ts@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'nodeimport { tmpdir } from 'node:os'import { join } from 'node:path'import { afterAll, beforeAll, describe, expect, it } from 'vitest'-import { readCodexRolloutMeta } from '../codex/rollout.js'+import { sessionMetaOf } from '../sessionFiles.js'import { hooks as codex } from '../codex/hookContract.js'import { isChildSession, knownTranscript } from './hookRules.js'@@ -41,12 +41,13 @@ const FIRST_RECORDS: Array<[string, string]> = []describe('Codex\'s declared child rule', () => {- // `registry` still reads rollouts with readCodexRolloutMeta, at load, to repair a parent a child's hook- // overwrote: the rule evaluated on the hook path must say what that reader says about every first record.- it.each(FIRST_RECORDS)('agrees with the rollout reader on %s', (name, text) => {+ // The registry reads a rollout's first record with Codex's declared session store (sessionMetaOf), at load, to+ // repair a parent a child's hook overwrote: the rule evaluated on the hook path must say what that reader says+ // about every first record.+ it.each(FIRST_RECORDS)('agrees with the session store\'s first-record reader on %s', (name, text) => {const file = join(root, `${name.replace(/\W+/g, '-')}.jsonl`)writeFileSync(file, text)- expect(isChildSession(file, codex.children!)).toBe(readCodexRolloutMeta(file)?.isSubagent === true)+ expect(isChildSession(file, codex.children!)).toBe(sessionMetaOf('codex', file)?.isSubagent === true)})it('finds the children it should', () => {@@ -67,7 +68,7 @@ describe('Codex\'s declared child rule', () => {symlinkSync(join(root, 'nowhere.jsonl'), join(root, 'dangling.jsonl'))for (const file of [join(root, 'missing.jsonl'), join(root, 'folder.jsonl'), join(root, 'dangling.jsonl')]) {expect(isChildSession(file, codex.children!)).toBe(false)- expect(readCodexRolloutMeta(file)).toBeNull()+ expect(sessionMetaOf('codex', file)).toBeNull()}})diff --git a/cli/src/engines/kit/resumeRepair.ts b/cli/src/engines/kit/resumeRepair.tsindex 0aea9fa11..62a91b823 100644--- a/cli/src/engines/kit/resumeRepair.ts+++ b/cli/src/engines/kit/resumeRepair.ts@@ -1,47 +1,22 @@/*** A stopped conversation's history made resumable, as the engine's launch contract declares it- * (facets/launch.ts `ResumeRepairContract`), and the lookup of a history by its session's id. Moved from- * engines/codex/portableHistory.ts and the lookup of engines/codex/rollout.ts, whose every write and refusal- * this reproduces (engines/launchPrep.golden.spec.ts). A resume is session control: this runs in core, with- * no worker.+ * (facets/launch.ts `ResumeRepairContract`). Moved from engines/codex/portableHistory.ts, whose every write and+ * refusal this reproduces (engines/launchPrep.golden.spec.ts). A history is found by its session's id with the+ * kit's lookup (kit/sessionRecords.ts), which the session store uses too. A resume is session control: this runs+ * in core, with no worker.*/import { createHash, randomUUID } from 'node:crypto'-import { closeSync, constants, existsSync, fsyncSync, fstatSync, lstatSync, openSync, readdirSync, readSync, realpathSync, renameSync, rmSync, writeSync, type Stats } from 'node:fs'+import { closeSync, constants, fsyncSync, fstatSync, lstatSync, openSync, readSync, realpathSync, renameSync, rmSync, writeSync, type Stats } from 'node:fs'import { isAbsolute, join, relative } from 'node:path'import type { ResumeRepairContract } from '../facets/launch.js'+import { findSessionFile } from './sessionRecords.js'type JsonObject = Record<string, unknown>-type Sessions = ResumeRepairContract['sessions']function object(value: unknown): value is JsonObject {return value !== null && typeof value === 'object' && !Array.isArray(value)}-/**- * Find one history by its session's id without scanning unbounded history: a file ending in the declared- * suffix whose name holds the id, under `root`, looking at no more than the declared number of entries.- */-export function findSessionFile(id: string, root: string, sessions: Pick<Sessions, 'suffix' | 'id' | 'walk'>): string | null {- if (!sessions.id.test(id) || !existsSync(root)) return null- const stack = [root]- let visited = 0- while (stack.length && visited < sessions.walk) {- const dir = stack.pop()!- let names: string[]- try { names = readdirSync(dir) } catch { continue }- for (const name of names) {- if (++visited > sessions.walk) break- const full = join(dir, name)- if (name.endsWith(sessions.suffix)) {- if (name.includes(id)) return full- } else if (!name.includes('.')) {- stack.push(full)- }- }- }- return null-}-/*** The relay's portable_reasoning_item contract. Plaintext engine reasoning has no vendor-stored id;* encrypted vendor reasoning must keep its original fields.diff --git a/cli/src/engines/kit/sessionRecords.ts b/cli/src/engines/kit/sessionRecords.tsnew file mode 100644index 000000000..9147d4f8e--- /dev/null+++ b/cli/src/engines/kit/sessionRecords.ts@@ -0,0 +1,93 @@+/**+ * Reading an engine's session files as its contracts declare them: one found by its id, and what its first+ * record says. Moved from engines/codex/rollout.ts (and the lookup from kit/resumeRepair.ts), whose every+ * answer this reproduces (engines/sessionStore.golden.spec.ts). Run as the registry loads and on the hook+ * path, so every read is bounded.+ */+import { closeSync, existsSync, openSync, readdirSync, readSync } from 'node:fs'+import { join } from 'node:path'+import type { SessionStoreContract } from '../facets/sessionStore.js'++type JsonObject = Record<string, unknown>++function object(value: unknown): JsonObject | null {+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : null+}++/**+ * Find one session file by its id without scanning unbounded history: a file ending in `suffix` whose name holds+ * the id, under `root`, looking at no more than `walk` entries. Only names with no `.` are folders worth entering.+ */+export function findSessionFile(id: string, root: string, sessions: { suffix: string; id: RegExp; walk: number }): string | null {+ if (!sessions.id.test(id) || !existsSync(root)) return null+ const stack = [root]+ let visited = 0+ while (stack.length && visited < sessions.walk) {+ const dir = stack.pop()!+ let names: string[]+ try { names = readdirSync(dir) } catch { continue }+ for (const name of names) {+ if (++visited > sessions.walk) break+ const full = join(dir, name)+ if (name.endsWith(sessions.suffix)) {+ if (name.includes(id)) return full+ } else if (!name.includes('.')) {+ stack.push(full)+ }+ }+ }+ return null+}++/** What a session file's first record says about it. */+export interface SessionMeta {+ id: string+ /** A session another session delegated to. */+ isSubagent: boolean+ /** The session that delegated to it, when the record names one. */+ parentThreadId: string | null+ /** The folder the session was started in: the one field that says where it belongs. */+ cwd: string | null+}++/** The value at `path` in `value`, every step an object; undefined where one is not. */+function valueAt(value: unknown, path: readonly string[]): unknown {+ let at: unknown = value+ for (const key of path) {+ const parent = object(at)+ if (!parent) return undefined+ at = parent[key]+ }+ return at+}++/** Read only the first record (the first line with anything on it, within the declared bound). Null for a+ * file that does not open with the declared record, or cannot be read or parsed. */+export function readFirstRecord(file: string, first: NonNullable<SessionStoreContract['first']>): SessionMeta | null {+ let fd: number | null = null+ try {+ fd = openSync(file, 'r')+ const buffer = Buffer.alloc(first.maxBytes)+ const bytes = readSync(fd, buffer, 0, buffer.length, 0)+ const firstLine = buffer.subarray(0, bytes).toString('utf8').split('\n').find((line) => line.trim())+ if (!firstLine) return null+ const record = object(JSON.parse(firstLine))+ if (record?.type !== first.type || !object(valueAt(record, first.id.slice(0, -1)))) return null+ const id = valueAt(record, first.id)+ const cwd = valueAt(record, first.cwd)+ const child = valueAt(record, first.child)+ const parent = valueAt(record, first.parent)+ return {+ id: typeof id === 'string' ? id : '',+ isSubagent: child !== undefined && child !== null,+ parentThreadId: typeof parent === 'string' && parent ? parent : null,+ cwd: typeof cwd === 'string' ? cwd : null,+ }+ } catch {+ return null+ } finally {+ if (fd !== null) {+ try { closeSync(fd) } catch { /* best effort */ }+ }+ }+}diff --git a/cli/src/engines/sessionFiles.ts b/cli/src/engines/sessionFiles.tsnew file mode 100644index 000000000..bbd0f9481--- /dev/null+++ b/cli/src/engines/sessionFiles.ts@@ -0,0 +1,40 @@+/**+ * Reading the engines' session files as their session stores declare them (engines/sessionStoreContracts.ts):+ * what a file's first record says, one file found by its id, and a conversation continued in another file. File+ * reads alone, applied with the kit, so the registry reads them as it loads without the process or tmux code of+ * session repair (lib/sessionRepair.ts), which reaches the registry back.+ */+import { sessionRoots } from '../lib/engineHomes.js'+import { continuedIn } from './kit/continuation.js'+import { findSessionFile, readFirstRecord, type SessionMeta } from './kit/sessionRecords.js'+import { sessionStoreOf } from './sessionStoreContracts.js'+import type { AgentEngine } from './types.js'++export type { SessionMeta }++/** The first record of `engine`'s session file at `path`; null for an engine that declares none, or a file that+ * does not open with one. */+export function sessionMetaOf(engine: AgentEngine | string, path: string): SessionMeta | null {+ const first = sessionStoreOf(engine)?.first+ return first ? readFirstRecord(path, first) : null+}++/**+ * One session file found by its id under `root`, else in each of the engine's sessions folders, without scanning+ * unbounded history: for an engine whose file name holds the id (`byId.layout: 'walk'`). The daemon's own folder+ * alone missed the sub-agents of a Codex in a moved home, and its Task cards closed with no tools and no totals.+ * Null for another engine: Claude Code's project folders are listed by session repair, never walked here.+ */+export function findSessionFileOf(engine: AgentEngine | string, id: string, root?: string): string | null {+ const byId = sessionStoreOf(engine)?.byId+ if (byId?.layout !== 'walk') return null+ if (root !== undefined) return findSessionFile(id, root, byId)+ return sessionRoots(engine).reduce<string | null>((found, sessions) => found ?? findSessionFile(id, sessions, byId), null)+}++/** The file a conversation continued in, when its transcript's last record says it moved there and that file holds+ * a turn; null for an engine that declares no continuation. */+export function continuationOf(engine: AgentEngine | string, transcriptPath: string): Promise<{ sessionId: string; transcriptPath: string } | null> {+ const rule = sessionStoreOf(engine)?.continuation+ return rule ? continuedIn(rule, transcriptPath) : Promise.resolve(null)+}diff --git a/cli/src/engines/sessionStore.golden.spec.ts b/cli/src/engines/sessionStore.golden.spec.tsnew file mode 100644index 000000000..715a2c899--- /dev/null+++ b/cli/src/engines/sessionStore.golden.spec.ts@@ -0,0 +1,592 @@+/**+ * Where Claude Code and Codex keep their sessions, and what core reads there, answer for answer: recorded+ * from the code as it stood before their session stores became declared data applied by the kit+ * (docs/design/2026-10-08-engine-launch.md, (c4)). It covers what runs as the registry loads, on the hook path+ * and in session repair:+ *+ * - the engine homes a person moves, as adopted, remembered and searched;+ * - which transcript paths the registry accepts, for every kind of engine;+ * - the registry's load: a Codex parent's transcript put back after a sub-agent's hook overwrote it, and+ * bindings released when their transcript is not the engine's own;+ * - a session found by its id, by a process's own record, by the session file a process holds open, and by a+ * scan of the engine's store; a conversation continued in another file;+ * - a Codex rollout's first record, and a rollout found by its thread id;+ * - what Stop captures before a pause, and which finder the handoff asks for each engine.+ *+ * Each case runs with `process.platform` pinned to darwin and to linux, and linux's are stored where they+ * differ. File birth times are a property of the filesystem, so only sessions born after their process are+ * recorded; the `wrote` tier is the unit specs'.+ *+ * `RECORD_SESSION_STORE_GOLDEN=1` writes the fixture. Record it again only for a change meant to alter what+ * core finds, and say so in that change.+ */+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../lib/registry.js'++// The record holds a UTC record read against a process started in local time, so the answer depends on the zone.+// It was recorded in America/New_York; pinned here, it is the same on every host (Linux CI runs in UTC, run 37828754630).+process.env.TZ = 'America/New_York'++const GOLDEN = fileURLToPath(new URL('./__fixtures__/session-store.golden.json', import.meta.url))+const RECORD = process.env.RECORD_SESSION_STORE_GOLDEN === '1'++let root = ''+const saved: Record<string, string | undefined> = {}+const VARS = ['ADAPTER_DATA_DIR', 'CLAUDE_PROJECTS_DIR', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'CURSOR_HOME', 'PI_HOME'] as const+type Modules = {+ homes: typeof import('../lib/engineHomes.js')+ registry: typeof import('../lib/registry.js')+ repair: typeof import('../lib/sessionRepair.js')+ stores: typeof import('./sessionStores.js')+ capture: typeof import('../lib/captureResumeIdentity.js')+ handoff: typeof import('../lib/handoffDiscovery.js')+}+let m: Modules++const A = 'aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa'+const B = 'bbbbbbbb-2222-4222-8222-bbbbbbbbbbbb'+const C = 'cccccccc-3333-4333-8333-cccccccccccc'+const CHILD = 'dddddddd-4444-4444-8444-dddddddddddd'+const OTHER = 'eeeeeeee-5555-4555-8555-eeeeeeeeeeee'+const PROFILE_ID = 'ffffffff-6666-4666-8666-ffffffffffff'+const MOVED_ID = '12121212-7777-4777-8777-121212121212'+const D = 'abababab-8888-4888-8888-abababababab'+const E = 'cdcdcdcd-9999-4999-8999-cdcdcdcdcdcd'++const write = (path: string, text: string): void => {+ mkdirSync(join(path, '..'), { recursive: true })+ writeFileSync(path, text)+ chmodSync(path, 0o644)+}+const jsonl = (...records: unknown[]): string => records.map((record) => typeof record === 'string' ? record : JSON.stringify(record)).join('\n') + '\n'+const meta = (id: string, cwd: string, source: unknown = 'cli') => ({ timestamp: 't', type: 'session_meta', payload: { id, cwd, source } })+const child = (id: string, parent: string | null, cwd: string) => meta(id, cwd, { subagent: parent ? { thread_spawn: { parent_thread_id: parent, depth: 1 } } : 'review' })++const norm = (value: unknown): unknown => value === undefined ? '<undefined>' : JSON.parse(JSON.stringify(value).split(root).join('<root>'))+async function attempt<T>(run: () => T | Promise<T>): Promise<unknown> {+ try { return norm(await run()) } catch (error) { return { threw: norm(error instanceof Error ? error.message : String(error)) } }+}++let paths: Record<string, string> = {}++beforeAll(async () => {+ root = realpathSync(mkdtempSync(join(tmpdir(), 'session-store-golden-')))+ for (const name of VARS) saved[name] = process.env[name]+ process.env.ADAPTER_DATA_DIR = join(root, 'data')+ process.env.CLAUDE_PROJECTS_DIR = join(root, 'claude', 'projects')+ process.env.CODEX_HOME = join(root, 'codex')+ process.env.CURSOR_HOME = join(root, 'cursor')+ process.env.PI_HOME = join(root, 'pi')+ delete process.env.CLAUDE_CONFIG_DIR+ mkdirSync(join(root, 'data'), { recursive: true })+ chmodSync(join(root, 'data'), 0o700)+ // The work folders sessions name. `linked` is the same folder by another path.+ for (const dir of ['work/a', 'work/b', 'work/c', 'elsewhere']) mkdirSync(join(root, dir), { recursive: true })+ symlinkSync(join(root, 'work/a'), join(root, 'linked-a'))+ const work = (name: string) => join(root, 'work', name)+ const day = (home: string) => join(home, 'sessions', '2026', '10', '08')+ paths = {+ claudeA: join(root, 'claude/projects/-work-a', `${A}.jsonl`),+ claudeSub: join(root, 'claude/projects/-work-a', A, 'subagents', 'agent-1.jsonl'),+ claudeOldSub: join(root, 'claude/projects/-work-a', 'agent-2.jsonl'),+ claudeB: join(root, 'claude/projects/-work-b', `${B}.jsonl`),+ claudeMoved: join(root, 'moved-claude/projects/-work-c', `${MOVED_ID}.jsonl`),+ claudeContinued: join(root, 'claude/projects/-work-b', `${C}.jsonl`),+ codexA: join(day(join(root, 'codex')), `rollout-2026-10-08T00-00-00-${A}.jsonl`),+ codexChild: join(day(join(root, 'codex')), `rollout-2026-10-08T00-00-01-${CHILD}.jsonl`),+ codexB: join(day(join(root, 'codex')), `rollout-2026-10-08T00-00-02-${B}.jsonl`),+ codexMoved: join(day(join(root, 'moved-codex')), `rollout-2026-10-08T00-00-03-${MOVED_ID}.jsonl`),+ codexProfile: join(day(join(root, 'profile')), `rollout-2026-10-08T00-00-04-${PROFILE_ID}.jsonl`),+ outside: join(root, 'elsewhere', `${OTHER}.jsonl`),+ }+ write(paths.claudeA, jsonl({ type: 'summary', leafUuid: 'x' }, { type: 'user', cwd: work('a'), isSidechain: false, sessionId: A }))+ write(paths.claudeSub, jsonl({ type: 'user', cwd: work('a'), isSidechain: true, sessionId: A }))+ write(paths.claudeOldSub, jsonl({ type: 'user', cwd: work('a'), isSidechain: true, sessionId: A }))+ write(paths.claudeB, jsonl({ type: 'user', cwd: work('b'), sessionId: B }, { type: 'continued-in', continuedInSessionId: C }))+ write(paths.claudeContinued, jsonl({ type: 'ai-title' }, { type: 'user', cwd: work('b'), sessionId: C }))+ write(paths.claudeMoved, jsonl({ type: 'user', cwd: work('c'), sessionId: MOVED_ID }))+ write(paths.codexA, jsonl(meta(A, work('a')), { type: 'response_item', payload: {} }))+ write(paths.codexChild, jsonl(child(CHILD, A, work('a'))))+ write(paths.codexB, jsonl(meta(B, work('b'))))+ write(paths.codexMoved, jsonl(meta(MOVED_ID, work('c'))))+ write(paths.codexProfile, jsonl(meta(PROFILE_ID, work('a'))))+ write(paths.outside, jsonl({ type: 'user', cwd: work('a') }))+ vi.resetModules()+ m = {+ homes: await import('../lib/engineHomes.js'),+ registry: await import('../lib/registry.js'),+ repair: await import('../lib/sessionRepair.js'),+ stores: await import('./sessionStores.js'),+ capture: await import('../lib/captureResumeIdentity.js'),+ handoff: await import('../lib/handoffDiscovery.js'),+ }+})++afterAll(() => {+ for (const name of VARS) {+ if (saved[name] === undefined) delete process.env[name]+ else process.env[name] = saved[name]+ }+ m?.homes.resetEngineHomes()+ rmSync(root, { recursive: true, force: true })+ vi.resetModules()+})++/** The person's moved homes: adopted, so remembered in the data folder, as the core does at start. */+function adoptMoved(): unknown {+ m.homes.resetEngineHomes()+ rmSync(join(root, 'data', 'engine-homes.json'), { force: true })+ return m.homes.adoptEngineHomes({ CLAUDE_CONFIG_DIR: join(root, 'moved-claude'), CODEX_HOME: join(root, 'moved-codex') },+ { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') })+}+function forgetMoved(): void {+ m.homes.resetEngineHomes()+ rmSync(join(root, 'data', 'engine-homes.json'), { force: true })+}++// --------------------------------------------------------------------------------------------- homes++async function homeCases(): Promise<Record<string, unknown>> {+ const h = m.homes+ const cases: Record<string, unknown> = {}+ const probe = () => ({+ moved: h.movedEngineHomes(),+ claudeRoots: h.claudeProjectsRoots(join(root, 'claude', 'projects')),+ codexRoots: h.codexHomeRoots(join(root, 'codex')),+ codexSettingRoots: h.homeRoots('CODEX_HOME'),+ sessionCodexHome: [+ h.sessionCodexHome({ codexHome: join(root, 'profile') }),+ h.sessionCodexHome({ transcriptPath: paths.codexMoved }),+ h.sessionCodexHome({ transcriptPath: join(root, 'moved-codex', 'archived_sessions', 'x.jsonl') }),+ h.sessionCodexHome({ transcriptPath: paths.codexA }),+ h.sessionCodexHome({ transcriptPath: paths.outside }),+ h.sessionCodexHome({}),+ ],+ sessionClaudeHome: [h.sessionClaudeHome({ transcriptPath: paths.claudeMoved }), h.sessionClaudeHome({ transcriptPath: paths.claudeA }),+ h.sessionClaudeHome({ transcriptPath: paths.outside }), h.sessionClaudeHome({})],+ saved: existsSync(join(root, 'data', 'engine-homes.json')) ? readFileSync(join(root, 'data', 'engine-homes.json'), 'utf8') : null,+ })+ forgetMoved()+ cases['none moved'] = norm(probe())+ cases['moved'] = norm({ adopted: adoptMoved(), ...probe() })+ cases['moved again'] = norm({ adopted: h.adoptEngineHomes({ CLAUDE_CONFIG_DIR: join(root, 'moved-claude'), CODEX_HOME: join(root, 'moved-codex') },+ { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') }), ...probe() })+ forgetMoved()+ cases['moved to the defaults, a relative path and a tilde'] = norm({+ adopted: [+ h.adoptEngineHomes({ CLAUDE_CONFIG_DIR: join(root, 'claude'), CODEX_HOME: join(root, 'codex') }, { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') }),+ h.adoptEngineHomes({ CLAUDE_CONFIG_DIR: 'relative/claude', CODEX_HOME: '~/codex' }, { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') }),+ h.adoptEngineHomes({ CLAUDE_CONFIG_DIR: `${join(root, 'moved-claude')}/`, CODEX_HOME: ` ${join(root, 'moved-codex')} ` }, { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') }),+ ],+ ...probe(),+ })+ // Remembered across a restart: a fresh module state reads the saved file.+ h.resetEngineHomes()+ cases['remembered'] = norm(probe())+ forgetMoved()+ const environments: Record<string, NodeJS.ProcessEnv> = {+ 'no variables': {},+ 'moved': { CODEX_HOME: join(root, 'moved-codex'), CLAUDE_CONFIG_DIR: join(root, 'moved-claude') },+ 'relative': { CODEX_HOME: 'codex', CLAUDE_CONFIG_DIR: 'claude' },+ 'trailing slash': { CODEX_HOME: `${join(root, 'moved-codex')}/`, CLAUDE_CONFIG_DIR: `${join(root, 'moved-claude')}/` },+ }+ for (const [name, environment] of Object.entries(environments)) {+ cases[`launch homes · ${name}`] = norm({+ codex: h.launchCodexHome(null, environment), codexProfile: h.launchCodexHome(join(root, 'profile'), environment),+ // Else the home folder itself, the spec run's own throwaway one.+ claude: h.launchClaudeConfigDir(environment).startsWith(root) ? h.launchClaudeConfigDir(environment) : '<home folder>',+ })+ }+ return cases+}++// ------------------------------------------------------------------------------------------- transcripts++function transcriptCases(): Record<string, unknown> {+ adoptMoved()+ const valid = m.registry.validTranscriptPath+ const link = join(root, 'claude/projects/-work-a', 'link-out.jsonl')+ if (!existsSync(link)) symlinkSync(paths.outside, link)+ const linkIn = join(root, 'elsewhere', 'link-in.jsonl')+ if (!existsSync(linkIn)) symlinkSync(paths.claudeA, linkIn)+ const cursor = join(root, 'cursor', 'projects', 'ws', 'agent-transcripts', A, `${A}.jsonl`)+ write(cursor, '{}\n')+ const cursorWrong = join(root, 'cursor', 'projects', 'ws', 'agent-transcripts', B, `${A}.jsonl`)+ write(cursorWrong, '{}\n')+ const files: Record<string, string> = {+ ...paths, link, linkIn, cursor, cursorWrong,+ missingClaude: join(root, 'claude/projects/-work-a', 'missing.jsonl'),+ missingCodex: join(root, 'codex/sessions/2026/10/08', 'rollout-missing.jsonl'),+ claudeDir: join(root, 'claude/projects/-work-a'),+ missingDir: join(root, 'claude/projects/-nope', 'x.jsonl'),+ }+ const cases: Record<string, unknown> = {}+ for (const engine of ['claude', 'codex', 'cursor', 'pi', 'opencode', 'terminal'] as const) {+ for (const [name, path] of Object.entries(files)) {+ const answers = [valid(engine, path), valid(engine, path, join(root, 'profile')), valid(engine, path, undefined, true), valid(engine, path, join(root, 'profile'), true)]+ if (answers.some(Boolean)) cases[`${engine} · ${name}`] = answers+ }+ }+ forgetMoved()+ for (const name of ['claudeMoved', 'codexMoved']) {+ cases[`not moved · ${name}`] = [valid('claude', paths[name]!), valid('codex', paths[name]!)]+ }+ cases['keeps a file'] = Object.fromEntries((['claude', 'codex', 'cursor', 'pi', 'opencode', 'kilo', 'hermes', 'devin', 'terminal'] as const)+ .map((engine) => [engine, m.registry.engineKeepsTranscriptFile(engine)]))+ return cases+}++// ---------------------------------------------------------------------------------------- finding a session++async function findCases(): Promise<Record<string, unknown>> {+ const r = m.repair+ const s = m.stores+ const cases: Record<string, unknown> = {}+ const work = (name: string) => join(root, 'work', name)+ for (const moved of [false, true]) {+ if (moved) adoptMoved(); else forgetMoved()+ const label = moved ? 'moved homes' : 'default homes'+ for (const [engine, id, opts] of [+ ['claude', A, undefined], ['claude', MOVED_ID, undefined], ['claude', 'not-hex', undefined], ['claude', OTHER, undefined],+ ['codex', A, undefined], ['codex', CHILD, undefined], ['codex', MOVED_ID, undefined], ['codex', PROFILE_ID, undefined],+ ['codex', PROFILE_ID, { codexHome: join(root, 'profile') }], ['codex', A, { codexHome: join(root, 'profile') }], ['codex', 'short', undefined],+ ['cursor', A, undefined], ['opencode', A, undefined],+ ] as const) {+ cases[`resumed · ${label} · ${engine} · ${id}${opts ? ' · profile' : ''}`] = await attempt(() => r.findResumedTranscript(engine, id, opts))+ }+ // Born after their process: every session file above was written just now.+ const now = Date.now()+ for (const [engine, cwd, opts] of [+ ['claude', work('a'), undefined], ['claude', work('b'), undefined], ['claude', work('c'), undefined], ['claude', join(root, 'linked-a'), undefined],+ ['claude', work('a'), { bornOnly: true }], ['claude', join(root, 'elsewhere'), undefined],+ ['codex', work('a'), undefined], ['codex', work('b'), undefined], ['codex', work('c'), undefined], ['codex', work('a'), { codexHome: join(root, 'profile') }],+ ['codex', work('a'), { pid: 2 ** 22 + 11 }],+ ] as const) {+ cases[`live · ${label} · ${engine} · ${cwd.split(root).join('')}${opts ? ` · ${Object.keys(opts).join(',')}` : ''}`] =+ await attempt(() => r.findLiveSession(engine, cwd, now - 1_000, opts))+ }+ // A process started after every file: nothing it could have opened.+ cases[`live · ${label} · claude · started later`] = await attempt(() => r.findLiveSession('claude', work('b'), Date.now() + 600_000))+ }+ forgetMoved()+ // Claude Code's subagent transcripts, each refused by one rule alone: one below a `subagents` folder whose first+ // record says nothing of it, and one in the project folder opening with `isSidechain: true`. Each conversation's+ // own transcript holds a sidechain record later, which does not count.+ write(join(root, 'claude/projects/-work-d', `${D}.jsonl`), jsonl({ type: 'user', cwd: work('d'), isSidechain: false, sessionId: D }, { type: 'user', isSidechain: true }))+ write(join(root, 'claude/projects/-work-d', D, 'subagents', 'agent-3.jsonl'), jsonl({ type: 'user', cwd: work('d'), sessionId: D }))+ write(join(root, 'claude/projects/-work-e', `${E}.jsonl`), jsonl({ type: 'mode' }, { type: 'user', cwd: work('e'), isSidechain: false, sessionId: E }, { type: 'user', isSidechain: true }))+ write(join(root, 'claude/projects/-work-e', 'agent-4.jsonl'), jsonl({ type: 'mode' }, { type: 'user', cwd: work('e'), isSidechain: true, sessionId: E }))+ // A moved home below a folder named `subagents`: the rule is read below the projects folder, never above it.+ write(join(root, 'subagents/home/projects/-work-f', `${OTHER}.jsonl`), jsonl({ type: 'user', cwd: work('f'), sessionId: OTHER }))+ for (const dir of ['work/d', 'work/e', 'work/f']) mkdirSync(join(root, dir), { recursive: true })+ const scanned = Date.now()+ cases['live · claude · a subagent below its folder'] = await attempt(() => r.findLiveSession('claude', work('d'), scanned - 1_000))+ cases['live · claude · a subagent by its first flag'] = await attempt(() => r.findLiveSession('claude', work('e'), scanned - 1_000))+ m.homes.adoptEngineHomes({ CLAUDE_CONFIG_DIR: join(root, 'subagents', 'home') }, { claudeHome: join(root, 'claude'), codexHome: join(root, 'codex') })+ cases['live · claude · a moved home below a subagents folder'] = await attempt(() => r.findLiveSession('claude', work('f'), scanned - 1_000))+ forgetMoved()+ // A process's own record (Claude's `<home>/sessions/<pid>.json`), in the default and a moved home.+ const procStart = 'Thu Oct 8 10:00:00 2026'+ const utc = '2026-10-08T10:00:00.000Z'+ const record = (home: string, pid: number, fields: Record<string, unknown>) =>+ write(join(root, home, 'sessions', `${pid}.json`), JSON.stringify({ pid, procStart, cwd: work('a'), sessionId: A, ...fields }))+ record('claude', 101, {})+ record('claude', 102, { procStart: utc })+ record('claude', 103, { pid: 999 })+ record('claude', 104, { cwd: work('b') })+ record('claude', 105, { sessionId: 7 })+ record('claude', 106, { sessionId: OTHER })+ record('claude', 107, { procStart: 3 })+ record('moved-claude', 108, { sessionId: MOVED_ID, cwd: work('c') })+ write(join(root, 'claude', 'sessions', '109.json'), '{not json')+ const local = Date.parse(procStart)+ const utcMs = Date.parse(utc)+ for (const moved of [false, true]) {+ if (moved) adoptMoved(); else forgetMoved()+ for (const [pid, cwd, startedAt, name] of [+ [101, work('a'), local, 'local start'], [101, join(root, 'linked-a'), local, 'linked folder'], [101, work('a'), local + 1000, 'another start'],+ [102, work('a'), utcMs, 'utc start'], [102, work('a'), local, 'utc record, local start'], [103, work('a'), local, 'another pid'],+ [104, work('a'), local, 'another folder'], [105, work('a'), local, 'no id'], [106, work('a'), local, 'no transcript'], [107, work('a'), local, 'no start'],+ [108, work('c'), local, 'moved home'], [109, work('a'), local, 'unreadable'], [110, work('a'), local, 'no record'], [-1, work('a'), local, 'bad pid'],+ [101, work('a'), Number.NaN, 'bad start'],+ ] as const) {+ cases[`process record · ${moved ? 'moved homes' : 'default homes'} · ${name}`] = await attempt(() => s.processSessionOf('claude', pid, cwd, startedAt))+ }+ cases[`process record · ${moved ? 'moved homes' : 'default homes'} · codex`] = await attempt(() => s.processSessionOf('codex', 101, work('a'), local))+ // Through findLiveSession with a pid: the record first, else the scan.+ cases[`live · ${moved ? 'moved homes' : 'default homes'} · claude · pid with a record`] = await attempt(() => r.findLiveSession('claude', work('a'), local, { pid: 101 }))+ }+ forgetMoved()+ // The rollout a Codex process holds open, and its native child's behind npm's Node launcher.+ const sessions = [join(root, 'codex', 'sessions'), join(root, 'moved-codex', 'sessions')]+ const held: Record<string, string[]> = {+ 'its rollout': [paths.codexA, '/dev/null'],+ 'a sub-agent rollout': [paths.codexChild],+ 'two rollouts': [paths.codexA, paths.codexB],+ 'the same rollout twice': [paths.codexA, paths.codexA],+ 'outside the sessions': [paths.outside, join(root, 'elsewhere', 'rollout-x.jsonl')],+ 'another folder': [paths.codexB],+ 'a moved home': [paths.codexMoved],+ 'nothing': [],+ }+ for (const [name, files] of Object.entries(held)) {+ for (const [cwdName, cwd] of [['a', work('a')], ['c', work('c')]] as const) {+ cases[`open files · ${name} · ${cwdName}`] = await attempt(() => s.openFileSessionOf('codex', 7, sessions, cwd, async () => files))+ }+ }+ // Only a file named as a rollout counts, however its first record reads.+ const heldRoot = join(root, 'held')+ write(join(heldRoot, `rollout-held-${B}.jsonl`), jsonl(meta(B, work('a'))))+ write(join(heldRoot, `notes-${C}.jsonl`), jsonl(meta(C, work('a'))))+ cases['open files · a rollout and another session-shaped file'] = await attempt(() => s.openFileSessionOf('codex', 7, heldRoot, work('a'),+ async () => [join(heldRoot, `notes-${C}.jsonl`), join(heldRoot, `rollout-held-${B}.jsonl`)]))+ cases['open files · one root'] = await attempt(() => s.openFileSessionOf('codex', 7, join(root, 'codex', 'sessions'), work('a'), async () => [paths.codexA]))+ cases['open files · claude'] = await attempt(() => s.openFileSessionOf('claude', 7, sessions, work('a'), async () => [paths.codexA]))+ const rows = (args: string, executable: string) => async () => [+ { pid: 7, parentPid: 1, executable, args },+ { pid: 8, parentPid: 7, executable: 'codex', args: 'codex --no-daemon' },+ { pid: 9, parentPid: 8, executable: 'rg', args: 'rg x' },+ ]+ const filesOf = (byPid: Record<number, string[]>) => async (pid: number) => byPid[pid] ?? []+ for (const [name, own, launcher, executable] of [+ ['own rollout', [paths.codexA], 'codex', 'codex'],+ ['node launcher', ['/dev/null'], 'node /opt/codex.js', 'node'],+ ['nodejs launcher', [], '/usr/bin/nodejs /opt/codex.js', '/usr/bin/nodejs'],+ ['not a launcher', ['/dev/null'], 'python3 x', 'python3'],+ ] as const) {+ cases[`process files · ${name}`] = await attempt(() => s.processFilesOf('codex', 7, filesOf({ 7: [...own], 8: [paths.codexB] }), rows(launcher, executable)))+ }+ cases['process files · no process table'] = await attempt(() => s.processFilesOf('codex', 7, filesOf({ 7: ['/dev/null'] }), async () => null))+ cases['process files · two children'] = await attempt(() => s.processFilesOf('codex', 7, filesOf({ 7: [], 8: [paths.codexB], 10: [paths.codexA] }), async () => [+ { pid: 7, parentPid: 1, executable: 'node', args: 'node /opt/codex.js' },+ { pid: 8, parentPid: 7, executable: 'codex', args: 'codex' }, { pid: 10, parentPid: 7, executable: 'codex', args: 'codex' }]))+ return cases+}++// ------------------------------------------------------------------------------------------- continuation++async function continuationCases(): Promise<Record<string, unknown>> {+ const dir = join(root, 'claude/projects/-work-b')+ const marker = (id: unknown) => ({ type: 'continued-in', continuedInSessionId: id })+ const big = 'x'.repeat(300 * 1024)+ const files: Record<string, string> = {+ 'continued, with a turn': jsonl({ type: 'user' }, marker(C)),+ 'continued, background': jsonl({ type: 'user' }, marker('a0a0a0a0-0000-4000-8000-a0a0a0a0a0a0')),+ 'continued, next missing': jsonl(marker('b0b0b0b0-0000-4000-8000-b0b0b0b0b0b0')),+ 'continued, next is a folder': jsonl(marker('c0c0c0c0-0000-4000-8000-c0c0c0c0c0c0')),+ 'continued, next is large': jsonl(marker('d0d0d0d0-0000-4000-8000-d0d0d0d0d0d0')),+ 'continued, next turn as assistant': jsonl(marker('e0e0e0e0-0000-4000-8000-e0e0e0e0e0e0')),+ 'continued, next is large without a turn': jsonl(marker('f0f0f0f0-0000-4000-8000-f0f0f0f0f0f0')),+ 'not the last line': jsonl(marker(C), { type: 'user' }),+ 'a marker without an id': jsonl({ type: 'continued-in' }),+ 'a marker with a number': jsonl(marker(5)),+ 'invalid JSON last': jsonl('{bad'),+ 'empty': '',+ 'trailing blank lines': `${JSON.stringify(marker(C))}\n\n \n`,+ }+ write(join(dir, 'a0a0a0a0-0000-4000-8000-a0a0a0a0a0a0.jsonl'), jsonl({ type: 'ai-title' }, { type: 'agent-name' }))+ mkdirSync(join(dir, 'c0c0c0c0-0000-4000-8000-c0c0c0c0c0c0.jsonl'), { recursive: true })+ write(join(dir, 'd0d0d0d0-0000-4000-8000-d0d0d0d0d0d0.jsonl'), jsonl({ type: 'file-history-snapshot', big }, { type: 'user' }))+ write(join(dir, 'e0e0e0e0-0000-4000-8000-e0e0e0e0e0e0.jsonl'), jsonl({ type: 'mode' }, '{"type":"assistant","x":"\\"user\\""}'))+ // Past the 256 KiB head and short of twice it, with no turn at all: taken for its length.+ write(join(dir, 'f0f0f0f0-0000-4000-8000-f0f0f0f0f0f0.jsonl'), jsonl({ type: 'file-history-snapshot', big }))+ const cases: Record<string, unknown> = {}+ for (const [name, text] of Object.entries(files)) {+ const path = join(dir, `${name.replace(/[^a-z]+/g, '-')}.jsonl`)+ write(path, text)+ cases[name] = await attempt(() => m.stores.continuationOf('claude', path))+ }+ cases['missing file'] = await attempt(() => m.stores.continuationOf('claude', join(dir, 'nope.jsonl')))+ cases['codex'] = await attempt(() => m.stores.continuationOf('codex', join(dir, 'continued-with-a-turn.jsonl')))+ return cases+}++// ----------------------------------------------------------------------------------------- rollouts++/** A rollout whose first line is exactly `bytes` long: its record names no machine path, so neither does its size. */+function sizedFirstLine(bytes: number): string {+ const base = JSON.stringify({ ...meta(A, '/w'), pad: '' })+ return jsonl({ ...meta(A, '/w'), pad: 'x'.repeat(bytes - base.length) })+}++function rolloutCases(): Record<string, unknown> {+ const dir = join(root, 'rollouts')+ const files: Record<string, string> = {+ 'a conversation': jsonl(meta(A, '/w')),+ 'a sub-agent of a parent': jsonl(child(CHILD, A, '/w')),+ 'a sub-agent without a parent': jsonl(child(CHILD, null, '/w')),+ 'a null sub-agent': jsonl(meta(A, '/w', { subagent: null })),+ 'an empty parent': jsonl(meta(A, '/w', { subagent: { thread_spawn: { parent_thread_id: '' } } })),+ 'no id, no cwd': jsonl({ type: 'session_meta', payload: { source: 'cli' } }),+ 'an id that is not text': jsonl({ type: 'session_meta', payload: { id: 7, cwd: 8 } }),+ 'no payload': jsonl({ type: 'session_meta' }),+ 'another record first': jsonl({ type: 'response_item', payload: {} }, meta(A, '/w')),+ 'blank lines first': `\n\n${JSON.stringify(meta(A, '/w'))}\n`,+ 'invalid JSON': '{bad\n',+ 'empty': '',+ 'a first line past 128 KiB': jsonl({ ...meta(A, '/w'), pad: 'x'.repeat(130 * 1024) }),+ 'a first line just under 128 KiB': jsonl({ ...meta(A, '/w'), pad: 'x'.repeat(127 * 1024) }),+ 'a first line 512 bytes past 128 KiB': sizedFirstLine(128 * 1024 + 512),+ }+ const cases: Record<string, unknown> = {}+ for (const [name, text] of Object.entries(files)) {+ const path = join(dir, `${name.replace(/[^a-z0-9]+/gi, '-')}.jsonl`)+ write(path, text)+ cases[`meta · ${name}`] = norm(m.stores.sessionMetaOf('codex', path))+ }+ cases['meta · missing'] = norm(m.stores.sessionMetaOf('codex', join(dir, 'missing.jsonl')))+ cases['meta · claude'] = norm(m.stores.sessionMetaOf('claude', paths.codexA))+ // Found by thread id: a `.jsonl` whose name holds it, under a root; folders with a dot are not entered.+ write(join(root, 'walk', '2026', '10', `rollout-x-${A}.jsonl`), '{}\n')+ write(join(root, 'walk', 'v1.2', `rollout-x-${B}.jsonl`), '{}\n')+ write(join(root, 'walk', `rollout-x-${C}.json`), '{}\n')+ for (const [name, id, at] of [+ ['nested', A, join(root, 'walk')], ['in a dotted folder', B, join(root, 'walk')], ['not jsonl', C, join(root, 'walk')],+ ['an id too short', 'abc', join(root, 'walk')], ['an id with a slash', 'aaaaaaaa/1111', join(root, 'walk')], ['a missing root', A, join(root, 'nope')],+ ] as const) {+ cases[`find · ${name}`] = norm(m.stores.findSessionFileOf('codex', id, at))+ }+ for (const moved of [false, true]) {+ if (moved) adoptMoved(); else forgetMoved()+ cases[`find · every home · ${moved ? 'moved' : 'default'}`] = norm([m.stores.findSessionFileOf('codex', A), m.stores.findSessionFileOf('codex', MOVED_ID), m.stores.findSessionFileOf('codex', PROFILE_ID)])+ }+ forgetMoved()+ cases['find · claude'] = norm(m.stores.findSessionFileOf('claude', A, join(root, 'walk')))+ return cases+}++// --------------------------------------------------------------------------------------- the registry++async function registryCases(): Promise<Record<string, unknown>> {+ const cases: Record<string, unknown> = {}+ const row = (over: Record<string, unknown>) => ({+ launcherId: 'h1', engine: 'codex', projectDir: 'p', cwd: join(root, 'work', 'a'), tmuxPane: '%8', source: null, title: null, model: null,+ processIdentity: null, registeredAt: 1, updatedAt: 1, lastHookAt: 1, lastTranscriptAt: 1, ...over,+ })+ const scenarios: Record<string, Array<Record<string, unknown>>> = {+ 'a codex parent overwritten by its sub-agent': [row({ sessionId: A, transcriptPath: paths.codexChild })],+ 'a codex row overwritten by another parent\'s sub-agent': [row({ sessionId: B, transcriptPath: paths.codexChild })],+ 'a codex parent whose own rollout is gone': [row({ sessionId: OTHER, transcriptPath: join(root, 'codex/sessions/2026/10/08', `rollout-x-${'1'.repeat(8)}.jsonl`) })],+ 'a codex parent on a profile, overwritten': [row({ sessionId: A, transcriptPath: paths.codexChild, codexHome: join(root, 'profile') })],+ 'a codex row with its own rollout': [row({ sessionId: A, transcriptPath: paths.codexA })],+ 'a codex row in a moved home': [row({ sessionId: MOVED_ID, transcriptPath: paths.codexMoved })],+ 'a codex row on a profile': [row({ sessionId: PROFILE_ID, transcriptPath: paths.codexProfile, codexHome: join(root, 'profile') })],+ 'a codex row on a profile, with the default rollout': [row({ sessionId: A, transcriptPath: paths.codexA, codexHome: join(root, 'profile') })],+ 'a codex row without a transcript': [row({ sessionId: A, transcriptPath: null })],+ 'a claude row': [row({ engine: 'claude', sessionId: A, transcriptPath: paths.claudeA })],+ 'a claude row in a moved home': [row({ engine: 'claude', sessionId: MOVED_ID, transcriptPath: paths.claudeMoved })],+ 'a claude row outside its projects': [row({ engine: 'claude', sessionId: OTHER, transcriptPath: paths.outside })],+ 'a claude row without a transcript': [row({ engine: 'claude', sessionId: A, transcriptPath: null })],+ 'a cursor row without a transcript': [row({ engine: 'cursor', sessionId: A, transcriptPath: null })],+ 'an unbound row': [row({ sessionId: '', transcriptPath: paths.codexA })],+ }+ const project = (s: RegisteredSession) => ({ agentId: s.agentId, engine: s.engine, sessionId: s.sessionId, transcriptPath: s.transcriptPath,+ projectDir: s.projectDir, codexHome: s.codexHome, bound: s.boundAt !== null })+ const logs: string[] = []+ const log = vi.spyOn(console, 'log').mockImplementation((...args: unknown[]) => { logs.push(args.map(String).join(' ')) })+ try {+ for (const moved of [false, true]) {+ if (moved) adoptMoved(); else forgetMoved()+ for (const [name, rows] of Object.entries(scenarios)) {+ const file = join(root, 'data', 'registry.json')+ writeFileSync(file, JSON.stringify(rows), { mode: 0o644 })+ chmodSync(file, 0o644)+ logs.length = 0+ m.registry.registry.load()+ const persisted = JSON.parse(readFileSync(file, 'utf8')) as Array<Record<string, unknown>>+ cases[`${moved ? 'moved homes' : 'default homes'} · ${name}`] = norm({+ loaded: m.registry.registry.list().map(project),+ persisted: persisted.map((saved) => ({ sessionId: saved.sessionId, transcriptPath: saved.transcriptPath, projectDir: saved.projectDir })),+ logged: logs.filter((line) => line.includes('[registry] repaired')),+ })+ }+ }+ } finally { log.mockRestore() }+ forgetMoved()+ return cases+}++// ------------------------------------------------------------------------------------- capture and handoff++async function captureCases(): Promise<Record<string, unknown>> {+ const cases: Record<string, unknown> = {}+ const session = (over: Partial<RegisteredSession>) => ({ agentId: 'a1', engine: 'claude', sessionId: A, transcriptPath: null, cwd: join(root, 'work', 'a'),+ codexHome: null, processIdentity: null, ...over }) as RegisteredSession+ adoptMoved()+ const shapes: Record<string, Partial<RegisteredSession>> = {+ 'claude, no transcript': {}, 'claude, a stale transcript': { transcriptPath: join(root, 'gone.jsonl') }, 'claude, its transcript': { transcriptPath: paths.claudeA },+ 'claude, in a moved home': { sessionId: MOVED_ID }, 'claude, unknown': { sessionId: OTHER },+ 'codex, no transcript': { engine: 'codex' }, 'codex, on a profile': { engine: 'codex', sessionId: PROFILE_ID, codexHome: join(root, 'profile') },+ 'codex, a sub-agent id': { engine: 'codex', sessionId: CHILD }, 'opencode': { engine: 'opencode' }, 'terminal': { engine: 'terminal' },+ 'claude, unbound, no process': { sessionId: '' },+ }+ for (const [name, over] of Object.entries(shapes)) {+ const out = await m.capture.captureResumeIdentity(session(over))+ cases[`capture · ${name}`] = norm({ sessionId: out.sessionId, transcriptPath: out.transcriptPath, source: out.source ?? null })+ }+ forgetMoved()+ // Which finder the handoff asks, per engine, and with what.+ for (const engine of ['claude', 'codex', 'pi', 'opencode', 'cursor'] as const) {+ const calls: unknown[] = []+ const discover = m.handoff.sessionDiscovery({+ findLiveSession: async (...args) => { calls.push(['findLiveSession', ...args]); return { sessionId: B, transcriptPath: paths.codexB } },+ processSession: async (...args) => { calls.push(['processSession', ...args]); return { sessionId: A, transcriptPath: paths.claudeA } },+ isLive: () => true, ownedByOther: () => false, isRecentlyDeleted: () => false,+ })+ const found = await discover(session({ engine, sessionId: '', codexHome: engine === 'codex' ? join(root, 'profile') : null,+ processIdentity: { pid: 42, startMarker: 'Thu Oct 8 10:00:00 2026', executable: engine } }))+ cases[`handoff · ${engine}`] = norm({ found, calls: calls.map((call) => (call as unknown[]).map((arg) => typeof arg === 'number' && arg > 1e12 ? '<start>' : arg)) })+ }+ return cases+}++type Sections = Record<string, Record<string, unknown>>+const PLATFORMS = ['darwin', 'linux'] as const++async function sectionsOn(platform: (typeof PLATFORMS)[number]): Promise<Sections> {+ const real = Object.getOwnPropertyDescriptor(process, 'platform')!+ Object.defineProperty(process, 'platform', { ...real, value: platform })+ try {+ return {+ homes: await homeCases(), transcripts: transcriptCases(), find: await findCases(), continuation: await continuationCases(),+ rollouts: rolloutCases(), registry: await registryCases(), capture: await captureCases(),+ }+ } finally { Object.defineProperty(process, 'platform', real) }+}++describe('core finds sessions where it did before Claude Code and Codex declared their stores', () => {+ it('homes, transcripts, finders, continuations, rollouts, the registry\'s load, capture and handoff match the record, on darwin and linux', async () => {+ const darwin = await sectionsOn('darwin')+ const linux = await sectionsOn('linux')+ const linuxDiffers = Object.fromEntries(Object.entries(linux).map(([section, cases]) => [section,+ Object.fromEntries(Object.entries(cases).filter(([key, value]) => JSON.stringify(value) !== JSON.stringify(darwin[section]![key])))]))+ if (RECORD) {+ const block = (cases: Record<string, unknown>): string => Object.entries(cases).map(([key, value]) => ` ${JSON.stringify(key)}: ${JSON.stringify(value)}`).join(',\n')+ const sections = (all: Sections): string => Object.entries(all).map(([section, cases]) => `${JSON.stringify(section)}: {\n${block(cases)}\n}`).join(',\n')+ writeFileSync(GOLDEN, `{\n${sections(darwin)},\n"linux": {\n${sections(linuxDiffers)}\n}\n}\n`)+ return+ }+ const { linux: linuxGolden, ...darwinGolden } = JSON.parse(readFileSync(GOLDEN, 'utf8')) as Sections & { linux: Sections }+ for (const [platform, actual, golden] of [+ ['darwin', darwin, darwinGolden],+ ['linux', linux, Object.fromEntries(Object.entries(darwinGolden).map(([section, cases]) => [section, { ...cases, ...linuxGolden[section] }]))],+ ] as const) {+ expect(Object.keys(actual), platform).toEqual(Object.keys(golden))+ for (const [section, cases] of Object.entries(golden)) {+ expect(Object.keys(actual[section]!).sort(), `${platform} · ${section}`).toEqual(Object.keys(cases).sort())+ for (const [key, value] of Object.entries(cases)) expect(actual[section]![key], `${platform} · ${section} · ${key}`).toEqual(value)+ }+ }+ }, 120_000)++ it('records no machine-specific path', () => {+ const text = readFileSync(GOLDEN, 'utf8')+ expect(text).not.toContain('session-store-golden-')+ expect(text).not.toContain(root)+ expect(text).not.toMatch(/\/Users\/|\/home\/runner/)+ })+})diff --git a/cli/src/engines/sessionStoreContracts.ts b/cli/src/engines/sessionStoreContracts.tsnew file mode 100644index 000000000..cf7b2e0a6--- /dev/null+++ b/cli/src/engines/sessionStoreContracts.ts@@ -0,0 +1,22 @@+/**+ * The engines' declared session stores (engines/{claude,codex}/sessionStore.ts): data only, imported by what+ * reads them in core (lib/engineHomes.ts, engines/sessionFiles.ts, lib/sessionRepair.ts, the registry) with+ * nothing else in the way, so none of those loads an engine's code.+ */+import { sessionStore as claude } from './claude/sessionStore.js'+import { sessionStore as codex } from './codex/sessionStore.js'+import type { SessionStoreContract } from './facets/sessionStore.js'+import type { AgentEngine } from './types.js'++export const sessionStoreContracts = { claude, codex } satisfies Record<string, SessionStoreContract>+export type SessionStoreEngine = keyof typeof sessionStoreContracts++/** Whether `engine` declares a session store. Any name: a session row's engine is a string. */+export function isSessionStoreEngine(engine: AgentEngine | string): engine is SessionStoreEngine {+ return Object.hasOwn(sessionStoreContracts, engine)+}++/** An engine's session store, for an engine that declares one. */+export function sessionStoreOf(engine: AgentEngine | string): SessionStoreContract | undefined {+ return isSessionStoreEngine(engine) ? sessionStoreContracts[engine] : undefined+}diff --git a/cli/src/engines/sessionStores.ts b/cli/src/engines/sessionStores.tsnew file mode 100644index 000000000..0af6db65f--- /dev/null+++ b/cli/src/engines/sessionStores.ts@@ -0,0 +1,9 @@+/**+ * Where an engine keeps its sessions, and how core reads them: a session file's first record, a session+ * file found by its id, the session a live process names, and a conversation continued in another file.+ * Each engine declares its store (engines/{claude,codex}/sessionStore.ts, listed in engines/sessionStoreContracts.ts)+ * and these apply it with the kit, in core: the registry, session repair, resume capture and the handoff name no+ * engine, and binding a session never waits on an engine worker.+ */+export { continuationOf, findSessionFileOf, sessionMetaOf, type SessionMeta } from './sessionFiles.js'+export { openFileSessionOf, processFilesOf, processSessionOf } from '../lib/sessionRepair.js'diff --git a/cli/src/lib/captureResumeIdentity.spec.ts b/cli/src/lib/captureResumeIdentity.spec.tsindex ff0c60941..77d10ed35 100644--- a/cli/src/lib/captureResumeIdentity.spec.ts+++ b/cli/src/lib/captureResumeIdentity.spec.ts@@ -1,10 +1,10 @@import { beforeEach, expect, it, vi } from 'vitest'import { captureResumeIdentity } from './captureResumeIdentity.js'import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'-import { claudeProcessSession, findLiveSession, findResumedTranscript } from './sessionRepair.js'+import { findLiveSession, findResumedTranscript, processSessionOf } from './sessionRepair.js'import { processRows, resumeSessionId } from './tmux.js'vi.mock('./registry.js', () => ({ validTranscriptPath: vi.fn(() => true), engineKeepsTranscriptFile: vi.fn(() => true) }))-vi.mock('./sessionRepair.js', () => ({ claudeProcessSession: vi.fn(), findLiveSession: vi.fn(), findResumedTranscript: vi.fn() }))+vi.mock('./sessionRepair.js', () => ({ processSessionOf: vi.fn(), findLiveSession: vi.fn(), findResumedTranscript: vi.fn() }))vi.mock('./tmux.js', () => ({ processRows: vi.fn(), resumeSessionId: vi.fn() }))let row: RegisteredSessionbeforeEach(() => {@@ -15,7 +15,7 @@ beforeEach(() => {vi.mocked(validTranscriptPath).mockReturnValue(true)vi.mocked(engineKeepsTranscriptFile).mockReturnValue(true)vi.mocked(resumeSessionId).mockReturnValue(null)- vi.mocked(claudeProcessSession).mockResolvedValue(null)+ vi.mocked(processSessionOf).mockResolvedValue(null)vi.mocked(findLiveSession).mockResolvedValue(null)vi.mocked(findResumedTranscript).mockResolvedValue(null)})@@ -86,8 +86,9 @@ it.each(['claude', 'codex'] as const)('captures an explicit %s resume without gu})it('prefers current Claude native metadata to old resume argv', async () => {vi.mocked(resumeSessionId).mockReturnValue('old')- vi.mocked(claudeProcessSession).mockResolvedValue({ sessionId: 'current', transcriptPath: '/current' })+ vi.mocked(processSessionOf).mockResolvedValue({ sessionId: 'current', transcriptPath: '/current' })expect(await captureResumeIdentity(row)).toMatchObject({ sessionId: 'current' }); expect(findResumedTranscript).not.toHaveBeenCalled()+ expect(processSessionOf).toHaveBeenCalledWith('claude', 77, '/work', Date.parse(row.processIdentity!.startMarker))})it('captures a unique fresh session before its first hook arrives', async () => {vi.mocked(findLiveSession).mockResolvedValue({ sessionId: 'new', transcriptPath: '/new' })diff --git a/cli/src/lib/captureResumeIdentity.ts b/cli/src/lib/captureResumeIdentity.tsindex 27383a66d..fce949366 100644--- a/cli/src/lib/captureResumeIdentity.ts+++ b/cli/src/lib/captureResumeIdentity.ts@@ -8,7 +8,7 @@* including the four that keep theirs in a database rather than a file.*/import { engineKeepsTranscriptFile, validTranscriptPath, type RegisteredSession } from './registry.js'-import { claudeProcessSession, findLiveSession, findResumedTranscript } from './sessionRepair.js'+import { findLiveSession, findResumedTranscript, processSessionOf } from './sessionRepair.js'import { processRows, resumeSessionId } from './tmux.js'import { sameProcessIdentity } from './terminalRuntime.js'import { isTerminalEngine } from '../engines/types.js'@@ -33,8 +33,8 @@ export async function captureResumeIdentity(session: RegisteredSession): Promise&& row.executable === expected.executable)if (!live) return sessionconst explicit = resumeSessionId(session.engine, live.args)- const native = session.engine === 'claude'- ? await claudeProcessSession(expected.pid, session.cwd, Date.parse(expected.startMarker)) : null+ // An engine whose process names its own session in a record (Claude Code's, removed at exit) is read now.+ const native = await processSessionOf(session.engine, expected.pid, session.cwd, Date.parse(expected.startMarker))const found = native ?? (explicit? { sessionId: explicit, transcriptPath: await findResumedTranscript(session.engine, explicit, options) }: await findLiveSession(session.engine, session.cwd, Date.parse(expected.startMarker), {diff --git a/cli/src/lib/engineHomes.spec.ts b/cli/src/lib/engineHomes.spec.tsindex 754f41505..de3ac8bc5 100644--- a/cli/src/lib/engineHomes.spec.ts+++ b/cli/src/lib/engineHomes.spec.ts@@ -3,7 +3,10 @@ import { homedir, tmpdir } from 'node:os'import { dirname, join } from 'node:path'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { env } from '../config/env.js'-import { adoptEngineHomes, claudeProjectsRoots, codexHomeRoots, launchClaudeConfigDir, launchCodexHome, movedEngineHomes, resetEngineHomes, sessionClaudeHome, sessionCodexHome } from './engineHomes.js'+import {+ adoptEngineHomes, adoptHomes, claudeProjectsRoots, codexHomeRoots, launchClaudeConfigDir, launchCodexHome, movedEngineHomes, movedHomes,+ ownHomeOf, profileEnvironment, resetEngineHomes, sessionClaudeHome, sessionCodexHome, sessionFolderOf, sessionRoots,+} from './engineHomes.js'// The login shell's environment, as the daemon captured it at start-up: none, unless a test says so.const shell = vi.hoisted(() => ({ env: {} as NodeJS.ProcessEnv }))@@ -106,6 +109,30 @@ describe('the homes the person moved', () => {} finally { shell.env = {} }})+ // Each engine's session store declares its movable home (engines/sessionStoreContracts.ts): which variable moves+ // it, the daemon's own, and the folder its sessions are in below it.+ it('adopts and searches every engine\'s home by its declared session store', () => {+ expect(ownHomeOf('claude')).toBe(dirname(env.CLAUDE_PROJECTS_DIR))+ expect(ownHomeOf('codex')).toBe(env.CODEX_HOME)+ const claude = join(root, 'claude-work'), codex = join(root, 'codex-work')+ // The daemon's own homes, as declared, move nothing.+ expect(adoptHomes({ CLAUDE_CONFIG_DIR: dirname(env.CLAUDE_PROJECTS_DIR), CODEX_HOME: env.CODEX_HOME })).toEqual({ claude: null, codex: null })+ expect(adoptHomes({ CLAUDE_CONFIG_DIR: claude, CODEX_HOME: codex })).toEqual({ claude, codex })+ expect([movedHomes('claude'), movedHomes('codex'), movedHomes('pi'), movedHomes('toString')]).toEqual([[claude], [codex], [], []])+ expect(sessionRoots('claude')).toEqual([env.CLAUDE_PROJECTS_DIR, join(claude, 'projects')])+ // Claude Code's sessions follow no profile of an agent's own; Codex's are on that profile alone.+ expect(sessionRoots('claude', '/profile')).toEqual(sessionRoots('claude'))+ expect(sessionRoots('codex')).toEqual([join(env.CODEX_HOME, 'sessions'), join(codex, 'sessions')])+ expect(sessionRoots('codex', '/profile')).toEqual([join('/profile', 'sessions')])+ expect([sessionRoots('pi'), sessionRoots('opencode', '/profile')]).toEqual([[], []])+ // The sessions folder a session's file is in, for the parent beside it.+ expect(sessionFolderOf('codex', { transcriptPath: join(codex, 'archived_sessions', 'thread.jsonl') })).toBe(join(codex, 'sessions'))+ expect(sessionFolderOf('codex', { profile: '/profile', transcriptPath: join(codex, 'sessions', 'thread.jsonl') })).toBe(join('/profile', 'sessions'))+ // An agent launched on its own profile is given it by the variable that moves its engine's home.+ expect([profileEnvironment('codex', '/profile'), profileEnvironment('claude', '/profile'), profileEnvironment('pi', '/profile')])+ .toEqual([{ CODEX_HOME: '/profile' }, undefined, undefined])+ })+it('Claude settings follow the bound home or current shell, with the settings default separate from folder trust', () => {const previous = join(root, 'previous-claude'), current = join(root, 'current-claude')adoptEngineHomes({ CLAUDE_CONFIG_DIR: previous }, defaults)diff --git a/cli/src/lib/engineHomes.ts b/cli/src/lib/engineHomes.tsindex bb25237e4..3407d217c 100644--- a/cli/src/lib/engineHomes.ts+++ b/cli/src/lib/engineHomes.ts@@ -24,10 +24,12 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'import { env } from '../config/env.js'import type { FolderSetting } from '../engines/facets/hooks.js'import type { LaunchHome } from '../engines/facets/launch.js'+import { sessionStoreContracts, sessionStoreOf, type SessionStoreEngine } from '../engines/sessionStoreContracts.js'+import type { AgentEngine } from '../engines/types.js'import { loginShellEnvironment } from './loginShellEnv.js'-const claudeHomes: string[] = []-const codexHomes: string[] = []+/** The homes each engine's person moved (its session store's `sessions.moved.variable`), by engine, as saved. */+const movedByEngine = Object.fromEntries(Object.keys(sessionStoreContracts).map((engine) => [engine, [] as string[]])) as Record<SessionStoreEngine, string[]>let loadedStamp = ''const savedFile = (): string => join(env.ADAPTER_DATA_DIR, 'engine-homes.json')@@ -40,14 +42,13 @@ function load(): void {const stamp = `${file}:${stat.ino}:${stat.mtimeMs}:${stat.size}`if (stamp === loadedStamp) returnloadedStamp = stamp- const saved = JSON.parse(readFileSync(file, 'utf8')) as { claude?: unknown; codex?: unknown }+ const saved = JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>const take = (list: unknown, into: string[]): void => {for (const home of Array.isArray(list) ? list : []) {if (typeof home === 'string' && isAbsolute(home) && !into.includes(home)) into.push(home)}}- take(saved.claude, claudeHomes)- take(saved.codex, codexHomes)+ for (const [engine, homes] of Object.entries(movedByEngine)) take(saved[engine], homes)} catch { /* none adopted yet, or unreadable: the login shell's are adopted again once it is read */ }}@@ -56,7 +57,7 @@ function save(): void {try {mkdirSync(dirname(file), { recursive: true })const draft = `${file}.${process.pid}.tmp`- writeFileSync(draft, JSON.stringify({ claude: claudeHomes, codex: codexHomes }) + '\n', { mode: 0o600 })+ writeFileSync(draft, JSON.stringify(movedByEngine) + '\n', { mode: 0o600 })renameSync(draft, file)} catch { /* best effort: adopted again at the next start, once the login shell is read */ }}@@ -69,49 +70,81 @@ export interface MovedHomes {/** Adopt the homes `environment` moves, beside the daemon's own (`defaults`), and say which are new. */export function adoptEngineHomes(environment: NodeJS.ProcessEnv, defaults: { claudeHome: string; codexHome: string }): MovedHomes {+ const moved = adoptHomes(environment, { claude: defaults.claudeHome, codex: defaults.codexHome })+ return { claude: moved.claude, codex: moved.codex }+}++/** The daemon's own home for the variable a person moves `engine`'s with (its session store's `sessions.moved`). */+export function ownHomeOf(engine: SessionStoreEngine): string {+ const { own, moved } = sessionStoreContracts[engine].sessions+ return moved.ownHome === 'setting' ? env[own.setting] : dirname(env[own.setting])+}++/**+ * Adopt the homes `environment` moves for every engine that declares a movable home, beside the daemon's own+ * (`own`, by engine: `ownHomeOf` unless given), and say which are new, by engine.+ */+export function adoptHomes(environment: NodeJS.ProcessEnv, own: Partial<Record<SessionStoreEngine, string>> = {}): Record<SessionStoreEngine, string | null> {load()- const adopt = (value: string | undefined, own: string, known: string[]): string | null => {+ const adopt = (value: string | undefined, home: string, known: string[]): string | null => {const dir = value?.trim()// A relative or `~` path is not a folder the engine resolves the same way from every directory.if (!dir || !isAbsolute(dir)) return null- const home = resolve(dir)- if (home === resolve(own) || known.includes(home)) return null- known.push(home)- return home- }- const moved = {- claude: adopt(environment.CLAUDE_CONFIG_DIR, defaults.claudeHome, claudeHomes),- codex: adopt(environment.CODEX_HOME, defaults.codexHome, codexHomes),+ const moved = resolve(dir)+ if (moved === resolve(home) || known.includes(moved)) return null+ known.push(moved)+ return moved}- if (moved.claude || moved.codex) save()+ const moved = Object.fromEntries((Object.keys(movedByEngine) as SessionStoreEngine[]).map((engine) => [engine,+ adopt(environment[sessionStoreContracts[engine].sessions.moved.variable], own[engine] ?? ownHomeOf(engine), movedByEngine[engine])])) as Record<SessionStoreEngine, string | null>+ if (Object.values(moved).some(Boolean)) save()return moved}+/** The homes the person moved `engine`'s to, adopted on this boot or an earlier one; none for an engine that+ * declares no movable home. */+export function movedHomes(engine: AgentEngine | string): string[] {+ load()+ return Object.hasOwn(movedByEngine, engine) ? [...movedByEngine[engine as SessionStoreEngine]] : []+}++/**+ * Every folder `engine`'s sessions may be in: the agent's own profile's alone, for an engine whose sessions follow+ * one; else the daemon's own folder and each moved home's. Empty for an engine that declares no session store.+ */+export function sessionRoots(engine: AgentEngine | string, profile?: string | null): string[] {+ const store = sessionStoreOf(engine)+ if (!store) return []+ const { own, moved, profile: followsProfile } = store.sessions+ const below = (home: string): string => own.folder ? join(home, own.folder) : home+ if (followsProfile && profile) return [below(profile)]+ return [below(env[own.setting]), ...movedHomes(engine).map((home) => join(home, moved.folder))]+}+/** Every moved home known: adopted on this boot or an earlier one. */export function movedEngineHomes(): { claude: string[]; codex: string[] } {- load()- return { claude: [...claudeHomes], codex: [...codexHomes] }+ return { claude: movedHomes('claude'), codex: movedHomes('codex') }}-/** Every folder Claude Code's transcripts may be in: the daemon's own, then each moved home's. */+/** Every folder Claude Code's transcripts may be in: `own`, then each moved home's. */export function claudeProjectsRoots(own: string): string[] {- load()- return [own, ...claudeHomes.map((home) => join(home, 'projects'))]+ return [own, ...movedHomes('claude').map((home) => join(home, sessionStoreContracts.claude.sessions.moved.folder))]}-/** Every Codex home whose rollouts are Codex's own: the daemon's, then each moved one. */+/** Every Codex home whose rollouts are Codex's own: `own`, then each moved one. */export function codexHomeRoots(own: string): string[] {- load()- return [own, ...codexHomes]+ return [own, ...movedHomes('codex')]}-/** The homes a setting's moves are remembered in, by setting: CODEX_HOME's are adopted above. */-const movedBySetting: Partial<Record<FolderSetting, string[]>> = { CODEX_HOME: codexHomes }--/** Every home a daemon setting names: the daemon's own, then each one the person moved and Harness adopted. */+/** Every home a daemon setting names: the daemon's own, then each one the person moved and Harness adopted (the+ * engines whose movable home is that setting's folder). */export function homeRoots(setting: FolderSetting): string[] {load()- return [env[setting], ...(movedBySetting[setting] ?? [])]+ const moved = (Object.keys(movedByEngine) as SessionStoreEngine[]).filter((engine) => {+ const { own, moved: movable } = sessionStoreContracts[engine].sessions+ return own.setting === setting && movable.ownHome === 'setting'+ })+ return [env[setting], ...moved.flatMap((engine) => movedByEngine[engine])]}/**@@ -150,12 +183,30 @@ export function launchHome(setting: FolderSetting, profile: string | null | unde* environment was unreadable. A bound transcript identifies its adopted home even in a service* without the core's shell cache. An explicit profile remains authoritative. */export function sessionCodexHome(session: { codexHome?: string | null; transcriptPath?: string | null }): string {- if (session.codexHome) return session.codexHome- const home = session.transcriptPath && codexHomeRoots(env.CODEX_HOME).find(root => {+ return sessionHomeOf('codex', { profile: session.codexHome, transcriptPath: session.transcriptPath })+}++/**+ * The home a session's file is in, for an engine whose movable home is its setting's folder (its session store's+ * `sessions.moved.ownHome` is `setting`: Codex's): the agent's own profile, else the known home whose sessions+ * (or archived sessions) hold the file, else the home a launch made now would use.+ */+export function sessionHomeOf(engine: SessionStoreEngine, session: { profile?: string | null; transcriptPath?: string | null }): string {+ if (session.profile) return session.profile+ const { own, archived } = sessionStoreContracts[engine].sessions+ const folders = [own.folder, archived].filter((folder): folder is string => !!folder)+ const home = session.transcriptPath && homeRoots(own.setting).find(root => {const path = relative(root, session.transcriptPath!)- return path.startsWith(`sessions${sep}`) || path.startsWith(`archived_sessions${sep}`)+ return folders.some((folder) => path.startsWith(`${folder}${sep}`))})- return home || launchCodexHome(null)+ return home || launchHome(own.setting, null)+}++/** The sessions folder of that home (`sessionHomeOf`): where a session beside the one in that file is. */+export function sessionFolderOf(engine: SessionStoreEngine, session: { profile?: string | null; transcriptPath?: string | null }): string {+ const { own } = sessionStoreContracts[engine].sessions+ const home = sessionHomeOf(engine, session)+ return own.folder ? join(home, own.folder) : home}/** Found by QA on a quiet machine: Claude's picker and effort read another login's settings.@@ -184,9 +235,15 @@ export function launchHomeOf(home: LaunchHome, profile: string | null | undefinereturn 'setting' in home ? launchHome(home.setting, profile, environment) : movedHome(environment[home.variable]) || homedir()}+/** The environment that runs an agent on its own profile `home`, for an engine whose sessions follow one (its+ * session store's `sessions.profile`): the variable that moves its home (`CODEX_HOME`). None for another engine. */+export function profileEnvironment(engine: AgentEngine | string, home: string): Record<string, string> | undefined {+ const sessions = sessionStoreOf(engine)?.sessions+ return sessions?.profile ? { [sessions.moved.variable]: home } : undefined+}+/** Test seam: forget every home, and read the data folder's again on next use. */export function resetEngineHomes(): void {- claudeHomes.length = 0- codexHomes.length = 0+ for (const homes of Object.values(movedByEngine)) homes.length = 0loadedStamp = ''}diff --git a/cli/src/lib/handoffDiscovery.spec.ts b/cli/src/lib/handoffDiscovery.spec.tsindex a0754f42d..c9f7152b3 100644--- a/cli/src/lib/handoffDiscovery.spec.ts+++ b/cli/src/lib/handoffDiscovery.spec.ts@@ -12,12 +12,12 @@ const agent = (over: Record<string, unknown> = {}): RegisteredSession => ({processIdentity: { pid: 4242, executable: 'claude', startMarker: MARKER }, ...over,}) as unknown as RegisteredSession-type Spied = DiscoveryDeps & { findLiveSession: ReturnType<typeof vi.fn>; claudeProcessSession: ReturnType<typeof vi.fn> }+type Spied = DiscoveryDeps & { findLiveSession: ReturnType<typeof vi.fn>; processSession: ReturnType<typeof vi.fn> }/** Codex is the default engine here: Claude is looked for through its process record only (its own block below). */function deps(over: Partial<DiscoveryDeps> = {}): Spied {const findLiveSession = vi.fn(async () => ({ sessionId: 's9', transcriptPath: '/t/s9.jsonl' }))- const claudeProcessSession = vi.fn(async () => ({ sessionId: 's9', transcriptPath: '/t/s9.jsonl' }))- return { findLiveSession, claudeProcessSession, isLive: () => true, ownedByOther: () => false, isRecentlyDeleted: () => false, ...over } as Spied+ const processSession = vi.fn(async () => ({ sessionId: 's9', transcriptPath: '/t/s9.jsonl' }))+ return { findLiveSession, processSession, isLive: () => true, ownedByOther: () => false, isRecentlyDeleted: () => false, ...over } as Spied}describe('sessionDiscovery', () => {@@ -48,7 +48,7 @@ describe('sessionDiscovery', () => {const d = deps()expect(await sessionDiscovery(d)(agent({ engine, processIdentity }))).toBeNull()expect(d.findLiveSession).not.toHaveBeenCalled()- expect(d.claudeProcessSession).not.toHaveBeenCalled()+ expect(d.processSession).not.toHaveBeenCalled()})}}@@ -58,21 +58,21 @@ describe('sessionDiscovery', () => {it('accepts only the session the record names, and never scans the project folder', async () => {const d = deps()expect(await sessionDiscovery(d)(agent({ engine: 'claude' }))).toEqual({ engine: 'claude', sessionId: 's9', transcriptPath: '/t/s9.jsonl' })- expect(d.claudeProcessSession).toHaveBeenCalledWith(4242, '/w', Date.parse(MARKER))+ expect(d.processSession).toHaveBeenCalledWith('claude', 4242, '/w', Date.parse(MARKER))expect(d.findLiveSession).not.toHaveBeenCalled()})it('answers nothing, with no scan to fall back on, when the record matches no session or does not exist', async () => {- const d = deps({ claudeProcessSession: async () => null })+ const d = deps({ processSession: async () => null })expect(await sessionDiscovery(d)(agent({ engine: 'claude' }))).toBeNull()expect(d.findLiveSession).not.toHaveBeenCalled()})it('still refuses a record whose session has no path, is a subagent file, is owned or deleted, or whose read throws', async () => {const claude = (over: Partial<DiscoveryDeps>) => sessionDiscovery(deps(over))(agent({ engine: 'claude' }))- expect(await claude({ claudeProcessSession: async () => ({ sessionId: 's9' }) })).toBeNull()- expect(await claude({ claudeProcessSession: async () => ({ sessionId: 'a', transcriptPath: '/p/s/subagents/agent-a.jsonl' }) })).toBeNull()+ expect(await claude({ processSession: async () => ({ sessionId: 's9' }) })).toBeNull()+ expect(await claude({ processSession: async () => ({ sessionId: 'a', transcriptPath: '/p/s/subagents/agent-a.jsonl' }) })).toBeNull()expect(await claude({ ownedByOther: () => true })).toBeNull()expect(await claude({ isRecentlyDeleted: () => true })).toBeNull()- expect(await claude({ claudeProcessSession: async () => { throw new Error('boom') } })).toBeNull()+ expect(await claude({ processSession: async () => { throw new Error('boom') } })).toBeNull()})})@@ -250,7 +250,7 @@ describe('handoffProviderDeps: each dependency reaches the right function with tmirror: { recentAsks: vi.fn(() => ['ask']), lastFullText: vi.fn(() => 'full'), recent: vi.fn(() => []) } as never,databaseHistory: vi.fn(() => undefined),findLiveSession: vi.fn(async () => null),- claudeProcessSession: vi.fn(async () => null),+ processSession: vi.fn(async () => null),isRecentlyDeleted: vi.fn(() => false),findResumedTranscript: vi.fn(async () => '/t/x.jsonl'),validTranscriptPath: vi.fn(() => true),@@ -302,30 +302,30 @@ describe('handoffProviderDeps: each dependency reaches the right function with tit('discovery: live means a running agent; the deleted check gets the found session id; Claude goes by its process record', async () => {const byAgent = vi.fn(() => ({}))const isRecentlyDeleted = vi.fn(() => false)- const claudeProcessSession = vi.fn(async () => ({ sessionId: 'sx', transcriptPath: '/t/sx.jsonl' }))- const f = fakes({ registry: { resolve: () => undefined, byAgent, bySession: () => undefined } as never, claudeProcessSession, isRecentlyDeleted })+ const processSession = vi.fn(async () => ({ sessionId: 'sx', transcriptPath: '/t/sx.jsonl' }))+ const f = fakes({ registry: { resolve: () => undefined, byAgent, bySession: () => undefined } as never, processSession, isRecentlyDeleted })expect(await handoffProviderDeps(f).discoverSession?.(live)).toEqual({ engine: 'claude', sessionId: 'sx', transcriptPath: '/t/sx.jsonl' })expect(byAgent).toHaveBeenCalledWith('a1')expect(isRecentlyDeleted).toHaveBeenCalledWith('sx')- expect(claudeProcessSession).toHaveBeenCalledWith(7, '/w', Date.parse(MARKER))+ expect(processSession).toHaveBeenCalledWith('claude', 7, '/w', Date.parse(MARKER))})it('discovery owns the session check against the running registry and the stopped store', async () => {- const claudeProcessSession = vi.fn(async () => ({ sessionId: 'sx', transcriptPath: '/t/sx.jsonl' }))- const running = fakes({ registry: { resolve: () => undefined, byAgent: () => ({}), bySession: (sid: string) => (sid === 'sx' ? { agentId: 'other' } : undefined) } as never, claudeProcessSession })+ const processSession = vi.fn(async () => ({ sessionId: 'sx', transcriptPath: '/t/sx.jsonl' }))+ const running = fakes({ registry: { resolve: () => undefined, byAgent: () => ({}), bySession: (sid: string) => (sid === 'sx' ? { agentId: 'other' } : undefined) } as never, processSession })expect(await handoffProviderDeps(running).discoverSession?.(live)).toBeNull()- const stopped = fakes({ registry: { resolve: () => undefined, byAgent: () => ({}), bySession: () => undefined }, stopped: { ids: () => ['old'], get: () => ({ agentId: 'old', sessionId: 'sx' }) as never }, claudeProcessSession })+ const stopped = fakes({ registry: { resolve: () => undefined, byAgent: () => ({}), bySession: () => undefined }, stopped: { ids: () => ['old'], get: () => ({ agentId: 'old', sessionId: 'sx' }) as never }, processSession })expect(await handoffProviderDeps(stopped).discoverSession?.(live)).toBeNull()})it('creates the discovery once: two prepares for the same agent share one search while it is pending', async () => {let release!: (v: null) => void- const claudeProcessSession = vi.fn(() => new Promise<null>((resolve) => { release = resolve }))- const d = handoffProviderDeps(fakes({ registry: { resolve: () => undefined, byAgent: () => ({}), bySession: () => undefined } as never, claudeProcessSession }))+ const processSession = vi.fn(() => new Promise<null>((resolve) => { release = resolve }))+ const d = handoffProviderDeps(fakes({ registry: { resolve: () => undefined, byAgent: () => ({}), bySession: () => undefined } as never, processSession }))// The same deps object serves every request: what the provider in cli.ts does.const first = d.discoverSession?.(live)const second = d.discoverSession?.(live)- expect(claudeProcessSession).toHaveBeenCalledTimes(1)+ expect(processSession).toHaveBeenCalledTimes(1)release(null)await Promise.all([first, second])})diff --git a/cli/src/lib/handoffDiscovery.ts b/cli/src/lib/handoffDiscovery.tsindex 3dfac7961..f93364128 100644--- a/cli/src/lib/handoffDiscovery.ts+++ b/cli/src/lib/handoffDiscovery.ts@@ -2,6 +2,7 @@// handoff provider's dependencies (cli.ts passes the real functions, specs pass fakes). Discovery is// read-only: it never binds anything, and it answers only when the answer is certain — a Change agent// must not guess whose conversation it hands over. Consumed by lib/agentHandoff.ts.+import { sessionStoreOf } from '../engines/sessionStoreContracts.js'import type { AgentEngine } from '../engines/types.js'import type { HandoffDeps } from './agentHandoff.js'import { isSubagentTranscript } from './subagentTranscript.js'@@ -12,10 +13,12 @@ import type { TurnSource } from './sessionSearch/sessionTurns.js'import { SQLITE_BACKED_ENGINES } from './sqliteRead.js'export interface DiscoveryDeps {- /** Engines other than Claude: the born, unique session of a process (sessionRepair findLiveSession). */+ /** Engines whose process keeps no record of its session: the born, unique session of a process (sessionRepair+ * findLiveSession). */findLiveSession(engine: AgentEngine, cwd: string, startedAtMs: number, opts: { bornOnly: true; pid: number; codexHome?: string }): Promise<RepairedSession | null>- /** Claude: the session its per-process record names, or null. Never a scan of the project folder. */- claudeProcessSession(pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null>+ /** An engine whose process keeps a record of its session (its session store's `live.record`, Claude Code's): the+ * session it names, or null. Never a scan of its store. */+ processSession(engine: AgentEngine, pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null>/** The agent has a live pane (not a stopped copy). */isLive(agentId: string): boolean/** Another agent, running or stopped, already holds this session. Must answer true when it cannot tell. */@@ -28,8 +31,8 @@ const DATABASE_ENGINES: ReadonlySet<string> = new Set(SQLITE_BACKED_ENGINES)/*** `HandoffDeps.discoverSession`: the session a live, unbound, non-fork agent of a file engine runs, found by its- * process (pid and start marker) — Claude only through its per-process record, the others only a session born to- * that process — or null. Null too when the session is a subagent's, was just deleted, or another agent holds it.+ * process (pid and start marker) — an engine that keeps a per-process record only through it, the others only a+ * session born to that process — or null. Null too when the session is a subagent's, was just deleted, or another agent holds it.* One search per agent at a time: a second request while one runs shares it.*/export function sessionDiscovery(deps: DiscoveryDeps): (session: RegisteredSession) => Promise<TurnSource | null> {@@ -37,8 +40,9 @@ export function sessionDiscovery(deps: DiscoveryDeps): (session: RegisteredSessiasync function find(session: RegisteredSession, cwd: string, pid: number, startedAt: number): Promise<TurnSource | null> {try {- const found = session.engine === 'claude'- ? await deps.claudeProcessSession(pid, cwd, startedAt)+ const live = sessionStoreOf(session.engine)?.live+ const found = live && 'record' in live+ ? await deps.processSession(session.engine, pid, cwd, startedAt): await deps.findLiveSession(session.engine, cwd, startedAt, { bornOnly: true, pid, codexHome: session.codexHome ?? undefined })const path = found?.transcriptPathif (!found || !found.sessionId || !path || isSubagentTranscript(path)) return null@@ -107,7 +111,7 @@ export interface HandoffWiring {}databaseHistory: HandoffDeps['readHistory']findLiveSession: DiscoveryDeps['findLiveSession']- claudeProcessSession: DiscoveryDeps['claudeProcessSession']+ processSession: DiscoveryDeps['processSession']isRecentlyDeleted(sessionId: string): booleanfindResumedTranscript: NonNullable<HandoffDeps['findTranscript']>validTranscriptPath(engine: AgentEngine, path: string, codexHome?: string): boolean@@ -128,7 +132,7 @@ export function handoffProviderDeps(w: HandoffWiring): HandoffDeps {// certain. Never a fork, never a database engine, never one another agent holds.discoverSession: sessionDiscovery({findLiveSession: w.findLiveSession,- claudeProcessSession: w.claudeProcessSession,+ processSession: w.processSession,isLive: (id) => !!w.registry.byAgent(id),ownedByOther: (sid, id) => ownedByOther({bySession: (s) => w.registry.bySession(s), stoppedIds: () => w.stopped.ids(), stopped: (s) => w.stopped.get(s),diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex c53591a12..0bc759e9c 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -17,6 +17,7 @@ import type { AgentEngine } from '../engines/types.js'import { subscriptionModelLaunch } from './subscriptionModel.js'import { ownLoginProviderArgs } from '../engines/launches.js'import { namedAgentArgs, supportsNamedAgent } from './engineLaunch.js'+import { profileEnvironment } from './engineHomes.js'import {buildGridEngineLaunch,gridConflictingEnvToClear,@@ -265,7 +266,7 @@ async function buildBaseLaunchOverrides(return {ok: true,overrides: {- env: { CODEX_HOME: source.codexHome, ...(ownLogin?.env ?? {}) },+ env: { ...profileEnvironment(engine, source.codexHome), ...(ownLogin?.env ?? {}) },extraArgs: [...(ownLogin?.extraArgs ?? [])],clearEnv: [],},diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex a02e13cb4..ddba2d3d0 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -40,8 +40,9 @@ import { join, basename, dirname, relative, isAbsolute } from 'path'import { machineNames } from './machineNames.js'import { cursorDataDir } from '../engines/cursor/home.js'import { env } from '../config/env.js'-import { claudeProjectsRoots, codexHomeRoots, sessionCodexHome } from './engineHomes.js'-import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'+import { sessionFolderOf, sessionRoots } from './engineHomes.js'+import { findSessionFileOf, sessionMetaOf } from '../engines/sessionFiles.js'+import { isSessionStoreEngine, sessionStoreContracts, sessionStoreOf } from '../engines/sessionStoreContracts.js'import { admitHook } from '../engines/hooks.js'import { ENGINES, isTerminalEngine, type AgentEngine } from '../engines/types.js'import type { GridAssignment } from './gridAssignment.js'@@ -772,20 +773,20 @@ function isWithin(root: string, file: string): boolean {* replaces so "this engine has no transcript" is a fact a caller can ASK for — Pause and Resume both* need it, and both used to demand a file every engine was assumed to have.*/-const TRANSCRIPT_ROOT: Readonly<Record<AgentEngine, ((codexHome?: string) => string) | null>> = {+const TRANSCRIPT_ROOT: Readonly<Record<AgentEngine, (() => string) | 'store' | null>> = {// Amp's root is OURS, not Amp's: the transcript is written by the adapter's own plugin because Amp// keeps no conversation on disk (see installAmpPlugin).amp: () => env.AMP_SESSIONS_DIR,muse: () => join(env.MUSE_HOME, 'sessions'),- // The specific agent's own CODEX_HOME profile, when it has one — see RegisteredSession.codexHome.- codex: codexHome => join(codexHome || env.CODEX_HOME, 'sessions'),+ // Declared by the engine's session store (engines/sessionStoreContracts.ts): the folders `transcriptRoots` names.+ codex: 'store',grok: () => join(env.GROK_HOME, 'sessions'),agy: () => join(env.AGY_HOME, 'brain'),copilot: () => join(env.COPILOT_HOME, 'session-state'),cursor: () => join(cursorDataDir(), 'projects'),pi: () => join(env.PI_HOME, 'agent', 'sessions'),commandcode: () => join(env.COMMANDCODE_HOME, 'projects'),- claude: () => env.CLAUDE_PROJECTS_DIR,+ claude: 'store',opencode: null,kilo: null,hermes: null,@@ -801,14 +802,12 @@ export function engineKeepsTranscriptFile(engine: AgentEngine): boolean {}/**- * The folders an engine's transcripts may be in: its own, and for Claude Code and Codex each home the- * person moved in their shell profile (lib/engineHomes.ts). An agent's own CODEX_HOME profile is its- * only one.+ * The folders an engine's transcripts may be in: its own, and for an engine with a declared session store each+ * home the person moved in their shell profile (lib/engineHomes.ts). An agent's own profile (its CODEX_HOME) is+ * its only one, for an engine whose sessions follow one.*/-function transcriptRoots(engine: AgentEngine, rootFor: (codexHome?: string) => string, codexHome?: string): string[] {- if (engine === 'claude') return claudeProjectsRoots(rootFor())- if (engine === 'codex' && !codexHome) return codexHomeRoots(env.CODEX_HOME).map((home) => join(home, 'sessions'))- return [rootFor(codexHome)]+function transcriptRoots(engine: AgentEngine, root: (() => string) | 'store', codexHome?: string): string[] {+ return root === 'store' ? sessionRoots(engine, codexHome) : [root()]}export function validTranscriptPath(engine: AgentEngine, filePath: string, codexHome?: string, allowMissing = false): boolean {@@ -1014,21 +1013,25 @@ class Registry {const rawCodexHome = raw?.codexHome ?? undefinedconst rawGridLaunch = normalizedGridLaunch(raw?.gridLaunch)const rawScmLaunch = parseScmLaunchRecord((raw as { scmLaunch?: unknown })?.scmLaunch)- let repairedCodexTranscript = false- if (engine === 'codex' && transcriptPath) {- const meta = readCodexRolloutMeta(transcriptPath)+ // A sub-agent's hooks run from its parent's pane, and an older daemon let them overwrite the parent's+ // binding with the child's file: put the parent's own back, found by its id in the same home (or its+ // profile), else release the binding. Declared by the engine's session store (`repairsOverwrittenParent`)+ // and read with the kit, in core.+ let repairedParentTranscript = false+ if (isSessionStoreEngine(engine) && sessionStoreContracts[engine].repairsOverwrittenParent && transcriptPath) {+ const meta = sessionMetaOf(engine, transcriptPath)if (meta?.isSubagent) {const repaired = meta.parentThreadId === rawSessionId- ? resolveCodexRollout(rawSessionId, join(sessionCodexHome({ codexHome: rawCodexHome, transcriptPath }), 'sessions'))+ ? findSessionFileOf(engine, rawSessionId, sessionFolderOf(engine, { profile: rawCodexHome, transcriptPath })): null- if (!repaired || !validTranscriptPath('codex', repaired, rawCodexHome) || readCodexRolloutMeta(repaired)?.isSubagent) {+ if (!repaired || !validTranscriptPath(engine, repaired, rawCodexHome) || sessionMetaOf(engine, repaired)?.isSubagent) {changed = truebound = falsetranscriptPath = null} else {- console.log(`[registry] repaired Codex parent ${rawSessionId.slice(0, 8)} transcript after child hook overwrite`)+ console.log(`[registry] repaired ${sessionStoreContracts[engine].label} parent ${rawSessionId.slice(0, 8)} transcript after child hook overwrite`)transcriptPath = repaired- repairedCodexTranscript = true+ repairedParentTranscript = truechanged = true}}@@ -1090,7 +1093,7 @@ class Registry {defaultName: normalizedDefaultName(raw.defaultName),title: titleDisplayName(typeof raw.title === 'string' ? raw.title : null),sessionId: bound ? rawSessionId : '',- projectDir: !repairedCodexTranscript && typeof raw.projectDir === 'string' && raw.projectDir+ projectDir: !repairedParentTranscript && typeof raw.projectDir === 'string' && raw.projectDir? raw.projectDir: transcriptPath? basename(dirname(transcriptPath))@@ -1993,9 +1996,11 @@ class Registry {return true}+ /** Fill in the profile a row did not know (its CODEX_HOME), for an engine whose sessions follow one (its session+ * store's `sessions.profile`). Never overwrites. */setCodexHome(agentId: string, codexHome: string): boolean {const session = this.agents.get(agentId)- if (!session || session.engine !== 'codex' || session.codexHome) return false+ if (!session || !sessionStoreOf(session.engine)?.sessions.profile || session.codexHome) return falsesession.codexHome = codexHomesession.touchedAt = Date.now()this.save()diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.tsindex ed8eb6f3f..ef51da287 100644--- a/cli/src/lib/sessionRepair.spec.ts+++ b/cli/src/lib/sessionRepair.spec.ts@@ -3,7 +3,9 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, utimesSync, writeFileSyncimport { execFileSync, spawn } from 'child_process'import { tmpdir } from 'os'import { join } from 'path'-import { claudeContinuation } from './sessionRepair.js'+import { continuationOf } from '../engines/sessionFiles.js'++const claudeContinuation = (path: string) => continuationOf('claude', path)/*** Repair binds a live launcher back to a session the daemon lost track of. The danger is not failing to@@ -500,7 +502,7 @@ describe('session repair — Codex profiles', () => {describe('session repair — a Codex process names its own rollout', () => {it('reads the native child of the npm launcher, never another launcher or a nested tool', async () => {- const { codexProcessFiles } = await import('./sessionRepair.js')+ const { processFilesOf } = await import('./sessionRepair.js')const own = '/tmp/profile/sessions/rollout-own.jsonl'const sibling = '/tmp/profile/sessions/rollout-sibling.jsonl'const files = vi.fn(async (pid: number) => pid === 43 ? [own] : pid === 50 ? [sibling] : ['/dev/null'])@@ -510,21 +512,21 @@ describe('session repair — a Codex process names its own rollout', () => {{ pid: 50, parentPid: 1, executable: '/opt/vendor/codex', args: '/opt/vendor/codex' },{ pid: 51, parentPid: 43, executable: '/opt/vendor/codex', args: '/opt/vendor/codex' },]- await expect(codexProcessFiles(42, files, async () => rows)).resolves.toEqual(['/dev/null', own])+ await expect(processFilesOf('codex', 42, files, async () => rows)).resolves.toEqual(['/dev/null', own])expect(files.mock.calls.map(([pid]) => pid)).toEqual([42, 43])// macOS's comm column can truncate the full Node path; argv still names the executable.- await expect(codexProcessFiles(42, files, async () => rows.map(row => row.pid === 42+ await expect(processFilesOf('codex', 42, files, async () => rows.map(row => row.pid === 42? { ...row, executable: '/Users/demo/.ha', args: '/Users/demo/.harness/node/bin/node /tmp/bin/codex' } : row))).resolves.toEqual(['/dev/null', own])- await expect(codexProcessFiles(42, files, async () => null)).resolves.toEqual(['/dev/null'])- await expect(codexProcessFiles(42, files, async () => [])).resolves.toEqual(['/dev/null'])- await expect(codexProcessFiles(42, files, async () => rows.filter(row => row.pid !== 43))).resolves.toEqual(['/dev/null'])- await expect(codexProcessFiles(42, files, async () => [...rows, { ...rows[1], pid: 44 }])).resolves.toEqual(['/dev/null'])+ await expect(processFilesOf('codex', 42, files, async () => null)).resolves.toEqual(['/dev/null'])+ await expect(processFilesOf('codex', 42, files, async () => [])).resolves.toEqual(['/dev/null'])+ await expect(processFilesOf('codex', 42, files, async () => rows.filter(row => row.pid !== 43))).resolves.toEqual(['/dev/null'])+ await expect(processFilesOf('codex', 42, files, async () => [...rows, { ...rows[1], pid: 44 }])).resolves.toEqual(['/dev/null'])// A native process owns its file directly. No walk into the tools it launched.const table = vi.fn(async () => rows)- await expect(codexProcessFiles(43, files, table)).resolves.toEqual([own])+ await expect(processFilesOf('codex', 43, files, table)).resolves.toEqual([own])expect(table).not.toHaveBeenCalled()- await expect(codexProcessFiles(51, files, table)).resolves.toEqual(['/dev/null'])+ await expect(processFilesOf('codex', 51, files, table)).resolves.toEqual(['/dev/null'])})it('does not give a starting process the only sibling rollout before its own file opens', async () => {@@ -532,10 +534,10 @@ describe('session repair — a Codex process names its own rollout', () => {const sibling = 'a1b2c3d4-1111-4a4a-8a8a-000000000009'writeCodexRollout(profile, sibling, CWD, Date.now())vi.resetModules()- const { codexProcessSession, findLiveSession } = await import('./sessionRepair.js')+ const { openFileSessionOf, findLiveSession } = await import('./sessionRepair.js')// October 6 full E2E: two Codex processes start together, but only one has written// its rollout yet. This process holds neither: a directory match is not ownership.- await expect(codexProcessSession(process.pid, join(profile, 'sessions'), CWD)).resolves.toBeNull()+ await expect(openFileSessionOf('codex', process.pid, join(profile, 'sessions'), CWD)).resolves.toBeNull()await expect(findLiveSession('codex', CWD, Date.now() - 1_000,{ codexHome: profile, bornOnly: true, pid: process.pid })).resolves.toBeNull()})@@ -548,17 +550,17 @@ describe('session repair — a Codex process names its own rollout', () => {const siblingFile = writeCodexRollout(profile, sibling, CWD, STARTED_AT + 2_000)const elsewhere = writeCodexRollout(tempRoot(), 'a1b2c3d4-1111-4a4a-8a8a-000000000005', CWD, STARTED_AT)vi.resetModules()- const { codexProcessSession, findLiveSession } = await import('./sessionRepair.js')+ const { openFileSessionOf, findLiveSession } = await import('./sessionRepair.js')const sessions = join(profile, 'sessions')// Two born in the folder since the process started: guessing would wire a tile to a sibling.await expect(findLiveSession('codex', CWD, STARTED_AT, { codexHome: profile, bornOnly: true })).resolves.toBeNull()// The process holds one of them open, beside files that are not rollouts or not this profile's.const held = async () => [forkFile, '/dev/null', join(profile, 'notes.jsonl'), elsewhere]- await expect(codexProcessSession(42, sessions, CWD, held)).resolves.toEqual({ sessionId: fork, transcriptPath: realpathSync(forkFile) })+ await expect(openFileSessionOf('codex', 42, sessions, CWD, held)).resolves.toEqual({ sessionId: fork, transcriptPath: realpathSync(forkFile) })// Two held, or one for another folder: nothing, rather than a guess.- await expect(codexProcessSession(42, sessions, CWD, async () => [forkFile, siblingFile])).resolves.toBeNull()- await expect(codexProcessSession(42, sessions, '/Users/demo/elsewhere', held)).resolves.toBeNull()- await expect(codexProcessSession(42, sessions, CWD, async () => [])).resolves.toBeNull()+ await expect(openFileSessionOf('codex', 42, sessions, CWD, async () => [forkFile, siblingFile])).resolves.toBeNull()+ await expect(openFileSessionOf('codex', 42, sessions, '/Users/demo/elsewhere', held)).resolves.toBeNull()+ await expect(openFileSessionOf('codex', 42, sessions, CWD, async () => [])).resolves.toBeNull()})it('reads a live process\'s open files, and binds the repair to the rollout it holds', async () => {@@ -608,9 +610,9 @@ describe('session repair — homes the person moved', () => {writeTranscript(join(claudeHome, 'projects'), 'project', id, CWD, STARTED_AT + 5_000)mkdirSync(join(claudeHome, 'sessions'))writeFileSync(join(claudeHome, 'sessions', '77.json'), JSON.stringify({ pid: 77, cwd: CWD, sessionId: id, procStart: new Date(STARTED_AT).toUTCString() }))- const { claudeProcessSession, findLiveSession } = await moved(claudeHome, tempRoot())+ const { processSessionOf, findLiveSession } = await moved(claudeHome, tempRoot())const transcriptPath = join(claudeHome, 'projects', 'project', `${id}.jsonl`)- await expect(claudeProcessSession(77, CWD, STARTED_AT)).resolves.toEqual({ sessionId: id, transcriptPath })+ await expect(processSessionOf('claude', 77, CWD, STARTED_AT)).resolves.toEqual({ sessionId: id, transcriptPath })// And by the folder scan, when there is no process record to read.await expect(findLiveSession('claude', CWD, STARTED_AT, { bornOnly: true })).resolves.toEqual({ sessionId: id, transcriptPath })})@@ -629,17 +631,17 @@ describe('session repair — homes the person moved', () => {const codexHome = tempRoot()const id = 'a1b2c3d4-1111-4a4a-8a8a-000000000101'const file = writeCodexRollout(codexHome, id, CWD, STARTED_AT + 5_000)- const { codexProcessSession, findLiveSession } = await moved(tempRoot(), codexHome)+ const { openFileSessionOf, findLiveSession } = await moved(tempRoot(), codexHome)await expect(findLiveSession('codex', CWD, STARTED_AT, { bornOnly: true })).resolves.toEqual({ sessionId: id, transcriptPath: file })const roots = [join(process.env.CODEX_HOME!, 'sessions'), join(codexHome, 'sessions')]- await expect(codexProcessSession(42, roots, CWD, async () => [file])).resolves.toEqual({ sessionId: id, transcriptPath: realpathSync(file) })+ await expect(openFileSessionOf('codex', 42, roots, CWD, async () => [file])).resolves.toEqual({ sessionId: id, transcriptPath: realpathSync(file) })// One conversation in each home for this folder: two agents, and no guess.writeCodexRollout(process.env.CODEX_HOME!, 'a1b2c3d4-1111-4a4a-8a8a-000000000102', CWD, STARTED_AT + 6_000)await expect(findLiveSession('codex', CWD, STARTED_AT, { bornOnly: true })).resolves.toBeNull()})})-describe('claudeContinuation', () => {+describe('a Claude Code conversation continued in another file (continuationOf)', () => {it('follows a continued-in marker to the new session file', async () => {const dir = tempRoot()const oldPath = join(dir, 'old-session.jsonl')@@ -822,7 +824,7 @@ it.each(['local', 'utc'])('recovers an old Claude process in a busy project from})it.each(['bad pid', 'bad start', 'missing file', 'bad json', 'different pid', 'different start', 'missing start', 'different cwd', 'missing cwd', 'missing id', 'invalid id', 'missing history'])('refuses stale/invalid Claude native metadata: %s', async mode => {const home = tempRoot(); const root = join(home, 'projects'); mkdirSync(root)- const { claudeProcessSession } = await load(root)+ const { processSessionOf } = await load(root)const record: Record<string, unknown> = { pid: 77, cwd: CWD, sessionId: '11111111-2222-4333-8444-555555555555', procStart: new Date(STARTED_AT).toUTCString() }if (mode === 'different pid') record.pid = 78if (mode === 'different start') record.procStart = new Date(STARTED_AT + 1000).toUTCString()@@ -833,7 +835,7 @@ it.each(['bad pid', 'bad start', 'missing file', 'bad json', 'different pid', 'dif (mode === 'invalid id') record.sessionId = '../escape'mkdirSync(join(home, 'sessions'))if (mode !== 'missing file') writeFileSync(join(home, 'sessions', '77.json'), mode === 'bad json' ? '{' : JSON.stringify(record))- expect(await claudeProcessSession(mode === 'bad pid' ? -1 : 77, CWD, mode === 'bad start' ? NaN : STARTED_AT)).toBeNull()+ expect(await processSessionOf('claude', mode === 'bad pid' ? -1 : 77, CWD, mode === 'bad start' ? NaN : STARTED_AT)).toBeNull()})/**diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex 6a6af311e..c0f92e6fb 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -15,18 +15,21 @@*/import { execFile } from 'child_process'-import { open, readdir, readFile, readlink, realpath, stat } from 'fs/promises'+import { readdir, readFile, readlink, realpath, stat } from 'fs/promises'import { basename, dirname, join, relative, sep } from 'path'import { env } from '../config/env.js'+import type { SessionStoreContract } from '../engines/facets/sessionStore.js'+import { headBytes } from '../engines/kit/continuation.js'import { museEvent, museWorkspaceRoot } from '../engines/muse/normalizer.js'+import { findSessionFileOf, sessionMetaOf } from '../engines/sessionFiles.js'+import { sessionStoreOf } from '../engines/sessionStoreContracts.js'import type { AgentEngine } from '../engines/types.js'-import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'import { agyConversationForPid, findAgyTranscript } from '../engines/agy/session.js'import { copilotSessionCwd, copilotSessionForPid, findCopilotTranscript } from '../engines/copilot/session.js'import { hermesDbPath, listHermesHomes } from '../engines/hermes/home.js'import { sqliteReadAll, type SqliteParam } from './sqliteRead.js'import { piSessionFolder, readPiHead } from './sessionSearch/externals/pi.js'-import { claudeProjectsRoots, codexHomeRoots } from './engineHomes.js'+import { sessionRoots } from './engineHomes.js'import { argvTokens, engineProcessMatchScore, processRows, type ProcessRow } from './tmux.js'/**@@ -83,11 +86,11 @@ const CWD_SCAN_LINES = 20const CWD_SCAN_CHARS = 256 * 1024/**- * The first `cwd` in a transcript's head and, when asked, its opening `isSidechain` flag. One bounded read- * (256 KB — transcripts run to hundreds of MB) shared by every file engine that declares its cwd in-file.- * Without `wantSide` it stops at the first cwd, exactly as it always did.+ * The first `cwd` in a transcript's head and, when asked, its opening flag named `sidechain` (an engine's session+ * store declares it: `scan.sidechain`). One bounded read (256 KB — transcripts run to hundreds of MB) shared by+ * every file engine that declares its cwd in-file. Without a flag it stops at the first cwd, exactly as it always did.*/-async function readTranscriptHead(path: string, wantSide: boolean): Promise<{ cwd: string; side: boolean | undefined } | null> {+async function readTranscriptHead(path: string, sidechain: string | null): Promise<{ cwd: string; side: boolean | undefined } | null> {try {// Preserve the existing UTF-16 character budget, including non-ASCII paths. Four// UTF-8 bytes per code unit is sufficient even when the cutoff splits a surrogate@@ -100,42 +103,47 @@ async function readTranscriptHead(path: string, wantSide: boolean): Promise<{ cwlet obj: Record<string, unknown>try { obj = JSON.parse(line) as Record<string, unknown> } catch { continue }if (!cwd && typeof obj.cwd === 'string' && obj.cwd) cwd = obj.cwd- if (wantSide && side === undefined && typeof obj.isSidechain === 'boolean') side = obj.isSidechain- if (cwd && (!wantSide || side !== undefined)) break+ if (sidechain && side === undefined && typeof obj[sidechain] === 'boolean') side = obj[sidechain] as boolean+ if (cwd && (!sidechain || side !== undefined)) break}return { cwd, side }} catch { return null }}async function readTranscriptMeta(path: string): Promise<TranscriptMeta | null> {- const head = await readTranscriptHead(path, false)+ const head = await readTranscriptHead(path, null)return head?.cwd ? { cwd: head.cwd } : null}/**- * `readTranscriptMeta` for Claude, which also refuses a SUBAGENT transcript.+ * How a scan of `engine`'s declared store reads a file (its session store's `scan`), refusing a session another+ * one delegated to.*- * Claude's subagents (the Task tool, background agents) write transcripts of their own in the same project- * directory tree, and a scan by directory cannot tell them from a conversation. Two layouts exist:+ * `head`: the first cwd of the opening lines, as `readTranscriptMeta`, but never a file below a `childFolder`+ * segment of the sessions folder it is in, nor one whose FIRST record carrying the boolean `sidechain` flag says+ * true. Claude's subagents write transcripts of their own in the same tree, which a scan by directory cannot tell+ * from a conversation; left in, the youngest subagent file of a parent still running was picked as the session of+ * the agent born next to it (a fork), and Stop capture then recorded that id. Later records are not consulted for+ * the flag: a main transcript can hold sidechain records, and only its opening says what the file is.*- * <projects>/<proj>/<parentSession>/subagents/agent-<id>.jsonl (current)- * <projects>/<proj>/agent-<id>.jsonl (older builds)- *- * Both open with `{type:'user', isSidechain:true, cwd, sessionId:<parent>}` — the cwd and the PARENT's- * session id — whereas a main transcript carries `isSidechain:false`. Left in the scan, the youngest- * subagent file of a parent that is still running was picked as the session of the agent born next to it- * (a fork): the sweep bound the fork to its parent's subagent, and Stop capture then recorded that id.- * So: a path with a `subagents` segment below the projects root is out before it is read, and so is a- * file whose FIRST record carrying a boolean `isSidechain` says true. Later records are not consulted for- * the flag — a main transcript can hold sidechain records, and only its opening says what the file is.+ * `first`: the file's first record (engines/sessionFiles.ts), whose id is the session's (the file name only holds+ * it), and never a child's: a subagent's rollout must never become an agent of its own.*/-async function readClaudeTranscriptMeta(path: string): Promise<TranscriptMeta | null> {- // Relative to the projects root it is under (the daemon's own, or a moved home's): the root itself may- // legitimately sit under a folder of that name.- const root = claudeProjectsRoots(env.CLAUDE_PROJECTS_DIR).find((one) => !relative(one, path).startsWith('..'))- if (root !== undefined && relative(root, path).split(sep).includes('subagents')) return null- const head = await readTranscriptHead(path, true)- return head && head.side !== true && head.cwd ? { cwd: head.cwd } : null+function scanMeta(engine: AgentEngine, scan: SessionStoreContract['scan']): (path: string) => Promise<TranscriptMeta | null> {+ if (scan.from === 'first') {+ return async (path) => {+ const meta = sessionMetaOf(engine, path)+ return meta && !meta.isSubagent ? { cwd: meta.cwd, sessionId: meta.id || undefined } : null+ }+ }+ return async (path) => {+ // Relative to the sessions folder it is under (the daemon's own, or a moved home's): that folder itself may+ // legitimately sit under a folder of the child's name.+ const root = sessionRoots(engine).find((one) => !relative(one, path).startsWith('..'))+ if (root !== undefined && relative(root, path).split(sep).includes(scan.childFolder)) return null+ const head = await readTranscriptHead(path, scan.sidechain)+ return head && head.side !== true && head.cwd ? { cwd: head.cwd } : null+ }}/** Session id from `<id>.jsonl`, or from pi's `<timestamp>_<id>.jsonl`. */@@ -279,45 +287,49 @@ async function copilotDirectoryScan(}, opts)}+/**+ * The session a live process of an engine with a declared store is running (engines/sessionStoreContracts.ts), in+ * every one of its sessions folders: the daemon's own and each home the person moved (lib/engineHomes.ts), or the+ * agent's own profile alone. The default alone left an agent in a moved home unbound.+ *+ * A process that names its own session in a record (`live.record`) is asked first: unlike a scan by folder, that+ * also identifies an old process in a busy project. One that holds its session file open (`live.open`) is only+ * ever matched by that file once its pid is known (the October 6 parallel-create incident: the only file in a+ * folder can belong to a sibling whose file opened first), and left unbound until then rather than guessed.+ */+async function storeSession(+ engine: AgentEngine,+ store: SessionStoreContract,+ cwd: string,+ startedAtMs: number,+ opts?: { bornOnly?: boolean; pid?: number; codexHome?: string },+): Promise<RepairedSession | null> {+ const scan = scanMeta(engine, store.scan)+ if ('record' in store.live) {+ const exact = opts?.pid ? await processSessionOf(engine, opts.pid, cwd, startedAtMs) : null+ return exact ?? fileEngineSession(sessionRoots(engine), cwd, startedAtMs, scan, opts)+ }+ const sessions = sessionRoots(engine, opts?.codexHome)+ if (opts?.pid) return openFileSessionOf(engine, opts.pid, sessions, cwd)+ return fileEngineSession(sessions, cwd, startedAtMs, scan, opts)+}+export async function findLiveSession(engine: AgentEngine,cwd: string,startedAtMs: number,- // codexHome: the specific agent's own CODEX_HOME profile, when it isn't this machine's default —- // see RegisteredSession.codexHome. Only the 'codex' case below reads it.+ // codexHome: the specific agent's own profile (its CODEX_HOME), when it isn't this machine's default —+ // see RegisteredSession.codexHome. Read only for an engine whose sessions follow one (`sessions.profile`).opts?: { bornOnly?: boolean; pid?: number; codexHome?: string },): Promise<RepairedSession | null> {+ const store = sessionStoreOf(engine)+ if (store) return storeSession(engine, store, cwd, startedAtMs, opts)const sinceMs = startedAtMs - START_SLACK_MS// The DB engines match on a directory STRING, so ask for both spellings of it (see sameDir).const real = await realpath(cwd).catch(() => cwd)const dirs = real === cwd ? [cwd] : [cwd, real]const dirList = placeholders(dirs.length)switch (engine) {- case 'claude': {- // Native Claude publishes a PID-to-conversation record even before a hook binds it.- // Unlike a directory scan this also identifies an old process in a busy project.- // Every home, the moved ones too (lib/engineHomes.ts): the default alone left an agent in a moved- // CLAUDE_CONFIG_DIR whose start-up hook did not bind it without a conversation.- const exact = opts?.pid ? await claudeProcessSession(opts.pid, cwd, startedAtMs) : null- return exact ?? fileEngineSession(claudeProjectsRoots(env.CLAUDE_PROJECTS_DIR), cwd, startedAtMs, readClaudeTranscriptMeta, opts)- }- case 'codex': {- // The agent's own profile alone, else the daemon's home and every one the person moved, as- // findResumedTranscript looks: the default alone missed a rollout in a moved CODEX_HOME.- const sessions = (opts?.codexHome ? [opts.codexHome] : codexHomeRoots(env.CODEX_HOME)).map((home) => join(home, 'sessions'))- // October 6 parallel-create incident: the only rollout in a folder can belong to a sibling- // whose file opened first. A known Codex process must name its own open rollout; until then,- // leave it unbound for its next discovery pass or startup hook, never guess from the folder.- if (opts?.pid) return codexProcessSession(opts.pid, sessions, cwd)- // Codex writes no `cwd` on line one; its rollout meta carries it — and says whether the rollout- // belongs to a subagent, which must never become an agent of its own.- // Its session id lives INSIDE the file: the name is `rollout-<timestamp>-<id>.jsonl`, so deriving- // the id from the filename produced the literal string "rollout-…" (seen on a live pane).- return fileEngineSession(sessions, cwd, startedAtMs, async (path) => {- const meta = readCodexRolloutMeta(path)- return meta && !meta.isSubagent ? { cwd: meta.cwd, sessionId: meta.id || undefined } : null- }, opts)- }case 'pi':return fileEngineSession(join(env.PI_HOME, 'agent', 'sessions'), cwd, startedAtMs, readTranscriptMeta, opts)case 'commandcode':@@ -451,130 +463,13 @@ async function agySession(pid: number): Promise<RepairedSession | null> {return { sessionId: conversationId, transcriptPath: transcriptPath ?? undefined }}-/** The last `maxBytes` of a file, as text. Bounded so a multi-MB transcript costs nothing to check. */-async function tailBytes(path: string, maxBytes: number): Promise<string> {- const handle = await open(path, 'r')- try {- const info = await handle.stat()- const start = Math.max(0, info.size - maxBytes)- const length = info.size - start- if (length <= 0) return ''- const buffer = Buffer.alloc(length)- await handle.read(buffer, 0, length, start)- return buffer.toString('utf-8')- } finally {- await handle.close()- }-}--const CLAUDE_CONTINUATION_TAIL_BYTES = 4 * 1024-/** Enough of a continuation to see whether anybody ever spoke in it. Its first turn is within a few- * lines of the top — the records before it are bookkeeping (mode, file history, title, agent name). */-const CLAUDE_CONTINUATION_HEAD_BYTES = 256 * 1024--async function headBytes(path: string, maxBytes: number): Promise<Buffer> {- const handle = await open(path, 'r')- try {- const length = Math.min((await handle.stat()).size, maxBytes)- if (length <= 0) return Buffer.alloc(0)- const buffer = Buffer.alloc(length)- let read = 0- while (read < length) {- const { bytesRead } = await handle.read(buffer, read, length - read, read)- if (!bytesRead) break- read += bytesRead- }- return buffer.subarray(0, read)- } finally {- await handle.close()- }-}--/**- * Whether a transcript holds a CONVERSATION, rather than being the file Claude opens for a session- * nobody has spoken in yet.- *- * `claude` writes the same `continued-in` marker for a BACKGROUND session as for a rollover, and the- * file it points at then holds two bookkeeping lines (`ai-title`, `agent-name`) and never grows,- * while the real conversation goes on in the original file. Following that marker moved an agent onto- * an empty session: its tile went quiet, and the conversation archived when the engine exited was the- * empty one — Open then asked `claude --resume <background id>`, which the CLI refuses outright- * ("is running as a background session … run `claude attach`"). Measured on one machine: of nine- * `continued-in` markers, three named a background session and every one of those files had exactly- * these two lines and no turn.- */-async function hasConversationTurn(path: string): Promise<boolean> {- let head: Buffer- try {- head = await headBytes(path, CLAUDE_CONTINUATION_HEAD_BYTES)- } catch {- return false- }- for (const line of head.toString('utf-8').split('\n')) {- if (!line.trim() || (!line.includes('"user"') && !line.includes('"assistant"'))) continue- try {- const record = JSON.parse(line) as { type?: unknown }- if (record.type === 'user' || record.type === 'assistant') return true- } catch { /* a line cut by the read bound, or one this version does not know */ }- }- // Nothing in the head, but more file than we read: a continuation can open on a `file-history-snapshot`- // large enough to push the first turn past the bound, and the thing being ruled out is two short- // lines. Anything this size is a conversation, so the bound must never be what refuses one.- // Count the bytes read, not decoded UTF-16 characters: Unicode bookkeeping must not make- // a read that hit the byte cap look smaller and strand the real turn beyond it.- return head.length >= CLAUDE_CONTINUATION_HEAD_BYTES-}--/**- * Claude rolls a long conversation's transcript over to a NEW file on its own (compaction, a resume- * chain) — the old file's last line names the new session and Claude simply starts writing there. No- * fresh SessionStart/UserPromptSubmit fires for it on its own if the actual turn that follows is- * served by a pooled/"spare" worker process rather than one spawned directly in the pane — so a- * hook-only bind can be left pointed at a transcript that has gone permanently quiet while the real- * conversation continues one file over. This is a cheap, bounded check for exactly that marker, read- * from the tail since it is always the very last line and tiny.- */-export async function claudeContinuation(transcriptPath: string): Promise<RepairedSession | null> {- let tail: string- try {- tail = await tailBytes(transcriptPath, CLAUDE_CONTINUATION_TAIL_BYTES)- } catch {- return null- }- const lines = tail.split('\n').map((line) => line.trim()).filter(Boolean)- const lastLine = lines[lines.length - 1]- if (!lastLine) return null- let record: Record<string, unknown>- try {- record = JSON.parse(lastLine) as Record<string, unknown>- } catch {- return null- }- const nextId = record.type === 'continued-in' && typeof record.continuedInSessionId === 'string'- ? record.continuedInSessionId- : ''- if (!nextId) return null- const nextPath = join(dirname(transcriptPath), `${nextId}.jsonl`)- try {- if (!(await stat(nextPath)).isFile()) return null- } catch {- return null- }- // A marker alone does not prove the conversation moved: the same one is written for a background- // session, whose file never holds a turn. Waiting for one costs nothing — this runs on every- // reconciler pass, so a continuation that is real binds on the pass after its first turn lands.- if (!await hasConversationTurn(nextPath)) return null- return { sessionId: nextId, transcriptPath: nextPath }-}-/**- * The transcript behind a session id a claude/codex process names on its own command line- * (`claude --resume <id>`, `codex resume <id>`) — the file `registry.register` insists on for those- * two engines, which argv does not carry. Claude keeps one file per session under- * `<projects>/<encoded cwd>/<id>.jsonl`; the cwd encoding is Claude's to define, so the project- * folders are listed rather than the name derived. Codex names its rollout after the thread id, and- * the rollout walker already knows that layout. Only a file that exists is returned: a resume of a- * session this machine never wrote (or one that was deleted) binds nothing.+ * The transcript behind a session id a process names on its own command line (`claude --resume <id>`,+ * `codex resume <id>`) — the file `registry.register` insists on for the engines with a declared store, which+ * argv does not carry. Found as the store declares (`byId`): in any one project folder directly below a sessions+ * folder (Claude's cwd encoding is its own to define, so the folders are listed rather than the name derived), or+ * by the walk for a file whose name holds the id (Codex's rollouts). Only a file that exists is returned: a resume+ * of a session this machine never wrote (or one that was deleted) binds nothing.*/export async function findResumedTranscript(engine: AgentEngine,@@ -602,23 +497,22 @@ export async function findResumedTranscript(return matches.length ? join(directory, matches[0]) : null}if (!/^[0-9a-f-]{16,}$/i.test(sessionId)) return null- // In every home the registry takes a transcript from (registry.validTranscriptPath): the daemon's own and- // each one the person moved in their shell profile (lib/engineHomes.ts), or an agent's own Codex profile- // alone. Only the default folders were looked in, so a resume typed into a pane for a conversation in a- // moved home found no file and never bound, though the registry would have taken it.- if (engine === 'codex') {- for (const home of opts?.codexHome ? [opts.codexHome] : codexHomeRoots(env.CODEX_HOME)) {- const found = resolveCodexRollout(sessionId, join(home, 'sessions'))+ const byId = sessionStoreOf(engine)?.byId+ if (!byId) return null+ // In every folder the registry takes a transcript from (registry.validTranscriptPath): the daemon's own and+ // each home the person moved in their shell profile (lib/engineHomes.ts), or an agent's own profile alone.+ // Only the default folders were looked in, so a resume typed into a pane for a conversation in a moved home+ // found no file and never bound, though the registry would have taken it.+ for (const root of sessionRoots(engine, opts?.codexHome)) {+ if (byId.layout === 'walk') {+ const found = findSessionFileOf(engine, sessionId, root)if (found) return found+ continue}- return null- }- if (engine !== 'claude') return null- for (const root of claudeProjectsRoots(env.CLAUDE_PROJECTS_DIR)) {let projects: string[]try { projects = await readdir(root) } catch { continue }for (const project of projects) {- const candidate = join(root, project, `${sessionId}.jsonl`)+ const candidate = join(root, project, `${sessionId}${byId.suffix}`)try {if ((await stat(candidate)).isFile()) return candidate} catch { /* not this project */ }@@ -627,7 +521,6 @@ export async function findResumedTranscript(return null}-/** Claude's native process record is removed at exit; capture it before Stop signals the engine. *//** The files a process holds open: `/proc` on Linux, `lsof` elsewhere. Empty when neither can say. */export async function openFiles(pid: number): Promise<string[]> {if (!Number.isSafeInteger(pid) || pid <= 0) return []@@ -643,73 +536,98 @@ export async function openFiles(pid: number): Promise<string[]> {return stdout.split('\n').filter((line) => line.startsWith('n/')).map((line) => line.slice(1))}-/** The rollout may be held by the native child of npm's Node launcher, not the launcher itself.- * October 6 ownership E2E: removing the folder guess exposed that distinction for a manually started- * Codex with no hook. Read only one direct Codex child of a Node launcher, never a nested tool. */-export async function codexProcessFiles(+type ProcessTable = () => Promise<readonly Pick<ProcessRow, 'pid' | 'parentPid' | 'executable' | 'args'>[] | null>++/**+ * The files a process of an engine that holds its session file open (`live.open`) has open, its native child's+ * too behind a launcher (the declared `launcher`, npm's Node one): the launcher holds no session file, its child+ * does. October 6 ownership E2E: removing the folder guess exposed that distinction for a manually started Codex+ * with no hook. Only one direct child of that engine is read, never a nested tool. Empty for another engine.+ */+export async function processFilesOf(+ engine: AgentEngine,pid: number,files: typeof openFiles = openFiles,- processes: () => Promise<readonly Pick<ProcessRow, 'pid' | 'parentPid' | 'executable' | 'args'>[] | null> = processRows,+ processes: ProcessTable = processRows,): Promise<string[]> {+ const live = sessionStoreOf(engine)?.live+ if (!live || !('open' in live)) return []+ const { file, launcher } = live.openconst own = await files(pid)- if (own.some(path => /rollout-[^/]*\.jsonl$/.test(path))) return own+ if (own.some(path => file.test(path))) return ownconst rows = await processes()const wrapper = rows?.find(row => row.pid === pid)if (!wrapper || ![wrapper.executable, argvTokens(wrapper.args)[0] ?? '']- .some(path => /^node(?:js)?$/.test(basename(path)))) return own- const children = rows!.filter(row => row.parentPid === pid && engineProcessMatchScore(row, 'codex') > 0)+ .some(path => launcher.test(basename(path)))) return own+ const children = rows!.filter(row => row.parentPid === pid && engineProcessMatchScore(row, engine) > 0)return children.length === 1 ? [...own, ...await files(children[0].pid)] : own}/**- * The conversation a Codex process is writing: the rollout it holds open.+ * The conversation a process of an engine that holds its session file open (`live.open`) is writing: the one+ * such file it holds below `sessionsRoot`, in `cwd`, never a child's. Null for another engine.** The one way to name a fork's conversation when its start-up hook was lost (a daemon restart in its* first second). `codex fork <id>` names only its source in argv, and a fork shares its source's* folder with every sibling started near it, so a scan of that folder finds them all and must refuse* to guess — the fork stayed without a conversation for good (e2e/chaos.e2e.ts).*/-export async function codexProcessSession(+export async function openFileSessionOf(+ engine: AgentEngine,pid: number,sessionsRoot: string | string[],cwd: string,- files: (pid: number) => Promise<string[]> = codexProcessFiles,+ files: (pid: number) => Promise<string[]> = (one) => processFilesOf(engine, one),): Promise<RepairedSession | null> {+ const live = sessionStoreOf(engine)?.live+ if (!live || !('open' in live)) return nullconst roots = await Promise.all((typeof sessionsRoot === 'string' ? [sessionsRoot] : sessionsRoot).map((one) => realpath(one).catch(() => one)))const found = new Map<string, RepairedSession>()for (const path of await files(pid)) {- if (!/rollout-[^/]*\.jsonl$/.test(path)) continue+ if (!live.open.file.test(path)) continueconst real = await realpath(path).catch(() => path)if (!roots.some((root) => real.startsWith(`${root}${sep}`))) continue- const meta = readCodexRolloutMeta(real)+ const meta = sessionMetaOf(engine, real)if (!meta || meta.isSubagent || !meta.id || !meta.cwd || !await sameDir(meta.cwd, cwd)) continuefound.set(real, { sessionId: meta.id, transcriptPath: real })}return found.size === 1 ? [...found.values()][0] : null}-export async function claudeProcessSession(pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null> {+/**+ * The session a live process names in a record of its own, for an engine that keeps one (`live.record`):+ * `<home>/<folder>/<pid><suffix>` beside each of its sessions folders, a moved home's too (lib/engineHomes.ts):+ * the default alone was read, so a process in a moved home was never named by its own record. Removed at exit,+ * so Stop captures it before signalling the engine. Null for another engine.+ */+export async function processSessionOf(engine: AgentEngine, pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null> {+ const live = sessionStoreOf(engine)?.live+ if (!live || !('record' in live)) return nullif (!Number.isSafeInteger(pid) || pid <= 0 || !Number.isFinite(startedAtMs)) return null- // `<home>/sessions/<pid>.json` in a moved CLAUDE_CONFIG_DIR too (lib/engineHomes.ts): the default alone- // was read, so a process in a moved home was never named by its own record.- for (const projects of claudeProjectsRoots(env.CLAUDE_PROJECTS_DIR)) {- const found = await claudeProcessRecord(join(dirname(projects), 'sessions', `${pid}.json`), pid, cwd, startedAtMs)+ const rule = live.record+ for (const sessions of sessionRoots(engine)) {+ const found = await processRecord(engine, rule, join(dirname(sessions), rule.folder, `${pid}${rule.suffix}`), pid, cwd, startedAtMs)if (found) return found}return null}-async function claudeProcessRecord(file: string, pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null> {+type ProcessRecordRule = Extract<SessionStoreContract['live'], { record: unknown }>['record']++async function processRecord(engine: AgentEngine, rule: ProcessRecordRule, file: string, pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null> {try {const record = JSON.parse(await readFile(file, 'utf8'))- // procStart is UTC in current Claude, while older builds used the host's local ps format.+ const start = record[rule.start]+ const folder = record[rule.cwd]+ const sessionId = record[rule.id]+ // Claude's procStart is UTC in current builds, while older builds used the host's local ps format.// Both represent the exact second, not the metadata file's modification time or a recycled PID.- if (record.pid !== pid || typeof record.procStart !== 'string'- || ![Date.parse(record.procStart), Date.parse(`${record.procStart} UTC`)].includes(startedAtMs)- || typeof record.cwd !== 'string' || !await sameDir(record.cwd, cwd)- || typeof record.sessionId !== 'string') return null- const transcriptPath = await findResumedTranscript('claude', record.sessionId)- return transcriptPath ? { sessionId: record.sessionId, transcriptPath } : null+ if (record[rule.pid] !== pid || typeof start !== 'string'+ || ![Date.parse(start), Date.parse(`${start} UTC`)].includes(startedAtMs)+ || typeof folder !== 'string' || !await sameDir(folder, cwd)+ || typeof sessionId !== 'string') return null+ const transcriptPath = await findResumedTranscript(engine, sessionId)+ return transcriptPath ? { sessionId, transcriptPath } : null} catch { return null }}diff --git a/docs/design/2026-10-08-engine-launch.md b/docs/design/2026-10-08-engine-launch.mdindex 8ffc17797..20fa44154 100644--- a/docs/design/2026-10-08-engine-launch.md+++ b/docs/design/2026-10-08-engine-launch.md@@ -7,7 +7,7 @@ declares what it needs as data on its launch contract (`Engine.launch`, `enginesShared mechanics in `engines/kit` read that data, and core runs them in line.(c) is too large to land as one change. It is split into five sub-batches, each green on its own. This-document records (c1), (c2) and (c3), which are done, and plans the other two.+document records (c1) to (c4), which are done, and plans the last.## (c1) Launch argv and the pane script: done@@ -245,14 +245,124 @@ reach no Claude Code or Codex file except the declared contracts and `rollout.ts`tmux.ts`, `terminalAgentDiscovery.ts`, `gridAssignment.ts`, `cwdRepair.ts`, the registry, the composition and bothkit modules.+## (c4) Registry load and session identity: done++Where Claude Code and Codex keep their sessions is read as the registry loads, on the hook path, by session repair,+by Stop's capture and by the handoff. A new facet, `SessionStoreContract` (`engines/facets/sessionStore.ts`),+declares it. Each engine declares it in `engines/{claude,codex}/sessionStore.ts`, listed in+`engines/sessionStoreContracts.ts`; Codex's reuses its launch contract's rollout layout and its hook contract's child+rule. Two kit modules apply it: `kit/sessionRecords.ts` (a file found by its id, and its first record) and+`kit/continuation.ts`. `engines/sessionFiles.ts` holds the file reads, which the registry calls without reaching+session repair, and `engines/sessionStores.ts` is the one place callers take the finders from.++| Was | Now |+| --- | --- |+| `engines/codex/rollout.ts` `readCodexRolloutMeta` and `resolveCodexRollout`, called by the registry and session repair | `first` (the record's type, where its id, folder, child marker and parent are, the read bound) and `byId` (`walk`: the suffix, the id's shape, the entries looked at). `sessionMetaOf` and `findSessionFileOf`. `rollout.ts` is a 20-line wrapper for Codex's own sub-agent reader. |+| The registry's Codex child-rollout repair at load, with its `engine === 'codex'` check and log line | `repairsOverwrittenParent`, and the parent found in the same home (`sessionFolderOf`) or the row's profile. The log line names the engine by the contract's `label`, unchanged. |+| The `claude` and `codex` rows of the registry's `TRANSCRIPT_ROOT` and `transcriptRoots` | `'store'`: the folders `engineHomes.sessionRoots` names. `setCodexHome` takes an engine whose sessions follow a profile (`sessions.profile`). |+| The `claude` and `codex` cases of `lib/sessionRepair.ts` `findLiveSession` and `findResumedTranscript`, `readClaudeTranscriptMeta` | `scan` (`head`: the child folder and sidechain flag; `first`: the first record) and `byId` (`projects`: one folder below each sessions folder). One `storeSession` for both. |+| `claudeProcessSession` and its record reader | `live.record` (the folder and suffix beside each sessions folder, the pid, start, folder and id fields). `processSessionOf`. |+| `codexProcessSession` and `codexProcessFiles` | `live.open` (the session file's name, the launcher whose one native child holds it). `openFileSessionOf` and `processFilesOf`. |+| `claudeContinuation`, and the `engine === 'claude'` check in `core/agents/bind.ts` | `continuation` (the marker's type and field, the next file's suffix, the tail and head bounds, the turn types). `continuationOf`. The registration's source and hook event are built from the engine and its `label`, unchanged. |+| The `engine === 'claude'` checks in `lib/captureResumeIdentity.ts` and `lib/handoffDiscovery.ts` | `processSessionOf` for any engine (null without a record); the handoff asks the record for an engine that declares `live.record` |+| `lib/engineHomes.ts`: the `claude` and `codex` arrays, `adoptEngineHomes`' two variables, the `archived_sessions` literal; `core/engines/hooks.ts`' adoption and its log line | `sessions` (the setting naming the daemon's own folder, the folder below it, the profile, the variable that moves the home and the folder below a moved one, the archive folder). `adoptHomes`, `movedHomes`, `sessionRoots`, `sessionHomeOf`, `ownHomeOf`. The former names are wrappers. The log line names the engine by `product`, unchanged. |+| `{ CODEX_HOME: … }` at create (`core/agents/create.ts`) and relaunch (`lib/launchOverrides.ts`) | `profileEnvironment(engine, home)`: the variable that moves the home, for an engine whose sessions follow a profile |++The kit's lookup by id (`findSessionFile`) moved from `kit/resumeRepair.ts` to `kit/sessionRecords.ts` unchanged,+and the resume repair imports it.++### The same answers++**Golden record.** `engines/sessionStore.golden.spec.ts` was recorded in its own commit, from the former code through+a composition (`engines/sessionStores.ts`), with throwaway homes under a temporary folder. It holds 226 cases:++- **9 home states:** adopted, adopted again, the defaults, relative, `~` and padded paths, remembered across a+ restart, and the homes a launch uses in four environments.+- **18 transcript checks:** which paths the registry accepts for six engines, with and without a profile, missing+ files allowed or not, through symlinks either way, and which engines keep a file.+- **112 lookups:** a session found by its id (Claude's projects, Codex's rollouts, a profile, moved homes, ids of+ the wrong shape), by a scan of the store (one, two or no candidates, a linked folder, a profile, born after the+ process or not, a subagent refused by its folder or by its first flag, a moved home below a folder named+ `subagents`), by a process's own record (UTC and local starts, wrong pid, folder, id or start, unreadable), by+ the rollout a process holds open (a sub-agent's, two, the same twice, outside the sessions, another file shaped+ like a session), and by the files behind npm's Node launcher.+- **15 continuations:** with a turn, a background session's, the next file missing or a folder, large with and+ without a turn, the marker not last, malformed.+- **26 first records and lookups by id:** sub-agents with and without a parent, malformed records, a first line+ past the 128 KiB bound, nested and dotted folders.+- **30 registry loads:** a parent overwritten by its sub-agent (put back, or released when its own rollout is gone+ or another parent's), profiles, moved homes, Claude rows inside and outside their projects, unbound rows. The+ saved file and the log line are recorded too.+- **16 captures and handoffs:** what Stop captures for each kind of row, and which finder the handoff asks for+ each engine.++Every case runs with `process.platform` pinned to darwin and to linux, and linux's are stored where they differ+(none). The spec also passes with `TMPDIR=/tmp`; no recorded size depends on the temporary folder's length. It+passes unchanged against the kit, and 24 of 25 one-line mutations fail it:++- Claude's record fields and folder, child folder, sidechain flag, continuation type, tail, head and turns, moved+ folder, own folder and file suffix;+- Codex's archive folder, read bound, launcher, file name, parent and folder paths, own folder, profile, scan,+ repair flag and label;+- the kit's head-length check, and the archive folder in `sessionHomeOf`.++The one that passes is the walk's entry limit off by one in `findSessionFile`, which moved unchanged. Pinning it+would need a folder of 5,000 entries read in an order the filesystem chooses.++### The registry's load time++`registry.load()` was timed on one fixed registry: 2,000 rows (Claude Code in the daemon's projects and a moved+home, Codex in its own home, a moved home and a profile, a Codex parent its sub-agent overwrote, Cursor and+OpenCode), every transcript on disk. The first load migrates the legacy rows and saves them. Each run then timed+40 loads of the saved file, as a daemon start reads it, after 3 warm-up loads. Twelve runs, six of each, alternated+between the former code (the record commit) and this change on the same machine, on main.++| | Median of run medians | Runs' medians | Runs' minimums |+| --- | --- | --- | --- |+| Before | 116.3 ms | 114.6 – 125.4 ms | 106.8 – 116.3 ms |+| After | 115.4 ms | 112.9 – 119.9 ms | 105.3 – 112.3 ms |++Every row stays bound. On the branch's earlier base, twenty runs (25 or 40 loads each) gave 116.8 ms before and+120.6 ms after, with the same fastest loads. Either way the difference is within the runs' spread.++Found while measuring, and unchanged here: the FIRST load of a registry whose rows all change (the migration of a+legacy file) took 15.6 s for the same 2,000 rows. `save()` merges every changed row against every row on disk, so+it is quadratic in the rows changed. A start with a few changed rows does not see it.++### Core closure++| | Lines | Files |+| --- | --- | --- |+| Before (the record commit, on main) | 71,654 | 386 |+| After | 71,865 | 392 |++**Left:** the Claude Code and Codex cases of `lib/sessionRepair.ts` (82 lines shorter), Codex's own reader in+`engines/codex/rollout.ts` (49 lines shorter) and the walk in `kit/resumeRepair.ts` (25). **Came in:** the two+stores (85 lines of data and comments), `sessionStoreContracts.ts` (23), `sessionFiles.ts` (41),+`kit/sessionRecords.ts` (94), `kit/continuation.ts` (100), and the generic homes in `lib/engineHomes.ts` (57).++`rollout.ts` is still in the core's process: the Codex transcript normalizer reaches it through its sub-agent+reader, which (c5) takes up. The session-control modules no longer do. `architecture.spec.ts` drops `rollout.ts`+from the declared files and adds a closure test:++- **Strict:** the registry, the handoff, `engineHomes.ts`, `sessionFiles.ts`, the store list and both kit modules+ reach no Claude Code or Codex file but the declared contracts. The store list reaches exactly the two stores and+ what Codex's shares with its launch and hook contracts. The kit modules reach none at all.+- **With one exception:** session repair, Stop's capture, the composition and `core/agents/bind.ts` reach the+ readers of Claude Code's and Codex's transcripts only through Pi's session reader+ (`lib/sessionSearch/externals/pi.ts`, through `lib/transcriptReader.ts`). Session repair names Pi's folders with+ it. The test walks their closures without that one file, and fails once it is no longer reached, so the+ exception is dropped with the change that takes it out.++The launch builders' closure test now admits the session stores too, since `lib/engineHomes.ts` reads them.+## The plan for the rest of (c)The sub-batches are ordered by risk: pure functions first, then async writes, then the hot and synchronous-paths. Each one records today's behavior in a golden spec first, in its own commit.+paths. Each one records today's behavior in a golden spec first, in its own commit. One is left.| | Scope | Why it is in this place | Golden proof || --- | --- | --- | --- |-| **(c4) Registry load and session identity** | The registry's Codex child-rollout repair (`lib/registry.ts` with `engines/codex/rollout.ts`), `lib/sessionRepair.ts` (about 190 of 716 lines), `lib/captureResumeIdentity.ts`, `lib/handoffDiscovery.ts`, and the moved engine homes of `lib/engineHomes.ts` (with the `CODEX_HOME` env literal at create and relaunch), which the registry and session repair read. | Synchronous, at load before any worker exists, and on the hook path. A wrong answer loses bindings at every restart. The moved homes go with it, since the registry and session repair are what read them. | Recorded transcripts and pid records → binding, session id and repair, read with the same bounds. || **(c5) Adoption readers and shared normalizers** | `lib/sessionSearch/externals/{claude,codex}.ts`, `lib/transcriptPages.ts`, `lib/transcriptReader.ts` and `lib/transcriptActivity.ts`. Also splitting the functions `engines/claude/normalize.ts` and `engines/codex/{normalizer,subagent}.ts` share with other engines into `engines/kit`. | The largest (1,000 to 2,000 lines) but async. Listing and paging sessions for adoption is not session control. Those readers may run in a worker, as long as adoption fails safe when it is down: refused with a reason, never a wrong session. | The adoption and paging specs, unchanged, plus a recorded corpus of transcripts → pages. |**Out of (c).** These stay as they are, as tables over every engine:diff --git a/docs/design/2026-10-08-engine-remaining-facets.md b/docs/design/2026-10-08-engine-remaining-facets.mdindex 61147305e..48fdd41eb 100644--- a/docs/design/2026-10-08-engine-remaining-facets.md+++ b/docs/design/2026-10-08-engine-remaining-facets.md@@ -119,7 +119,7 @@ About 220 lines would leave, and with them core's only native child process and4. **(c) Launch, discovery and resume.** The largest. It has the most synchronous call sites (registryload, discovery tables, argv). It is split by risk into (c1) launch argv and the pane script (done),(c2) launch preparation (trust writes and the resume repair, done), (c3) discovery and process matching (done),- (c4) registry load and session identity, and (c5) adoption readers and the shared normalizers+ (c4) registry load and session identity (done), and (c5) adoption readers and the shared normalizers([engine launch](2026-10-08-engine-launch.md)). Session control stays worker-free throughout, as in (b).This puts (d) before (b) and (c), unlike the order the owner listed. The reason: async work that is