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.

harnessd: agents bind when the person keeps Claude Code's or Codex's data elsewhere (round 26) (#779)

Dee22d86c3b9926
diff --git a/cli/e2e/enginehomes.e2e.ts b/cli/e2e/enginehomes.e2e.ts
new file mode 100644
index 000000000..e6370e181
--- /dev/null
+++ b/cli/e2e/enginehomes.e2e.ts
@@ -0,0 +1,69 @@
+/**
+ * The person's engines keeping their data somewhere of their own, for Claude Code and Codex.
+ * `CLAUDE_CONFIG_DIR` moves Claude Code's settings (and with them its hooks), transcripts and process
+ * records; `CODEX_HOME` moves Codex's hooks and rollouts. People set them in their shell profile to keep
+ * a work and a personal account apart, and the daemon launches every engine through that shell, so the
+ * 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 { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+
+type Engine = 'claude' | 'codex'
+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)
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+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})`)
+ client.send('message', { agentId, content })
+ expect((await started).payload?.userMessage).toBe(content)
+ await ended
+}
+
+describe('the person\'s engines keeping their data elsewhere', () => {
+ let daemon: IsolatedDaemon | undefined
+ afterEach(async () => { await daemon?.close(); daemon = undefined })
+
+ it.each([
+ ['claude', 'CLAUDE_CONFIG_DIR', 'claude-work'],
+ ['codex', 'CODEX_HOME', 'codex-work'],
+ ] as const)('%s with %s set in the person\'s shell profile: an agent binds, works and comes back after a restart', async (engine: Engine, variable, folder) => {
+ // The daemon installs its hooks, as it does on a person's machine: Claude Code's and Codex's alone,
+ // into this test's throwaway home, the moved one included.
+ const d = await IsolatedDaemon.create({ env: { DISABLE_HOOK_INSTALL: 'false', HOOK_INSTALL_ENGINES: 'claude,codex' } })
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ const home = join(d.root, folder)
+ mkdirSync(home, { recursive: true })
+ // The profile every shell the daemon starts reads; the daemon itself never sees this variable.
+ writeFileSync(join(d.env.ZDOTDIR!, '.zshrc'), `export ${variable}=${JSON.stringify(home)}\n`)
+ await d.start()
+ let client = await LocalClient.connect(d)
+ const cwd = join(d.projectsDir, `homes-${engine}`)
+ mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agent = await until(`the ${engine} agent to bind with its data in ${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, `with ${variable} set`)
+ client.close()
+
+ await d.restart()
+ client = await LocalClient.connect(d)
+ await until(`the ${engine} agent back after the restart`, async () => {
+ const now = await row(client, agent.id)
+ return now?.status === 'active' && now.sessionId === agent.sessionId ? now : null
+ }, 60_000, 500)
+ await turn(client, agent.id, `after the restart, with ${variable} set`)
+ client.close()
+ }, 300_000)
+})
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index a24d63371..8b4e163d2 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -58,11 +58,26 @@ export async function run(engine, config) {
const fork = args.includes('--fork-session')
let sessionId = resumed && !fork ? resumed : randomUUID()
const cwd = process.cwd()
+ // The person's own data folders, as the real CLIs honour them: CLAUDE_CONFIG_DIR moves Claude Code's
+ // settings (its hooks with them), its transcripts and its process records; CODEX_HOME moves Codex's
+ // hooks.json and its rollouts. Set in the person's shell profile, they reach the engine through the
+ // shell it is launched in, whatever the daemon's own environment says. Unset (or Codex's the same as
+ // the daemon's), everything is where it always was.
+ const claudeHome = engine === 'claude' && process.env.CLAUDE_CONFIG_DIR ? process.env.CLAUDE_CONFIG_DIR : null
+ const ownCodexHome = engine === 'codex' && process.env.CODEX_HOME && process.env.CODEX_HOME !== config.codexHome ? process.env.CODEX_HOME : null
+ const projectsDir = claudeHome ? join(claudeHome, 'projects') : config.claudeProjectsDir
+ const codexHome = ownCodexHome ?? config.codexHome
+ /** Whether this engine's own settings carry the daemon's hooks: a moved home has none unless the daemon put them there. */
+ const hooksInstalled = () => {
+ const file = claudeHome ? join(claudeHome, 'settings.json') : ownCodexHome ? join(ownCodexHome, 'hooks.json') : null
+ if (!file) return true
+ try { return readFileSync(file, 'utf8').includes('notify.mjs') } catch { return false }
+ }
let transcript = engine === 'claude'
- ? join(config.claudeProjectsDir, cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${sessionId}.jsonl`)
+ ? join(projectsDir, cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${sessionId}.jsonl`)
: resumed && !fork && config.rolloutFor?.[resumed]
? config.rolloutFor[resumed]
- : join(config.codexHome, 'sessions', '2026', '10', '03', `rollout-2026-10-03T00-00-00-${sessionId}.jsonl`)
+ : join(codexHome, 'sessions', '2026', '10', '03', `rollout-2026-10-03T00-00-00-${sessionId}.jsonl`)
mkdirSync(dirname(transcript), { recursive: true })
if (!existsSync(transcript)) writeFileSync(transcript, '')
// What each CLI leaves for whoever needs to know which conversation this process is writing, as the
@@ -75,7 +90,7 @@ export async function run(engine, config) {
if (held !== null) closeSync(held)
held = openSync(transcript, 'r')
} else if (procStart) {
- const sessions = join(dirname(config.claudeProjectsDir), 'sessions')
+ const sessions = join(dirname(projectsDir), 'sessions')
mkdirSync(sessions, { recursive: true })
writeFileSync(join(sessions, `${process.pid}.json`), JSON.stringify({ pid: process.pid, sessionId, cwd: process.cwd(), procStart }))
}
@@ -95,6 +110,7 @@ export async function run(engine, config) {
}
const hook = async (path, body) => {
+ if (!hooksInstalled()) return
const token = readFileSync(join(config.dataDir, 'hook-credential'), 'utf8').trim()
const pane = process.env.TMUX_PANE
const response = await fetch(`http://127.0.0.1:${config.port}/api/hook/${path}`, {
@@ -218,8 +234,8 @@ export async function run(engine, config) {
await hook('session-end', { reason: 'clear' })
sessionId = randomUUID()
transcript = engine === 'claude'
- ? join(config.claudeProjectsDir, cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${sessionId}.jsonl`)
- : join(config.codexHome, 'sessions', '2026', '10', '03', `rollout-2026-10-03T00-00-00-${sessionId}.jsonl`)
+ ? join(projectsDir, cwd.replace(/[^a-zA-Z0-9]/g, '-'), `${sessionId}.jsonl`)
+ : join(codexHome, 'sessions', '2026', '10', '03', `rollout-2026-10-03T00-00-00-${sessionId}.jsonl`)
mkdirSync(dirname(transcript), { recursive: true })
writeFileSync(transcript, '')
parent = null
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index ad680c54f..117a880fb 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -3246,7 +3246,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
localClient: () => ({ kind: 'desktop', name: terminalHintMachineName().slice(0, 64), machineId: backend.machineId }),
})
// Every engine's hooks, pointed at the port the local server actually bound (core/engines/hooks.ts).
- if (!env.DISABLE_HOOK_INSTALL) installEngineHooks(hookPort)
+ if (!env.DISABLE_HOOK_INSTALL) installEngineHooks(hookPort, { only: env.HOOK_INSTALL_ENGINES, loginShell: loginShellEnvPromise })
backend.setDashboardPort(hookPort) // surfaced to the web (e2e_status) so it can link here to approve
console.log(`[cli] local dashboard → http://127.0.0.1:${hookPort}`)
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index 6083c68ec..bf4437a66 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -258,6 +258,12 @@ const envSchema = z.object({
ADAPTER_COMPUTER_ID_FILE: z.string().default(computerIdFile),
// Set to 'true' to skip auto-installing lifecycle hooks for every supported engine.
DISABLE_HOOK_INSTALL: z.string().default('false').transform((v) => v === 'true'),
+ // Install only these engines' hooks (comma-separated, e.g. `claude,codex`); every engine's when unset.
+ // For a machine where Harness should leave the other tools' settings alone, and for the end-to-end
+ // suite, which installs Claude Code's and Codex's alone, inside its throwaway home.
+ HOOK_INSTALL_ENGINES: z.string().optional().transform((v) => v === undefined
+ ? null
+ : new Set(v.split(',').map((name) => name.trim()).filter(Boolean))),
// `harness start` and `harness login` install the `grid` CLI when the machine has none (see
// lib/gridInstall.ts). Off for tests and for a machine whose grid is managed some other way.
DISABLE_GRID_INSTALL: z.string().default('false').transform((v) => v === 'true'),
diff --git a/cli/src/core/engines/hooks.spec.ts b/cli/src/core/engines/hooks.spec.ts
index a6948c204..07c343c00 100644
--- a/cli/src/core/engines/hooks.spec.ts
+++ b/cli/src/core/engines/hooks.spec.ts
@@ -2,8 +2,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import * as hooks from '../../lib/hooks.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { processRows } from '../../lib/terminalAgentDiscovery.js'
+import { dirname } from 'node:path'
+import { env } from '../../config/env.js'
+import { adoptEngineHomes, movedEngineHomes } from '../../lib/engineHomes.js'
import { createEngineHooks, installEngineHooks, type EngineHookDeps } from './hooks.js'
+vi.mock('../../lib/engineHomes.js', () => ({
+ adoptEngineHomes: vi.fn(() => ({ claude: null, codex: null })),
+ movedEngineHomes: vi.fn(() => ({ claude: [], codex: [] })),
+}))
vi.mock('../../lib/terminalAgentDiscovery.js', async (real) => ({ ...await real<object>(), processRows: vi.fn(async () => []) }))
vi.mock('../../lib/hooks.js', async (real) => ({
...await real<object>(),
@@ -130,6 +137,46 @@ describe('installing every engine\'s hooks', () => {
expect(console.warn).not.toHaveBeenCalled()
})
+ it('only the engines asked for (HOOK_INSTALL_ENGINES), the homes they moved included', () => {
+ vi.mocked(movedEngineHomes).mockReturnValueOnce({ claude: ['/w/claude'], codex: ['/w/codex'] })
+ installEngineHooks(4242, { only: new Set(['codex']), environment: {} })
+ expect(hooks.installCodexHooks).toHaveBeenCalledWith(4242)
+ expect(hooks.installCodexHooks).toHaveBeenCalledWith(4242, '/w/codex')
+ for (const install of installs.filter((one) => one !== hooks.installCodexHooks)) expect(install).not.toHaveBeenCalled()
+ })
+
+ // lib/engineHomes.ts: with CLAUDE_CONFIG_DIR or CODEX_HOME in the person's profile, no agent ever bound.
+ it('puts the hooks in every home adopted on an earlier boot, at every start', () => {
+ vi.mocked(movedEngineHomes).mockReturnValueOnce({ claude: ['/w/claude'], codex: ['/w/codex'] })
+ installEngineHooks(4242, { environment: {} })
+ expect(hooks.installSessionHooks).toHaveBeenCalledWith(4242, '/w/claude/settings.json')
+ expect(hooks.installCodexHooks).toHaveBeenCalledWith(4242, '/w/codex')
+ })
+
+ it('adopts the homes its own environment moves, then the login shell\'s once that is read, and installs there', async () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const own = { CLAUDE_CONFIG_DIR: '/m/claude' }
+ const shell = { CODEX_HOME: '/s/codex' }
+ vi.mocked(adoptEngineHomes)
+ .mockReturnValueOnce({ claude: '/m/claude', codex: null })
+ .mockReturnValueOnce({ claude: null, codex: '/s/codex' })
+ installEngineHooks(4242, { environment: own, loginShell: Promise.resolve(shell) })
+ expect(adoptEngineHomes).toHaveBeenCalledWith(own, { claudeHome: dirname(env.CLAUDE_PROJECTS_DIR), codexHome: env.CODEX_HOME })
+ expect(hooks.installSessionHooks).toHaveBeenCalledWith(4242, '/m/claude/settings.json')
+ expect(log).toHaveBeenCalledWith('[hooks] engines keep their data elsewhere here: Claude Code in /m/claude')
+ await Promise.resolve()
+ expect(adoptEngineHomes).toHaveBeenLastCalledWith(shell, { claudeHome: dirname(env.CLAUDE_PROJECTS_DIR), codexHome: env.CODEX_HOME })
+ expect(hooks.installCodexHooks).toHaveBeenCalledWith(4242, '/s/codex')
+ expect(log).toHaveBeenCalledWith('[hooks] engines keep their data elsewhere here: Codex in /s/codex')
+ })
+
+ it('reads the daemon\'s own environment when none is given, and logs nothing when nothing moved', () => {
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})
+ installEngineHooks(4242)
+ expect(adoptEngineHomes).toHaveBeenCalledWith(process.env, expect.anything())
+ expect(log).not.toHaveBeenCalled()
+ })
+
it('one at a time: a vendor whose install throws is skipped and named, and the rest still install', () => {
vi.mocked(hooks.installCodexHooks).mockImplementationOnce(() => { throw new Error('config.toml is read-only') })
vi.mocked(hooks.installGrokHooks).mockImplementationOnce(() => { throw 'settings mid-write' })
diff --git a/cli/src/core/engines/hooks.ts b/cli/src/core/engines/hooks.ts
index 674ac5798..f89147216 100644
--- a/cli/src/core/engines/hooks.ts
+++ b/cli/src/core/engines/hooks.ts
@@ -4,7 +4,10 @@
*
* Moved verbatim out of `runForeground` (the core boundary, step 12: docs/design/2026-10-03-harnessd.md).
*/
+import { dirname, join } from 'node:path'
+import { env } from '../../config/env.js'
import { chooseHookAgent, type HookServerHandlers } from '../../hookServer.js'
+import { adoptEngineHomes, movedEngineHomes } from '../../lib/engineHomes.js'
import {
installAgyHooks, installAmpPlugin, installCodexHooks, installCommandCodeHooks, installCopilotHooks, installCursorHooks,
installDevinHooks, installGrokHooks, installHermesHooks, installKiloPlugin, installOpencodePlugin, installPiExtension,
@@ -97,6 +100,15 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry }: En
return { resolveHookAgent, onSessionEnd }
}
+export interface InstallEngineHooksOptions {
+ /** Only these engines' hooks (`HOOK_INSTALL_ENGINES`); every engine's when absent. */
+ only?: ReadonlySet<string> | null
+ /** The daemon's own environment, for the homes it moves; `process.env` when absent. */
+ environment?: NodeJS.ProcessEnv
+ /** The login shell's environment, when it has been read (`warmLoginShellEnvironment`). */
+ loginShell?: Promise<NodeJS.ProcessEnv>
+}
+
/**
* Install every engine's hooks with the port the local server actually bound.
*
@@ -104,12 +116,30 @@ export function createEngineHooks({ tmuxBackend, agentReconciler, registry }: En
* files owned by thirteen different CLIs, and one that is malformed, read-only or mid-write is not
* a reason for the other twelve to go uninstalled — let alone for the daemon not to come up.
*/
-export function installEngineHooks(port: number): void {
+export function installEngineHooks(port: number, options: InstallEngineHooksOptions = {}): void {
const hookStep = (vendor: string, install: () => void): void => {
+ if (options.only && !options.only.has(vendor)) return
try { install() } catch (error) {
console.warn(`[hooks] ${vendor} install skipped · ${error instanceof Error ? error.message : error}`)
}
}
+ // The homes the person moved (lib/engineHomes.ts) get the hooks too: every one adopted before, those
+ // the daemon's own environment names, and those of the login shell every engine is launched through
+ // once it has been read. That read is never waited on (cli.ts), so an engine started in the first
+ // seconds of a daemon's very first start with a moved home may miss its first hook.
+ const installIn = (homes: { claude: Array<string | null>; codex: Array<string | null> }): void => {
+ for (const home of homes.claude) if (home) hookStep('claude', () => installSessionHooks(port, join(home, 'settings.json')))
+ for (const home of homes.codex) if (home) hookStep('codex', () => installCodexHooks(port, home))
+ }
+ const adopt = (environment: NodeJS.ProcessEnv): void => {
+ const moved = adoptEngineHomes(environment, { claudeHome: dirname(env.CLAUDE_PROJECTS_DIR), codexHome: env.CODEX_HOME })
+ if (!moved.claude && !moved.codex) return
+ console.log(`[hooks] engines keep their data elsewhere here: ${[moved.claude && `Claude Code in ${moved.claude}`, moved.codex && `Codex in ${moved.codex}`].filter(Boolean).join(', ')}`)
+ installIn({ claude: [moved.claude], codex: [moved.codex] })
+ }
+ installIn(movedEngineHomes())
+ adopt(options.environment ?? process.env)
+ void options.loginShell?.then(adopt)
hookStep('claude', () => installSessionHooks(port))
hookStep('codex', () => installCodexHooks(port))
hookStep('cursor', () => installCursorHooks(port))
diff --git a/cli/src/engines/codex/lastTurn.spec.ts b/cli/src/engines/codex/lastTurn.spec.ts
index fc8f0fe48..b4aaf49a3 100644
--- a/cli/src/engines/codex/lastTurn.spec.ts
+++ b/cli/src/engines/codex/lastTurn.spec.ts
@@ -58,7 +58,9 @@ describe('Codex recap from the latest file turn', () => {
writeFileSync(file, prefix.join('\n') + '\n')
expect(await readLastCodexTurnText(file), `prefix ${end}`).toEqual(lastCodexTurnText(prefix))
}
- })
+ // A file write and a read per prefix: 5,044 ms on a loaded CI runner (run 37285695917), against
+ // vitest's 5 s default. The work is fixed; only the machine's speed varies.
+ }, 30_000)
it('discards tool receipts from a long latest turn before the final parser sees them', async () => {
const rows = [ask('prompt'), JSON.stringify({ type: 'response_item', payload: { type: 'function_call_output', output: 'x'.repeat(2 * 1024 * 1024) } }),
diff --git a/cli/src/lib/engineHomes.spec.ts b/cli/src/lib/engineHomes.spec.ts
new file mode 100644
index 000000000..ac5321bef
--- /dev/null
+++ b/cli/src/lib/engineHomes.spec.ts
@@ -0,0 +1,78 @@
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { env } from '../config/env.js'
+import { adoptEngineHomes, claudeProjectsRoots, codexHomeRoots, movedEngineHomes, resetEngineHomes } from './engineHomes.js'
+
+const saved = () => join(env.ADAPTER_DATA_DIR, 'engine-homes.json')
+const defaults = { claudeHome: '/home/someone/.claude', codexHome: '/home/someone/.codex' }
+
+describe('the homes the person moved', () => {
+ let root: string
+ beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'engine-homes-'))
+ rmSync(saved(), { force: true })
+ resetEngineHomes()
+ })
+ afterEach(() => {
+ rmSync(root, { recursive: true, force: true })
+ rmSync(saved(), { force: true })
+ resetEngineHomes()
+ })
+
+ it('adopts each absolute home that is not the daemon\'s own, once, beside the defaults', () => {
+ const claude = join(root, 'claude-work'), codex = join(root, 'codex-work')
+ expect(adoptEngineHomes({ CLAUDE_CONFIG_DIR: claude, CODEX_HOME: `${codex}/` }, defaults)).toEqual({ claude, codex })
+ // The same environment again moves nothing new.
+ expect(adoptEngineHomes({ CLAUDE_CONFIG_DIR: claude, CODEX_HOME: codex }, defaults)).toEqual({ claude: null, codex: null })
+ expect(claudeProjectsRoots('/own/projects')).toEqual(['/own/projects', join(claude, 'projects')])
+ expect(codexHomeRoots('/own/codex')).toEqual(['/own/codex', codex])
+ expect(movedEngineHomes()).toEqual({ claude: [claude], codex: [codex] })
+ })
+
+ it('takes no relative, `~`, empty or unset path, and not the daemon\'s own home', () => {
+ for (const value of ['work/.claude', '~/.claude-work', ' ', undefined]) {
+ expect(adoptEngineHomes({ CLAUDE_CONFIG_DIR: value, CODEX_HOME: value }, defaults)).toEqual({ claude: null, codex: null })
+ }
+ expect(adoptEngineHomes({ CLAUDE_CONFIG_DIR: '/home/someone/.claude/', CODEX_HOME: defaults.codexHome }, defaults)).toEqual({ claude: null, codex: null })
+ expect(movedEngineHomes()).toEqual({ claude: [], codex: [] })
+ expect(existsSync(saved())).toBe(false)
+ })
+
+ // The login shell is read after the registry checks the saved agents' transcripts: a home known only
+ // from this boot's shell lost every agent bound in it at each restart.
+ it('remembers what it adopted in the data folder, and knows it on the next boot before any root is asked for', () => {
+ const claude = join(root, 'claude-work'), codex = join(root, 'codex-work')
+ adoptEngineHomes({ CLAUDE_CONFIG_DIR: claude }, defaults)
+ adoptEngineHomes({ CODEX_HOME: codex }, defaults)
+ expect(JSON.parse(readFileSync(saved(), 'utf8'))).toEqual({ claude: [claude], codex: [codex] })
+ resetEngineHomes()
+ expect(claudeProjectsRoots('/own')).toEqual(['/own', join(claude, 'projects')])
+ resetEngineHomes()
+ expect(codexHomeRoots('/own')).toEqual(['/own', codex])
+ })
+
+ it('reads past a malformed or foreign file: only absolute paths it has not read already', () => {
+ writeFileSync(saved(), JSON.stringify({ claude: ['/a/claude', 'relative', 7, '/a/claude'], codex: 'not a list' }))
+ expect(movedEngineHomes()).toEqual({ claude: ['/a/claude'], codex: [] })
+ resetEngineHomes()
+ writeFileSync(saved(), '{ not json')
+ expect(movedEngineHomes()).toEqual({ claude: [], codex: [] })
+ })
+
+ it('still adopts when the data folder cannot be written; the next boot adopts again', () => {
+ const blocked = join(root, 'blocked')
+ writeFileSync(blocked, 'a file where the folder should be')
+ const before = env.ADAPTER_DATA_DIR
+ env.ADAPTER_DATA_DIR = join(blocked, 'data')
+ try {
+ const claude = join(root, 'claude-work')
+ expect(adoptEngineHomes({ CLAUDE_CONFIG_DIR: claude }, defaults)).toEqual({ claude, codex: null })
+ expect(claudeProjectsRoots('/own')).toEqual(['/own', join(claude, 'projects')])
+ } finally {
+ env.ADAPTER_DATA_DIR = before
+ }
+ mkdirSync(root, { recursive: true })
+ })
+})
diff --git a/cli/src/lib/engineHomes.ts b/cli/src/lib/engineHomes.ts
new file mode 100644
index 000000000..877f70058
--- /dev/null
+++ b/cli/src/lib/engineHomes.ts
@@ -0,0 +1,106 @@
+/**
+ * The folders where the person's Claude Code and Codex keep their data, when the person has moved them.
+ *
+ * `CLAUDE_CONFIG_DIR` moves Claude Code's settings (its hooks with them), transcripts and process
+ * records; `CODEX_HOME` moves Codex's hooks and rollouts. People set them in their shell profile, to
+ * keep a work and a personal account apart, and every engine is launched through that shell, so the
+ * engine takes them. The daemon never read the profile: the desktop app or launchd starts it. Measured
+ * end to end (`e2e/enginehomes.e2e.ts`): with either one set, no agent ever bound. The engine read no
+ * Harness hooks and wrote its transcript where the daemon never looked.
+ *
+ * So a moved home is adopted once the daemon reads its own or the login shell's environment
+ * (`core/engines/hooks.ts`): the daemon's hooks are installed there as well, and a transcript beneath
+ * it is the engine's own (`registry.validTranscriptPath`). The defaults stay: a session started without
+ * the variable, from another terminal or before the profile set it, still lands in them.
+ *
+ * ⚠️ Remembered in the data folder (`engine-homes.json`), and read before the first transcript check.
+ * The login shell is read after start-up begins, never waited on, and the registry checks every saved
+ * agent's transcript as it loads: a home known only from this boot's shell was unknown at that check,
+ * 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 { dirname, isAbsolute, join, resolve } from 'node:path'
+import { env } from '../config/env.js'
+
+const claudeHomes: string[] = []
+const codexHomes: string[] = []
+let loaded = false
+
+const savedFile = (): string => join(env.ADAPTER_DATA_DIR, 'engine-homes.json')
+
+/** The homes adopted on earlier boots, once per process, before anything asks for a root. */
+function load(): void {
+ if (loaded) return
+ loaded = true
+ try {
+ const saved = JSON.parse(readFileSync(savedFile(), 'utf8')) as { claude?: unknown; codex?: unknown }
+ const take = (list: unknown, into: string[]): void => {
+ for (const home of Array.isArray(list) ? list : []) {
+ if (typeof home === 'string' && isAbsolute(home) && !into.includes(home)) into.push(home)
+ }
+ }
+ take(saved.claude, claudeHomes)
+ take(saved.codex, codexHomes)
+ } catch { /* none adopted yet, or unreadable: the login shell's are adopted again once it is read */ }
+}
+
+function save(): void {
+ const file = savedFile()
+ try {
+ mkdirSync(dirname(file), { recursive: true })
+ const draft = `${file}.${process.pid}.tmp`
+ writeFileSync(draft, JSON.stringify({ claude: claudeHomes, codex: codexHomes }) + '\n', { mode: 0o600 })
+ renameSync(draft, file)
+ } catch { /* best effort: adopted again at the next start, once the login shell is read */ }
+}
+
+/** The homes an environment moved that the daemon did not already use: null where it moved none new. */
+export interface MovedHomes {
+ claude: string | null
+ codex: string | null
+}
+
+/** Adopt the homes `environment` moves, beside the daemon's own (`defaults`), and say which are new. */
+export function adoptEngineHomes(environment: NodeJS.ProcessEnv, defaults: { claudeHome: string; codexHome: string }): MovedHomes {
+ load()
+ const adopt = (value: string | undefined, own: string, known: string[]): string | null => {
+ const dir = value?.trim()
+ // A relative or `~` path is not a folder the engine resolves the same way from every directory.
+ if (!dir || !isAbsolute(dir)) return null
+ const home = resolve(dir)
+ if (home === resolve(own) || known.includes(home)) return null
+ known.push(home)
+ return home
+ }
+ const moved = {
+ claude: adopt(environment.CLAUDE_CONFIG_DIR, defaults.claudeHome, claudeHomes),
+ codex: adopt(environment.CODEX_HOME, defaults.codexHome, codexHomes),
+ }
+ if (moved.claude || moved.codex) save()
+ return moved
+}
+
+/** Every moved home known: adopted on this boot or an earlier one. */
+export function movedEngineHomes(): { claude: string[]; codex: string[] } {
+ load()
+ return { claude: [...claudeHomes], codex: [...codexHomes] }
+}
+
+/** Every folder Claude Code's transcripts may be in: the daemon's own, then each moved home's. */
+export function claudeProjectsRoots(own: string): string[] {
+ load()
+ return [own, ...claudeHomes.map((home) => join(home, 'projects'))]
+}
+
+/** Every Codex home whose rollouts are Codex's own: the daemon's, then each moved one. */
+export function codexHomeRoots(own: string): string[] {
+ load()
+ return [own, ...codexHomes]
+}
+
+/** Test seam: forget every home, and read the data folder's again on next use. */
+export function resetEngineHomes(): void {
+ claudeHomes.length = 0
+ codexHomes.length = 0
+ loaded = false
+}
diff --git a/cli/src/lib/hooks.spec.ts b/cli/src/lib/hooks.spec.ts
index 22526d591..b1a5b9736 100644
--- a/cli/src/lib/hooks.spec.ts
+++ b/cli/src/lib/hooks.spec.ts
@@ -602,3 +602,26 @@ describe('Hermes hook allowlist', () => {
expect(new Set(ours.map((a) => a.event)).size).toBe(ours.length)
})
})
+
+// lib/engineHomes.ts: a Claude Code home the person moved (CLAUDE_CONFIG_DIR) reads its own settings,
+// so the daemon's hooks must be written there too, beside whatever the person keeps in it.
+describe('Claude Code hooks in a moved home', () => {
+ let home = ''
+ beforeEach(() => { home = mkdtempSync(join(tmpdir(), 'adapter-claude-moved-')) })
+ afterEach(() => { rmSync(home, { recursive: true, force: true }) })
+
+ it('writes the hooks into the settings file it is given, keeping what is there, once', async () => {
+ const file = join(home, 'work', 'settings.json')
+ mkdirSync(join(home, 'work'), { recursive: true })
+ writeFileSync(file, JSON.stringify({ model: 'opus', hooks: { Stop: [{ hooks: [{ type: 'command', command: 'say done' }] }] } }))
+ const { installSessionHooks } = await loadHooks()
+ installSessionHooks(19473, file)
+ const first = readFileSync(file, 'utf-8')
+ const settings = JSON.parse(first)
+ expect(settings.model).toBe('opus')
+ expect(settings.hooks.SessionStart[0].hooks[0].command).toContain('notify.mjs')
+ expect(settings.hooks.Stop.map((block: { hooks: Array<{ command: string }> }) => block.hooks[0].command)).toEqual(['say done', expect.stringContaining('notify.mjs')])
+ installSessionHooks(19473, file)
+ expect(readFileSync(file, 'utf-8')).toBe(first)
+ })
+})
diff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.ts
index 0427cd962..01c9d6de8 100644
--- a/cli/src/lib/hooks.ts
+++ b/cli/src/lib/hooks.ts
@@ -97,10 +97,11 @@ function isOurs(block: HookBlock): boolean {
return Array.isArray(block?.hooks) && block.hooks.some((h) => h?.command?.includes('notify.mjs'))
}
-export function installSessionHooks(port: number): void {
+/** `settingsPath`: another Claude Code home's settings, for a home the person moved (lib/engineHomes.ts). */
+export function installSessionHooks(port: number, settingsPath: string = SETTINGS_PATH): void {
let settings: Settings = {}
try {
- settings = JSON.parse(readFileSync(SETTINGS_PATH, 'utf-8')) as Settings
+ settings = JSON.parse(readFileSync(settingsPath, 'utf-8')) as Settings
} catch {
// missing / unreadable → start from empty settings
}
@@ -134,12 +135,12 @@ export function installSessionHooks(port: number): void {
}
try {
- mkdirSync(dirname(SETTINGS_PATH), { recursive: true })
- writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2) + '\n')
+ mkdirSync(dirname(settingsPath), { recursive: true })
+ writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n')
console.log(
updated
? `[hooks] updated (path/port changed) → ${HOOK_SCRIPT} --port ${port}`
- : `[hooks] installed Claude session + turn (Stop/StopFailure) hooks → ${SETTINGS_PATH}`,
+ : `[hooks] installed Claude session + turn (Stop/StopFailure) hooks → ${settingsPath}`,
)
console.log('[hooks] (takes effect on the next claude session start)')
} catch (err) {
diff --git a/cli/src/lib/registry.spec.ts b/cli/src/lib/registry.spec.ts
index 916c19ef2..ac39156a2 100644
--- a/cli/src/lib/registry.spec.ts
+++ b/cli/src/lib/registry.spec.ts
@@ -1275,6 +1275,30 @@ describe('agent identity: the process owns the agent, the session is bound to it
})
})
+ // lib/engineHomes.ts: CLAUDE_CONFIG_DIR or CODEX_HOME in the person's profile put the engine's
+ // transcripts where no root reached, and no agent bound there.
+ it('takes a transcript beneath a home the person moved as the engine\'s own, and nothing beside it', async () => {
+ const { validTranscriptPath } = await loadRegistryModule()
+ const { adoptEngineHomes } = await import('./engineHomes.js')
+ const moved = mkdtempSync(join(tmpdir(), 'adapter-moved-homes-'))
+ try {
+ const claudeFile = join(moved, 'claude-work', 'projects', '-work', 's1.jsonl')
+ const codexFile = join(moved, 'codex-work', 'sessions', '2026', 'rollout-x.jsonl')
+ const beside = join(moved, 'claude-work', 'elsewhere.jsonl')
+ for (const file of [claudeFile, codexFile, beside]) { mkdirSync(join(file, '..'), { recursive: true }); writeFileSync(file, '{}\n') }
+ expect(validTranscriptPath('claude', claudeFile)).toBe(false)
+ expect(validTranscriptPath('codex', codexFile)).toBe(false)
+ adoptEngineHomes({ CLAUDE_CONFIG_DIR: join(moved, 'claude-work'), CODEX_HOME: join(moved, 'codex-work') }, { claudeHome: dataDir, codexHome: dataDir })
+ expect(validTranscriptPath('claude', claudeFile)).toBe(true)
+ expect(validTranscriptPath('codex', codexFile)).toBe(true)
+ // Beneath the moved home but outside its transcripts, and an agent's own profile still rules alone.
+ expect(validTranscriptPath('claude', beside)).toBe(false)
+ expect(validTranscriptPath('codex', codexFile, dataDir)).toBe(false)
+ } finally {
+ rmSync(moved, { recursive: true, force: true })
+ }
+ })
+
it('validates a Codex transcript against the agent\'s own profile, not the daemon default', async () => {
const { validTranscriptPath } = await loadRegistryModule()
const profile = mkdtempSync(join(tmpdir(), 'adapter-codex-profile-'))
diff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.ts
index 86422ef72..e95d41c0c 100644
--- a/cli/src/lib/registry.ts
+++ b/cli/src/lib/registry.ts
@@ -40,6 +40,7 @@ import { join, basename, dirname, relative, isAbsolute } from 'path'
import { hostname, uptime } from 'os'
import { cursorDataDir } from '../engines/cursor/home.js'
import { env } from '../config/env.js'
+import { claudeProjectsRoots, codexHomeRoots } from './engineHomes.js'
import { readCodexRolloutMeta, resolveCodexRollout } from '../engines/codex/rollout.js'
import { ENGINES, isTerminalEngine, type AgentEngine } from '../engines/types.js'
import type { GridAssignment } from './gridAssignment.js'
@@ -767,15 +768,26 @@ export function engineKeepsTranscriptFile(engine: AgentEngine): boolean {
return TRANSCRIPT_ROOT[engine] !== null
}
+/**
+ * The folders an engine's transcripts may be in: its own, and for Claude Code and Codex each home the
+ * person moved in their shell profile (lib/engineHomes.ts). An agent's own CODEX_HOME profile is its
+ * only one.
+ */
+function transcriptRoots(engine: AgentEngine, rootFor: (codexHome?: string) => string, codexHome?: string): string[] {
+ if (engine === 'claude') return claudeProjectsRoots(rootFor())
+ if (engine === 'codex' && !codexHome) return codexHomeRoots(env.CODEX_HOME).map((home) => join(home, 'sessions'))
+ return [rootFor(codexHome)]
+}
+
export function validTranscriptPath(engine: AgentEngine, filePath: string, codexHome?: string, allowMissing = false): boolean {
const rootFor = TRANSCRIPT_ROOT[engine]
if (!rootFor) return false
try {
const missing = allowMissing && !existsSync(filePath)
const actual = missing ? join(realpathSync(dirname(filePath)), basename(filePath)) : realpathSync(filePath)
- const root = realpathSync(rootFor(codexHome))
+ const within = (root: string): boolean => { try { return isWithin(realpathSync(root), actual) } catch { return false } }
const st = statSync(missing ? dirname(actual) : actual)
- if (!(missing ? st.isDirectory() : st.isFile()) || !isWithin(root, actual)) return false
+ if (!(missing ? st.isDirectory() : st.isFile()) || !transcriptRoots(engine, rootFor, codexHome).some(within)) return false
if (engine === 'cursor') {
const id = basename(actual).replace(/\.jsonl$/, '')
if (!id || basename(dirname(actual)) !== id || basename(dirname(dirname(actual))) !== 'agent-transcripts') return false