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 and Codex: trust and resumes in moved homes, forks on their own login, archived Codex conversations (#846)
Dee2d4a4dfc1e7f
diff --git a/cli/e2e/adopt.e2e.ts b/cli/e2e/adopt.e2e.tsnew file mode 100644index 000000000..f5694d652--- /dev/null+++ b/cli/e2e/adopt.e2e.ts@@ -0,0 +1,57 @@+/**+ * Opening a conversation Harness did not start, found on this computer (Cmd-P, `agent_create` with a+ * `resumeSessionId`): a Codex conversation a person had in a terminal opens as a harness on it. One Codex+ * archived does not: Codex refuses to resume it until `codex unarchive <id>` puts it back, and opening it+ * started a pane that only printed Codex's error. The daemon now says so, and opens nothing.+ */+import { mkdirSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { LocalClient } from './harness/client.js'+import { IsolatedDaemon, until } from './harness/daemon.js'++type Row = Record<string, any>++const rows = async (client: LocalClient): Promise<Row[]> =>+ (await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agents+const row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)++describe('opening a Codex conversation Harness did not start', () => {+ let daemon: IsolatedDaemon | undefined+ afterEach(async () => { await daemon?.close(); daemon = undefined })++ it('one from a terminal opens as a harness on it; one Codex archived is refused, saying how to put it back', async () => {+ const d = await IsolatedDaemon.create()+ daemon = d+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })+ const cwd = join(d.projectsDir, 'by-hand')+ mkdirSync(cwd, { recursive: true })+ // Two conversations Codex wrote in a terminal, as it leaves them: one where it keeps them, and one it+ // archived (`archived_sessions/`).+ const rollout = (dir: string, id: string): void => {+ mkdirSync(dir, { recursive: true })+ writeFileSync(join(dir, `rollout-2026-10-03T00-00-00-${id}.jsonl`),+ `${JSON.stringify({ timestamp: new Date().toISOString(), type: 'session_meta', payload: { id, cli_version: '0.159.0', cwd, source: 'cli' } })}\n`)+ }+ const kept = '019a0c0d-0000-7000-8000-0000000000a1'+ const archived = '019a0c0d-0000-7000-8000-0000000000a2'+ rollout(join(d.engineConfig.codexHome, 'sessions', '2026', '10', '03'), kept)+ rollout(join(d.engineConfig.codexHome, 'archived_sessions'), archived)+ await d.start()+ const client = await LocalClient.connect(d)++ // As the apps open a search hit: its engine, its folder and its id (desktop `resumeConversation`).+ const refused = await client.request('agent_create', { engine: 'codex', cwd, resumeSessionId: archived, bypassPermission: true }, 90_000)+ expect(refused.error, JSON.stringify(refused)).toBe('SESSION_ARCHIVED')+ expect(String(refused.detail)).toContain(`codex unarchive ${archived}`)+ expect(await rows(client)).toEqual([])++ const opened = await client.request('agent_create', { engine: 'codex', cwd, resumeSessionId: kept, bypassPermission: true }, 90_000)+ expect(opened.error, JSON.stringify(opened)).toBeUndefined()+ await until('the harness on the conversation from the terminal', async () => {+ const now = await row(client, opened.agent.id)+ return now?.sessionId === kept && now.status === 'active' ? now : null+ }, 60_000, 500)+ client.close()+ }, 240_000)+})diff --git a/cli/e2e/chaos.e2e.ts b/cli/e2e/chaos.e2e.tsindex c85e989cd..85e10915f 100644--- a/cli/e2e/chaos.e2e.ts+++ b/cli/e2e/chaos.e2e.ts@@ -46,8 +46,8 @@ function enginesByPane(daemon: IsolatedDaemon, panes: Array<{ id: string; pid: nfor (const pane of panes) {const tree = new Set<number>([pane.pid])for (const pid of tree) for (const child of children.get(pid) ?? []) tree.add(child)- // The fake engines take their engine's name as their process title.- result.set(pane.id, table.filter(([, pid, , command]) => tree.has(Number(pid)) && /^(claude|codex)$/.test(command.trim())).length)+ // The fake engines' process title is their engine's name, then their arguments, as a CLI's is.+ result.set(pane.id, table.filter(([, pid, , command]) => tree.has(Number(pid)) && /^(claude|codex)(?:\s|$)/.test(command.trim())).length)}void daemonreturn resultdiff --git a/cli/e2e/churn.e2e.ts b/cli/e2e/churn.e2e.tsindex ffe267b4f..4ff03b1b4 100644--- a/cli/e2e/churn.e2e.ts+++ b/cli/e2e/churn.e2e.ts@@ -59,7 +59,7 @@ function engines(d: IsolatedDaemon): number {.map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line)).filter((m): m is RegExpExecArray => !!m).map((m) => ({ pid: Number(m[1]), ppid: Number(m[2]), command: m[3].trim() }))const launchers = new Set(table.filter((p) => p.command.includes(join(d.root, 'bin'))).map((p) => p.pid))- return table.filter((p) => (p.command === 'claude' || p.command === 'codex') && launchers.has(p.ppid)).length+ return table.filter((p) => /^(claude|codex)(?:\s|$)/.test(p.command) && launchers.has(p.ppid)).length}const panes = async (d: IsolatedDaemon): Promise<number> =>(await d.tmux.run('list-panes', '-a', '-F', '#{pane_id}').catch(() => '')).split('\n').filter(Boolean).lengthdiff --git a/cli/e2e/content.e2e.ts b/cli/e2e/content.e2e.tsindex 9c9c91733..fbed4038d 100644--- a/cli/e2e/content.e2e.ts+++ b/cli/e2e/content.e2e.ts@@ -45,7 +45,7 @@ function engines(d: IsolatedDaemon): number {.map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line)).filter((m): m is RegExpExecArray => !!m).map((m) => ({ pid: Number(m[1]), ppid: Number(m[2]), command: m[3].trim() }))const launchers = new Set(table.filter((p) => p.command.includes(join(d.root, 'bin'))).map((p) => p.pid))- return table.filter((p) => (p.command === 'claude' || p.command === 'codex') && launchers.has(p.ppid)).length+ return table.filter((p) => /^(claude|codex)(?:\s|$)/.test(p.command) && launchers.has(p.ppid)).length}const ESC = '\x1b'diff --git a/cli/e2e/enginehomes.e2e.ts b/cli/e2e/enginehomes.e2e.tsindex e6370e181..ff1ec0239 100644--- a/cli/e2e/enginehomes.e2e.ts+++ b/cli/e2e/enginehomes.e2e.ts@@ -6,7 +6,7 @@* 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, writeFileSync } from 'node:fs'+import { mkdirSync, readFileSync, 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'@@ -19,6 +19,10 @@ const rows = async (client: LocalClient): Promise<Row[]> =>(await client.request<{ agents: Row[] }>('agents_list', { includeStopped: true }, 30_000)).agentsconst row = async (client: LocalClient, agentId: string) => (await rows(client)).find((agent) => agent.id === agentId)const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId+async function type(d: IsolatedDaemon, pane: string, text: string): Promise<void> {+ await d.tmux.run('send-keys', '-t', pane, '-l', text)+ await d.tmux.run('send-keys', '-t', pane, 'Enter')+}async function turn(client: LocalClient, agentId: string, content: string): Promise<void> {const started = client.next(isTurn('turn_started', agentId), 45_000, `turn_started (${content})`)const ended = client.next(isTurn('turn_ended', agentId), 45_000, `turn_ended (${content})`)@@ -66,4 +70,91 @@ describe('the person\'s engines keeping their data elsewhere', () => {await turn(client, agent.id, `after the restart, with ${variable} set`)client.close()}, 300_000)++ // A conversation in a moved home, resumed by hand in a terminal tile (`claude --resume <id>`, `codex+ // resume <id>`). Discovery reads the id off the engine's command line and binds it once it finds the+ // conversation's file; with no hook to say so (only the other engine's hooks are installed here), that+ // is all there is. The file was looked for in the default folders alone, and the tile never bound.+ it.each([+ ['claude', 'CLAUDE_CONFIG_DIR', 'codex'],+ ['codex', 'CODEX_HOME', 'claude'],+ ] as const)('%s with %s: a resume typed into a terminal binds the conversation kept in the moved home', 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-resume-${engine}`)+ mkdirSync(cwd, { recursive: true })+ // The conversation as the engine left it in the moved home, where the engine resumes it from.+ const sessionId = engine === 'claude' ? 'c1a0de00-0000-4000-8000-000000000001' : '019a0c0d-0000-7000-8000-000000000001'+ const at = new Date().toISOString()+ if (engine === 'claude') {+ const dir = join(home, 'projects', cwd.replace(/[^a-zA-Z0-9]/g, '-'))+ mkdirSync(dir, { recursive: true })+ writeFileSync(join(dir, `${sessionId}.jsonl`), `${JSON.stringify({ parentUuid: null, isSidechain: false, userType: 'external', cwd, sessionId,+ version: '2.1.270', timestamp: at, uuid: 'b0b0b0b0-0000-4000-8000-000000000001', type: 'user', message: { role: 'user', content: 'from before' } })}\n`)+ } else {+ const dir = join(home, 'sessions', '2026', '10', '03')+ mkdirSync(dir, { recursive: true })+ writeFileSync(join(dir, `rollout-2026-10-03T00-00-00-${sessionId}.jsonl`),+ `${JSON.stringify({ timestamp: at, type: 'session_meta', payload: { id: sessionId, cli_version: '0.159.0', cwd, source: 'cli' } })}\n`)+ }+ await d.start()+ // The daemon learns a moved home from the login shell, which it reads once it is up.+ 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 === 'claude' ? `claude --resume ${sessionId}` : `codex resume ${sessionId}`)+ const back = await until(`the tile to bind the ${engine} conversation kept in ${variable}`, async () => {+ const now = await row(client, tile.id)+ return now?.engine === engine && now.sessionId === sessionId ? now : null+ }, 45_000, 500)+ expect(back.status).toBe('active')+ 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+ // ~/.claude.json alone, so the engine asked anyway and the new agent waited on its question for good.+ it.each([+ ['claude', 'CLAUDE_CONFIG_DIR'],+ ['codex', 'CODEX_HOME'],+ ['codex', 'its own Codex profile'],+ ] as const)('%s with %s: a project folder Harness made is trusted where the engine reads it, and the agent starts without asking', async (engine: Engine, where) => {+ const d = await IsolatedDaemon.create({ trustPrompt: true })+ 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 })+ // The engine has run there before: its config exists, which is when the daemon adds to it.+ const config = join(home, engine === 'claude' ? '.claude.json' : 'config.toml')+ writeFileSync(config, engine === 'claude' ? '{}' : 'model = "gpt-6"\n')+ const profile = where === 'its own Codex profile'+ if (!profile) writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), `export ${where}=${JSON.stringify(home)}\n`)+ await d.start()+ // The daemon learns a moved home from the login shell, which it reads once it is up.+ 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, projectSource: 'new', creationId: `trust-${engine}-${profile ? 'profile' : 'moved'}-0001`,+ ...(profile ? { codexHome: home } : {}),+ }, 90_000)+ expect(created.state, JSON.stringify(created)).toBe('created')+ const agent = await until(`the ${engine} agent to start without asking about its folder`, async () => {+ const now = await row(client, created.agent.id)+ return now?.sessionId && now.status === 'active' ? now : null+ }, 60_000, 500)+ await turn(client, agent.id, 'in a folder Harness made')+ const folder: string = agent.project?.cwd ?? agent.cwd+ expect(readFileSync(config, 'utf8')).toContain(engine === 'claude' ? JSON.stringify(folder) : `[projects.${JSON.stringify(folder)}]`)+ client.close()+ }, 300_000)})diff --git a/cli/e2e/forks.e2e.ts b/cli/e2e/forks.e2e.tsindex a3416483a..d371a6e79 100644--- a/cli/e2e/forks.e2e.ts+++ b/cli/e2e/forks.e2e.ts@@ -3,7 +3,7 @@* source stopped under its fork, and both coming back after a daemon restart. A fork is its own agent* with its own conversation from the moment it exists; nothing one does reaches the other.*/-import { mkdirSync } from 'node:fs'+import { mkdirSync, readFileSync, 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'@@ -111,6 +111,42 @@ describe('forks at their edges', () => {client.close()})+ // A Codex agent moved back off a grid relaunches on the model it had before (the row's+ // `subscriptionModel`, `-m`) and on its own provider (`-c model_provider=…`), as a restart and a resume+ // build it (launch.ts `relaunchOverrides`). A fork was launched without either, and came back on Codex's+ // default model.+ it('codex: a fork of an agent moved back to its own login runs on that agent\'s model, as its restart does', async () => {+ const d = await fresh()+ let client = await LocalClient.connect(d)+ const source = await create(d, client, 'codex', 'fork-own-login')+ await turn(client, source.id, 'before the move back')+ // The model the agent runs, as the frame names it (`runtime-v1:<session>:codex:<model>@<effort>`).+ const model = async (agentId: string) => /:codex:([^@]+)@/.exec(String((await row(client, agentId))?.selectedModel))?.[1]+ expect(await model(source.id)).toBe('gpt-6')+ client.close()+ await d.stop()+ // What a move back off a grid leaves on the row (retarget.ts `setSubscriptionModel`): the model to come+ // back to. No grid is reachable from a test, so the row is given what that move would have written.+ const file = join(d.dataDir, 'registry.json')+ const saved = JSON.parse(readFileSync(file, 'utf8')) as Array<Record<string, unknown>>+ const entry = saved.find((one) => one.agentId === source.id)+ expect(entry, JSON.stringify(saved)).toBeTruthy()+ entry!.subscriptionModel = 'gpt-6-mini'+ writeFileSync(file, JSON.stringify(saved))+ await d.start()+ client = await LocalClient.connect(d)+ await bound(client, source.id)+ const child = await fork(client, source.id, 'the fork')+ await turn(client, child.id, 'in the fork')+ expect(await model(child.id)).toBe('gpt-6-mini')+ // The same model a restart of the source comes back on.+ expect((await client.request('agent_restart', { agentId: source.id }, 90_000)).error).toBeUndefined()+ await bound(client, source.id)+ await turn(client, source.id, 'after the restart')+ expect(await model(source.id)).toBe('gpt-6-mini')+ client.close()+ })+it.each(engines)('%s: after a daemon restart the source and its fork are both back, each on its own conversation', async (engine) => {const d = await fresh()let client = await LocalClient.connect(d)diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.tsindex 1b058b86c..99a7b67d5 100644--- a/cli/e2e/harness/daemon.ts+++ b/cli/e2e/harness/daemon.ts@@ -40,6 +40,8 @@ export interface EngineConfig {startDelayMs?: numberfirstHookDelayMs?: numberupdateAvailable?: string+ /** Ask whether to trust a folder the engine's own config has no answer for, as the real CLIs do. */+ trustPrompt?: boolean}export interface DaemonOptions {@@ -64,6 +66,8 @@ export interface DaemonOptions {beside?: IsolatedDaemon/** Ask for this port instead of a free one: a daemon started on another daemon's port. */port?: number+ /** The fake engines ask whether to trust a folder their config has no answer for (fakeEngine.mjs). */+ trustPrompt?: boolean}async function freePort(): Promise<number> {@@ -193,6 +197,7 @@ export class IsolatedDaemon {port, dataDir: dirs.data, claudeProjectsDir: dirs.claudeProjects, codexHome: dirs.codexHome,claudeModel: options.claudeModel, codexModel: options.codexModel,root, hookLog: join(own, 'fake-engine-hooks.log'),+ ...(options.trustPrompt ? { trustPrompt: true } : {}),}const engine = pathToFileURL(join(here, 'fakeEngine.mjs')).hreffor (const name of ['claude', 'codex']) {diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjsindex e54927dd6..7dee8e4c4 100644--- a/cli/e2e/harness/fakeEngine.mjs+++ b/cli/e2e/harness/fakeEngine.mjs@@ -42,7 +42,8 @@// its first SessionStart takes to reach the daemon once the engine is up: the hook command starting on a// loaded machine, while the daemon has already found the engine and its conversation. `root` is the// test's throwaway root, the only place whose hooks it will run, and `hookLog` where it notes every hook-// it ran.+// it ran. `trustPrompt` makes it ask whether to trust a folder its own config has no answer for. Codex+// refuses to resume a conversation it archived, as the real one does.//// Ctrl+Z suspends it, as both CLIs do on Unix (Claude Code 2.1.289: "Claude Code has been suspended.// Run `fg` to bring Claude Code back."; Codex 0.160: "`ctrl-z` is reserved for suspending the terminal@@ -53,7 +54,7 @@// child in the same process group and terminal (`codexWrapper`).import { execFileSync, spawn } from 'node:child_process'import { randomUUID } from 'node:crypto'-import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readFileSync, writeFileSync } from 'node:fs'+import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'import { homedir } from 'node:os'import { dirname, isAbsolute, join, relative, resolve } from 'node:path'import { fileURLToPath, pathToFileURL } from 'node:url'@@ -142,7 +143,12 @@ export async function run(engine, config = {}, { native = false } = {}) {: `error: unexpected argument '${refused}' found\n\nUsage: codex [OPTIONS] [PROMPT]\n\nFor more information, try '--help'.\n`)process.exit(engine === 'claude' ? 1 : 2)}- process.title = engine+ // The process table shows it as it shows the real CLI: named `claude` or `codex`, with the command line+ // it was started with, both of which discovery reads (tmux.ts: a resume typed into a pane names its+ // conversation on that command line). The title used to be the name alone, so no argument was ever on+ // the command line discovery read. The name is padded to the 16 columns macOS's `ps` gives a name in a+ // table, so the arguments are not read as part of it; a control character is shown as `ps` shows one.+ process.title = [engine.padEnd(16), ...args].join(' ').replace(/[\x00-\x1f\x7f]/g, '?')// Raw at once, as the real CLIs are (Ink and ratatui take the terminal before they draw anything): a// terminal still in line mode keeps at most 1 KiB of a line, so a paste that arrived before the// engine was ready lost the rest of itself (measured: 1,018 of 2,406 characters).@@ -223,6 +229,69 @@ export async function run(engine, config = {}, { native = false } = {}) {return parsed && typeof parsed.hooks === 'object' && parsed.hooks ? parsed.hooks : {}} catch { return {} }})()+ // A conversation Codex archived (its rollout moved to `archived_sessions/`) is not resumed: Codex+ // refuses before its TUI is up (codex-rs app-server thread_processor.rs) until `codex unarchive <id>`+ // moves it back under `sessions/`.+ if (engine === 'codex' && resumed && !fork) {+ const holds = (dir) => {+ let names = []+ try { names = readdirSync(dir, { withFileTypes: true }) } catch { return false }+ return names.some((entry) => entry.isDirectory() ? holds(join(dir, entry.name)) : entry.name.startsWith('rollout-') && entry.name.endsWith(`-${resumed}.jsonl`))+ }+ if (!holds(join(codexHome, 'sessions')) && holds(join(codexHome, 'archived_sessions'))) {+ process.stderr.write(`Error: session ${resumed} is archived. Run \`codex unarchive ${resumed}\` to unarchive it first.\n`)+ process.exit(1)+ }+ }+ // Asking whether to trust the folder (`trustPrompt`), before any conversation starts, as both CLIs+ // ask in a folder they have no answer for, reading the answer from their own config: Claude Code's+ // `projects[<folder or one above it>].hasTrustDialogAccepted` in `.claude.json` in CLAUDE_CONFIG_DIR,+ // else the home folder (2.1.290: `join(CLAUDE_CONFIG_DIR || homedir(), '.claude.json')`); Codex's+ // `[projects."<folder>"] trust_level = "trusted"` in its CODEX_HOME's config.toml (0.160:+ // onboarding/directory_trust.rs, whatever the permission flags). Enter or 1 trusts and saves it as they+ // do; Esc, 2 or ctrl+c quits. Off unless a test asks: the real ones also skip folders this models+ // nothing of (Codex a folder outside any project, Claude Code a sandbox), and the daemon answers the+ // question only for folders it made empty (lib/claudeTrust.ts).+ if (config.trustPrompt) {+ const trustFile = engine === 'claude' ? join(claudeHome ?? homedir(), '.claude.json') : join(codexHome, 'config.toml')+ const trusted = (() => {+ let text = ''+ try { text = readFileSync(trustFile, 'utf8') } catch { return false }+ if (engine === 'codex') {+ const at = text.indexOf(`[projects.${JSON.stringify(cwd)}]`)+ return at >= 0 && /^trust_level\s*=\s*"trusted"/m.test(text.slice(at).split(/\n\[/)[0])+ }+ try {+ const projects = JSON.parse(text).projects ?? {}+ return Object.entries(projects).some(([key, entry]) => entry?.hasTrustDialogAccepted === true+ && (cwd === key.replace(/\/+$/, '') || cwd.startsWith(`${key.replace(/\/+$/, '')}/`)))+ } catch { return false }+ })()+ if (!trusted) {+ process.stdout.write(engine === 'claude'+ ? `\r\n Accessing workspace:\r\n\r\n ${cwd}\r\n\r\n Quick safety check: Is this a project you created or one you trust?\r\n\r\n`+ + ' \x1b[36m❯ 1. Yes, I trust this folder\x1b[39m\r\n 2. No, exit\r\n\r\n Enter to confirm · Esc to cancel\r\n'+ : `\r\n> You are in ${cwd}\r\n\r\n Trust this folder? Codex can read, edit, and run files here, subject to your permission settings.\r\n\r\n`+ + '\x1b[36m› 1. Trust and continue\x1b[39m\r\n 2. Quit\r\n\r\n enter\x1b[2m continue · \x1b[0mesc\x1b[2m quit\x1b[0m\r\n')+ const trust = await new Promise((resolve) => {+ const keys = (chunk) => {+ for (const token of String(chunk).match(/\x1b\[200~[\s\S]*?(?:\x1b\[201~|$)|\x1b\[[0-9;]*[A-Za-z~]|\x1b|[\s\S]/g) ?? []) {+ if (token === '\r' || token === '\n' || token === '1') { process.stdin.off('data', keys); resolve(true); return }+ if (token === '\x1b' || token === '2' || token === '\x03') { process.stdin.off('data', keys); resolve(false); return }+ }+ }+ process.stdin.on('data', keys)+ })+ if (!trust) process.exit(1)+ if (engine === 'codex') appendFileSync(trustFile, `\n[projects.${JSON.stringify(cwd)}]\ntrust_level = "trusted"\n`)+ else {+ let saved = {}+ try { saved = JSON.parse(readFileSync(trustFile, 'utf8')) } catch { /* none yet */ }+ writeFileSync(trustFile, JSON.stringify({ ...saved, projects: { ...saved.projects, [cwd]: { ...saved.projects?.[cwd], hasTrustDialogAccepted: true } } }))+ }+ process.stdout.write('\x1b[H\x1b[2J')+ }+ }let transcript = engine === 'claude'? join(projectsDir, cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${sessionId}.jsonl`): resumed && !fork && config.rolloutFor?.[resumed]@@ -265,8 +334,11 @@ export async function run(engine, config = {}, { native = false } = {}) {: args.includes('--permission-mode') ? args[args.indexOf('--permission-mode') + 1] ?? 'default' : 'default'): (args.includes('--dangerously-bypass-approvals-and-sandbox') ? 'bypassPermissions' : 'default')// The model and effort the thread runs on: what Codex writes in each turn's context, and what its- // `/model` picker changes (below).- let current = { model: config.codexModel ?? 'gpt-6', effort: 'high' }+ // `/model` picker changes (below). Its `-m`/`--model` on the command line outranks the configured one, as+ // in the real CLI: that is how a relaunch puts an agent back on the model it had before a grid+ // (subscriptionModel.ts).+ const modelAt = engine === 'codex' ? args.findIndex((arg) => arg === '-m' || arg === '--model') : -1+ let current = { model: (modelAt >= 0 && args[modelAt + 1]) || config.codexModel || 'gpt-6', effort: 'high' }/*** The JSON an event hands its hooks on stdin, in each CLI's own shape: what notify.mjs reads (session,* transcript, folder, the event and its source, prompt or reason) and the rest of what the real CLIsdiff --git a/cli/e2e/stall.e2e.ts b/cli/e2e/stall.e2e.tsindex babe772cd..b98f6fda1 100644--- a/cli/e2e/stall.e2e.ts+++ b/cli/e2e/stall.e2e.ts@@ -63,7 +63,7 @@ async function turn(client: LocalClient, agentId: string, content: string, durin}/** The engine processes in each tmux pane, by pid, from tmux's own pane list and the process table. The- * fake engines take their engine's name as their process title. */+ * fake engines' process title is their engine's name, then their arguments, as a CLI's is. */async function enginePids(d: IsolatedDaemon): Promise<Map<string, number[]>> {const panes = (await d.tmux.run('list-panes', '-a', '-F', '#{pane_id} #{pane_pid}')).trim().split('\n').map((line) => line.split(' ')).map(([id, pid]) => ({ id, pid: Number(pid) }))@@ -75,7 +75,7 @@ async function enginePids(d: IsolatedDaemon): Promise<Map<string, number[]>> {for (const pane of panes) {const tree = new Set<number>([pane.pid])for (const pid of tree) for (const child of children.get(pid) ?? []) tree.add(child)- result.set(pane.id, table.filter(([, pid, , command]) => tree.has(Number(pid)) && /^(claude|codex)$/.test(command.trim()))+ result.set(pane.id, table.filter(([, pid, , command]) => tree.has(Number(pid)) && /^(claude|codex)(?:\s|$)/.test(command.trim())).map(([, pid]) => Number(pid)))}return resultdiff --git a/cli/e2e/suspend.e2e.ts b/cli/e2e/suspend.e2e.tsindex 6ac5fabcf..6dba45578 100644--- a/cli/e2e/suspend.e2e.ts+++ b/cli/e2e/suspend.e2e.ts@@ -61,9 +61,11 @@ const processTable = () => execFileSync('ps', ['-A', '-o', 'pid=,ppid=,command='* names its process `codex` as the real binary's reads in ps. */function enginePid(d: IsolatedDaemon, root: number, engine: Engine, native = false): number | null {const table = processTable()- const job = table.find((p) => p.ppid === root && (p.command === engine || p.command.includes(join(d.root, 'bin', engine))))+ // A fake engine's process title is its name, then its arguments, as a CLI's command line is.+ const titled = (command: string) => command === engine || command.startsWith(`${engine} `)+ const job = table.find((p) => p.ppid === root && (titled(p.command) || p.command.includes(join(d.root, 'bin', engine))))if (!job || !native) return job?.pid ?? null- return table.find((p) => p.ppid === job.pid && p.command === engine)?.pid ?? null+ return table.find((p) => p.ppid === job.pid && titled(p.command))?.pid ?? null}/** Whether the pane's terminal is in line mode rather than raw, as an engine keeps it. */async function lineMode(d: IsolatedDaemon, pane: string): Promise<boolean> {diff --git a/cli/e2e/tmuxsocket.e2e.ts b/cli/e2e/tmuxsocket.e2e.tsindex 6552299b6..a2a654e26 100644--- a/cli/e2e/tmuxsocket.e2e.ts+++ b/cli/e2e/tmuxsocket.e2e.ts@@ -43,7 +43,7 @@ function engines(d: IsolatedDaemon): string[] {.map((line) => /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line)).filter((m): m is RegExpExecArray => !!m).map((m) => ({ pid: Number(m[1]), ppid: Number(m[2]), command: m[3].trim() }))const launchers = new Set(table.filter((p) => p.command.includes(join(d.root, 'bin'))).map((p) => p.pid))- return table.filter((p) => (p.command === 'claude' || p.command === 'codex') && launchers.has(p.ppid))+ return table.filter((p) => /^(claude|codex)(?:\s|$)/.test(p.command) && launchers.has(p.ppid)).map((p) => `${p.pid} ${p.command}`)}const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 618e20dd5..dc09a5805 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -3625,6 +3625,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {announceSession,attachDsh,prepareApiTools,+ relaunchOverrides,gridName: () => backend.gridName(),})diff --git a/cli/src/core/agents/adopt.spec.ts b/cli/src/core/agents/adopt.spec.tsindex 77e9a5164..816b15cf9 100644--- a/cli/src/core/agents/adopt.spec.ts+++ b/cli/src/core/agents/adopt.spec.ts@@ -55,6 +55,18 @@ describe('whether a conversation can be opened here', () => {expect(await run.adoption.adoptableSession('c1', 'claude', null)).toMatchObject({ error: 'SESSION_FOLDER_GONE' })})+ // Codex will not resume a conversation it archived ("session <id> is archived. Run `codex unarchive+ // <id>` to unarchive it first"). Search finds archived ones, and opening one used to start a pane that+ // only printed that error: refused before anything starts or is stopped, with how to get it back.+ it('refuses a conversation Codex archived, saying how to put it back, before asking who has it open', async () => {+ const run = setup()+ run.found.set('c1', conversation({ engine: 'codex', archived: true }))+ expect(await run.adoption.adoptableSession('c1', 'codex', 'now')).toEqual({+ ok: false, error: 'SESSION_ARCHIVED', detail: 'Codex archived this conversation. Run `codex unarchive c1` in a terminal, then open it here.',+ })+ expect(run.deps.openSessions.owner).not.toHaveBeenCalled()+ })+it('opens one nobody has open, under its own title, or search\'s, or none', async () => {const run = setup({ search: { session: () => ({ title: 'From search' }) } })run.found.set('c1', conversation({ launchArgs: ['--model', 'opus'] }))diff --git a/cli/src/core/agents/adopt.ts b/cli/src/core/agents/adopt.tsindex 1ec9789d7..df4814e98 100644--- a/cli/src/core/agents/adopt.ts+++ b/cli/src/core/agents/adopt.ts@@ -44,6 +44,12 @@ export function createAdoption({ bySession, byAgent, stoppedAgents, externalSess}if (!found) return { ok: false, error: 'SESSION_NOT_FOUND', detail: 'This conversation is no longer on this machine.' }if (found.engine !== engine) return { ok: false, error: 'INVALID_ENGINE', detail: `This is a ${found.engine} conversation.` }+ // Codex will not resume a conversation it archived ("session <id> is archived. Run `codex unarchive+ // <id>` to unarchive it first"), and search finds archived ones: opened, the pane only printed that+ // error and the harness never started. Refused before anything starts or is stopped.+ if (found.archived) {+ return { ok: false, error: 'SESSION_ARCHIVED', detail: `Codex archived this conversation. Run \`codex unarchive ${found.sessionId}\` in a terminal, then open it here.` }+ }// The Codex app keeps a thread in a folder of its own, which people tidy away. Checked before// anything is stopped: a take-over that then cannot open would only have closed it.if (!existsSync(found.cwd)) {diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 9e3643afd..3c3561610 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -220,7 +220,10 @@ describe('creating an agent', () => {const pane = vi.mocked(createAndRegisterPane).mock.calls[0][0]expect(pane).toMatchObject({ dsh: 'blender', dshRuntime: expect.any(String), label: 'Blender', env: expect.objectContaining({ HARNESS_DSH: 'blender' }) })await create(request({ dsh: 'blender', engine: 'codex' }))- expect(preTrustCodexProject).toHaveBeenCalled()+ expect(preTrustCodexProject).toHaveBeenLastCalledWith(expect.any(String), null)+ // A Codex agent on its own profile is trusted in that profile's config.toml, which it reads.+ await create(request({ dsh: 'blender', engine: 'codex', codexHome: '/profiles/work' }))+ expect(preTrustCodexProject).toHaveBeenLastCalledWith(expect.any(String), '/profiles/work')// A folder that already held something, or could not be read: trust stays the person's call.await create(request({ dsh: 'blender', cwd: folder(['README.md']) }))await create(request({ dsh: 'blender', engine: 'pi' }))diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex c207c2f2d..2a8be3e4f 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -173,7 +173,8 @@ export function createAgentCreator({if (emptyBefore && materialized.created.some((item) => item.startsWith('template'))) {try {if (engine === 'claude') preTrustClaudeProject(cwd)- if (engine === 'codex') preTrustCodexProject(cwd)+ // In the agent's own profile when it has one: that config.toml is the one it reads.+ if (engine === 'codex') preTrustCodexProject(cwd, codexHome)} catch (error) { console.warn(`[dsh] pre-trust ${cwd} · ${error instanceof Error ? error.message : error}`) }}} catch (error) {diff --git a/cli/src/core/agents/fork.spec.ts b/cli/src/core/agents/fork.spec.tsindex 771f8e17d..f84f12863 100644--- a/cli/src/core/agents/fork.spec.ts+++ b/cli/src/core/agents/fork.spec.ts@@ -57,6 +57,10 @@ function setup(row: RegisteredSession | null = source(), over: Partial<ForkAgentannounceSession: vi.fn(),attachDsh: vi.fn(),prepareApiTools: vi.fn(),+ // What a restart or a resume relaunches the row with (launch.ts): a Codex profile's CODEX_HOME here.+ relaunchOverrides: vi.fn(async (session: RegisteredSession) => ({+ ok: true as const, overrides: { env: (session.codexHome ? { CODEX_HOME: session.codexHome } : {}) as Record<string, string>, extraArgs: [] as string[], clearEnv: [] as string[] },+ })),gridName: () => 'grid-me',...over,}@@ -137,6 +141,33 @@ describe('forking an agent', () => {expect(vi.mocked(createAndRegisterPane).mock.calls[1][0]).toMatchObject({ forkedFrom: { agentId: 'a1', sessionId: 's1' } })})+ // A fork launched without the overrides a restart and a resume rebuild from the row: a Codex agent+ // moved back off a grid lost `-c model_provider=…` and its model, and the fork came back on Codex's+ // default model where a restart came back on the agent's own.+ it('launches with the row\'s own-login overrides, as a restart and a resume do, the harness and named agent its own', async () => {+ vi.mocked(installedDsh).mockReturnValue({ manifest: { name: 'Blender' } } as never)+ const relaunchOverrides = vi.fn(async () => ({+ ok: true as const,+ overrides: { env: { CODEX_HOME: '/codex', MODEL_ENV: 'x' }, extraArgs: ['-c', 'model_provider="openai"', '-m', 'gpt-6'], clearEnv: ['HARNESS_DSH'] },+ }))+ const row = source({ engine: 'codex', codexHome: '/codex', subscriptionModel: 'gpt-6', dsh: 'blender', agent: 'reviewer' } as Partial<RegisteredSession>)+ await setup(row, { relaunchOverrides }).fork({ agentId: 'a1', name: null, prompt: null })+ // The harness's runtime is the fork's own and so is its named agent: neither is rebuilt from the row.+ expect(relaunchOverrides).toHaveBeenCalledWith(row, expect.objectContaining({ codexHome: '/codex', subscriptionModel: 'gpt-6', dsh: null, agent: null }))+ expect(vi.mocked(buildEngineLaunchArgv).mock.calls[0][1]).toMatchObject({+ extraArgs: ['-c', 'model_provider="openai"', '-m', 'gpt-6', '--dsh', '--agent', 'reviewer'],+ // What the harness's launch provides is never cleared under it.+ clearEnv: expect.not.arrayContaining(['HARNESS_DSH']),+ })+ expect(vi.mocked(createAndRegisterPane).mock.calls[0][0]).toMatchObject({ env: { CODEX_HOME: '/codex', MODEL_ENV: 'x', HARNESS_DSH: 'blender' }, codexHome: '/codex' })+ vi.mocked(installedDsh).mockReset().mockReturnValue(undefined)+ // A launch the row cannot be given (a saved API since removed) is refused before any pane opens.+ vi.mocked(createAndRegisterPane).mockClear()+ const refused = vi.fn(async () => ({ ok: false as const, error: 'API_UNAVAILABLE', detail: 'gone' }))+ expect(await setup(source(), { relaunchOverrides: refused }).fork({ agentId: 'a1', name: null, prompt: null })).toEqual({ ok: false, error: 'API_UNAVAILABLE', detail: 'gone' })+ expect(createAndRegisterPane).not.toHaveBeenCalled()+ })+it('carries the harness and the named agent over, when the engine still takes it', async () => {vi.mocked(installedDsh).mockReturnValue({ manifest: { name: 'Blender' } } as never)vi.mocked(createAndRegisterPane).mockResolvedValue({ ok: true, spawned: { runtime: { paneId: '%3' } }, pending: { ...pending, dsh: 'blender' } } as never)diff --git a/cli/src/core/agents/fork.ts b/cli/src/core/agents/fork.tsindex 091ce03ad..c4825b0f8 100644--- a/cli/src/core/agents/fork.ts+++ b/cli/src/core/agents/fork.ts@@ -23,6 +23,7 @@ import { forkName, planFork } from '../../lib/forkAgent.js'import { buildHarnessSessionLabel } from '../../lib/harnessSessionLabel.js'import { projectDisplayName, type registry, type RegisteredSession } from '../../lib/registry.js'import type { TmuxBackend } from '../../lib/tmuxBackend.js'+import type { createLaunchHelpers } from './launch.js'import { mergedLaunchEnv } from './launchEnv.js'import type { createPaneWatcher } from './newPane.js'@@ -38,12 +39,14 @@ export interface ForkAgentDeps {announceSession: (session: RegisteredSession) => voidattachDsh: (session: RegisteredSession) => voidprepareApiTools: (cwd: string | null | undefined, engine: string) => void+ /** What a restart or a resume relaunches the row with (launch.ts): its own login, model and profile. */+ relaunchOverrides: ReturnType<typeof createLaunchHelpers>['relaunchOverrides']/** This account's private grid, as the socket knows it (BackendSocket.gridName). */gridName: () => string | null}export function createAgentForker({- tmuxBackend, registry, mirror, pendingForkInherit, watchNewPane, announceSession, attachDsh, prepareApiTools, gridName,+ tmuxBackend, registry, mirror, pendingForkInherit, watchNewPane, announceSession, attachDsh, prepareApiTools, relaunchOverrides, gridName,}: ForkAgentDeps) {const forkAgent: ForkAgent = async ({ agentId, name, prompt }) => {if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }@@ -89,11 +92,19 @@ export function createAgentForker({dshArgs = prepared.launch.argsdshLabel = installed.manifest.name}+ // The row's own login, model and profile, as a restart and a resume relaunch it (launch.ts): a Codex+ // agent moved back off a grid names its provider again (`-c model_provider=…`,+ // engines/codex/ownLoginProvider.ts) and the model it had before the grid (`-m`), and a profile gets+ // its hooks. A fork was launched without any of them, and came back on Codex's default model where a+ // restart of its source came back on the source's own (e2e/forks.e2e.ts). The harness and the named+ // agent are the fork's own (a new runtime, above and below), so they are not rebuilt here.+ const built = await relaunchOverrides(source, { ...source, dsh: null, agent: null })+ if (!built.ok) return { ok: false, error: built.error, detail: built.detail }const installIfMissing = enginePathOverride(engine) ? undefined : engineInstallRecipe(engine)// Same guard as a relaunch (`buildLaunchOverrides`): an opencode agent recorded on v1 forks on v2// as a general session rather than handing the v2 TUI an `--agent` it exits on.const forkMajor = opencodeMajorVersion()- const extraArgs = [...dshArgs, ...(source.agent && supportsNamedAgent(engine, forkMajor) ? namedAgentArgs(engine, source.agent, forkMajor) : [])]+ const extraArgs = [...built.overrides.extraArgs, ...dshArgs, ...(source.agent && supportsNamedAgent(engine, forkMajor) ? namedAgentArgs(engine, source.agent, forkMajor) : [])]const firstPrompt = plan.level === 'native' ? (prompt ?? undefined) : plan.firstPromptconst launchOptions = {clearEnv: harnessEnvToClear(dshEnv),@@ -123,7 +134,7 @@ export function createAgentForker({cwd: source.cwd,sessionLabel: label,argv,- env: mergedLaunchEnv(source.codexHome ? { CODEX_HOME: source.codexHome } : undefined, dshEnv),+ env: mergedLaunchEnv(Object.keys(built.overrides.env).length ? built.overrides.env : undefined, dshEnv),grid: null,gridLaunchRecord: null,codexHome: source.codexHome ?? null,diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.tsindex 8629a527f..50da3c327 100644--- a/cli/src/core/agents/launches.spec.ts+++ b/cli/src/core/agents/launches.spec.ts@@ -303,8 +303,8 @@ describe('agent_create with a receipt', () => {expect(preTrustClaudeProject).toHaveBeenCalledWith('/projects/prepared')vi.mocked(codexTrusts).mockReturnValueOnce(true)await launch({ engine: 'codex', projectSource: 'worktree', gitSource: '/repo', branchName: 'feature' }, 2)- expect(codexTrusts).toHaveBeenCalledWith('/repo')- expect(preTrustCodexProject).toHaveBeenCalledWith('/projects/prepared')+ expect(codexTrusts).toHaveBeenCalledWith('/repo', null)+ expect(preTrustCodexProject).toHaveBeenCalledWith('/projects/prepared', null)await launch({ engine: 'claude', projectSource: 'worktree', gitSource: '/repo', branchName: 'feature' }, 3)await launch({ engine: 'claude', projectSource: 'branch', gitSource: '/repo', branchRef: 'refs/heads/main' }, 4)await launch({ engine: 'pi', projectSource: 'new' }, 5)@@ -318,6 +318,21 @@ describe('agent_create with a receipt', () => {expect(claudeTrusts).toHaveBeenCalledWith('/repo')})+ // A Codex agent on its own profile reads its trust from THAT profile's config.toml: the trust was+ // read and written in ~/.codex alone, so it got Codex's trust prompt in a folder Harness had just made.+ it('asks and records a Codex agent\'s trust in its own profile', async () => {+ const { ask, replies } = setup()+ const empty = join(root.projects, 'fresh-profile')+ mkdirSync(empty)+ vi.mocked(codexTrusts).mockReturnValueOnce(true)+ await ask({ creationId: `${CREATION}-1`, engine: 'codex', codexHome: '/profiles/work', projectSource: 'worktree', gitSource: '/repo', branchName: 'feature' })+ await ask({ creationId: `${CREATION}-2`, engine: 'codex', codexHome: '/profiles/work', cwd: empty })+ await vi.waitFor(() => expect(replies).toHaveLength(2))+ expect(codexTrusts).toHaveBeenCalledWith('/repo', '/profiles/work')+ expect(preTrustCodexProject).toHaveBeenNthCalledWith(1, '/projects/prepared', '/profiles/work')+ expect(preTrustCodexProject).toHaveBeenNthCalledWith(2, empty, '/profiles/work')+ })+it('trusts an empty workspace this machine\'s own window made in the projects folder, and nothing else', async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})const { ask, replies } = setup()@@ -330,7 +345,7 @@ describe('agent_create with a receipt', () => {await launch({ engine: 'claude', cwd: empty }, true, 1)await launch({ engine: 'codex', cwd: empty }, true, 2)expect(preTrustClaudeProject).toHaveBeenCalledWith(empty)- expect(preTrustCodexProject).toHaveBeenCalledWith(empty)+ expect(preTrustCodexProject).toHaveBeenCalledWith(empty, null)await launch({ engine: 'claude', cwd: filled }, true, 3)await launch({ engine: 'claude', cwd: join(root.projects, 'missing') }, true, 4)await launch({ engine: 'claude', cwd: empty }, false, 5)diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.tsindex 41573eba8..ac1e228ce 100644--- a/cli/src/core/agents/launches.ts+++ b/cli/src/core/agents/launches.ts@@ -255,8 +255,9 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeA// the person's own repo is theirs to answer for (lib/claudeTrust.ts); a worktree gets only// the answer its source repo already has. `branch` IS the source folder: nothing to record.try {- const engineTrust = input.engine === 'claude' ? { trusts: claudeTrusts, record: preTrustClaudeProject }- : input.engine === 'codex' ? { trusts: codexTrusts, record: preTrustCodexProject } : null+ // A Codex agent on its own profile reads its trust from that profile's config.toml, not ~/.codex.+ const engineTrust = input.engine === 'claude' ? { trusts: (path: string) => claudeTrusts(path), record: (path: string) => preTrustClaudeProject(path) }+ : input.engine === 'codex' ? { trusts: (path: string) => codexTrusts(path, input.codexHome), record: (path: string) => preTrustCodexProject(path, input.codexHome) } : nullif (engineTrust && (projectFolder.source === 'new'|| (projectFolder.source === 'worktree' && engineTrust.trusts(projectFolder.gitSource)))) {engineTrust.record(preparedFolder)@@ -281,7 +282,7 @@ export function createLaunchRequests({ receipts, createAgent, forkAgent, resumeAconst empty = await readdir(input.cwd).then((names) => names.length === 0, () => false)if (empty) {if (input.engine === 'claude') preTrustClaudeProject(input.cwd)- if (input.engine === 'codex') preTrustCodexProject(input.cwd)+ if (input.engine === 'codex') preTrustCodexProject(input.cwd, input.codexHome)}} catch (error) { console.warn(`[agent] pre-trust ${input.cwd} · ${error instanceof Error ? error.message : error}`) }}diff --git a/cli/src/lib/claudeTrust.spec.ts b/cli/src/lib/claudeTrust.spec.tsindex 255ba29c2..3b3ad6857 100644--- a/cli/src/lib/claudeTrust.spec.ts+++ b/cli/src/lib/claudeTrust.spec.ts@@ -1,7 +1,7 @@import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, symlinkSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { claudeTrusts, codexTrusts, preTrustClaudeProject, preTrustCodexProject } from './claudeTrust.js'describe('preTrustClaudeProject', () => {@@ -76,23 +76,23 @@ describe('preTrustCodexProject', () => {it('records Codex trust as a projects table, once, and only when Codex is here', () => {const home = mkdtempSync(join(tmpdir(), 'trust-'))- expect(preTrustCodexProject('/w', home)).toBe('skipped')+ expect(preTrustCodexProject('/w', join(home, '.codex'))).toBe('skipped')mkdirSync(join(home, '.codex'))writeFileSync(join(home, '.codex', 'config.toml'), 'model = "gpt-5"\n\n[projects."/old"]\ntrust_level = "trusted"\n')- expect(preTrustCodexProject('/Users/x/harnesses/harness-3', home)).toBe('trusted')+ expect(preTrustCodexProject('/Users/x/harnesses/harness-3', join(home, '.codex'))).toBe('trusted')const after = readFileSync(join(home, '.codex', 'config.toml'), 'utf8')expect(after).toContain('model = "gpt-5"')expect(after).toContain('[projects."/old"]\ntrust_level = "trusted"')expect(after.endsWith('[projects."/Users/x/harnesses/harness-3"]\ntrust_level = "trusted"\n')).toBe(true)- expect(preTrustCodexProject('/Users/x/harnesses/harness-3', home)).toBe('already')+ expect(preTrustCodexProject('/Users/x/harnesses/harness-3', join(home, '.codex'))).toBe('already')})it('is idempotent: a second call leaves the file byte for byte as the first left it', () => {const home = codexHome('model = "gpt-5"')- expect(preTrustCodexProject('/Users/example/harnesses/harness-1', home)).toBe('trusted')+ expect(preTrustCodexProject('/Users/example/harnesses/harness-1', join(home, '.codex'))).toBe('trusted')const once = configOf(home)expect(once).toBe('model = "gpt-5"\n\n[projects."/Users/example/harnesses/harness-1"]\ntrust_level = "trusted"\n')- expect(preTrustCodexProject('/Users/example/harnesses/harness-1', home)).toBe('already')+ expect(preTrustCodexProject('/Users/example/harnesses/harness-1', join(home, '.codex'))).toBe('already')expect(configOf(home)).toBe(once)expect(readdirSync(join(home, '.codex'))).toEqual(['config.toml'])})@@ -101,14 +101,14 @@ describe('preTrustCodexProject', () => {for (const header of [`[projects.'/Users/example/w']`, `[ projects . "/Users/example/w" ]`, ` [projects."/Users/\\u0065xample/w"] # trusted by hand`]) {const text = `${header}\ntrust_level = "untrusted"\n`const home = codexHome(text)- expect(preTrustCodexProject('/Users/example/w', home), header).toBe('already')+ expect(preTrustCodexProject('/Users/example/w', join(home, '.codex')), header).toBe('already')expect(configOf(home), header).toBe(text)}})it('does not count a header that is only a comment', () => {const home = codexHome('# [projects."/Users/example/w"]\n')- expect(preTrustCodexProject('/Users/example/w', home)).toBe('trusted')+ expect(preTrustCodexProject('/Users/example/w', join(home, '.codex'))).toBe('trusted')expect(configOf(home)).toBe('# [projects."/Users/example/w"]\n\n[projects."/Users/example/w"]\ntrust_level = "trusted"\n')})@@ -122,7 +122,7 @@ describe('preTrustCodexProject', () => {'[projects."/Users/example/\\U0001F600"]\ntrust_level = "trusted"\n',]) {const home = codexHome(text)- expect(preTrustCodexProject('/Users/example/w', home), text).toBe('skipped')+ expect(preTrustCodexProject('/Users/example/w', join(home, '.codex')), text).toBe('skipped')expect(configOf(home), text).toBe(text)}})@@ -130,9 +130,9 @@ describe('preTrustCodexProject', () => {it('writes a header TOML can read for a folder with a quote or a DEL in its name, and finds it again', () => {const cwd = '/Users/example/a"b\x7f'const home = codexHome('')- expect(preTrustCodexProject(cwd, home)).toBe('trusted')+ expect(preTrustCodexProject(cwd, join(home, '.codex'))).toBe('trusted')expect(configOf(home)).toBe('\n\n[projects."/Users/example/a\\"b\\u007f"]\ntrust_level = "trusted"\n')- expect(preTrustCodexProject(cwd, home)).toBe('already')+ expect(preTrustCodexProject(cwd, join(home, '.codex'))).toBe('already')})it('writes through a symlinked config.toml instead of replacing the link', () => {@@ -141,7 +141,7 @@ describe('preTrustCodexProject', () => {mkdirSync(join(home, '.codex'))writeFileSync(join(home, 'dotfiles', 'codex.toml'), 'model = "gpt-5"\n')symlinkSync(join(home, 'dotfiles', 'codex.toml'), join(home, '.codex', 'config.toml'))- expect(preTrustCodexProject('/Users/example/w', home)).toBe('trusted')+ expect(preTrustCodexProject('/Users/example/w', join(home, '.codex'))).toBe('trusted')expect(lstatSync(join(home, '.codex', 'config.toml')).isSymbolicLink()).toBe(true)expect(readFileSync(join(home, 'dotfiles', 'codex.toml'), 'utf8')).toContain('[projects."/Users/example/w"]')})@@ -167,12 +167,62 @@ describe('whether a source repo is already trusted (a worktree inherits only thait('reads Codex trust from exactly that folder\'s table', () => {const home = mkdtempSync(join(tmpdir(), 'trust-'))- expect(codexTrusts('/work/repo', home)).toBe(false)+ expect(codexTrusts('/work/repo', join(home, '.codex'))).toBe(false)mkdirSync(join(home, '.codex'))writeFileSync(join(home, '.codex', 'config.toml'),'[projects."/work/repo"]\ntrust_level = "trusted"\n\n[projects."/work/other"]\ntrust_level = "untrusted"\n')- expect(codexTrusts('/work/repo', home)).toBe(true)- expect(codexTrusts('/work/other', home)).toBe(false)- expect(codexTrusts('/work', home)).toBe(false)+ expect(codexTrusts('/work/repo', join(home, '.codex'))).toBe(true)+ expect(codexTrusts('/work/other', join(home, '.codex'))).toBe(false)+ expect(codexTrusts('/work', join(home, '.codex'))).toBe(false)+ })+})++// The trust an engine reads is in ITS config: Codex's in `<CODEX_HOME>/config.toml`, Claude Code's in+// `<CLAUDE_CONFIG_DIR or home>/.claude.json`. Both used to be read and written in the default places+// alone, so a Codex agent on its own profile, or a person who moved either home in their shell profile,+// got the engine's trust prompt in a folder Harness had just made, or had trust written to a file their+// engine never reads.+describe('the config each engine actually reads', () => {+ afterEach(() => { vi.unstubAllEnvs() })+ const temp = (): string => mkdtempSync(join(tmpdir(), 'trust-'))++ it('a Codex agent on its own profile is trusted in that profile\'s config.toml', () => {+ const profile = temp()+ writeFileSync(join(profile, 'config.toml'), 'model = "gpt-5"\n')+ expect(codexTrusts('/w', profile)).toBe(false)+ expect(preTrustCodexProject('/w', profile)).toBe('trusted')+ expect(readFileSync(join(profile, 'config.toml'), 'utf8')).toBe('model = "gpt-5"\n\n[projects."/w"]\ntrust_level = "trusted"\n')+ expect(codexTrusts('/w', profile)).toBe(true)+ })++ it('with no profile, Codex is trusted in the CODEX_HOME the person moved, never in ~/.codex', () => {+ const home = temp()+ const moved = temp()+ mkdirSync(join(home, '.codex'))+ writeFileSync(join(home, '.codex', 'config.toml'), '')+ writeFileSync(join(moved, 'config.toml'), '')+ vi.stubEnv('HOME', home)+ vi.stubEnv('CODEX_HOME', moved)+ expect(preTrustCodexProject('/w')).toBe('trusted')+ expect(codexTrusts('/w')).toBe(true)+ expect(readFileSync(join(moved, 'config.toml'), 'utf8')).toContain('[projects."/w"]')+ expect(readFileSync(join(home, '.codex', 'config.toml'), 'utf8')).toBe('')+ })++ it('Claude Code is trusted in the .claude.json of the CLAUDE_CONFIG_DIR the person moved, as Claude Code reads it', () => {+ const home = temp()+ const moved = temp()+ writeFileSync(join(home, '.claude.json'), '{}')+ writeFileSync(join(moved, '.claude.json'), '{}')+ vi.stubEnv('HOME', home)+ vi.stubEnv('CLAUDE_CONFIG_DIR', moved)+ expect(preTrustClaudeProject('/w')).toBe('trusted')+ expect(claudeTrusts('/w')).toBe(true)+ expect(JSON.parse(readFileSync(join(moved, '.claude.json'), 'utf8')).projects['/w'].hasTrustDialogAccepted).toBe(true)+ expect(readFileSync(join(home, '.claude.json'), 'utf8')).toBe('{}')+ // Not moved: the home folder's, as before.+ vi.stubEnv('CLAUDE_CONFIG_DIR', '')+ expect(preTrustClaudeProject('/v')).toBe('trusted')+ expect(claudeTrusts('/v')).toBe(true)})})diff --git a/cli/src/lib/claudeTrust.ts b/cli/src/lib/claudeTrust.tsindex f598b5e5d..b4590c9ca 100644--- a/cli/src/lib/claudeTrust.ts+++ b/cli/src/lib/claudeTrust.ts@@ -4,6 +4,10 @@* template was laid into — there is nothing in it to review, so the daemon records the answer the way* Claude Code does: `projects[<path>].hasTrustDialogAccepted` in `~/.claude.json`.*+ * In the config the engine launched there actually reads (lib/engineHomes.ts): `.claude.json` in a moved+ * CLAUDE_CONFIG_DIR, and `config.toml` in the agent's own Codex profile or a moved CODEX_HOME. Both were+ * read and written in the default places alone, and such an agent got the trust prompt anyway.+ ** ⚠️ Never for a folder with content the person has not been asked about — a clone, their own repo,* a worktree of one: that answer is theirs. The callers decide; see `backendSocket.ts` (project* folders) and `cli.ts` (harness templates). A worktree only inherits the answer its source repo@@ -13,8 +17,8 @@* (no `~/.claude.json`), when the file does not parse, or when the entry already says yes.*/import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'-import { homedir } from 'node:os'import { join } from 'node:path'+import { launchClaudeConfigDir, launchCodexHome } from './engineHomes.js'function isPlainObject(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value)@@ -32,7 +36,8 @@ function replaceConfigFile(file: string, text: string): void {renameSync(tmp, target)}-export function preTrustClaudeProject(cwd: string, home = homedir()): 'trusted' | 'already' | 'skipped' {+/** `home`: the folder holding the `.claude.json` Claude Code reads (CLAUDE_CONFIG_DIR, else the home folder). */+export function preTrustClaudeProject(cwd: string, home = launchClaudeConfigDir()): 'trusted' | 'already' | 'skipped' {const file = join(home, '.claude.json')if (!existsSync(file)) return 'skipped'let config: unknown@@ -57,7 +62,7 @@ export function preTrustClaudeProject(cwd: string, home = homedir()): 'trusted'/** Whether Claude Code already trusts `path`: its own entry, or a folder above it, says yes — the* same inheritance Claude Code applies. Unreadable or absent config reads as no. */-export function claudeTrusts(path: string, home = homedir()): boolean {+export function claudeTrusts(path: string, home = launchClaudeConfigDir()): boolean {const file = join(home, '.claude.json')if (!existsSync(file)) return falselet config: unknown@@ -82,9 +87,10 @@ function tomlKey(quoted: string): string | null {try { return JSON.parse(quoted) as string } catch { return null }}-/** Whether Codex already trusts exactly `path` (a `[projects."<path>"]` table saying `trusted`). */-export function codexTrusts(path: string, home = homedir()): boolean {- const file = join(home, '.codex', 'config.toml')+/** Whether Codex already trusts exactly `path` (a `[projects."<path>"]` table saying `trusted`), in the+ * config of the agent's own profile (`codexHome`) or, without one, of the Codex home a launch uses. */+export function codexTrusts(path: string, codexHome?: string | null): boolean {+ const file = join(launchCodexHome(codexHome), 'config.toml')if (!existsSync(file)) return falseconst text = readFileSync(file, 'utf8')for (const match of text.matchAll(CODEX_PROJECT_HEADER_RE)) {@@ -98,7 +104,7 @@ export function codexTrusts(path: string, home = homedir()): boolean {}/**- * Codex keeps the same answer in `~/.codex/config.toml` as a `[projects."<path>"]` table with+ * Codex keeps the same answer in `<CODEX_HOME>/config.toml` as a `[projects."<path>"]` table with* `trust_level = "trusted"`. Same rules: only a folder the daemon made empty (or a worktree of one Codex* already trusts), only when Codex has a config here, never rewriting what is there — the table is* appended at the end.@@ -107,8 +113,8 @@ export function codexTrusts(path: string, home = homedir()): boolean {* or `projects` written as an inline table or dotted keys, would make the appended table a duplicate* definition — a config.toml Codex refuses to load. Those are left alone.*/-export function preTrustCodexProject(cwd: string, home = homedir()): 'trusted' | 'already' | 'skipped' {- const file = join(home, '.codex', 'config.toml')+export function preTrustCodexProject(cwd: string, codexHome?: string | null): 'trusted' | 'already' | 'skipped' {+ const file = join(launchCodexHome(codexHome), 'config.toml')if (!existsSync(file)) return 'skipped'const text = readFileSync(file, 'utf8')const keys = [...text.matchAll(CODEX_PROJECT_HEADER_RE)].map((match) => tomlKey(match[1]))diff --git a/cli/src/lib/engineHomes.spec.ts b/cli/src/lib/engineHomes.spec.tsindex ac5321bef..898f1c0cc 100644--- a/cli/src/lib/engineHomes.spec.ts+++ b/cli/src/lib/engineHomes.spec.ts@@ -1,9 +1,13 @@import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'-import { tmpdir } from 'node:os'+import { homedir, tmpdir } from 'node:os'import { join } from 'node:path'-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { env } from '../config/env.js'-import { adoptEngineHomes, claudeProjectsRoots, codexHomeRoots, movedEngineHomes, resetEngineHomes } from './engineHomes.js'+import { adoptEngineHomes, claudeProjectsRoots, codexHomeRoots, launchClaudeConfigDir, launchCodexHome, movedEngineHomes, resetEngineHomes } 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 }))+vi.mock('./loginShellEnv.js', () => ({ loginShellEnvironment: () => shell.env }))const saved = () => join(env.ADAPTER_DATA_DIR, 'engine-homes.json')const defaults = { claudeHome: '/home/someone/.claude', codexHome: '/home/someone/.codex' }@@ -76,3 +80,35 @@ describe('the homes the person moved', () => {mkdirSync(root, { recursive: true })})})++// The home an agent launched now writes in, for what has to be in that engine's own config before it+// starts (its folder trust): the pane runs through the person's login shell, so the home that shell+// moves is the engine's, over the daemon's own environment; an agent's own Codex profile outranks both.+describe('the home an engine launched now uses', () => {+ afterEach(() => { shell.env = {}; vi.unstubAllEnvs() })++ it('Codex: the agent\'s own profile, else the CODEX_HOME the environment moves, else the daemon\'s', () => {+ expect(launchCodexHome('/profiles/work', { CODEX_HOME: '/moved' })).toBe('/profiles/work')+ expect(launchCodexHome(null, { CODEX_HOME: '/moved/' })).toBe('/moved')+ expect(launchCodexHome(undefined, {})).toBe(env.CODEX_HOME)+ // A relative or `~` path is not one the engine resolves the same way from every folder.+ expect(launchCodexHome(null, { CODEX_HOME: '~/codex' })).toBe(env.CODEX_HOME)+ expect(launchCodexHome(null, { CODEX_HOME: ' ' })).toBe(env.CODEX_HOME)+ })++ it('Claude Code: the CLAUDE_CONFIG_DIR the environment moves, else the home folder, as Claude Code resolves .claude.json', () => {+ expect(launchClaudeConfigDir({ CLAUDE_CONFIG_DIR: '/claude-work' })).toBe('/claude-work')+ expect(launchClaudeConfigDir({ CLAUDE_CONFIG_DIR: 'relative' })).toBe(homedir())+ expect(launchClaudeConfigDir({})).toBe(homedir())+ })++ it('reads the login shell\'s environment over the daemon\'s own: the profile is what the pane runs', () => {+ vi.stubEnv('CODEX_HOME', '/daemon-codex')+ vi.stubEnv('CLAUDE_CONFIG_DIR', '/daemon-claude')+ expect(launchCodexHome(null)).toBe('/daemon-codex')+ expect(launchClaudeConfigDir()).toBe('/daemon-claude')+ shell.env = { CODEX_HOME: '/profile-codex', CLAUDE_CONFIG_DIR: '/profile-claude' }+ expect(launchCodexHome(null)).toBe('/profile-codex')+ expect(launchClaudeConfigDir()).toBe('/profile-claude')+ })+})diff --git a/cli/src/lib/engineHomes.ts b/cli/src/lib/engineHomes.tsindex 877f70058..f3713d9d8 100644--- a/cli/src/lib/engineHomes.ts+++ b/cli/src/lib/engineHomes.ts@@ -19,8 +19,10 @@* and every agent bound in it lost its binding at each restart (measured, the same test).*/import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { homedir } from 'node:os'import { dirname, isAbsolute, join, resolve } from 'node:path'import { env } from '../config/env.js'+import { loginShellEnvironment } from './loginShellEnv.js'const claudeHomes: string[] = []const codexHomes: string[] = []@@ -98,6 +100,43 @@ export function codexHomeRoots(own: string): string[] {return [own, ...codexHomes]}+/**+ * The environment an engine launched now starts with, as far as its homes go. Every pane runs the engine+ * through the person's login shell, which reads their profile, so the login shell's variables outrank the+ * daemon's own; before that shell has been read (the first seconds of a start), the daemon's alone.+ */+function launchEnvironment(): NodeJS.ProcessEnv {+ return { ...process.env, ...loginShellEnvironment() }+}++/** A home an environment moves, absolute; null for none, or for one the engine would not resolve the+ * same way from every folder (relative, `~`). */+function movedHome(value: string | undefined): string | null {+ const dir = value?.trim()+ return dir && isAbsolute(dir) ? resolve(dir) : null+}++/**+ * The Codex home an agent launched now reads its `config.toml` from: its own profile (the row's+ * `codexHome`, set on its pane as CODEX_HOME), else the CODEX_HOME the person's shell moves, else the+ * daemon's. What has to be in that config before Codex starts (its folder trust, lib/claudeTrust.ts) was+ * written to `~/.codex` alone, so an agent on its own profile, or a person who moved CODEX_HOME, got+ * Codex's trust prompt in a folder Harness had just made.+ */+export function launchCodexHome(codexHome: string | null | undefined, environment: NodeJS.ProcessEnv = launchEnvironment()): string {+ return codexHome || movedHome(environment.CODEX_HOME) || env.CODEX_HOME+}++/**+ * The folder Claude Code keeps `.claude.json` in for an agent launched now: the CLAUDE_CONFIG_DIR the+ * person's shell sets, else the home folder. Claude Code's own rule (2.1.290:+ * `join(process.env.CLAUDE_CONFIG_DIR || homedir(), '.claude.json')`); its folder trust was read and+ * written in `~/.claude.json` alone, which a moved Claude Code never reads.+ */+export function launchClaudeConfigDir(environment: NodeJS.ProcessEnv = launchEnvironment()): string {+ return movedHome(environment.CLAUDE_CONFIG_DIR) || homedir()+}+/** Test seam: forget every home, and read the data folder's again on next use. */export function resetEngineHomes(): void {claudeHomes.length = 0diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.tsindex 7cf04b4d7..6a193d143 100644--- a/cli/src/lib/sessionRepair.spec.ts+++ b/cli/src/lib/sessionRepair.spec.ts@@ -678,6 +678,30 @@ describe('findResumedTranscript', () => {await expect(findResumedTranscript('codex', id, { codexHome: profile })).resolves.toBe(file)})+ // A home the person moved in their shell profile (CLAUDE_CONFIG_DIR, CODEX_HOME: lib/engineHomes.ts)+ // holds the conversations their engine wrote there, and the registry takes them (#779). A resume of one+ // typed into a pane was looked for in the default folders alone, found nowhere, and never bound.+ it('finds a conversation in a home the person moved, Claude Code\'s and Codex\'s', async () => {+ const claudeHome = tempRoot()+ const codexHome = tempRoot()+ const claudeId = 'f56f0a36-aa58-4af1-a6e2-a77386122399'+ const codexId = 'a1b2c3d4-1111-4a4a-8a8a-000000000099'+ writeTranscript(join(claudeHome, 'projects'), '-w', claudeId, CWD, STARTED_AT)+ const rollout = writeCodexRollout(codexHome, codexId, CWD, STARTED_AT)+ const { findResumedTranscript } = await load(tempRoot())+ const homes = await import('./engineHomes.js')+ homes.adoptEngineHomes({ CLAUDE_CONFIG_DIR: claudeHome, CODEX_HOME: codexHome }, { claudeHome: '/nowhere/.claude', codexHome: '/nowhere/.codex' })+ try {+ await expect(findResumedTranscript('claude', claudeId)).resolves.toBe(join(claudeHome, 'projects', '-w', `${claudeId}.jsonl`))+ await expect(findResumedTranscript('codex', codexId)).resolves.toBe(rollout)+ // An agent's own Codex profile is its only home.+ await expect(findResumedTranscript('codex', codexId, { codexHome: tempRoot() })).resolves.toBeNull()+ } finally {+ rmSync(join(process.env.ADAPTER_DATA_DIR!, 'engine-homes.json'), { force: true })+ homes.resetEngineHomes()+ }+ })+it('never treats an argv value that is not a session id as one', async () => {const root = tempRoot()const { findResumedTranscript } = await load(root)diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex a66c72f27..7ec05946b 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -27,6 +27,7 @@ import { hermesDbPath, listHermesHomes } from '../engines/hermes/home.js'import { sqlitePreflightMessage } from './sqliteAvailability.js'import { sqliteReadAll, type SqliteParam } from './sqliteRead.js'import { piSessionFolder, readPiHead } from './sessionSearch/externals/pi.js'+import { claudeProjectsRoots, codexHomeRoots } from './engineHomes.js'/*** Clock granularity only. `ps` reports start time to the second, so a file created in the same second@@ -589,15 +590,27 @@ export async function findResumedTranscript(return matches.length ? join(directory, matches[0]) : null}if (!/^[0-9a-f-]{16,}$/i.test(sessionId)) return null- if (engine === 'codex') return resolveCodexRollout(sessionId, join(opts?.codexHome || env.CODEX_HOME, 'sessions'))+ // 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'))+ if (found) return found+ }+ return null+ }if (engine !== 'claude') return null- let projects: string[]- try { projects = await readdir(env.CLAUDE_PROJECTS_DIR) } catch { return null }- for (const project of projects) {- const candidate = join(env.CLAUDE_PROJECTS_DIR, project, `${sessionId}.jsonl`)- try {- if ((await stat(candidate)).isFile()) return candidate- } catch { /* not this project */ }+ 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`)+ try {+ if ((await stat(candidate)).isFile()) return candidate+ } catch { /* not this project */ }+ }}return null}diff --git a/cli/src/lib/sessionSearch/externals/codex.spec.ts b/cli/src/lib/sessionSearch/externals/codex.spec.tsindex a00a8c33f..f866e1ac6 100644--- a/cli/src/lib/sessionSearch/externals/codex.spec.ts+++ b/cli/src/lib/sessionSearch/externals/codex.spec.ts@@ -117,6 +117,9 @@ describe('codexProvider', () => {[D, 'codex-app', ''],].sort())expect(found.find((s) => s.sessionId === C)).toMatchObject({ engine: 'codex', transcriptPath: live, mtime: Date.parse('2026-09-25T00:00:00Z') })+ // An archived one is found, to read, and says so: Codex resumes it only once `codex unarchive` puts it back.+ expect(found.find((s) => s.sessionId === C)).not.toHaveProperty('archived')+ expect(found.find((s) => s.sessionId === D)).toMatchObject({ archived: true })})it('knows its owners from the rollouts Codex processes hold open, and asks their rollout about the turn', async () => {diff --git a/cli/src/lib/sessionSearch/externals/codex.ts b/cli/src/lib/sessionSearch/externals/codex.tsindex b693f44b9..275eb275d 100644--- a/cli/src/lib/sessionSearch/externals/codex.ts+++ b/cli/src/lib/sessionSearch/externals/codex.ts@@ -115,17 +115,18 @@ export function codexProvider(options: { home: string }): ExternalProvider {async scan(ctx: ScanContext): Promise<ExternalSession[]> {const titles = await codexTitles(join(options.home, 'session_index.jsonl'), ctx)const found: ExternalSession[] = []- for (const path of [- ...await rollouts(join(options.home, 'sessions')),- ...await rollouts(join(options.home, 'archived_sessions')),- ]) {+ const archived = new Set(await rollouts(join(options.home, 'archived_sessions')))+ for (const path of [...await rollouts(join(options.home, 'sessions')), ...archived]) {const stamp = await fileStamp(path)if (!stamp) continue// A rollout's first line never changes: read once, however the file grows.const head = await ctx.head(`codex:${path}`, stamp.stamp, () => readCodexHead(path))await ctx.pace()if (!head || ctx.excluded(head.cwd)) continue- found.push({ ...head, engine: 'codex', title: titles.get(head.sessionId) ?? '', mtime: stamp.mtime, transcriptPath: path })+ found.push({+ ...head, engine: 'codex', title: titles.get(head.sessionId) ?? '', mtime: stamp.mtime, transcriptPath: path,+ ...(archived.has(path) ? { archived: true as const } : {}),+ })}return found},diff --git a/cli/src/lib/sessionSearch/externals/types.ts b/cli/src/lib/sessionSearch/externals/types.tsindex ed88c981d..82548866c 100644--- a/cli/src/lib/sessionSearch/externals/types.ts+++ b/cli/src/lib/sessionSearch/externals/types.ts@@ -43,6 +43,12 @@ export interface ExternalSession {launchArgs?: readonly string[]/** Its other ids: one Hermes conversation carries on under a new id each time it is compressed. */aliases?: readonly string[]+ /**+ * Codex archived it (`archived_sessions/`). Found, to read, but not opened: Codex refuses to resume+ * one until `codex unarchive <id>` puts it back (codex-rs thread_processor.rs, "session <id> is+ * archived"), so a harness opened on it only showed that error.+ */+ archived?: true}/** A file's head that cannot be judged yet: the engine is still writing its first lines. */