Skip to content

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

Claude Code and Codex in moved homes: unhooked conversations bind, Codex restarts and reopens, its own provider (#865)

Dee4c339811d609
diff --git a/cli/e2e/enginehomes.e2e.ts b/cli/e2e/enginehomes.e2e.ts
index ff1ec0239..e888e49d9 100644
--- a/cli/e2e/enginehomes.e2e.ts
+++ b/cli/e2e/enginehomes.e2e.ts
@@ -6,7 +6,8 @@
* engine takes them whatever the daemon's own environment says: the desktop app starts the daemon
* without the profile. An agent must still bind, take turns and come back after a restart.
*/
-import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { execFileSync } from 'node:child_process'
+import { mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
import { LocalClient, type Frame } from './harness/client.js'
@@ -31,6 +32,22 @@ async function turn(client: LocalClient, agentId: string, content: string): Prom
await ended
}
+/** The one conversation file an engine wrote in a moved home: Claude Code's transcript, Codex's rollout. */
+function conversationIn(engine: Engine, home: string): string | null {
+ const walk = (dir: string): string[] => {
+ let entries
+ try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return [] }
+ return entries.flatMap((entry) => entry.isDirectory() ? walk(join(dir, entry.name)) : entry.name.endsWith('.jsonl') ? [entry.name] : [])
+ }
+ const files = walk(join(home, engine === 'claude' ? 'projects' : 'sessions'))
+ if (files.length !== 1) return null
+ return engine === 'claude' ? files[0].replace(/\.jsonl$/, '') : /-([0-9a-f-]{36})\.jsonl$/.exec(files[0])?.[1] ?? null
+}
+/** The command lines of the fake Codex processes running a conversation, as the process table shows them. */
+const codexCommands = (sessionId: string): string[] =>
+ execFileSync('ps', ['-A', '-o', 'command='], { encoding: 'utf8' }).split('\n')
+ .filter((line) => /^codex\s/.test(line.trim()) && line.includes(sessionId))
+
describe('the person\'s engines keeping their data elsewhere', () => {
let daemon: IsolatedDaemon | undefined
afterEach(async () => { await daemon?.close(); daemon = undefined })
@@ -120,6 +137,91 @@ describe('the person\'s engines keeping their data elsewhere', () => {
client.close()
}, 300_000)
+ // A conversation started by hand in a terminal tile (`claude`, `codex`), with no hook to name it: only the
+ // 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.
+ it.each([
+ ['claude', 'CLAUDE_CONFIG_DIR', 'codex'],
+ ['codex', 'CODEX_HOME', 'claude'],
+ ] as const)('%s with %s: a conversation started by hand in a terminal binds, with no hook to name it', async (engine: Engine, variable, hooked) => {
+ const d = await IsolatedDaemon.create({ env: { HOOK_INSTALL_ENGINES: hooked } })
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ const home = join(d.root, `${engine}-work`)
+ mkdirSync(home, { recursive: true })
+ writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), `export ${variable}=${JSON.stringify(home)}\n`)
+ const cwd = join(d.projectsDir, `typed-new-${engine}`)
+ mkdirSync(cwd, { recursive: true })
+ await d.start()
+ await until('the daemon to read the login shell', () => /\[env\] read \d+ variables from the login shell/.test(d.log()), 30_000)
+ const client = await LocalClient.connect(d)
+ const opened = await client.request('agent_create', { engine: 'terminal', cwd }, 60_000)
+ expect(opened.error, JSON.stringify(opened)).toBeUndefined()
+ const tile = await until('the terminal tile to be up', async () => {
+ const now = await row(client, opened.agent.id)
+ return now?.status === 'active' && now.tmuxPane ? now : null
+ }, 60_000, 250)
+ await type(d, tile.tmuxPane, engine)
+ const sessionId = await until(`the ${engine} conversation to be written in ${variable}`, async () => conversationIn(engine, home), 30_000, 250)
+ const back = await until(`the tile to bind the ${engine} conversation it started in ${variable}`, async () => {
+ const now = await row(client, tile.id)
+ return now?.engine === engine && now.sessionId ? now : null
+ }, 45_000, 500)
+ expect(back.sessionId).toBe(sessionId)
+ expect(back.status).toBe('active')
+ client.close()
+ }, 300_000)
+
+ // A Codex agent in a moved CODEX_HOME, restarted, then stopped and opened again. Its rollout was held to the
+ // daemon's own CODEX_HOME before the relaunch (portableHistory.ts) and refused as outside the profile: the
+ // restart failed after Codex had already been stopped, and the reopen said RESUME_PREPARATION_FAILED. And
+ // the relaunch names the person's own provider, the `model_provider` in the moved config.toml: it read the
+ // daemon's ~/.codex/config.toml (ownLoginProvider.ts) and named Codex's default, which outranks the config.
+ it('codex with CODEX_HOME: a restart and a reopen come back on the conversation, on the provider its config names', async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ const home = join(d.root, 'codex-work')
+ mkdirSync(home, { recursive: true })
+ writeFileSync(join(home, 'config.toml'), 'model_provider = "azure"\n')
+ writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), `export CODEX_HOME=${JSON.stringify(home)}\n`)
+ const cwd = join(d.projectsDir, 'moved-codex-relaunch')
+ mkdirSync(cwd, { recursive: true })
+ await d.start()
+ await until('the daemon to read the login shell', () => /\[env\] read \d+ variables from the login shell/.test(d.log()), 30_000)
+ const client = await LocalClient.connect(d)
+ const created = await client.request('agent_create', { engine: 'codex', cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const bound = (what: string, sessionId?: string) => until(what, async () => {
+ const now = await row(client, created.agent.id)
+ return now?.sessionId && now.status === 'active' && (!sessionId || now.sessionId === sessionId) ? now : null
+ }, 60_000, 500)
+ const agent = await bound('the codex agent to bind with its data in codex-work')
+ expect(conversationIn('codex', home)).toBe(agent.sessionId)
+ await turn(client, agent.id, 'before the restart')
+
+ const restarted = await client.request('agent_restart', { agentId: agent.id }, 90_000)
+ expect(restarted.error, JSON.stringify(restarted)).toBeUndefined()
+ await bound('the codex agent back on its conversation after the restart', agent.sessionId)
+ await turn(client, agent.id, 'after the restart')
+ const commands = await until('the restarted Codex in the process table', async () => {
+ const found = codexCommands(agent.sessionId)
+ return found.length ? found : null
+ }, 15_000, 250)
+ expect(commands.join('\n')).toContain('model_provider="azure"')
+
+ const stopped = await client.request('agent_delete', { agentId: agent.id }, 60_000)
+ expect(stopped.error, JSON.stringify(stopped)).toBeUndefined()
+ await until('the codex agent to stop', async () => (await row(client, agent.id))?.status === 'stopped' || null, 45_000, 500)
+ const resumed = await client.request('agent_resume', { agentId: agent.id }, 90_000)
+ expect(resumed.error, JSON.stringify(resumed)).toBeUndefined()
+ await bound('the codex agent back on its conversation after the reopen', agent.sessionId)
+ await turn(client, agent.id, 'after the reopen')
+ client.close()
+ }, 300_000)
+
// An engine reads whether it trusts a folder from ITS config: Codex from config.toml in its CODEX_HOME
// (the one the person moved, or the agent's own profile), Claude Code from .claude.json in
// CLAUDE_CONFIG_DIR. The daemon answered for a folder it had just made in ~/.codex/config.toml and
diff --git a/cli/src/engines/codex/ownLoginProvider.spec.ts b/cli/src/engines/codex/ownLoginProvider.spec.ts
index 817a42f39..2c7a661b5 100644
--- a/cli/src/engines/codex/ownLoginProvider.spec.ts
+++ b/cli/src/engines/codex/ownLoginProvider.spec.ts
@@ -4,7 +4,7 @@
* The parsing is deliberately small — one key, top level only — so what is worth pinning is where
* it must NOT find that key, and what it hands back when it finds nothing.
*/
-import { describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import {
CODEX_DEFAULT_PROVIDER,
codexConfigPath,
@@ -12,6 +12,11 @@ import {
parseCodexModelProvider,
} from './ownLoginProvider.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 }))
+vi.mock('../../lib/loginShellEnv.js', () => ({ loginShellEnvironment: () => shell.env }))
+afterEach(() => { shell.env = {} })
+
describe('parseCodexModelProvider', () => {
it('reads a top-level key, with either kind of quote and any spacing', () => {
expect(parseCodexModelProvider('model_provider = "azure"')).toBe('azure')
@@ -69,6 +74,18 @@ describe('codexConfigPath', () => {
it('falls back to CODEX_HOME when the agent names no profile', () => {
expect(codexConfigPath(null, { CODEX_HOME: '/elsewhere' })).toBe('/elsewhere/config.toml')
})
+
+ // The CODEX_HOME a person moves is set in their shell profile, which every pane's Codex reads and the
+ // daemon never does: the desktop app or launchd starts it. Read from the daemon's own environment, the
+ // provider a move back off a grid named came from ~/.codex/config.toml, and argv outranks the config, so
+ // the person's own `model_provider` in the moved config.toml was overridden with Codex's default.
+ it('reads the CODEX_HOME the login shell moves, as every pane\'s Codex does', () => {
+ shell.env = { CODEX_HOME: '/codex-work' }
+ expect(codexConfigPath(null)).toBe('/codex-work/config.toml')
+ expect(codexConfigPath('/profiles/work')).toBe('/profiles/work/config.toml')
+ const read = (path: string) => path === '/codex-work/config.toml' ? 'model_provider = "azure"' : null
+ expect(ownLoginProviderArgs('codex', null, { read })).toEqual(['-c', 'model_provider="azure"'])
+ })
})
describe('ownLoginProviderArgs', () => {
diff --git a/cli/src/engines/codex/ownLoginProvider.ts b/cli/src/engines/codex/ownLoginProvider.ts
index 2010d29aa..c6a653455 100644
--- a/cli/src/engines/codex/ownLoginProvider.ts
+++ b/cli/src/engines/codex/ownLoginProvider.ts
@@ -29,9 +29,9 @@
* is asked first and `openai` is the fallback — the same value Codex itself would have picked.
*/
import { readFileSync } from 'node:fs'
-import { homedir } from 'node:os'
import { join } from 'node:path'
import type { AgentEngine } from '../../engines/types.js'
+import { launchCodexHome } from '../../lib/engineHomes.js'
/** What Codex uses when nothing configures otherwise. */
export const CODEX_DEFAULT_PROVIDER = 'openai'
@@ -71,9 +71,11 @@ function stripComment(line: string): string {
return line
}
-/** Where Codex keeps its configuration — the same resolution `prepareCodexResume` uses. */
-export function codexConfigPath(codexHome: string | null | undefined, env = process.env): string {
- return join(codexHome || env.CODEX_HOME || join(homedir(), '.codex'), 'config.toml')
+/** Where the Codex about to be launched reads its config (lib/engineHomes.ts `launchCodexHome`). The daemon's
+ * own CODEX_HOME was read, not the login shell's: a person who moved it had their own `model_provider`
+ * overridden with Codex's default, which argv outranks the config with. */
+export function codexConfigPath(codexHome: string | null | undefined, environment?: NodeJS.ProcessEnv): string {
+ return join(launchCodexHome(codexHome, environment), 'config.toml')
}
/** Read a Codex `config.toml`; an unreadable or absent file is "nothing configured", not an error. */
@@ -96,7 +98,7 @@ export function ownLoginProviderArgs(
): string[] {
if (engine !== 'codex') return []
const read = deps.read ?? readCodexConfig
- const toml = read(codexConfigPath(codexHome, deps.env ?? process.env))
+ const toml = read(codexConfigPath(codexHome, deps.env))
const configured = toml ? parseCodexModelProvider(toml) : null
return ['-c', `model_provider="${configured ?? CODEX_DEFAULT_PROVIDER}"`]
}
diff --git a/cli/src/engines/codex/portableHistory.spec.ts b/cli/src/engines/codex/portableHistory.spec.ts
index 2c9831e72..149f62cf3 100644
--- a/cli/src/engines/codex/portableHistory.spec.ts
+++ b/cli/src/engines/codex/portableHistory.spec.ts
@@ -179,6 +179,32 @@ describe('preparing a stopped Codex session for resume', () => {
expect(readdirSync(join(profile, 'sessions', '2026', '09', '15'))).toHaveLength(1)
})
+ // A person who moved CODEX_HOME in their shell profile keeps their rollouts there, and an agent of theirs
+ // names no profile of its own. The rollout was held to the daemon's own CODEX_HOME, refused as "outside the
+ // session profile", and every restart or reopen of that agent failed after its engine had been stopped.
+ it('prepares a rollout kept in a CODEX_HOME the person moved, for an agent on no profile of its own', async () => {
+ writeFileSync(file, history(badReasoning()))
+ vi.resetModules()
+ vi.stubEnv('CODEX_HOME', join(profile, 'daemon-codex'))
+ const homes = await import('../../lib/engineHomes.js')
+ homes.adoptEngineHomes({ CODEX_HOME: profile }, { claudeHome: '/nowhere/.claude', codexHome: '/nowhere/.codex' })
+ try {
+ const fresh = await import('./portableHistory.js')
+ expect(fresh.prepareCodexResume({ ...source(), codexHome: null }).repairedItems).toBe(1)
+ // Found by its id there too, when the registry has no path for it.
+ writeFileSync(file, history(badReasoning()))
+ expect(fresh.prepareCodexResume({ ...source(), codexHome: null, transcriptPath: null }).repairedItems).toBe(1)
+ // A file in no Codex home at all is still refused.
+ const stray = join(profile, 'stray.jsonl')
+ writeFileSync(stray, history(badReasoning()))
+ expect(() => fresh.prepareCodexResume({ ...source(), codexHome: null, transcriptPath: stray })).toThrow('outside the session profile')
+ } finally {
+ vi.unstubAllEnvs()
+ rmSync(join(process.env.ADAPTER_DATA_DIR!, 'engine-homes.json'), { force: true })
+ homes.resetEngineHomes()
+ }
+ })
+
it('refuses a different session instead of modifying the wrong history', () => {
const original = history(badReasoning())
writeFileSync(file, original)
diff --git a/cli/src/engines/codex/portableHistory.ts b/cli/src/engines/codex/portableHistory.ts
index 372a93b18..4719b7000 100644
--- a/cli/src/engines/codex/portableHistory.ts
+++ b/cli/src/engines/codex/portableHistory.ts
@@ -1,7 +1,8 @@
import { createHash, randomUUID } from 'node:crypto'
import { closeSync, constants, fsyncSync, fstatSync, lstatSync, openSync, readSync, realpathSync, renameSync, rmSync, writeSync, type Stats } from 'node:fs'
-import { homedir } from 'node:os'
import { isAbsolute, join, relative } from 'node:path'
+import { env } from '../../config/env.js'
+import { codexHomeRoots } from '../../lib/engineHomes.js'
import { resolveCodexRollout } from './rollout.js'
type JsonObject = Record<string, unknown>
@@ -149,20 +150,29 @@ export interface CodexResumeSource {
* for a truncation and replay in full. */
export function prepareCodexResume(source: CodexResumeSource): { repairedItems: number; repairedBytes?: number; backupPath?: string } {
if (source.engine !== 'codex' || !source.sessionId) return { repairedItems: 0 }
- const sessions = join(source.codexHome || process.env.CODEX_HOME || join(homedir(), '.codex'), 'sessions')
- let file = source.transcriptPath || resolveCodexRollout(source.sessionId, sessions)
+ // The agent's own profile, else every home the person moved too (lib/engineHomes.ts): a rollout in a moved
+ // CODEX_HOME was refused as outside the profile, so a restart or reopen failed after Codex had stopped.
+ const sessionRoots = (source.codexHome ? [source.codexHome] : codexHomeRoots(env.CODEX_HOME)).map((home) => join(home, 'sessions'))
+ const byId = () => sessionRoots.reduce<string | null>((found, sessions) => found ?? resolveCodexRollout(source.sessionId, sessions), null)
+ let file = source.transcriptPath || byId()
// A missing history still follows the engine's existing resume/fresh fallback.
if (!file) return { repairedItems: 0 }
let before: ReturnType<typeof lstatSync>
try { before = lstatSync(file) } catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
// The registry may still point at a rollout that was moved; Codex resolves the session by id.
- file = resolveCodexRollout(source.sessionId, sessions)
+ file = byId()
if (!file) return { repairedItems: 0 }
before = lstatSync(file)
}
- const rel = relative(realpathSync(sessions), realpathSync(file))
- if (!before.isFile() || before.isSymbolicLink() || isAbsolute(rel) || rel === '..' || rel.startsWith('../')
+ const real = realpathSync(file)
+ const inside = sessionRoots.some((sessions) => {
+ let root: string
+ try { root = realpathSync(sessions) } catch { return false }
+ const rel = relative(root, real)
+ return !isAbsolute(rel) && rel !== '..' && !rel.startsWith('../')
+ })
+ if (!before.isFile() || before.isSymbolicLink() || !inside
|| (typeof process.getuid === 'function' && before.uid !== process.getuid())) {
throw new Error('Codex rollout is outside the session profile or is not an owned regular file')
}
diff --git a/cli/src/engines/codex/rollout.ts b/cli/src/engines/codex/rollout.ts
index 75fb80607..66afb46c8 100644
--- a/cli/src/engines/codex/rollout.ts
+++ b/cli/src/engines/codex/rollout.ts
@@ -1,13 +1,13 @@
import { closeSync, existsSync, openSync, readSync, readdirSync } from 'fs'
-import { homedir } from 'os'
import { join } from 'path'
+import { env } from '../../config/env.js'
+import { codexHomeRoots } from '../../lib/engineHomes.js'
type JsonObject = Record<string, unknown>
const MAX_WALK_ENTRIES = 5_000
const MAX_META_BYTES = 128 * 1024
const THREAD_ID_RE = /^[a-zA-Z0-9-]{8,128}$/
-const CODEX_SESSIONS_DIR = join(process.env.CODEX_HOME || join(homedir(), '.codex'), 'sessions')
export interface CodexRolloutMeta {
id: string
@@ -56,8 +56,13 @@ export function readCodexRolloutMeta(file: string): CodexRolloutMeta | null {
}
}
-/** Find one rollout by thread id without scanning unbounded user history. */
-export function resolveCodexRollout(threadId: string, root = CODEX_SESSIONS_DIR): string | null {
+/** 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. */
+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)
+ }
if (!THREAD_ID_RE.test(threadId) || !existsSync(root)) return null
const stack = [root]
let visited = 0
diff --git a/cli/src/engines/codex/subagent.spec.ts b/cli/src/engines/codex/subagent.spec.ts
index c48bbcad8..093bfd59a 100644
--- a/cli/src/engines/codex/subagent.spec.ts
+++ b/cli/src/engines/codex/subagent.spec.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
@@ -42,6 +42,35 @@ describe('Codex child rollout reader', () => {
})
})
+ // A person who moved CODEX_HOME in their shell profile runs Codex there, and its sub-agents' rollouts are
+ // written beside the parent's. The default resolver read the daemon's own CODEX_HOME alone, so every Task
+ // card of an agent in a moved home closed with no tools inside it and no totals.
+ it('finds a child rollout in a CODEX_HOME the person moved, for an agent on no profile of its own', async () => {
+ const childId = '019f35c1-8017-7391-beb4-06a01ceda2be'
+ const moved = join(root, 'codex-work')
+ const dir = join(moved, 'sessions', '2026', '10', '05')
+ mkdirSync(dir, { recursive: true })
+ writeFileSync(join(dir, `rollout-2026-10-05T12-00-00-${childId}.jsonl`), [
+ line('2026-10-05T12:00:00.000Z', 'session_meta', { id: childId, source: { subagent: 'explorer' } }),
+ line('2026-10-05T12:00:03.000Z', 'event_msg', { type: 'token_count', info: { total_token_usage: { total_tokens: 789 } } }),
+ ].join('\n'))
+ vi.resetModules()
+ vi.stubEnv('CODEX_HOME', join(root, 'daemon-codex'))
+ const homes = await import('../../lib/engineHomes.js')
+ homes.adoptEngineHomes({ CODEX_HOME: moved }, { claudeHome: '/nowhere/.claude', codexHome: '/nowhere/.codex' })
+ try {
+ const { codexSubagentResolverFor, resolveCodexSubagent } = await import('./subagent.js')
+ expect(resolveCodexSubagent(childId)?.totalTokens).toBe(789)
+ expect(codexSubagentResolverFor(null)(childId)?.totalTokens).toBe(789)
+ // An agent's own profile is its only home.
+ expect(codexSubagentResolverFor(join(root, 'elsewhere'))(childId)).toBeNull()
+ } finally {
+ vi.unstubAllEnvs()
+ rmSync(join(process.env.ADAPTER_DATA_DIR!, 'engine-homes.json'), { force: true })
+ homes.resetEngineHomes()
+ }
+ })
+
it('rejects unsafe child ids before walking the filesystem', () => {
expect(resolveChildRollout('../../etc/passwd', root)).toBeNull()
})
diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.ts
index 6a193d143..8b2616a8c 100644
--- a/cli/src/lib/sessionRepair.spec.ts
+++ b/cli/src/lib/sessionRepair.spec.ts
@@ -540,6 +540,64 @@ describe('session repair — a Codex process names its own rollout', () => {
})
})
+// A home the person moved in their shell profile (CLAUDE_CONFIG_DIR, CODEX_HOME: lib/engineHomes.ts) is where
+// the engine they start by hand writes: Claude Code its transcript and its process record, Codex its rollout.
+// With no start-up hook to name the conversation (the engine's hooks not installed there yet, or the hook
+// lost to a daemon restart), the process repair is all that binds it, and it looked in the default folders
+// alone: the agent in a moved home stayed without a conversation.
+describe('session repair — homes the person moved', () => {
+ const lines = (...records: object[]) => `${records.map(r => JSON.stringify(r)).join('\n')}\n`
+ async function moved(claudeHome: string, codexHome: string) {
+ // Empty stand-in defaults, so nothing depends on this machine's own ~/.claude or ~/.codex.
+ process.env.CODEX_HOME = tempRoot()
+ const loaded = await load(join(tempRoot(), 'projects'))
+ const homes = await import('./engineHomes.js')
+ homes.adoptEngineHomes({ CLAUDE_CONFIG_DIR: claudeHome, CODEX_HOME: codexHome }, { claudeHome: '/nowhere/.claude', codexHome: '/nowhere/.codex' })
+ return loaded
+ }
+ afterEach(async () => {
+ delete process.env.CODEX_HOME
+ rmSync(join(process.env.ADAPTER_DATA_DIR!, 'engine-homes.json'), { force: true })
+ ;(await import('./engineHomes.js')).resetEngineHomes()
+ })
+
+ it('Claude Code: the process record and the transcript in CLAUDE_CONFIG_DIR', async () => {
+ const claudeHome = tempRoot()
+ const id = '11111111-2222-4333-8444-555555555501'
+ 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 transcriptPath = join(claudeHome, 'projects', 'project', `${id}.jsonl`)
+ await expect(claudeProcessSession(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 })
+ })
+
+ it('Claude Code: a sub-agent\'s transcript in the moved home is still never an agent of its own', async () => {
+ const claudeHome = tempRoot()
+ const file = join(claudeHome, 'projects', 'proj', 'p-sess', 'subagents', 'agent-a1.jsonl')
+ mkdirSync(join(file, '..'), { recursive: true })
+ writeFileSync(file, lines({ type: 'user', cwd: CWD }))
+ utimesSync(file, new Date(STARTED_AT + 60_000), new Date(STARTED_AT + 60_000))
+ const { findLiveSession } = await moved(claudeHome, tempRoot())
+ await expect(findLiveSession('claude', CWD, STARTED_AT, { bornOnly: true })).resolves.toBeNull()
+ })
+
+ it('Codex: the rollout in CODEX_HOME, by the file its process holds open and by the folder scan', async () => {
+ 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)
+ 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) })
+ // 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', () => {
it('follows a continued-in marker to the new session file', async () => {
const dir = tempRoot()
diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.ts
index 7ec05946b..355504c07 100644
--- a/cli/src/lib/sessionRepair.ts
+++ b/cli/src/lib/sessionRepair.ts
@@ -130,8 +130,10 @@ async function readTranscriptMeta(path: string): Promise<TranscriptMeta | null>
* the flag — a main transcript can hold sidechain records, and only its opening says what the file is.
*/
async function readClaudeTranscriptMeta(path: string): Promise<TranscriptMeta | null> {
- // Relative to the projects root: the root itself may legitimately sit under a folder of that name.
- if (relative(env.CLAUDE_PROJECTS_DIR, path).split(sep).includes('subagents')) return 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
}
@@ -189,7 +191,7 @@ function hasRun(lines: string[]): boolean {
}
async function fileEngineSession(
- root: string,
+ root: string | string[],
cwd: string,
startedAtMs: number,
readMeta: (path: string) => Promise<TranscriptMeta | null>,
@@ -198,7 +200,10 @@ async function fileEngineSession(
const since = startedAtMs - START_SLACK_MS
const born: RepairedSession[] = []
const wrote: RepairedSession[] = []
- for (const file of await transcripts(root)) {
+ // Several roots are one pool, newest first: one conversation in each of two homes is two agents, as in one.
+ const files = typeof root === 'string' ? await transcripts(root)
+ : (await Promise.all(root.map((one) => transcripts(one)))).flat().sort((a, b) => b.mtimeMs - a.mtimeMs)
+ for (const file of files) {
if (file.mtimeMs < since) break // sorted newest-first: everything after is older still
const meta = await readMeta(file.path)
if (!meta?.cwd || !await sameDir(meta.cwd, cwd)) continue
@@ -290,11 +295,15 @@ export async function findLiveSession(
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(env.CLAUDE_PROJECTS_DIR, cwd, startedAtMs, readClaudeTranscriptMeta, opts)
+ return exact ?? fileEngineSession(claudeProjectsRoots(env.CLAUDE_PROJECTS_DIR), cwd, startedAtMs, readClaudeTranscriptMeta, opts)
}
case 'codex': {
- const sessions = join(opts?.codexHome || env.CODEX_HOME, 'sessions')
+ // 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'))
// Exact first, as for Claude: the rollout the process holds open (see `codexProcessSession`).
const exact = opts?.pid ? await codexProcessSession(opts.pid, sessions, cwd) : null
// Codex writes no `cwd` on line one; its rollout meta carries it — and says whether the rollout
@@ -641,16 +650,17 @@ export async function openFiles(pid: number): Promise<string[]> {
*/
export async function codexProcessSession(
pid: number,
- sessionsRoot: string,
+ sessionsRoot: string | string[],
cwd: string,
files: (pid: number) => Promise<string[]> = openFiles,
): Promise<RepairedSession | null> {
- const root = await realpath(sessionsRoot).catch(() => sessionsRoot)
+ const 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
const real = await realpath(path).catch(() => path)
- if (!real.startsWith(`${root}${sep}`)) continue
+ if (!roots.some((root) => real.startsWith(`${root}${sep}`))) continue
const meta = readCodexRolloutMeta(real)
if (!meta || meta.isSubagent || !meta.id || !meta.cwd || !await sameDir(meta.cwd, cwd)) continue
found.set(real, { sessionId: meta.id, transcriptPath: real })
@@ -660,8 +670,18 @@ export async function codexProcessSession(
export async function claudeProcessSession(pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null> {
if (!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)
+ if (found) return found
+ }
+ return null
+}
+
+async function claudeProcessRecord(file: string, pid: number, cwd: string, startedAtMs: number): Promise<RepairedSession | null> {
try {
- const record = JSON.parse(await readFile(join(dirname(env.CLAUDE_PROJECTS_DIR), 'sessions', `${pid}.json`), 'utf8'))
+ const record = JSON.parse(await readFile(file, 'utf8'))
// procStart is UTC in current Claude, 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'