Skip to content

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.

fix(codex): identify shared-daemon hooks by their payload thread (#1232)

eneskircaa1affe31840f
diff --git a/CLAUDE.md b/CLAUDE.md
index 2f698594b..1395e5a9a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -962,8 +962,10 @@ Lifecycle, by intent:
plain terminal, or by an agent through `open-terminal --cmd codex` / `write` — carries that
node's `NODETERM_NODE_ID` and, on 0.157+, can still start the account's daemon with it; managed
threads' tool shells then keep the leaked id (the prelude skips a set one). Changing the prelude
- to prefer the thread record over a set id was rejected: a bind-refused fallback pane legitimately
- runs a thread another node's record names. (2) A launch-command override or custom `launchCmd`
+ to prefer the thread record over a set id was rejected FOR TOOL SHELLS: a bind-refused fallback
+ pane legitimately runs a thread another node's record names. HOOKS are different (#1175, below):
+ their payload names the event's own thread, so the codex hook script lets that thread's record
+ outrank an inherited id unless the pane is marked `NODETERM_CODEX_PLAIN=1`. (2) A launch-command override or custom `launchCmd`
that runs a DIFFERENT codex than PATH's (`npx @openai/[email protected]`) is given the flag from
PATH's probe and dies on it; the fix there is the user's (drop the pin or add the flag to their
own command) — we cannot probe an arbitrary command line. (3) The Windows argv planner
@@ -3418,6 +3420,23 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
layout by construction on all three surfaces) and then the well-known data dirs; it is monotone
— advertised dir first, keyed by node-id filename in every candidate, and a foreign instance's
dir yields a foreign `kid` = `legacy` = exactly what presenting nothing already gave.
+ - **A Codex HOOK under the shared app-server is identified by its PAYLOAD, not its env** (#1150,
+ #1175). MEASURED on codex-cli 0.162.0 (private CODEX_HOME + tmux socket, a hook dumping env and
+ stdin): a hook process is the DAEMON's child, carries the daemon's env and NEVER
+ `CODEX_THREAD_ID` (only tool shells get that), and its stdin starts `{"session_id":"<thread>"`.
+ So a scrubbed daemon ran every managed node's hooks with no node id (silent exit, #1150), and a
+ daemon a plain `codex` pane started ran them under THAT pane's long-gone `NODETERM_NODE_ID`
+ (#1175). The codex managed script (local only — remote scripts carry no prelude) now reads stdin
+ FIRST, takes the LEADING `session_id` with builtins (anchored, so a nested one in tool input
+ never matches), and hands it to the prelude (`hookPayloadThread`), where a record for that thread
+ wins over an INHERITED node id and the stale endpoint vars are unset before the record's
+ endpoint file is sourced. The one exception is a pane our launcher ran in-process
+ (`nt_exec_plain` exports `NODETERM_CODEX_PLAIN=1`; never on a `--remote` exit): its env is its
+ own and stands. Tool shells and both shims keep the old rule (a set id is never touched). The
+ event is still verified against the bound node's 0600 token, so a forged payload buys nothing a
+ same-user process could not already do. Residuals: a node launched with a bare `codex` (shared
+ identity off) whose thread has ANOTHER node's record reports as that node; and a codex typed
+ inside a marked plain pane's tool shell starts a daemon that carries the marker.
- **Every LOCAL generated sh client recovers shared-Codex identity before its env gate.** A tool
shell forked by the account-scoped app-server carries `CODEX_THREAD_ID`, not the pane's
`NODETERM_*`. Managed hooks, local `nodeterm.sh`, and local `context.sh` therefore prepend
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6c027d736..4debbb264 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -984,6 +984,13 @@ record path into a remote host is both wrong and a local-layout leak. A guard te
(`remote-shim-neutrality.guard.test.ts`), because the leak is silent — the remote shim keeps
working, and nothing goes red.
+**A Codex hook is identified by its payload, not its env.** Hooks the shared app-server runs are
+the daemon's children: they carry the daemon's env (often a stale pane's `NODETERM_NODE_ID`) and no
+`CODEX_THREAD_ID`. The codex hook script reads the payload's leading `session_id` before the prelude
+and lets that thread's record outrank an inherited id; only a pane marked `NODETERM_CODEX_PLAIN=1`
+(the launcher's in-process exits) keeps its own. Do not move the codex payload read back below the
+prelude (`codex-shared-daemon-hook.test.ts` runs the real script against the real hook server).
+
**That prelude may not decide anything a pane already decided.** It exports the agent id and the
canvas-control grant the ownership RECORD carries, never constants. They used to be hardcoded
(`codex`, granted) and both are `buildPtyEnv`'s answers: a custom agent inheriting the codex harness
diff --git a/src/core/agents/hooks/antigravity-script.test.ts b/src/core/agents/hooks/antigravity-script.test.ts
index d983fad36..127e3b420 100644
--- a/src/core/agents/hooks/antigravity-script.test.ts
+++ b/src/core/agents/hooks/antigravity-script.test.ts
@@ -187,30 +187,34 @@ describe('the managed script for antigravity', () => {
// dir once it exists, token read by `read` instead of `head`, the `[A-Za-z0-9._-]` curl-config
// header fast path): the shared script changed for every agent, so every pin moved. Each
// change is pinned behaviourally in managed-script / node-token-sh / hook-curl-config tests.
+ //
+ // RECOMPUTED again for #1150/#1175 on top of that: the shared codex prelude changed, so every
+ // IDENTITY-ROOT variant (the second hash of each pair) moved — codex's most, since it reads its
+ // payload first. The no-root (remote) variants did not.
const expected: Record<string, [string, string]> = {
claude: [
'0c160e0081608c44e327bb22f394aa51e17e852bc277523d0edee9c6d867711d',
- 'e0fd180e49fd26fca4b74b281f1357c8d26eea6338b39dc20e6a38e266ced42f'
+ '57fb9ccb0731a2baa5042741309c7bd52cc559db45738d0742d651fda668e2a5'
],
codex: [
'592fe88ee069db002c9f5c385a2e0465f9659bade3f0bd18c86b5b51f7644e59',
- '3a09c15cb7a3ce6ba71f8bc695a50e58346f05c8015b2eb8812b8003a2e384ea'
+ '0399f289c489544c377f90b747437621e6f7b8fe813bb2c46a364975bc8c6bbe'
],
gemini: [
'c3fb01424ff2a78012ffd6e87200430badfe60b05f603731bf205ee3b791f988',
- '23d62f97dc80483fba92ef760c0dc6a5b3e2f923ce706915739baee1b76579d8'
+ '9e984e142b62c2a5d158f3ecefbd77fc5e775f20522bfe2b3e52807df781dd7a'
],
opencode: [
'910dc7bc71c9af9043f05509d72584c633a790c0dee66d621baeee1db671845f',
- '89d5b0c9b9fc083befb429493093af76d48c5ff5782b6f9cfdb2cdb1adf44344'
+ '19ba31a1dfaa981678e87bcc92417a473c3a98720fb86287e9ca285f01e96500'
],
grok: [
'fe9636e0e6e961109a3d96079a5f10d0304d77e751a6d1de57aa2810b2075b6c',
- '313c0e80dd5160d61b893d8438c952d8a40a1d13bb9ff5280730df507ae910b2'
+ 'd2e66a9386d62eb56c5d520fd695545b447c0facc77bb0948bfb2a0e4240be56'
],
copilot: [
'8907ee6ac3274cc92f3aa44f55119cc3d42b5a2446fcbd4a847fe42064c1f015',
- '27117418faf66ab0c5960cdec22d0bf2594058df0874910b5da16cb56c10c528'
+ '101b2d44c3fb11126cb8d487a425951b63f8f0c1262ed1aa2d6241bce060ec55'
]
}
const sha = (s: string): string => createHash('sha256').update(s).digest('hex')
diff --git a/src/core/agents/hooks/codex-shared-daemon-hook.test.ts b/src/core/agents/hooks/codex-shared-daemon-hook.test.ts
new file mode 100644
index 000000000..fff0ee88e
--- /dev/null
+++ b/src/core/agents/hooks/codex-shared-daemon-hook.test.ts
@@ -0,0 +1,177 @@
+// Issues #1150 and #1175, end to end: the REAL generated codex hook script under /bin/sh, the REAL
+// curl, the REAL hook server, and the server's own verdict about WHICH node the event belongs to.
+//
+// MEASURED on codex-cli 0.162.0 (2026-10-16, private CODEX_HOME + private tmux socket): under the
+// shared app-server a hook process is the daemon's child. It carries the DAEMON's environment and
+// never CODEX_THREAD_ID; its stdin payload starts with `{"session_id":"<thread id>", …`. The env
+// each case below hands the script is one of those measured shapes.
+import { spawn, spawnSync } from 'node:child_process'
+import { mkdirSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
+import { buildManagedScript } from './managed-script'
+import { hookServer } from '../hook-server'
+import { nodeAuthToken } from '../node-auth-token'
+import { initPlatform, resetPlatformForTests } from '../../platform'
+import { fakePlatform } from '../../platform-fake'
+import { testTmpDir } from '../../test-tmp'
+
+const SECRET = Buffer.alloc(32, 5)
+const THREAD = '01a1440f-e72b-7581-b7fc-3842cf6839db'
+const sh = spawnSync('sh', ['-c', 'exit 0'])
+const shAvailable = sh.status === 0 && !sh.error
+
+let dir = ''
+let root = ''
+let endpoint = ''
+let tokens = ''
+let codexScript = ''
+let claudeScript = ''
+let raws: { agentId: string; nodeId: string; verified: boolean }[] = []
+
+beforeAll(async () => {
+ dir = testTmpDir('nt-codex-shared-hook-')
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: join(dir, 'userData') }))
+ await hookServer.start()
+ hookServer.setNodeAuthSecret(SECRET)
+ hookServer.setRawListener((agentId, nodeId, _payload, meta) => {
+ raws.push({ agentId, nodeId, verified: meta.verified })
+ })
+ root = join(dir, 'codex-thread-nodes')
+ mkdirSync(root, { recursive: true })
+ tokens = join(dir, 'node-tokens')
+ mkdirSync(tokens, { recursive: true })
+ for (const id of ['node-A', 'node-B', 'node-C']) {
+ writeFileSync(join(tokens, id), `${nodeAuthToken(SECRET, id)}\n`, { mode: 0o600 })
+ }
+ endpoint = join(dir, 'hook-endpoint.env')
+ writeFileSync(
+ endpoint,
+ `NODETERM_HOOK_PORT=${hookServer.getPort()}\nNODETERM_HOOK_TOKEN=${hookServer.getToken()}\n` +
+ `NODETERM_HOOK_VERSION=2\nNODETERM_NODE_TOKEN_DIR=${tokens}\n`
+ )
+ codexScript = join(dir, 'codex.sh')
+ writeFileSync(codexScript, buildManagedScript('codex', root), { mode: 0o755 })
+ claudeScript = join(dir, 'claude.sh')
+ writeFileSync(claudeScript, buildManagedScript('claude', root), { mode: 0o755 })
+})
+
+afterAll(() => {
+ hookServer.clearNodeAuthSecretForTests()
+ hookServer.stop()
+})
+
+beforeEach(() => {
+ raws = []
+})
+
+/** A thread → node record exactly as the launcher's bind writes it (system scope). */
+function record(threadId: string, nodeId: string): void {
+ writeFileSync(
+ join(root, threadId),
+ `accountId=\nnodeId=${nodeId}\nendpoint=${endpoint}\nagentId=codex\ncanvasControl=1\nsignature=x\n`
+ )
+}
+
+function payload(threadId: string, event = 'Stop'): string {
+ return (
+ `{"session_id":"${threadId}","turn_id":"t1","transcript_path":"/x/rollout-${threadId}.jsonl",` +
+ `"cwd":"/w","hook_event_name":"${event}","model":"m","tool_input":{"session_id":"nested"}}`
+ )
+}
+
+/** Runs the hook; its POST is backgrounded, so wait for the server to hear it (or not). */
+async function runHook(
+ script: string,
+ env: Record<string, string>,
+ stdin: string,
+ expectEvents: number
+): Promise<typeof raws> {
+ await new Promise<void>((resolve) => {
+ const child = spawn('sh', [script], {
+ env: { PATH: process.env.PATH ?? '', HOME: join(dir, 'home'), ...env },
+ stdio: ['pipe', 'ignore', 'ignore']
+ })
+ child.stdin.end(stdin)
+ child.on('close', () => resolve())
+ })
+ const deadline = Date.now() + (expectEvents ? 5000 : 800)
+ while (Date.now() < deadline && raws.length < Math.max(expectEvents, 1)) {
+ await new Promise((r) => setTimeout(r, 25))
+ }
+ return raws
+}
+
+/** The env of a hook spawned by a STALE daemon: the pane that started it, long gone. */
+const staleDaemonEnv = {
+ NODETERM_NODE_ID: 'node-A',
+ NODETERM_AGENT_ID: 'codex',
+ // A dead port + bogus credentials: whatever the rebind does must not keep these.
+ NODETERM_HOOK_PORT: '1',
+ NODETERM_HOOK_TOKEN: 'stale-token',
+ // The record's endpoint file advertises no socket, so a stale one must not survive the rebind.
+ NODETERM_HOOK_SOCK: join('/nonexistent', 'hook.sock'),
+ NODETERM_NODE_TOKEN_DIR: join('/nonexistent', 'tokens')
+}
+
+describe.skipIf(!shAvailable)('codex hooks under the shared app-server', () => {
+ it('#1150: a scrubbed daemon (no NODETERM_*, no CODEX_THREAD_ID) reports for the thread\'s node', async () => {
+ record(THREAD, 'node-B')
+ const got = await runHook(codexScript, {}, payload(THREAD), 1)
+ expect(got).toEqual([{ agentId: 'codex', nodeId: 'node-B', verified: true }])
+ })
+
+ it('#1175: a stale daemon\'s inherited node id is outranked by the thread record', async () => {
+ record(THREAD, 'node-B')
+ const got = await runHook(codexScript, staleDaemonEnv, payload(THREAD), 1)
+ expect(got).toEqual([{ agentId: 'codex', nodeId: 'node-B', verified: true }])
+ })
+
+ it('a plain in-process pane (NODETERM_CODEX_PLAIN=1) keeps its own id, record or not', async () => {
+ // The bind-refused fallback: node-C runs a thread whose record names node-B.
+ record(THREAD, 'node-B')
+ const got = await runHook(
+ codexScript,
+ {
+ NODETERM_NODE_ID: 'node-C',
+ NODETERM_CODEX_PLAIN: '1',
+ NODETERM_HOOK_ENDPOINT: endpoint
+ },
+ payload(THREAD),
+ 1
+ )
+ expect(got).toEqual([{ agentId: 'codex', nodeId: 'node-C', verified: true }])
+ })
+
+ it('a thread with no record changes nothing (an inherited id still posts as before)', async () => {
+ const got = await runHook(
+ codexScript,
+ { NODETERM_NODE_ID: 'node-C', NODETERM_HOOK_ENDPOINT: endpoint },
+ payload('thread-without-record'),
+ 1
+ )
+ expect(got).toEqual([{ agentId: 'codex', nodeId: 'node-C', verified: true }])
+ })
+
+ it('no node id, no record: still the silent exit (a user\'s own codex)', async () => {
+ expect(await runHook(codexScript, {}, payload('thread-without-record'), 0)).toEqual([])
+ })
+
+ it('reads only the LEADING session_id — a nested one in tool input never names a file', async () => {
+ record('nested', 'node-B')
+ const body = `{"hook_event_name":"Stop","tool_input":{"session_id":"nested"}}`
+ expect(await runHook(codexScript, {}, body, 0)).toEqual([])
+ })
+
+ it('refuses a payload thread id that could escape the record directory', async () => {
+ record(THREAD, 'node-B')
+ expect(await runHook(codexScript, {}, payload('..'), 0)).toEqual([])
+ expect(await runHook(codexScript, {}, payload('../codex-thread-nodes/x'), 0)).toEqual([])
+ })
+
+ it('the claude script ignores the payload: its session_id is never a codex thread', async () => {
+ record(THREAD, 'node-B')
+ expect(await runHook(claudeScript, {}, payload(THREAD), 0)).toEqual([])
+ })
+})
diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.ts
index b6d5bc1d8..7e8291787 100644
--- a/src/core/agents/hooks/managed-script.ts
+++ b/src/core/agents/hooks/managed-script.ts
@@ -262,6 +262,9 @@ export function buildManagedScript(
identityRoot: string | null = safeIdentityRoot()
): string {
const antigravity = agentId === 'antigravity'
+ // The codex hook reads its payload BEFORE the identity prelude: the payload's session_id is the
+ // only thread id a hook under the shared app-server has (#1150/#1175, codex-thread-identity-sh.ts).
+ const codexPayloadFirst = agentId === 'codex' && !!identityRoot
// The event name rides the POST for antigravity only — its payload never carries one.
const eventField = antigravity
? [` --data-urlencode "nodeterm_hook_event=\${${ANTIGRAVITY_EVENT_ENV}}" \\`]
@@ -269,7 +272,23 @@ export function buildManagedScript(
return [
'#!/bin/sh',
...(antigravity ? antigravityAnswerFirst() : []),
- ...(identityRoot ? [codexThreadIdentityResolverSh(identityRoot)] : []),
+ ...(codexPayloadFirst
+ ? [
+ '# Payload first (codex only): its leading session_id is this event\'s thread. Parsed with',
+ '# builtins, anchored at the first byte, so a nested "session_id" in tool input never matches.',
+ 'nt_pre_payload=$(cat)',
+ 'nt_hook_thread=\'\'',
+ 'case "$nt_pre_payload" in',
+ ' \'{"session_id":"\'*)',
+ ' nt_hook_thread=${nt_pre_payload#\'{"session_id":"\'}',
+ ' nt_hook_thread=${nt_hook_thread%%\'"\'*}',
+ ' ;;',
+ 'esac'
+ ]
+ : []),
+ ...(identityRoot
+ ? [codexThreadIdentityResolverSh(identityRoot, { hookPayloadThread: codexPayloadFirst })]
+ : []),
'# GATE FIRST, and drain stdin before bailing (issues #186/#187). Order is load-bearing twice:',
'# - The codex thread-identity prelude above may DERIVE the node id (and endpoint) from its',
'# thread id, so the gate cannot move above it — but nothing below needs to run for a',
@@ -331,7 +350,7 @@ export function buildManagedScript(
'[ "${#nt_context_window}" -le 16 ] || nt_context_window=""'
]
: ['nt_context_window=""']),
- 'payload=$(cat)',
+ codexPayloadFirst ? 'payload=$nt_pre_payload' : 'payload=$(cat)',
'if [ -z "$payload" ]; then',
...(antigravity
? [
diff --git a/src/core/codex-identity-proxy.ts b/src/core/codex-identity-proxy.ts
index 662d401d8..37b66f470 100644
--- a/src/core/codex-identity-proxy.ts
+++ b/src/core/codex-identity-proxy.ts
@@ -889,9 +889,19 @@ nt_run_shared() {
# in-process. The launch line normally carries it already (the desktop probed its own codex); on a
# host nobody probed (an SSH launcher) this asks the binary about to run, and a codex that does not
# advertise the flag gets the caller's arguments untouched — clap exits on an unknown option.
+#
+# Every IN-PROCESS exit is marked NODETERM_CODEX_PLAIN=1: its hooks run with THIS pane's env, which
+# is authoritative even when the thread's record names another node (the bind-refused fallback).
+# The hook prelude lets a thread record outrank only an INHERITED id — a daemon's (#1175). A
+# --remote exit runs its hooks in the daemon, so it is not marked.
nt_exec_plain() {
for nt_plain_arg in "$@"; do
- case "$nt_plain_arg" in --no-daemon|--remote|--remote=*) exec codex "$@" ;; esac
+ case "$nt_plain_arg" in --remote|--remote=*) exec codex "$@" ;; esac
+ done
+ NODETERM_CODEX_PLAIN=1
+ export NODETERM_CODEX_PLAIN
+ for nt_plain_arg in "$@"; do
+ case "$nt_plain_arg" in --no-daemon) exec codex "$@" ;; esac
done
if codex --help 2>/dev/null | grep -q -E '${CODEX_NO_DAEMON_HELP_ERE}'; then
exec codex --no-daemon "$@"
diff --git a/src/core/codex-launcher-sh.test.ts b/src/core/codex-launcher-sh.test.ts
index d65c45d7d..5dc4c3fe2 100644
--- a/src/core/codex-launcher-sh.test.ts
+++ b/src/core/codex-launcher-sh.test.ts
@@ -834,3 +834,34 @@ describe('--no-daemon: stripped from the managed thread, kept or added on plain
expect(codexArgv()).toEqual(['hello'])
})
})
+
+// #1175: a hook under a STALE shared daemon inherits the node id of the pane that started it, so
+// the hook prelude lets the payload thread's record outrank an inherited id. Our own plain exits
+// run codex IN-PROCESS: their hooks carry THIS pane's env, which must keep winning even when the
+// thread's record names another node (the bind-refused fallback). The marker says so.
+describe('NODETERM_CODEX_PLAIN marks the in-process exits, never the --remote client', () => {
+ const plainMarks = (): string[] =>
+ fs.readFileSync(argvLog, 'utf8').split('\n').filter((l) => l.startsWith('PLAIN='))
+ beforeEach(() => {
+ fakeHelpNoDaemon = true
+ writeFakeCodex(`printf 'PLAIN=%s\\n' "\${NODETERM_CODEX_PLAIN-}" >> ${JSON.stringify(argvLog)}`)
+ })
+
+ it('the bind-refused fallback runs plain codex marked', async () => {
+ bindAnswer = null
+ await callLauncher(['resume', 'thread-xyz'])
+ expect(codexArgv()[0]).toBe('--no-daemon resume thread-xyz')
+ expect(plainMarks()).toEqual(['PLAIN=1'])
+ })
+
+ it('a preflight fallback that already carries --no-daemon is marked too', async () => {
+ await callLauncher(['fix the bug', '--no-daemon'], { NODETERM_HOOK_ENDPOINT: '' })
+ expect(plainMarks()).toEqual(['PLAIN=1'])
+ })
+
+ it('the managed --remote resume is NOT marked (its hooks run in the daemon)', async () => {
+ await callLauncher(['resume', 'thread-xyz'])
+ expect(codexArgv()[0]).toBe('--remote unix:// resume thread-xyz')
+ expect(plainMarks()).toEqual(['PLAIN='])
+ })
+})
diff --git a/src/core/codex-thread-identity-sh.ts b/src/core/codex-thread-identity-sh.ts
index ee11f9e5e..afe67cd0b 100644
--- a/src/core/codex-thread-identity-sh.ts
+++ b/src/core/codex-thread-identity-sh.ts
@@ -35,7 +35,8 @@
* it was written; a record that names an agent is exported as it stands, grant included, and never
* falls back to the guess.
*
- * Inert for every other agent: without `CODEX_THREAD_ID` the whole block is skipped. A machine with
+ * Inert for every other agent: without `CODEX_THREAD_ID` (or, in the codex HOOK script only, the
+ * payload's `session_id` — see HOOK_PAYLOAD_THREAD_SH) the whole block is skipped. A machine with
* no managed accounts has no subdirs, so the scan reduces to the one bare-root read S4 did — the
* legacy layout keeps resolving byte-for-byte (Constraint 12).
*
@@ -44,6 +45,35 @@
*/
import { posixQuote } from '../shared/ssh'
+/**
+ * The HOOK variant (#1150, #1175). MEASURED on codex-cli 0.162.0, 2026-10-16 (private CODEX_HOME,
+ * private tmux socket, a hook that dumped its env and stdin): under the shared app-server a hook
+ * process is a child of the DAEMON, carries the daemon's environment and NEVER `CODEX_THREAD_ID`
+ * (only tool shells get that). So:
+ * - a daemon our launcher started (scrubbed) runs hooks with no node id at all and the gate
+ * below exits silently: every managed Codex node stayed dark (#1150);
+ * - a daemon a plain `codex` pane started keeps THAT pane's `NODETERM_NODE_ID` and runs every
+ * later node's hooks under it: events land on a stale node (#1175).
+ * What a hook does carry is its payload, whose first key is `session_id` = the thread id (the
+ * rollout file is named after it). The managed script reads stdin first and hands this block the
+ * id in `nt_hook_thread`; it is still validated by the case below before it names a file.
+ *
+ * The payload's thread is this EVENT's own, so a record for it outranks an INHERITED node id — but
+ * only an inherited one. A pane whose own env is authoritative (our launcher's plain-codex exit,
+ * which runs codex in-process with `--no-daemon`) is marked `NODETERM_CODEX_PLAIN=1`, and there the
+ * env id stands: that is the bind-refused fallback that legitimately runs a thread another node's
+ * record names. A thread with no record changes nothing either way.
+ *
+ * A forged payload buys nothing: the record only names a node whose 0600 token file the same user
+ * can already read, and the event is still verified against that token (docs/node-identity.md).
+ */
+const HOOK_PAYLOAD_THREAD_SH = `# A HOOK never gets CODEX_THREAD_ID; its payload's session_id is this event's thread.
+if [ -n "\${nt_hook_thread-}" ]; then
+ nt_codex_tid=$nt_hook_thread
+ [ "\${NODETERM_CODEX_PLAIN-}" = 1 ] || nt_codex_rebind=1
+fi
+`
+
/**
* PROBE U5 (Codex 0.146.0, 2026-08-19 — docs/superpowers/probes/2026-08-codex-tool-shell-env.md):
* a shared `app-server`-spawned tool shell carries `CODEX_THREAD_ID` (measured — a fresh id per
@@ -55,11 +85,16 @@ import { posixQuote } from '../shared/ssh'
* @param identityRoot absolute path of the thread → node record directory
* (`codexThreadIdentityRoot()`, i.e. under `CorePlatform.userDataDir` — NOT `~`).
*/
-export function codexThreadIdentityResolverSh(identityRoot: string): string {
+export function codexThreadIdentityResolverSh(
+ identityRoot: string,
+ opts: { hookPayloadThread?: boolean } = {}
+): string {
return `# A shared-app-server Codex tool shell inherits CODEX_THREAD_ID, not the TUI client's
# NODETERM_* env. Recover this thread's exact node binding (account-scoped), or change nothing.
-if [ -z "\${NODETERM_NODE_ID-}" ] && [ -n "\${CODEX_THREAD_ID-}" ]; then
- case "$CODEX_THREAD_ID" in
+nt_codex_tid=\${CODEX_THREAD_ID-}
+nt_codex_rebind=0
+${opts.hookPayloadThread ? HOOK_PAYLOAD_THREAD_SH : ''}if { [ -z "\${NODETERM_NODE_ID-}" ] || [ "$nt_codex_rebind" = 1 ]; } && [ -n "$nt_codex_tid" ]; then
+ case "$nt_codex_tid" in
# '.' and '..' MATCH the charset and are path segments: "$identityRoot"/.. is the record dir's
# PARENT. Refused by name here for the same reason isSafeThreadId refuses them in TypeScript.
''|.|..|*[!A-Za-z0-9._-]*) ;;
@@ -147,7 +182,7 @@ if [ -z "\${NODETERM_NODE_ID-}" ] && [ -n "\${CODEX_THREAD_ID-}" ]; then
case "\${NODETERM_CODEX_ACCOUNT_ID-}" in
'')
# Unknown account: scan every scope, bind only if exactly one candidate matches.
- nt_codex_try "$nt_codex_root/$CODEX_THREAD_ID" ''
+ nt_codex_try "$nt_codex_root/$nt_codex_tid" ''
for nt_codex_dir in "$nt_codex_root"/*/; do
[ -d "$nt_codex_dir" ] || continue
nt_codex_scope=\${nt_codex_dir%/}
@@ -155,19 +190,23 @@ if [ -z "\${NODETERM_NODE_ID-}" ] && [ -n "\${CODEX_THREAD_ID-}" ]; then
case "$nt_codex_scope" in
''|.|..|system|*[!A-Za-z0-9._-]*) continue ;;
esac
- nt_codex_try "$nt_codex_dir$CODEX_THREAD_ID" "$nt_codex_scope"
+ nt_codex_try "$nt_codex_dir$nt_codex_tid" "$nt_codex_scope"
done
;;
# A daemon scope that could escape the mapping directory, or the reserved system word used
# as a managed id: resolve nothing.
.|..|system|*[!A-Za-z0-9._-]*) ;;
*)
- nt_codex_try "$nt_codex_root/\${NODETERM_CODEX_ACCOUNT_ID}/$CODEX_THREAD_ID" \\
+ nt_codex_try "$nt_codex_root/\${NODETERM_CODEX_ACCOUNT_ID}/$nt_codex_tid" \\
"$NODETERM_CODEX_ACCOUNT_ID"
;;
esac
if [ "$nt_codex_matches" -eq 1 ] && [ -n "$nt_codex_node" ] && [ -n "$nt_codex_endpoint" ]
then
+ # The endpoint's own values come from sourcing the RECORD's endpoint file below; anything
+ # left over belongs to the env this shell inherited (a stale daemon's, when rebinding).
+ unset NODETERM_HOOK_PORT NODETERM_HOOK_TOKEN NODETERM_HOOK_SOCK NODETERM_NODE_TOKEN_DIR \\
+ NODETERM_CANVAS_CONTROL
NODETERM_NODE_ID="$nt_codex_node"
NODETERM_HOOK_ENDPOINT="$nt_codex_endpoint"
NODETERM_AGENT_ID="$nt_codex_agent"