Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
Codex hook trust: sandbox HOME in tests, repair trust at launch, decoded TOML keys (#1139)
Fabrício Casalie28fd47d8aa8
diff --git a/CLAUDE.md b/CLAUDE.mdindex f832c8d10..2f1a6fb4e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3031,7 +3031,52 @@ else, and its context links must keep classifying across restarts).put a `.cmd` command on a Linux host); and `isManagedCommand` matches **both** leaves(`codex.sh` AND `codex-hook.cmd`) on every platform — matching only the local one would leave apre-fix entry unrecognized, so the fresh one is appended beside it, which is #558 on a second- file. Matching both is what REPAIRS an existing Windows install at the next launch. **Both+ file. Matching both is what REPAIRS an existing Windows install at the next launch.+ **Codex hook trust is re-checked at every LOCAL Codex spawn, not only at boot, in the HOME that+ session runs under** (`ensureCodexHooksCurrent(home)` in `core/agents/hooks/codex.ts`, called+ from `PtyManager.spawnSession` inside the local codex-scope block with the same+ `codexScope.CODEX_HOME` it puts in the pane's env — a managed account's private home or the+ system one). Codex reads hooks.json and the config.toml `trusted_hash` blocks from its+ CODEX_HOME at SESSION START and silently skips an untrusted hook; boot was the only install, so a+ config.toml rewritten while the app ran (codex's own /hooks flow, another tool, a test run on the+ real home) left every Codex session started afterwards dark — measured on a Windows desktop:+ every message to those nodes queued as `targetStatusStale` and expired. `codexHookDrift(home)`+ is read-only (script + Windows wrapper bytes, our hooks.json entries via the same+ `buildCodexHooksAndTrust`, and each trust key's hash); only drift re-runs+ `installCodexHooks(home)`, with a warning naming the home and what was repaired, so a current+ install never rewrites config.toml (codex writes it too). It never throws into the spawn, never+ creates a missing home, and an `accountId` that is not a known Codex account gets no repair+ (never a fallback to `~/.codex`). **Both repairs are consent-gated (issue #744):** the spawn+ check is reached only through `currentIntegrationLifecycle()?.ensureCodexHooksForLaunch(home)`+ and the account-home pass only inside `reconcile()` — both in `core/agent-integrations.ts`, both+ a no-op unless codex is `enabled` (declined, undecided, the Server Edition veto, or no lifecycle+ registered ⇒ nothing is written). Calling `ensureCodexHooksCurrent` from anywhere else would+ re-install hooks for a user who declined them. **Managed account homes symlink hooks.json + config.toml to+ `~/.codex`** (`initializeAccountHome`), so every write goes through the link (`writeTarget`,+ realpath) — a temp+rename onto the link would replace it with a private copy no later system+ install reaches. A home whose links were never made or were replaced by real files is repaired in+ place; boot now covers those homes too (`ensureCodexHooksForAccounts`, from the lifecycle's reconcile in both shells), where before+ it installed only `~/.codex` and relied on the links. Not covered: SSH hosts (RemoteHooks owns+ those files) and an in-pane restart/resume that types `codex` without a new spawn.+ **A trust table is found by its DECODED key, never by spelling** (`tableHeaderPath`,+ `codex-trust.ts`): bare, `"basic"` (escapes, `\u`) and `'literal'` segments name the same TOML+ key. Measured live on a Windows desktop (2026-10-07): config.toml held our tables as+ `[hooks.state.'C:\…']`, the matcher only knew our `"C:\\…"` spelling, the repair APPENDED a second+ table per key, and Codex refused to start ("duplicate key") — every Codex node dead. The boot+ install had the same flaw before the launch repair existed; the launch repair just ran it more+ often. A repair now REWRITES the existing table whatever its quoting (keeping `enabled = false`),+ and **an edit that would leave any `[table]` defined twice is refused** (`assertTomlTablesUnique`,+ run inside `upsertHookTrustEntriesInContent` whenever it changed the text): the local installer+ computes the config.toml edit BEFORE writing hooks.json, so a refusal writes nothing and warns; the+ SSH installer throws inside its update and writes no config.toml. No TOML parser is in our deps, so+ the guard is the duplicate-table check, not full validation. **A managed hook command is matched+ only under our own directories** (`OWN_HOOK_DIRS`: `/.nodeterm`, `/node-terminal`,+ `/.nodeterm-server` + `/agent-hooks/<leaf>`), never a bare `agent-hooks/<leaf>` tail: another tool keeps+ `~/.other/agent-hooks/codex-hook.cmd` and the tail match stripped it on every repair (and that tool+ did the same to ours). A stale entry from a Server Edition run with a custom `--data-dir` is no+ longer swept — **by repair OR by a declined codex's cleanup** (`removeCodexHooks` shares the+ matcher). Decided, not overlooked: a decline removes exactly what we wrote, and a tail match cannot+ tell our legacy entry from another tool's live one, so the inert legacy entry is left. install-helper's matcher for the other agents still matches by tail (not changed here). **Bothsides of the managed-entry match go through `normalizeHookCommand`** — the marker used to befolded to `/` while the stored command was compared raw, so on Windows nodeterm never recognizedits OWN entry and appended a fresh set every launch (#558: nine copies of nine events, nine@@ -9890,6 +9935,32 @@ For every OTHER test dir, two layers, both needed:`hookServer.stop()` now drop the memo. Found with `strace -f -e trace=mkdir,rename` — an EMPTYleftover dir is the signature of a late writer, not of a missing `rm`.+## The test suite never touches the real home++The hook installers write the user's real agent config — `~/.codex/hooks.json` plus the+`[hooks.state."…"]` trust blocks in `~/.codex/config.toml`, `~/.claude/settings.json`,+`~/.gemini/settings.json`, grok's and copilot's hook files — and they resolve home through+`import { homedir } from 'os'`. **A `vi.spyOn(os, 'homedir')` does not reach that binding**:+measured on a Windows dev box, running `src/core/agents/hooks/index.test.ts` alone (which+"isolated" home with exactly that spy) rewrote the developer's real `~/.codex/config.toml` and+`hooks.json`. Runs from several worktrees then raced each other, and the user's own Codex, on those+files; a Codex session started inside that window had no trust entries for nodeterm's hooks, so its+hooks never fired and every agent message to it expired as `targetStatusStale`.++- **Every run gets a private home** (`test/setup/home-sandbox.ts` + `home-worker-env.ts`,+ `src/core/test-home.ts`): HOME and USERPROFILE point at one directory created and removed by+ `globalSetup`, re-asserted per worker (refusing to run without it), and the agents' relocation+ variables (`CODEX_HOME`, `CLAUDE_CONFIG_DIR`, `GROK_HOME`, `COPILOT_HOME`, `GEMINI_CLI_HOME`,+ `KIMI_CODE_HOME`, `XDG_*`) are cleared. On Windows APPDATA/LOCALAPPDATA move inside it too.+ `os.homedir()` reads the variable on every call, so every installer and every child process lands+ in the sandbox whatever its import style. Registered BEFORE the temp sandbox (it lives in the real+ temp dir and is never counted as a leak there).+- A test that needs its own home uses a MODULE mock (`vi.mock('os', …)` returning `homedir`, as+ `install-helper.fs.test.ts` and `codex.ensure.test.ts` do), never the spy.+- `src/core/test-home.guard.test.ts` runs the real `installCodexHooks()` and proves it wrote the+ sandbox while the real `~/.codex` (read from `os.userInfo().homedir`, which ignores HOME) kept its+ size and mtime.+## Conventions- **Two docs, two audiences — keep both.** This file holds the deep invariants with theirdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex bb092ff53..2f1ef4ef7 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1348,6 +1348,15 @@ tmux without carrying `TMUX_TMPDIR` into it, which is the one way left to escape`src/core/tmux-socket-isolation.guard.test.ts` holds the short allowlist of suites that name aproduction socket on purpose; adding a third is a review conversation, not a checkbox.+**A test never touches the real home.** The hook installers write `~/.codex/config.toml` (Codex's+trust in nodeterm's hooks), `~/.claude/settings.json` and friends, and they use+`import { homedir } from 'os'`, which `vi.spyOn(os, 'homedir')` does not reach — one test doing that+rewrote a developer's real Codex config and Codex stopped running nodeterm's hooks. Every run points+HOME/USERPROFILE at a private sandbox (`test/setup/home-sandbox.ts`) and clears `CODEX_HOME`,+`CLAUDE_CONFIG_DIR` and the other relocation variables (one list, `HOME_OVERRIDE_ENV` in+`src/core/test-home.ts`, which `test/setup/agent-env.ts` reuses). If a test needs its own home, mock the+module (`vi.mock('os', …)`, see `install-helper.fs.test.ts`), never spy on it.+**Session code has two local backends on POSIX: tmux and Zellij.** `settings.sessionBackend` pickswhere a NEW local terminal's session is created (default tmux); an existing session is alwaysreattached in the backend that holds it. If you add a `PtyManager` method that talks to tmux about adiff --git a/src/core/agent-integrations.test.ts b/src/core/agent-integrations.test.tsindex b46f79e7e..f464b13b5 100644--- a/src/core/agent-integrations.test.ts+++ b/src/core/agent-integrations.test.ts@@ -24,6 +24,7 @@ import { buildContextLinkSkillBody, frameInstructionsBlock } from './context-linimport { MAX_RETAINED } from './integration-files'import { registerClaudeAccountsSource, resetClaudeAccountsSourceForTests } from './claude-config-dir'import { accountConfigDir } from './claude-accounts-core'+import { codexAccountHome } from './codex-accounts-core'import type { ClaudeAccount } from '../shared/types'const ENV_KEYS = ['HOME', 'USERPROFILE', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'GROK_HOME', 'COPILOT_HOME', 'XDG_CONFIG_HOME', 'GEMINI_CLI_HOME']@@ -332,3 +333,47 @@ describe('skillsFor — the invocation follows the host and the agent\'s tool sh}})})++// The codex hook-trust repairs (spawn-time + managed account homes) write the user's real+// ~/.codex/hooks.json and config.toml, so they obey the same consent as the boot install: a+// declined or undecided codex — or the Server Edition veto — gets nothing written, ever.+describe('codex hook repair is consent-gated', () => {+ const codexAccount = { id: 'acct-1', label: 'work', createdAt: 1 } as Settings['codexAccounts'][number]++ it('a launch repair writes NOTHING for an undecided or declined codex, or under the veto', () => {+ const cases: Array<[Settings, boolean]> = [+ [DEFAULT_SETTINGS, false],+ [withAgents({ codex: 'declined' }), false],+ [withAgents({ claude: 'enabled' }), false],+ [withAgents({ codex: 'enabled' }), true]+ ]+ for (const [settings, veto] of cases) {+ const { lc } = lifecycle(() => settings, { veto, realHooks: true })+ lc.ensureCodexHooksForLaunch(path.join(home, '.codex'))+ expect(filesUnder(home), JSON.stringify(settings.agentIntegrations ?? 'undecided')).toEqual([])+ }+ })++ it('a launch repair installs hooks + trust for an ENABLED codex', () => {+ const { lc } = lifecycle(() => withAgents({ codex: 'enabled' }), { realHooks: true })+ lc.ensureCodexHooksForLaunch(path.join(home, '.codex'))+ expect(read(path.join(home, '.codex', 'hooks.json'))).toContain('agent-hooks')+ expect(read(path.join(home, '.codex', 'config.toml'))).toContain('trusted_hash')+ })++ it('managed codex account homes are repaired by reconcile only when codex is enabled', () => {+ const acctHome = codexAccountHome(userData, codexAccount.id)+ mkdirSync(acctHome, { recursive: true })+ const choices: Array<Record<string, 'enabled' | 'declined'>> = [{}, { codex: 'declined' }, { claude: 'enabled' }]+ for (const agents of choices) {+ const { lc } = lifecycle(() => withAgents(agents, { codexAccounts: [codexAccount] }), { realHooks: true })+ lc.reconcile()+ expect(readdirSync(acctHome), JSON.stringify(agents)).toEqual([])+ }+ const { lc } = lifecycle(() => withAgents({ codex: 'enabled' }, { codexAccounts: [codexAccount] }), {+ realHooks: true+ })+ lc.reconcile()+ expect(read(path.join(acctHome, 'config.toml'))).toContain('trusted_hash')+ })+})diff --git a/src/core/agent-integrations.ts b/src/core/agent-integrations.tsindex e73ab828f..b011e6149 100644--- a/src/core/agent-integrations.ts+++ b/src/core/agent-integrations.ts@@ -32,6 +32,7 @@ import {installClaudeHooksInto,removeClaudeHooksFrom} from './agents/hooks/claude'+import { ensureCodexHooksCurrent, ensureCodexHooksForAccounts } from './agents/hooks/codex'import { copilotHomeDir } from './agents/hooks/copilot'import { managedHookScriptPath } from './agents/hooks/install-helper'import { opencodeConfigDir } from './agents/hooks/opencode'@@ -114,6 +115,8 @@ export interface IntegrationLifecycleDeps {/** Test seams. */installHooks?: (agents: ReadonlySet<string>) => voidremoveHooks?: (agents: ReadonlySet<string>) => void+ ensureCodexHome?: (home: string) => void+ ensureCodexAccounts?: (userDataDir: string, accounts: ReadonlyArray<{ id: string }>) => voidhome?: () => string}@@ -218,6 +221,10 @@ export interface IntegrationLifecycle {onSettingsChanged(settings: Settings): void/** For a managed/linked Claude account dir just added: install there if claude is enabled. */installIntoClaudeAccount(configDir: string): void+ /** Right before a LOCAL Codex session spawns under `codexHome`: repair its hook install if it+ * drifted — only when codex is enabled (never for a declined or undecided agent, never under the+ * veto). Never throws. */+ ensureCodexHooksForLaunch(codexHome: string): void/** The last report (for Settings). */lastReport(): IntegrationReport | null/** The ownership receipts (also used for skills written on SSH hosts). */@@ -234,6 +241,8 @@ export function createIntegrationLifecycle(deps: IntegrationLifecycleDeps): Inteconst receipts = new ReceiptStore(() => deps.userDataDir())const installHooks = deps.installHooks ?? installManagedAgentHooksconst removeHooks = deps.removeHooks ?? removeManagedAgentHooks+ const ensureCodexHome = deps.ensureCodexHome ?? ensureCodexHooksCurrent+ const ensureCodexAccounts = deps.ensureCodexAccounts ?? ensureCodexHooksForAccountslet last: IntegrationReport | null = nulllet lastSig = ''@@ -289,6 +298,21 @@ export function createIntegrationLifecycle(deps: IntegrationLifecycleDeps): Inte// this consent (it links INTO the account dir, never writes the user's skills).if (a.shareSystemSkills) void applySkillShare(dir, true)}+ // Codex accounts: each local managed home is its own CODEX_HOME. Its hooks.json/config.toml+ // normally symlink to the system ones (just installed above), but a link never made or since+ // replaced by a real file leaves that account's sessions with no trusted hooks. Drift-gated, so+ // a linked home costs reads only. Enabled only — a declined codex is cleaned in the system home+ // by `removeHooks`; a private copy inside an account home is the account's own file and is left.+ if (enabled.includes('codex')) {+ try {+ ensureCodexAccounts(+ deps.userDataDir(),+ (settings.codexAccounts ?? []).filter((a) => !a.host && !a.pending)+ )+ } catch (e) {+ console.warn('[integrations] codex account hook check failed', e)+ }+ }// A $CLAUDE_CONFIG_DIR that moved the system dir leaves the legacy ~/.claude behind.const legacyClaude = path.join(home, '.claude')if (declined.includes('claude') && legacyClaude !== claudeSystemConfigDir()) {@@ -372,6 +396,15 @@ export function createIntegrationLifecycle(deps: IntegrationLifecycleDeps): Inteconsole.warn('[integrations] account install failed', configDir, e)}},+ ensureCodexHooksForLaunch(codexHome) {+ if (deps.veto) return+ try {+ if (integrationsOf(deps.settings()).agents?.codex !== 'enabled') return+ ensureCodexHome(codexHome)+ } catch (e) {+ console.warn('[integrations] codex launch hook check failed', codexHome, e)+ }+ },lastReport: () => last,receipts}diff --git a/src/core/agents/hooks/codex-trust.test.ts b/src/core/agents/hooks/codex-trust.test.tsnew file mode 100644index 000000000..0fea07163--- /dev/null+++ b/src/core/agents/hooks/codex-trust.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest'+import {+ assertTomlTablesUnique,+ tableHeaderPath,+ upsertHookTrustEntriesInContent,+ type CodexTrustEntry+} from './codex-trust'++describe('tableHeaderPath', () => {+ it('decodes basic, literal and bare segments to the same key', () => {+ const key = 'C:\\Users\\u\\.codex\\hooks.json:stop:0:0'+ expect(tableHeaderPath(`[hooks.state."C:\\\\Users\\\\u\\\\.codex\\\\hooks.json:stop:0:0"]`)).toEqual([+ 'hooks',+ 'state',+ key+ ])+ expect(tableHeaderPath(`[hooks.state.'${key}']`)).toEqual(['hooks', 'state', key])+ expect(tableHeaderPath(` [ hooks . "state" . '${key}' ] # note`)).toEqual(['hooks', 'state', key])+ expect(tableHeaderPath('[hooks.state."caf\\u00e9"]')).toEqual(['hooks', 'state', 'café'])+ })++ it('is null for arrays of tables, keys and malformed headers', () => {+ expect(tableHeaderPath('[[profiles]]')).toBeNull()+ expect(tableHeaderPath('model = "x"')).toBeNull()+ expect(tableHeaderPath('[hooks.state."open]')).toBeNull()+ expect(tableHeaderPath('[a] trailing')).toBeNull()+ })+})++describe('assertTomlTablesUnique', () => {+ it('throws on one table spelled two ways', () => {+ const toml = `[hooks.state.'/h/hooks.json:stop:0:0']\nenabled = true\n\n[hooks.state."/h/hooks.json:stop:0:0"]\nenabled = true\n`+ expect(() => assertTomlTablesUnique(toml)).toThrow(/defined twice/)+ })++ it('accepts repeated arrays of tables and headers inside multi-line strings', () => {+ const toml = `[[p]]\na = 1\n[[p]]\na = 2\n[x]\ns = """\n[x]\n"""\n`+ expect(() => assertTomlTablesUnique(toml)).not.toThrow()+ })+})++describe('upsertHookTrustEntriesInContent', () => {+ const entry: CodexTrustEntry = {+ sourcePath: '/nonexistent/h/hooks.json',+ eventLabel: 'stop',+ groupIndex: 0,+ handlerIndex: 0,+ command: 'sh /x'+ }++ it('rewrites a literal-quoted table in place instead of appending a second one', () => {+ const before = `model = "o4"\n\n[hooks.state.'/nonexistent/h/hooks.json:stop:0:0']\nenabled = false\ntrusted_hash = "sha256:00"\n`+ const after = upsertHookTrustEntriesInContent(before, [entry])+ expect(after.match(/\[hooks\.state\./g)).toHaveLength(1)+ expect(after).toContain('enabled = false') // a user's disable survives+ expect(after).not.toContain('sha256:00')+ expect(() => assertTomlTablesUnique(after)).not.toThrow()+ })++ it('refuses to hand back a config it changed that defines a table twice', () => {+ const before = `[other]\na = 1\n[other]\nb = 2\n`+ expect(() => upsertHookTrustEntriesInContent(before, [entry])).toThrow(/defined twice/)+ })+})diff --git a/src/core/agents/hooks/codex-trust.ts b/src/core/agents/hooks/codex-trust.tsindex 5756bf771..c5bfc8b6c 100644--- a/src/core/agents/hooks/codex-trust.ts+++ b/src/core/agents/hooks/codex-trust.ts@@ -5,8 +5,7 @@* Self-contained: only node fs/path/crypto. We port just the functions our* installer needs (trust hashing/keys, byte-preserving config.toml edits) and* deliberately drop the project-trust path (upsertProjectTrustLevel) — out- * of scope. `escapeRegex` is inlined (rather than pulling in unrelated- * modules); the rename itself goes through core/fs-atomic.ts.+ * of scope. The rename itself goes through core/fs-atomic.ts.*/import {copyFileSync,@@ -192,18 +191,11 @@ function isCodexEventLabel(value: string): value is CodexEventLabel {// Why: TOML 1.0 forbids BOMs but real-world editors (especially on Windows) sometimes// write them. A leading would break header regexes anchored at `^[ \t]*\[`, so// strip it once at the file boundary and let the rest of the parser stay simple.-function readTomlFile(configPath: string): string {+export function readTomlFile(configPath: string): string {const raw = readFileSync(configPath, 'utf-8')return raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw}-// Why: escape special regex characters so a path/key can be matched literally-// in a RegExp. Inlined to keep this module-// self-contained.-function escapeRegex(value: string): string {- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')-}-// Why: regex-edit ~/.codex/config.toml rather than parse + reserialize. The// file is hand-edited by users (and other tools) and a round-trip through// any TOML library would lose comments, key ordering, and inline-table@@ -237,6 +229,9 @@ export function upsertHookTrustEntriesInContent(for (const entry of entries) {updated = upsertTrustBlock(updated, computeTrustKey(entry), computeTrustedHash(entry))}+ // Never hand back a config Codex refuses to load: one WE changed must not carry a table defined+ // twice ("duplicate key" = codex will not start). Throws; every caller fails open.+ if (updated !== existing) assertTomlTablesUnique(updated)return updated}@@ -303,13 +298,90 @@ function upsertTrustBlock(content: string, key: string, hash: string): string {return deduped + content.slice(cursor)}-// Why: Codex emits the canonical form with the key double-quoted; we never-// share this slot with another tool, so we don't bother accepting bare-// dotted-key variants. The caller applies this only to complete physical lines-// outside TOML multi-line strings.-function buildHeaderLinePattern(key: string): RegExp {- const escapedKey = escapeRegex(escapeTomlString(key))- return new RegExp(`^[ \\t]*\\[hooks\\.state\\."${escapedKey}"\\][ \\t]*(?:#[^\\r\\n]*)?$`)+// Why: a header is matched by its DECODED key path, never by spelling. Codex (or another tool)+// may write the same table as `[hooks.state.'C:\…']` (literal string) where we write+// `[hooks.state."C:\\…"]` (basic string) — one key to TOML. Matching only our spelling made a+// repair APPEND a second table for that key, and Codex then refused to start ("duplicate key";+// measured on a Windows desktop, 2026-10-07). The caller applies this only to complete physical+// lines outside TOML multi-line strings.+function isTrustHeaderFor(line: string, key: string): boolean {+ const path = tableHeaderPath(line)+ return (+ path !== null &&+ path.length === 3 &&+ path[0] === 'hooks' &&+ path[1] === 'state' &&+ path[2] === key+ )+}++/**+ * The decoded key path of a `[table]` header line (bare, `"basic"` and `'literal'` segments), or+ * null for anything else — including an `[[array.of.tables]]` header, which may repeat.+ */+export function tableHeaderPath(line: string): string[] | null {+ const text = line.replace(/\r$/, '').trimStart()+ if (!text.startsWith('[') || text.startsWith('[[')) return null+ const path: string[] = []+ let i = 1+ const skipWs = (): void => {+ while (text[i] === ' ' || text[i] === '\t') i+++ }+ for (;;) {+ skipWs()+ const ch = text[i]+ if (ch === '"') {+ let j = i + 1+ while (j < text.length && text[j] !== '"') j += text[j] === '\\' ? 2 : 1+ if (j >= text.length) return null+ path.push(unescapeTomlString(text.slice(i + 1, j)))+ i = j + 1+ } else if (ch === "'") {+ const j = text.indexOf("'", i + 1)+ if (j === -1) return null+ path.push(text.slice(i + 1, j))+ i = j + 1+ } else {+ const m = /^[A-Za-z0-9_-]+/.exec(text.slice(i))+ if (!m) return null+ path.push(m[0])+ i += m[0].length+ }+ skipWs()+ if (text[i] === '.') {+ i+++ continue+ }+ if (text[i] !== ']') return null+ return /^\s*(#.*)?$/.test(text.slice(i + 1)) ? path : null+ }+}++/**+ * Throws when a `[table]` is defined twice (by decoded key path) — the way our line edits can+ * produce a config.toml Codex will not load. Not a full TOML validator (none is in our deps): it+ * guards the failure mode these edits can introduce, reading headers outside multi-line strings.+ */+export function assertTomlTablesUnique(content: string): void {+ const seen = new Set<string>()+ const dupes = new Set<string>()+ let multilineState: TomlMultilineState = { basic: false, literal: false }+ for (const raw of content.split('\n')) {+ const line = raw.replace(/\r$/, '')+ if (!isInsideTomlMultilineString(multilineState)) {+ const path = tableHeaderPath(line)+ if (path) {+ const id = JSON.stringify(path)+ if (seen.has(id)) dupes.add(path.join('.'))+ seen.add(id)+ continue+ }+ }+ multilineState = updateTomlMultilineState(multilineState, line)+ }+ if (dupes.size > 0) {+ throw new Error(`refusing to write config.toml: table defined twice: ${[...dupes].join(', ')}`)+ }}type TrustBlockRange = {@@ -319,7 +391,6 @@ type TrustBlockRange = {}function findTrustBlockRanges(content: string, key: string): TrustBlockRange[] {- const headerPattern = buildHeaderLinePattern(key)const ranges: TrustBlockRange[] = []let cursor = 0let multilineState: TomlMultilineState = { basic: false, literal: false }@@ -329,7 +400,7 @@ function findTrustBlockRanges(content: string, key: string): TrustBlockRange[] {const rawLine = content.slice(cursor, lineEnd)const line = rawLine.replace(/\r$/, '')const nextCursor = newlineIdx === -1 ? content.length : newlineIdx + 1- if (!isInsideTomlMultilineString(multilineState) && headerPattern.test(line)) {+ if (!isInsideTomlMultilineString(multilineState) && isTrustHeaderFor(line, key)) {const headerLineEnd = rawLine.endsWith('\r') ? lineEnd - 1 : lineEndconst after = content.slice(headerLineEnd)const nextHeaderRel = findNextTableHeader(after)@@ -588,7 +659,6 @@ export function readHookTrustEntries(configPath: string): Map<string, CodexHookT// `'''...'''` multi-line string isn't mistaken for a real header.// Why: accept an optional `# inline comment` after `]` — TOML permits it,// and rejecting hides a real entry, making getStatus misreport trustMissing.- const headerLineRegex = /^[ \t]*\[hooks\.state\."((?:[^"\\]|\\.)*)"\][ \t]*(?:#[^\r\n]*)?$/let cursor = 0let multilineState: TomlMultilineState = { basic: false, literal: false }while (cursor < content.length) {@@ -597,12 +667,14 @@ export function readHookTrustEntries(configPath: string): Map<string, CodexHookTconst rawLine = content.slice(cursor, lineEnd)const line = rawLine.replace(/\r$/, '')const nextCursor = newlineIdx === -1 ? content.length : newlineIdx + 1- const headerMatch = isInsideTomlMultilineString(multilineState)- ? null- : headerLineRegex.exec(line)- if (headerMatch) {- const escapedKey = headerMatch[1]- const key = unescapeTomlString(escapedKey)+ const headerPath = isInsideTomlMultilineString(multilineState) ? null : tableHeaderPath(line)+ if (+ headerPath &&+ headerPath.length === 3 &&+ headerPath[0] === 'hooks' &&+ headerPath[1] === 'state'+ ) {+ const key = headerPath[2]// Why: block ends at the next *real* header (multi-line aware).const after = content.slice(nextCursor)const nextHeaderRel = findNextTableHeader(after)@@ -646,6 +718,17 @@ function unescapeTomlString(escaped: string): string {result += '"'} else if (next === '\\') {result += '\\'+ } else if (next === 'u' || next === 'U') {+ // \uXXXX / \UXXXXXXXX: two spellings of one key must decode to the same key.+ const len = next === 'u' ? 4 : 8+ const hex = escaped.slice(i + 2, i + 2 + len)+ const cp = /^[0-9A-Fa-f]+$/.test(hex) && hex.length === len ? Number.parseInt(hex, 16) : -1+ if (cp >= 0 && cp <= 0x10ffff) {+ result += String.fromCodePoint(cp)+ i += 2 + len+ continue+ }+ result += `\\${next}`}// Why: unknown escapes round-trip — preserve the backslash so we don't// silently drop information.diff --git a/src/core/agents/hooks/codex.ensure.test.ts b/src/core/agents/hooks/codex.ensure.test.tsnew file mode 100644index 000000000..f03660b56--- /dev/null+++ b/src/core/agents/hooks/codex.ensure.test.ts@@ -0,0 +1,275 @@+// Launch-time repair of the codex hook install (ensureCodexHooksCurrent).+//+// Codex runs a hook only when ~/.codex/config.toml holds a matching `trusted_hash`, and reads it at+// session start. These pin that drift is repaired before a Codex pane spawns, that a CURRENT+// install is not rewritten (codex writes config.toml too), and that a broken install never throws+// into the spawn path.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'++let home = ''+vi.mock('os', async (orig) => {+ const actual = await orig<typeof import('os')>()+ return { ...actual, default: { ...actual, homedir: () => home }, homedir: () => home }+})++import {+ codexHookDrift,+ ensureCodexHooksCurrent,+ ensureCodexHooksForAccounts,+ installCodexHooks+} from './codex'+import { codexAccountHome } from '../../codex-accounts-core'+import { assertTomlTablesUnique } from './codex-trust'++const toml = (): string => path.join(home, '.codex', 'config.toml')+const hooks = (): string => path.join(home, '.codex', 'hooks.json')++beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-ensure-'))+ vi.spyOn(console, 'warn').mockImplementation(() => {})+})+afterEach(() => {+ vi.restoreAllMocks()+ fs.rmSync(home, { recursive: true, force: true })+})++describe('ensureCodexHooksCurrent', () => {+ it('installs on a home that has never had the hooks', () => {+ expect(codexHookDrift()).not.toEqual([])+ ensureCodexHooksCurrent()+ expect(codexHookDrift()).toEqual([])+ expect(fs.readFileSync(toml(), 'utf8')).toContain('trusted_hash')+ })++ it('does not rewrite a current install', () => {+ installCodexHooks()+ const past = new Date(Date.now() - 60_000)+ for (const f of [toml(), hooks()]) fs.utimesSync(f, past, past)+ const before = [toml(), hooks()].map((f) => fs.statSync(f).mtimeMs)+ ensureCodexHooksCurrent()+ expect([toml(), hooks()].map((f) => fs.statSync(f).mtimeMs)).toEqual(before)+ expect(console.warn).not.toHaveBeenCalled()+ })++ it('repairs config.toml that lost the trust entries (the incident shape)', () => {+ installCodexHooks()+ // What was found on the machine: the user's own config kept, nodeterm's trust blocks gone.+ fs.writeFileSync(toml(), 'model = "gpt-5"\n')+ expect(codexHookDrift()).toEqual(['config.toml trust (8/8)'])+ ensureCodexHooksCurrent()+ expect(codexHookDrift()).toEqual([])+ expect(fs.readFileSync(toml(), 'utf8')).toContain('model = "gpt-5"')+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining('config.toml trust'))+ })++ it('repairs a trust hash that no longer matches the hook', () => {+ installCodexHooks()+ const text = fs.readFileSync(toml(), 'utf8')+ fs.writeFileSync(toml(), text.replace(/trusted_hash = "sha256:[0-9a-f]+"/, 'trusted_hash = "sha256:00"'))+ expect(codexHookDrift()).toEqual(['config.toml trust (1/8)'])+ ensureCodexHooksCurrent()+ expect(codexHookDrift()).toEqual([])+ })++ it('repairs hooks.json that lost our entries, keeping the user hooks', () => {+ installCodexHooks()+ const user = { hooks: { Stop: [{ hooks: [{ type: 'command', command: 'echo mine' }] }] } }+ fs.writeFileSync(hooks(), JSON.stringify(user))+ expect(codexHookDrift()).toContain('hooks.json entries')+ ensureCodexHooksCurrent()+ expect(codexHookDrift()).toEqual([])+ expect(fs.readFileSync(hooks(), 'utf8')).toContain('echo mine')+ })++ it('never throws when the install cannot be read', () => {+ fs.mkdirSync(toml(), { recursive: true }) // config.toml is a DIRECTORY: every read fails+ expect(() => ensureCodexHooksCurrent()).not.toThrow()+ })+})++// The live failure on a Windows desktop (2026-10-07): config.toml held our trust tables spelled+// with LITERAL-string keys (`[hooks.state.'C:\…']`), the repair appended basic-string copies of the+// same keys, and Codex refused to start ("duplicate key").+describe('trust tables in another TOML spelling', () => {+ const headers = (): string[] =>+ fs.readFileSync(toml(), 'utf8').split('\n').filter((l) => l.startsWith('[hooks.state.'))+ /** Rewrite `which` of our basic-string headers as literal-string ones (the key is unchanged). */+ const toLiteral = (which: (i: number) => boolean): void => {+ let i = 0+ const text = fs.readFileSync(toml(), 'utf8').replace(/^\[hooks\.state\."(.*)"\]$/gm, (line, key: string) =>+ // A TOML basic string's escapes (`\\`, `\"`, `\uXXXX`) are JSON's: decode it in one pass.+ which(i++) ? `[hooks.state.'${JSON.parse(`"${key}"`) as string}']` : line+ )+ fs.writeFileSync(toml(), text)+ }+ const drift = (): void =>+ fs.writeFileSync(toml(), fs.readFileSync(toml(), 'utf8').replace(/sha256:[0-9a-f]+/g, 'sha256:00'))++ it('a current config spelled with literal keys is current — nothing is written', () => {+ installCodexHooks()+ toLiteral(() => true)+ const past = new Date(Date.now() - 60_000)+ fs.utimesSync(toml(), past, past)+ const before = fs.statSync(toml()).mtimeMs+ expect(codexHookDrift()).toEqual([])+ ensureCodexHooksCurrent()+ expect(fs.statSync(toml()).mtimeMs).toBe(before)+ })++ it.each([+ ['all literal', (): boolean => true],+ ['mixed', (i: number): boolean => i % 2 === 0]+ ])('drifted hashes under %s keys are repaired in place, one table per key', (_label, which) => {+ installCodexHooks()+ toLiteral(which)+ drift()+ expect(codexHookDrift()).toEqual(['config.toml trust (8/8)'])+ ensureCodexHooksCurrent()+ expect(codexHookDrift()).toEqual([])+ expect(headers()).toHaveLength(8)+ expect(() => assertTomlTablesUnique(fs.readFileSync(toml(), 'utf8'))).not.toThrow()+ })++ it('writes NOTHING when the result would still define a table twice, and does not throw', () => {+ fs.mkdirSync(path.dirname(toml()), { recursive: true })+ const broken = '[profiles.a]\nmodel = "x"\n\n[profiles.a]\nmodel = "y"\n'+ fs.writeFileSync(toml(), broken)+ expect(() => ensureCodexHooksCurrent()).not.toThrow()+ expect(fs.readFileSync(toml(), 'utf8')).toBe(broken)+ expect(fs.existsSync(hooks())).toBe(false) // hooks.json is not written ahead of a refused trust edit+ })+})+++// Managed Codex accounts: a pane bound to one runs with CODEX_HOME = that account's private home,+// and codex reads hooks.json + config.toml trust from THERE, not from ~/.codex.+describe('managed Codex account homes', () => {+ const USER_DATA = '/isolated/userdata'+ const sys = (): string => path.join(home, '.codex')+ const acct = (id: string): string => codexAccountHome(USER_DATA, id)+ const files = (h: string): string[] => [path.join(h, 'config.toml'), path.join(h, 'hooks.json')]+ const stamps = (h: string): number[] => files(h).map((f) => fs.statSync(f).mtimeMs)+ const age = (h: string): void => {+ const past = new Date(Date.now() - 60_000)+ for (const f of files(h)) fs.utimesSync(f, past, past)+ }++ beforeEach(() => {+ for (const id of ['acct-a', 'acct-b']) fs.mkdirSync(acct(id), { recursive: true })+ for (const h of [sys(), acct('acct-a'), acct('acct-b')]) {+ installCodexHooks(h)+ age(h)+ }+ })++ it('every home starts current, and checking them rewrites nothing', () => {+ const before = [sys(), acct('acct-a'), acct('acct-b')].map(stamps)+ for (const h of [sys(), acct('acct-a'), acct('acct-b')]) ensureCodexHooksCurrent(h)+ expect([sys(), acct('acct-a'), acct('acct-b')].map(stamps)).toEqual(before)+ expect(console.warn).not.toHaveBeenCalled()+ })++ it('drift in one account home is repaired in THAT home only', () => {+ fs.writeFileSync(path.join(acct('acct-a'), 'config.toml'), 'model = "o4"\n')+ const others = [sys(), acct('acct-b')].map(stamps)+ expect(codexHookDrift(acct('acct-a'))).toEqual(['config.toml trust (8/8)'])+ ensureCodexHooksCurrent(acct('acct-a'))+ expect(codexHookDrift(acct('acct-a'))).toEqual([])+ expect(fs.readFileSync(path.join(acct('acct-a'), 'config.toml'), 'utf8')).toContain('model = "o4"')+ expect([sys(), acct('acct-b')].map(stamps)).toEqual(others)+ expect(console.warn).toHaveBeenCalledWith(expect.stringContaining(acct('acct-a')))+ })++ it('a managed pane never touches ~/.codex, even when ~/.codex has never been installed', () => {+ fs.rmSync(sys(), { recursive: true, force: true })+ fs.writeFileSync(path.join(acct('acct-b'), 'hooks.json'), '{}')+ ensureCodexHooksCurrent(acct('acct-b'))+ expect(codexHookDrift(acct('acct-b'))).toEqual([])+ expect(fs.existsSync(sys())).toBe(false)+ })++ it('a missing account home is not created', () => {+ const ghost = acct('acct-ghost')+ ensureCodexHooksCurrent(ghost)+ expect(fs.existsSync(ghost)).toBe(false)+ })++ it('boot: repairs drifted account homes, skips unsafe ids and missing homes', () => {+ fs.writeFileSync(path.join(acct('acct-b'), 'config.toml'), '')+ const sysBefore = stamps(sys())+ const aBefore = stamps(acct('acct-a'))+ ensureCodexHooksForAccounts(USER_DATA, [+ { id: 'acct-a' },+ { id: 'acct-b' },+ { id: '../escape' },+ { id: 'acct-ghost' }+ ])+ expect(codexHookDrift(acct('acct-b'))).toEqual([])+ expect(stamps(acct('acct-a'))).toEqual(aBefore)+ expect(stamps(sys())).toEqual(sysBefore)+ expect(fs.existsSync(acct('acct-ghost'))).toBe(false)+ })++ // initializeAccountHome symlinks hooks.json + config.toml to ~/.codex. A repair must write+ // THROUGH the link, or the account silently stops sharing the system install.+ it('repairs through a linked account home without breaking the links', (ctx) => {+ const linked = acct('acct-linked')+ fs.mkdirSync(linked, { recursive: true })+ try {+ for (const f of ['config.toml', 'hooks.json']) {+ fs.symlinkSync(path.join(sys(), f), path.join(linked, f), 'file')+ }+ } catch {+ ctx.skip() // Windows without symlink privilege+ }+ fs.writeFileSync(path.join(sys(), 'config.toml'), '')+ expect(codexHookDrift(linked)).not.toEqual([])+ ensureCodexHooksCurrent(linked)+ expect(codexHookDrift(linked)).toEqual([])+ for (const f of ['config.toml', 'hooks.json']) {+ expect(fs.lstatSync(path.join(linked, f)).isSymbolicLink()).toBe(true)+ }+ expect(codexHookDrift(sys())).toEqual([])+ })+})++describe('PtyManager wiring', () => {+ it("checks the SESSION's CODEX_HOME, for local codex panes of a known account only", () => {+ const text = fs+ .readFileSync(path.join(__dirname, '..', '..', 'pty-manager.ts'), 'utf8')+ .replace(/\r\n/g, '\n')+ // Through the consent-gated lifecycle (issue #744), never the raw installer.+ const at = text.indexOf('currentIntegrationLifecycle()?.ensureCodexHooksForLaunch(codexScope.CODEX_HOME)')+ expect(at).toBeGreaterThan(0)+ expect(text.split('ensureCodexHooksForLaunch(').length - 1).toBe(1)+ expect(text).not.toContain('ensureCodexHooksCurrent')+ // Inside the LOCAL codex-scope block, which sets CODEX_HOME from the same codexScope.+ const scope = text.slice(text.lastIndexOf('if (needsCodexAccountScope(', at), at)+ expect(scope).toContain('!options.sshRemote')+ expect(scope).toContain('env.CODEX_HOME = codexScope.CODEX_HOME')+ expect(scope).toContain("capabilityAgentId(options.agentId as AgentId) === 'codex'")+ expect(scope).toContain('!options.accountId || this.isCodexAccount(options.accountId)')+ })++ // The repairs write the user's real ~/.codex, so only the consent lifecycle may call them: a+ // direct call from a shell or the spawn path re-installs hooks for a user who declined codex.+ it('only core/agent-integrations.ts reaches the codex repair functions', () => {+ const src = path.join(__dirname, '..', '..', '..')+ const callers: string[] = []+ const walk = (d: string): void => {+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {+ const p = path.join(d, e.name)+ if (e.isDirectory()) walk(p)+ else if (/\.tsx?$/.test(e.name) && !/\.test\.tsx?$/.test(e.name)) {+ const t = fs.readFileSync(p, 'utf8')+ if (/\bensureCodexHooks(Current|ForAccounts)\b/.test(t)) callers.push(path.relative(src, p).split(path.sep).join('/'))+ }+ }+ }+ walk(src)+ expect(callers.sort()).toEqual(['core/agent-integrations.ts', 'core/agents/hooks/codex.ts'])+ })+})diff --git a/src/core/agents/hooks/codex.test.ts b/src/core/agents/hooks/codex.test.tsindex b1f874b9c..3106d42e7 100644--- a/src/core/agents/hooks/codex.test.ts+++ b/src/core/agents/hooks/codex.test.ts@@ -164,7 +164,7 @@ describe('buildCodexHooksAndTrust', () => {})it('is idempotent — re-running on its own output does not duplicate the managed handler', () => {- const command = buildManagedCommand('/x/agent-hooks/codex.sh')+ const command = buildManagedCommand('/home/u/.nodeterm/agent-hooks/codex.sh')const first = buildCodexHooksAndTrust({}, command, '/x/hooks.json')!const second = buildCodexHooksAndTrust(first.config, command, '/x/hooks.json')!for (const ev of CODEX_EVENTS) {@@ -177,7 +177,7 @@ describe('buildCodexHooksAndTrust', () => {})it('preserves a user-authored hook at its original index before the managed handler', () => {- const command = buildManagedCommand('/x/agent-hooks/codex.sh')+ const command = buildManagedCommand('/home/u/.nodeterm/agent-hooks/codex.sh')const userDef = { hooks: [{ type: 'command' as const, command: 'echo mine' }] }const built = buildCodexHooksAndTrust({ hooks: { Stop: [userDef] } }, command, '/x/hooks.json')!const stop = built.config.hooks?.Stop ?? []@@ -186,7 +186,7 @@ describe('buildCodexHooksAndTrust', () => {})it('keeps two user definitions at their trust-key indices and trusts the managed tail', () => {- const command = buildManagedCommand('/x/agent-hooks/codex.sh')+ const command = buildManagedCommand('/home/u/.nodeterm/agent-hooks/codex.sh')const firstUserDef = { hooks: [{ type: 'command' as const, command: 'echo first' }] }const secondUserDef = { hooks: [{ type: 'command' as const, command: 'echo second' }] }const built = buildCodexHooksAndTrust(@@ -205,7 +205,7 @@ describe('buildCodexHooksAndTrust', () => {})it('sweeps a stale managed handler out of an event we no longer subscribe to', () => {- const command = buildManagedCommand('/x/agent-hooks/codex.sh')+ const command = buildManagedCommand('/home/u/.nodeterm/agent-hooks/codex.sh')// PreCompact is not in CODEX_EVENTS; a stale managed copy there must be removed.const stale = { hooks: [{ type: 'command' as const, command }] }const built = buildCodexHooksAndTrust({ hooks: { PreCompact: [stale] } }, command, '/x/hooks.json')!@@ -271,7 +271,7 @@ describe('buildCodexHooksAndTrust', () => {// BARE quoted wrapper path — the entry PowerShell reads as a string literal and never runs. It// has to be REPLACED, not appended beside: were the matcher to miss it, the dead entry would// survive every launch while still being reported `Completed`. The matcher keys off the- // `agent-hooks/codex-hook.cmd` tail, which both spellings carry, so the strip catches it.+ // `.nodeterm/agent-hooks/codex-hook.cmd` path, which both spellings carry, so the strip catches it.it('replaces the pre-#685 bare-quoted wrapper entry with the cmd /c one', () => {const stale = {hooks: [@@ -303,6 +303,34 @@ describe('buildCodexHooksAndTrust', () => {expect(built.config.hooks!.Stop).toEqual([{ hooks: [{ type: 'command', command }] }])})+ // Another tool with the same layout is not us. Measured on a Windows desktop: another tool's own+ // `~/.other/agent-hooks/codex-hook.cmd` entry was stripped by every repair because the matcher+ // keyed off the bare `agent-hooks/<leaf>` tail.+ it("keeps another tool's agent-hooks entry with the same leaf name", () => {+ const other = { hooks: [{ type: 'command' as const, command: 'C:/Users/u/.other/agent-hooks/codex-hook.cmd' }] }+ const otherPosix = { hooks: [{ type: 'command' as const, command: "sh '/home/u/.other/agent-hooks/codex.sh'" }] }+ const command = buildManagedCommand('C:\\Users\\u\\.nodeterm\\agent-hooks\\codex.sh', 'win32')+ const built = buildCodexHooksAndTrust(+ { hooks: { Stop: [other, otherPosix] } },+ command,+ 'C:\\Users\\u\\.codex\\hooks.json'+ )!+ expect(built.config.hooks!.Stop).toEqual([other, otherPosix, { hooks: [{ type: 'command', command }] }])+ expect(built.trustEntries.find((e) => e.eventLabel === 'stop')).toMatchObject({ groupIndex: 2 })+ })++ // The directories we HAVE written to are still ours, so a stale entry from them is replaced.+ it.each([+ '/home/u/.nodeterm/agent-hooks/codex.sh',+ "C:\\Users\\u\\AppData\\Roaming\\node-terminal\\agent-hooks\\codex.sh",+ '/root/.nodeterm-server/agent-hooks/codex.sh'+ ])('still sweeps a stale entry of ours at %s', (script) => {+ const stale = { hooks: [{ type: 'command' as const, command: `sh '${script}'` }] }+ const command = buildManagedCommand('/home/u/.nodeterm/agent-hooks/codex.sh', 'linux')+ const built = buildCodexHooksAndTrust({ hooks: { Stop: [stale] } }, command, '/h/hooks.json')!+ expect(built.config.hooks!.Stop).toEqual([{ hooks: [{ type: 'command', command }] }])+ })+it('subscribes the subagent pair (spawn_agent fan-out) with snake_case labels', () => {expect(CODEX_EVENTS).toContain('SubagentStart')expect(CODEX_EVENTS).toContain('SubagentStop')diff --git a/src/core/agents/hooks/codex.ts b/src/core/agents/hooks/codex.tsindex 7bb133b38..4b93d91a3 100644--- a/src/core/agents/hooks/codex.ts+++ b/src/core/agents/hooks/codex.ts@@ -19,6 +19,8 @@ import path from 'path'import {existsSync,readFileSync,+ realpathSync,+ statSync,writeFileSync,mkdirSync,chmodSync,@@ -26,17 +28,22 @@ import {} from 'fs'import { randomUUID } from 'crypto'import { renameAtomicSync } from '../../fs-atomic'+import { codexAccountHome } from '../../codex-accounts-core'+import { isSafeAccountId } from '../../../shared/codex-account'import { buildManagedScript } from './managed-script'import { normalizeHookCommand } from './install-helper'import { buildCodexWindowsWrapper, CODEX_WINDOWS_WRAPPER_FILE } from './codex-windows-wrapper'import { buildWindowsHookInvocation, defaultWindowsCmdExe } from './windows-hook-wrapper'import {computeTrustedHash,+ computeTrustKey,getCodexCanonicalTrustPath,parseTrustKey,readHookTrustEntries,+ readTomlFile,removeHookTrustEntries,- upsertHookTrustEntries,+ upsertHookTrustEntriesInContent,+ writeConfigAtomically,type CodexEventLabel,type CodexTrustEntry} from './codex-trust'@@ -80,17 +87,32 @@ type HookCommandConfig = { type: 'command'; command: string; [k: string]: unknowtype HookDefinition = { hooks?: HookCommandConfig[]; [k: string]: unknown }export type HooksConfig = { hooks?: Record<string, HookDefinition[]>; [k: string]: unknown }-function codexHome(): string {+function defaultCodexHome(): string {// Default CODEX_HOME. We intentionally write into the user's REAL ~/.codex.return path.join(homedir(), '.codex')}-function hooksJsonPath(): string {- return path.join(codexHome(), 'hooks.json')+// Every function below takes the CODEX_HOME it acts on: the system one (default) or a managed+// account's private home, which codex reads instead of ~/.codex for that account's sessions.+function hooksJsonPath(home: string): string {+ return path.join(home, 'hooks.json')}-function configTomlPath(): string {- return path.join(codexHome(), 'config.toml')+function configTomlPath(home: string): string {+ return path.join(home, 'config.toml')+}++/**+ * Where a write to `file` must land. A managed account home SYMLINKS its hooks.json and+ * config.toml to the system ones (`initializeAccountHome`); a temp+rename onto the link itself+ * would replace it with a private copy that no later system install reaches. Write through it.+ */+function writeTarget(file: string): string {+ try {+ return realpathSync(file)+ } catch {+ return file+ }}/** Stable, machine-wide — the same rule as install-helper's `scriptPathFor` (see its note). */@@ -114,13 +136,29 @@ function isManagedCommand(command: string | undefined): boolean {// logic here would keep it and append a second one, which is #558 all over again. Matching both is// also what REPAIRS a Windows hooks.json that already carries the unrunnable POSIX command: it is// stripped before the fresh one is pushed, so the next app launch heals the file.+ //+ // ANCHORED to our own hook directories, never a bare `agent-hooks/<leaf>` tail. Other tools ship+ // the same layout under the same leaf names (measured: another tool's+ // `~/.other/agent-hooks/codex-hook.cmd` on a Windows desktop) and the tail match treated their entry as ours, stripping it from+ // hooks.json on every repair. The anchors are the directories we have ever written to:+ // `~/.nodeterm` (current, local and SSH), the desktop's old userData dir (`node-terminal`) and the+ // Server Edition's default data dir (`.nodeterm-server`). A script left in a Server Edition run with+ // a custom `--data-dir` is no longer swept; that entry is inert once its directory is gone.+ // DECIDED (issue #744 decline cleanup): `removeCodexHooks` — what a DECLINED codex runs — shares+ // this matcher, so it does not remove such a legacy entry either. That is deliberate: a decline+ // must remove exactly what we wrote, and a bare-tail match cannot tell our legacy entry from+ // another tool's live one. Removing someone else's hook is the worse error than leaving an inert+ // command of ours behind; the user can delete it from hooks.json by hand.const c = normalizeHookCommand(command)- return (- c.includes(`agent-hooks/${SCRIPT_FILE_NAME}`) ||- c.includes(`agent-hooks/${CODEX_WINDOWS_WRAPPER_FILE}`)+ return OWN_HOOK_DIRS.some(+ (dir) =>+ c.includes(`${dir}/agent-hooks/${SCRIPT_FILE_NAME}`) ||+ c.includes(`${dir}/agent-hooks/${CODEX_WINDOWS_WRAPPER_FILE}`))}+const OWN_HOOK_DIRS = ['/.nodeterm', '/node-terminal', '/.nodeterm-server'] as const+function definitionHasManagedCommand(def: HookDefinition): boolean {return Array.isArray(def.hooks) && def.hooks.some((h) => isManagedCommand(h.command))}@@ -315,7 +353,8 @@ function readHooksJson(file: string): HooksConfig | null {}// Why: temp+rename so a crash mid-write leaves the original hooks.json intact.-function writeHooksJson(file: string, config: HooksConfig): void {+function writeHooksJson(link: string, config: HooksConfig): void {+ const file = writeTarget(link)const dir = path.dirname(file)mkdirSync(dir, { recursive: true })const tmp = path.join(dir, `.${Date.now()}-${randomUUID()}.tmp`)@@ -385,7 +424,7 @@ function writeWindowsWrapper(script: string): void {}}-export function installCodexHooks(): void {+export function installCodexHooks(home: string = defaultCodexHome()): void {const script = scriptPath()try {writeManagedScript(script)@@ -398,7 +437,7 @@ export function installCodexHooks(): void {}const command = buildManagedCommand(script)- const hooksFile = hooksJsonPath()+ const hooksFile = hooksJsonPath(home)const config = readHooksJson(hooksFile)if (!config) {console.warn('[agent-hooks] codex install: could not parse hooks.json; skipping')@@ -414,19 +453,108 @@ export function installCodexHooks(): void {// realpath's it to match how codex keys it).const built = buildCodexHooksAndTrust(config, command, hooksFile)if (!built) return+ // Compute the config.toml edit BEFORE writing anything: it throws rather than produce a file+ // Codex refuses to load (a table defined twice), and then nothing at all is written.+ const tomlFile = writeTarget(configTomlPath(home))+ const currentToml = existsSync(tomlFile) ? readTomlFile(tomlFile) : ''+ const nextToml = upsertHookTrustEntriesInContent(currentToml, built.trustEntries)writeHooksJson(hooksFile, built.config)// Why: write trust LAST so a half-write can't leave a hash pointing at a// hook that doesn't exist. upsert does a line-level merge that preserves// all other config.toml content.- upsertHookTrustEntries(configTomlPath(), built.trustEntries)+ if (nextToml !== currentToml) writeConfigAtomically(tomlFile, nextToml)} catch (e) {console.warn('[agent-hooks] codex install failed', e)}}+/**+ * What is missing from this machine's codex hook install, read-only. Empty = current.+ *+ * Codex runs a hook only when config.toml holds a `trusted_hash` for it, and reads both files at+ * SESSION START. Boot used to be the only repair, so anything that rewrote config.toml while the+ * app ran (codex's own /hooks flow racing us, another tool, a test run on the real home) left every+ * Codex session started afterwards with no status hooks at all — measured on a Windows desktop:+ * every agent message to those nodes queued as `targetStatusStale` and expired.+ */+export function codexHookDrift(home: string = defaultCodexHome()): string[] {+ const drift: string[] = []+ const script = scriptPath()+ try {+ if (readFileSync(script, 'utf8') !== buildManagedScript('codex')) drift.push('hook script')+ } catch {+ drift.push('hook script')+ }+ if (process.platform === 'win32') {+ try {+ const wrapper = path.join(path.dirname(script), CODEX_WINDOWS_WRAPPER_FILE)+ if (readFileSync(wrapper, 'utf8') !== buildCodexWindowsWrapper()) drift.push('windows wrapper')+ } catch {+ drift.push('windows wrapper')+ }+ }+ const hooksFile = hooksJsonPath(home)+ const config = readHooksJson(hooksFile)+ // Unparseable hooks.json: the installer would leave it alone too, so it is not drift we can fix.+ const built = config ? buildCodexHooksAndTrust(config, buildManagedCommand(script), hooksFile) : null+ if (!built) return drift+ if (!existsSync(hooksFile) || JSON.stringify(built.config) !== JSON.stringify(config)) {+ drift.push('hooks.json entries')+ }+ const trust = readHookTrustEntries(configTomlPath(home))+ const missing = built.trustEntries.filter(+ (e) => trust.get(computeTrustKey(e))?.trustedHash !== computeTrustedHash(e)+ )+ if (missing.length) drift.push(`config.toml trust (${missing.length}/${built.trustEntries.length})`)+ return drift+}++/**+ * Called right before a LOCAL Codex session spawns, with the CODEX_HOME that session will run+ * under: re-install only when something drifted, so a current install costs a few small reads and+ * config.toml (which codex also writes) is never rewritten for nothing. A home that does not exist+ * is left alone (a managed account's home is created by its own login flow, never by this). Never+ * throws — a launch must not depend on it.+ */+export function ensureCodexHooksCurrent(home: string = defaultCodexHome()): void {+ try {+ if (home !== defaultCodexHome() && !statSync(home).isDirectory()) return+ const drift = codexHookDrift(home)+ if (!drift.length) return+ console.warn(`[agent-hooks] codex hook install in ${home} drifted (${drift.join(', ')}); repairing`)+ installCodexHooks(home)+ } catch (e) {+ console.warn(`[agent-hooks] codex hook check failed for ${home}`, e)+ }+}++/**+ * Boot install for every LOCAL managed Codex account home. Those homes symlink hooks.json and+ * config.toml to ~/.codex, so the system install usually covers them — but only while the links+ * survive: a link never made (the system file was absent when the account was created) or replaced+ * by a real file leaves the account's sessions without trusted hooks. Drift-gated like the launch+ * check, so a linked home costs reads only. An unsafe id or a missing home is skipped.+ */+export function ensureCodexHooksForAccounts(+ userDataDir: string,+ accounts: ReadonlyArray<{ id: string }>+): void {+ for (const { id } of accounts) {+ if (!isSafeAccountId(id)) continue+ let home: string+ try {+ home = codexAccountHome(userDataDir, id)+ if (!statSync(home).isDirectory()) continue+ } catch {+ continue+ }+ ensureCodexHooksCurrent(home)+ }+}+export function removeCodexHooks(): void {- const hooksFile = hooksJsonPath()+ const hooksFile = hooksJsonPath(defaultCodexHome())const command = buildManagedCommand(scriptPath())try {@@ -462,7 +590,7 @@ export function removeCodexHooks(): void {// command — a sourcePath-only filter would wipe the user's manually-approved// entries that happen to share the path. Best-effort.try {- const tomlPath = configTomlPath()+ const tomlPath = writeTarget(configTomlPath(defaultCodexHome()))const existing = readHookTrustEntries(tomlPath)const canonicalSource = getCodexCanonicalTrustPath(hooksFile)const managedEventLabels = new Set<CodexEventLabel>(diff --git a/src/core/agents/hooks/index.test.ts b/src/core/agents/hooks/index.test.tsindex 617322910..713182ae9 100644--- a/src/core/agents/hooks/index.test.ts+++ b/src/core/agents/hooks/index.test.ts@@ -25,11 +25,18 @@ vi.mock('../../exec-path', async (orig) => ({resolveShellEnvVar: async () => shellAnswer}))-let home: string+// A MODULE mock, not `vi.spyOn(os, 'homedir')`: the installers this reaches (codex.ts, grok, …)+// `import { homedir } from 'os'`, a binding the spy never touches. With the spy, this file rewrote+// the developer's real ~/.codex/config.toml and hooks.json — and every other agent's hook file —+// on every run. The run-wide HOME sandbox (src/core/test-home.ts) is the floor under this.+let home = ''+vi.mock('os', async (orig) => {+ const actual = await orig<typeof import('os')>()+ return { ...actual, default: { ...actual, homedir: () => home }, homedir: () => home }+})beforeEach(() => {home = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-home-probe-'))- vi.spyOn(os, 'homedir').mockReturnValue(home)initPlatform(fakePlatform({ userDataDir: home }))_resetGrokHomeProbeForTests()})diff --git a/src/core/codex-accounts-core.test.ts b/src/core/codex-accounts-core.test.tsindex 6caaf5d84..da257f18e 100644--- a/src/core/codex-accounts-core.test.ts+++ b/src/core/codex-accounts-core.test.ts@@ -12,7 +12,7 @@ import {} from 'fs'import os from 'os'import path from 'path'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import {ACCOUNT_ID_RE,assertCodexAccountId,@@ -124,8 +124,15 @@ describe('managed Codex account paths', () => {it('keeps the managed daemon socket below macOS SUN_LEN', () => {const userData = '/Users/example/Library/Application Support/node-terminal'+ // The short root hangs off the HOME, so the claim is about a real macOS home — not the test+ // run's sandboxed one (test/setup/home-sandbox.ts), which sits much deeper in the temp dir.+ const home = vi.spyOn(os, 'homedir').mockReturnValue('/Users/example')const accountId = 'be28d3d4-c18c-430c-a257-ae550d3dd7ed'- expect(Buffer.byteLength(codexSocketForAccount(userData, accountId))).toBeLessThan(104)+ try {+ expect(Buffer.byteLength(codexSocketForAccount(userData, accountId))).toBeLessThan(104)+ } finally {+ home.mockRestore()+ }})})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 24eac804f..cd38d44ed 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -24,6 +24,7 @@ import {import { bundledTmuxPath, findCommand, findFixedTmux, tmuxInstall } from './tmux-hint'import { hookServer, PERM_WAIT_SECS_DEFAULT } from './agents/hook-server'import { findAgy, pathWithAgyDir } from './agents/hooks/antigravity'+import { currentIntegrationLifecycle } from './agent-integrations'import {probeSaysAbsent,remoteHookEnvArgs,@@ -4319,6 +4320,22 @@ export class PtyManager {env.CODEX_HOME = codexScope.CODEX_HOMEenv.NODETERM_CODEX_ACCOUNT_ID = codexScope.NODETERM_CODEX_ACCOUNT_IDfor (const k of CODEX_AUTH_ENV_STRIP) delete env[k]+ // Codex reads its hooks and their config.toml trust at SESSION START, from THIS session's+ // CODEX_HOME (a managed account's private home, or the system one). Boot was the only place+ // we installed them, so a config.toml rewritten while the app ran left every Codex session+ // started afterwards with no status hooks (badge dark, messages expiring targetStatusStale).+ // Re-check that home before the pane spawns; repairs only on drift and never throws. An id+ // that is not a known Codex account gets no repair (and never a fallback to ~/.codex). SSH+ // sessions run the host's codex, whose files RemoteHooks owns. Routed through the+ // agent-integration lifecycle (issue #744): only an ENABLED codex is repaired, and with no+ // lifecycle registered nothing is written.+ if (+ options.agentId &&+ capabilityAgentId(options.agentId as AgentId) === 'codex' &&+ (!options.accountId || this.isCodexAccount(options.accountId))+ ) {+ currentIntegrationLifecycle()?.ensureCodexHooksForLaunch(codexScope.CODEX_HOME)+ }}// Shared model gateway: resolve through the node's BASE harness in one shared mapping, thendiff --git a/src/core/test-home.guard.test.ts b/src/core/test-home.guard.test.tsnew file mode 100644index 000000000..ac302d5fc--- /dev/null+++ b/src/core/test-home.guard.test.ts@@ -0,0 +1,53 @@+// Guard for the run-wide HOME sandbox (src/core/test-home.ts): a hook installer run anywhere in the+// suite must land in the sandbox, never in the developer's real home.+//+// The real home is read from the account database (`os.userInfo().homedir` — getpwuid on POSIX,+// the user profile on Windows), which ignores HOME/USERPROFILE. That is the directory a broken+// sandbox would let `installCodexHooks()` write into, and it is what this test watches.+import { execFileSync } from 'child_process'+import fs from 'fs'+import os, { homedir } from 'os'+import path from 'path'+import { describe, expect, it } from 'vitest'+import { HOME_SANDBOX_ENV } from './test-home'+import { installCodexHooks } from './agents/hooks/codex'++const sandbox = process.env[HOME_SANDBOX_ENV] as string++function stamp(file: string): string {+ try {+ const st = fs.statSync(file)+ return `${st.size}:${st.mtimeMs}`+ } catch {+ return 'absent'+ }+}++describe('HOME sandbox', () => {+ it('os.homedir() resolves inside the sandbox — through the namespace AND a named import', () => {+ expect(sandbox).toBeTruthy()+ expect(os.homedir()).toBe(sandbox)+ // codex.ts and friends use the named import; a `vi.spyOn(os, 'homedir')` never reached it.+ expect(homedir()).toBe(sandbox)+ expect(path.resolve(os.userInfo().homedir)).not.toBe(path.resolve(sandbox))+ })++ it('a child process inherits it', () => {+ const out = execFileSync(process.execPath, ['-e', "process.stdout.write(require('os').homedir())"], {+ encoding: 'utf8'+ })+ expect(out).toBe(sandbox)+ })++ it('the real codex installer writes the sandbox and leaves the real ~/.codex untouched', () => {+ const realCodex = path.join(os.userInfo().homedir, '.codex')+ const before = ['config.toml', 'hooks.json'].map((f) => stamp(path.join(realCodex, f)))+ installCodexHooks()+ expect(fs.existsSync(path.join(sandbox, '.codex', 'hooks.json'))).toBe(true)+ expect(fs.readFileSync(path.join(sandbox, '.codex', 'config.toml'), 'utf8')).toContain(+ 'trusted_hash'+ )+ const after = ['config.toml', 'hooks.json'].map((f) => stamp(path.join(realCodex, f)))+ expect(after).toEqual(before)+ })+})diff --git a/src/core/test-home.ts b/src/core/test-home.tsnew file mode 100644index 000000000..5fe594c15--- /dev/null+++ b/src/core/test-home.ts@@ -0,0 +1,55 @@+// TEST-ONLY — the run-wide HOME sandbox. Nothing under src/ may import this outside a test.+//+// The hook installers write the user's REAL agent config: `~/.codex/hooks.json` and+// `~/.codex/config.toml` (whose `[hooks.state."…"]` trust entries Codex needs before it runs a+// hook), `~/.claude/settings.json`, `~/.gemini/settings.json`, grok's and copilot's hook files.+// They resolve that home through `import { homedir } from 'os'` — a binding a+// `vi.spyOn(os, 'homedir')` in a test does NOT reach. Measured on a Windows dev box: running+// `src/core/agents/hooks/index.test.ts` alone, which "isolated" home with exactly that spy,+// rewrote the developer's real `~/.codex/config.toml` and `hooks.json`. Parallel runs across+// worktrees then raced each other — and the user's running Codex — on those files, and a Codex+// session started in that window loaded a config with no trust entries for nodeterm's hooks: its+// hooks never fired, and every agent message to it expired as `targetStatusStale`.+//+// So the whole run gets a private home, the same shape as the tmux and temp sandboxes: `setup`+// (globalSetup, main process) creates it and points HOME/USERPROFILE at it; the worker setup file+// re-asserts it and refuses to run without it; `teardown` removes it. `os.homedir()` reads HOME on+// POSIX and USERPROFILE on Windows on every call, so every installer — whatever import style —+// lands inside the sandbox, and so does every child process a test spawns with the inherited env.+//+// The agents' own relocation variables are cleared too: with `CODEX_HOME` or `CLAUDE_CONFIG_DIR`+// exported in the developer's shell, a sandboxed HOME would still send those writes to the real+// directory they name.+import fs from 'fs'+import path from 'path'++export const HOME_SANDBOX_ENV = 'NODETERM_TEST_HOME'++/** Variables that relocate an agent's (or the platform's) config dir away from HOME. */+export const HOME_OVERRIDE_ENV = [+ 'CODEX_HOME',+ 'CLAUDE_CONFIG_DIR',+ 'GEMINI_CLI_HOME',+ 'GROK_HOME',+ 'COPILOT_HOME',+ 'KIMI_CODE_HOME',+ 'XDG_CONFIG_HOME',+ 'XDG_DATA_HOME',+ 'XDG_STATE_HOME',+ 'XDG_CACHE_HOME'+] as const++/** Point this process (and every child it spawns) at `dir` as its home. */+export function enterHomeSandbox(dir: string): void {+ process.env[HOME_SANDBOX_ENV] = dir+ process.env.HOME = dir+ process.env.USERPROFILE = dir+ for (const k of HOME_OVERRIDE_ENV) delete process.env[k]+ if (process.platform === 'win32') {+ // The vendor-location lookups (agy, the staged session host) read these, not USERPROFILE.+ process.env.APPDATA = path.join(dir, 'AppData', 'Roaming')+ process.env.LOCALAPPDATA = path.join(dir, 'AppData', 'Local')+ fs.mkdirSync(process.env.APPDATA, { recursive: true })+ fs.mkdirSync(process.env.LOCALAPPDATA, { recursive: true })+ }+}diff --git a/test/setup/agent-env.ts b/test/setup/agent-env.tsindex df550f9b2..5e1edf197 100644--- a/test/setup/agent-env.ts+++ b/test/setup/agent-env.ts@@ -6,13 +6,14 @@// account dir (measured: a server boot test overwrote the session's `get-linked-context` skill).// CI never sets these; stripping them here makes every machine behave like CI. A test that needs// one sets it itself.+//+// The relocation list has ONE home — `HOME_OVERRIDE_ENV` in `src/core/test-home.ts`, which the+// HOME sandbox (`home-sandbox.ts` / `home-worker-env.ts`) clears too. Only the nodeterm session+// variables, which relocate nothing, are added here.+import { HOME_OVERRIDE_ENV } from '../../src/core/test-home'+for (const k of [- 'CLAUDE_CONFIG_DIR',- 'CODEX_HOME',- 'GROK_HOME',- 'COPILOT_HOME',- 'GEMINI_CLI_HOME',- 'XDG_CONFIG_HOME',+ ...HOME_OVERRIDE_ENV,'NODETERM_NODE_ID','NODETERM_HOOK_ENDPOINT','NODETERM_CANVAS_CONTROL'diff --git a/test/setup/home-sandbox.ts b/test/setup/home-sandbox.tsnew file mode 100644index 000000000..22c38d524--- /dev/null+++ b/test/setup/home-sandbox.ts@@ -0,0 +1,40 @@+// TEST-ONLY — the run-wide HOME sandbox. See `src/core/test-home.ts` for why.+//+// Created in the REAL temp dir (registered before `tmp-sandbox.ts`, so it is not counted as a leak+// there) and removed at teardown. The environment it replaces is restored, so a vitest process that+// keeps running (watch mode) does not carry a deleted home into its next run.+import fs from 'fs'+import os from 'os'+import path from 'path'+import { HOME_OVERRIDE_ENV, HOME_SANDBOX_ENV, enterHomeSandbox } from '../../src/core/test-home'++const SAVED_KEYS = [+ HOME_SANDBOX_ENV,+ 'HOME',+ 'USERPROFILE',+ 'APPDATA',+ 'LOCALAPPDATA',+ ...HOME_OVERRIDE_ENV+]+let dir: string | null = null+let saved: Record<string, string | undefined> = {}++export async function setup(): Promise<void> {+ saved = Object.fromEntries(SAVED_KEYS.map((k) => [k, process.env[k]]))+ dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ntvh-')))+ enterHomeSandbox(dir)+}++export async function teardown(): Promise<void> {+ if (!dir) return+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k]+ else process.env[k] = v+ }+ try {+ fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5 })+ } catch {+ /* never fail teardown: the other sandboxes' teardowns must still run */+ }+ dir = null+}diff --git a/test/setup/home-worker-env.ts b/test/setup/home-worker-env.tsnew file mode 100644index 000000000..69be19db7--- /dev/null+++ b/test/setup/home-worker-env.ts@@ -0,0 +1,18 @@+// TEST-ONLY — the worker half of the HOME sandbox; see `src/core/test-home.ts`.+//+// Re-asserts the sandbox inside each worker (env inheritance from `globalSetup` is vitest's+// implementation detail, not its contract — same reasoning as `tmux-worker-env.ts`) and refuses+// to run without it: a silent fallback would put every hook installer back on the developer's+// real `~/.codex`, `~/.claude` and `~/.gemini`.+import fs from 'fs'+import { HOME_SANDBOX_ENV, enterHomeSandbox } from '../../src/core/test-home'++const sandbox = process.env[HOME_SANDBOX_ENV]+if (!sandbox || !fs.existsSync(sandbox)) {+ throw new Error(+ `home sandbox missing (${HOME_SANDBOX_ENV}=${sandbox ?? 'unset'}). vitest.config.ts must keep ` ++ 'test/setup/home-sandbox.ts in `globalSetup` — without it the hook installers rewrite the ' ++ "real ~/.codex/config.toml and drop Codex's trust in nodeterm's hooks."+ )+}+enterHomeSandbox(sandbox)diff --git a/vitest.config.ts b/vitest.config.tsindex 259ea5c27..5a9dc0caf 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -37,12 +37,18 @@ export default defineConfig({// The temp sandbox does the same for `os.tmpdir()`: the whole run writes its scratch dirs into// one private directory, and teardown FAILS the run naming any test dir left in it (then removes// it). The suite used to strand ~1,500 dirs in /tmp per run. See src/core/test-tmp.ts.+ //+ // The HOME sandbox points HOME/USERPROFILE at a private dir for the whole run, so no hook+ // installer a test reaches can rewrite the developer's real ~/.codex/config.toml (which made+ // Codex drop its trust in nodeterm's hooks). Created before the temp sandbox, so it is never+ // counted as a leak there. See src/core/test-home.ts.globalSetup: ['test/setup/fake-platform-root.ts','test/setup/tmux-sandbox.ts',+ 'test/setup/home-sandbox.ts','test/setup/tmp-sandbox.ts'],- setupFiles: ['test/setup/tmux-worker-env.ts', 'test/setup/agent-env.ts', 'test/setup/tmp-worker-env.ts', 'test/setup/jsdom-storage.ts'],+ setupFiles: ['test/setup/tmux-worker-env.ts', 'test/setup/home-worker-env.ts', 'test/setup/agent-env.ts', 'test/setup/tmp-worker-env.ts', 'test/setup/jsdom-storage.ts'],// Issue #160: with the default (one worker per core), a 10-core Mac runs ~10 fs-heavy suites// at once and transient fd exhaustion (EMFILE) turns into silent test flakiness — probes like// `fs.existsSync` swallow the error and answer false, so whole files fail in ways that never