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
fix(hooks): one token resolver for every sh client, so a pinned endpoint stops stranding a node
enes7cf83149e789
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2504d51a1..2c37bfb13 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -973,6 +973,19 @@ else, and its context links must keep classifying across restarts).the Server Edition silently without the feature; the boundary tests cannot tell you a field is*missing*. `hook-verified-parity.test.ts` asserts it at source level because this repo hasshipped a one-shell hook-server change three times.+ - **Every generated sh client reads the token through ONE resolver** (`nt_read_node_token`,+ `core/agents/node-token-sh.ts`) — the managed hook script, `nodeterm.sh` and `context.sh`. The+ token dir is advertised only by the endpoint FILE, and a session is pinned for life to the+ endpoint PATH it got at tmux creation, so a client that reads only what that file advertises+ presents nothing forever when the file is pre-v2 (SSH hosts' shared `~/.nodeterm/hook-+ endpoint.env`, whose per-project socket path is re-bound on every connect, so it stays LIVE) or+ unreadable (a phone-spawned session). Issue #384: the hook script FAILS OVER and re-reads the+ token from the endpoint it adopts, the two shims did neither — so the same node proved itself+ through one client and was refused through the other by the trust-on-first-proof latch, for the+ life of the session. The resolver falls back to `<dir of the endpoint file>/node-tokens` (the+ 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.Enforcement is dated (`NODE_IDENTITY_STRICT_AFTER`, 2026-10-13, read through `isStrictInstant` so aclock years ahead cannot enter strict mode early) with a `settings.hookIdentityStrict` escape hatchdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 4cb5bf426..b7089aff8 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -134,6 +134,15 @@ here has: not while the kanban board covers it, not while the user is typing.reasoning. A comment that restates the code is noise; one that says "do not simplify this back,here is what broke" is the point.+**A generated sh client reads its node token through the one resolver.** Every POSIX-sh client we+emit (the managed hook script, `nodeterm.sh`, `context.sh`) presents this node's per-node identity by+calling `nt_read_node_token` from `core/agents/node-token-sh.ts` — never by re-typing+`head -n 1 "$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID"`. That copy was issue #384: a session is+pinned for life to the endpoint FILE path it got at tmux creation, so a client that trusts only what+that file advertises presents nothing forever when the file is old or unreadable — and because the+hook script alone could heal itself, the same node proved itself through one client and was refused+through another for the life of the session.+**Agent features attach to base harness capabilities, not frontend allowlists.** A custom agent caninherit a builtin harness, so add the capability and its one shared leaf (`src/shared/agents`) andlet every UI ask the helper. Repeating Claude/Codex/etc. cases in menus breaks that inheritance anddiff --git a/docs/node-identity.md b/docs/node-identity.mdindex 3981ad471..80c63d8f8 100644--- a/docs/node-identity.md+++ b/docs/node-identity.md@@ -343,9 +343,54 @@ the latch shippable, not the window:- every token sweep releases the latch (collision refusal, delete/re-create, remote refusal);- the clock clamp;+- the shared token resolver (below), so a client cannot fail to FIND a token that exists;- and the escape hatch, which must be reachable **in the UI**, because a stranded user's symptomnever says "clock" or "collision".+### ⚠ A client that cannot FIND the token is indistinguishable from one that has none — issue #384++The token dir is advertised by ONE thing, the endpoint file, and a session is pinned for life to the+endpoint **path** it was handed at tmux creation (`buildPtyEnv` / `remoteHookEnvArgs`). So a session+whose endpoint file does not carry a `NODETERM_NODE_TOKEN_DIR` line presents nothing, forever, while+its token file sits in the standard place. Three populations, all measured on a real host:++- **A pre-v2 endpoint file that is still LIVE.** SSH hosts used to share one+ `~/.nodeterm/hook-endpoint.env`; the current build writes per-project+ `hook-endpoint-<projectId>.env` and never touches the old path again. The old file names+ `~/.nodeterm/hook-<projectId>.sock` — a path **re-bound on every connect of that project** — so it+ keeps reaching a current server while advertising no dir. Observed: a `VERSION=1` file a month old+ pointing at a socket created minutes earlier.+- **A session whose transport rides the env with no readable endpoint file** — what the phone hands+ a session it spawns.+- **A partial read** of an endpoint file being rewritten under the reader.++What made it a *refusal* rather than an unverified call is that the CLIENTS DISAGREED. The managed+hook script has an endpoint failover: on a failed POST it adopts a live sibling endpoint and re-reads+the token from **that** endpoint's dir — so the node proves itself and latches. The two sh shims had+no failover and no fallback, so every canvas-control and context-link call from that session was+refused with `IDENTITY_REFUSED_NOTE` for the rest of its life. **Proven by one client, refused+through another.**++The fix is one resolver, `nt_read_node_token`, emitted by `core/agents/node-token-sh.ts` and used by+all three clients (the codex launcher is deliberately excluded — it refuses outright on an unreadable+endpoint and reports a named degrade, a different contract). It tries the advertised dir, then+`<dir of the endpoint file>/node-tokens` — the layout **by construction** on all three surfaces — then+the same well-known data dirs the hook script already walks for endpoint files.++It is **monotone**, and that is the whole safety argument: the advertised dir is always first, so+nothing that verifies today changes; the lookup is by node-id FILENAME in every candidate, so a+session can still only present its own token; and a dir belonging to another instance mints under a+different secret, so its token carries a foreign `kid` — `legacy`, bit-for-bit what presenting+nothing already gave, and never `forged`. Each candidate can turn `legacy` into `verified` and+nothing else.++**The advice was wrong too.** Both notes said "Restart this node (right-click it, *Restart agent*)".+That action re-launches the CLI **inside the same pane** and deliberately leaves the pty, the tmux+session and therefore the whole environment untouched (`terminal/agent-restart.ts`) — so it could+never change what a session presents. They now say *close and reopen the node* (a new tmux session is+what picks up the current `-e` env), *reconnect the SSH project* (the only thing that rewrites the+host's endpoint file, shim, hook script and token files), and name the escape hatch.+Known and **not** fixed: two processes on one node id after a re-attach. A shell from an older apprun, whose shim never learned to send the header, posts nothing while the re-attached session provesthe node — and is then refused for as long as it lives. It is genuinely indistinguishable from andiff --git a/src/core/agents/hook-identity-enforcement.test.ts b/src/core/agents/hook-identity-enforcement.test.tsindex 87d0a9ba0..ad8bdb62e 100644--- a/src/core/agents/hook-identity-enforcement.test.ts+++ b/src/core/agents/hook-identity-enforcement.test.ts@@ -540,12 +540,17 @@ describe('a node that can NEVER have an identity is told so, and not told to resexpect(controlCalls).toEqual([])})- it('does not say "Restart", because restarting is the thing that cannot work', () => {+ it('advises no recovery action on the node, because none can work', () => {+ // The contrast, on the axis that matters: the ordinary refusal names a way back (reopen the+ // node — #384 moved it off the in-place "Restart agent", which reuses the same environment and+ // therefore could never help either); this one refuses to name any, because for a colliding or+ // invalid node id there is none short of editing project.json.+ expect(IDENTITY_UNMINTABLE_NOTE).not.toContain('Close and reopen this node')expect(IDENTITY_UNMINTABLE_NOTE).not.toContain('Restart')- expect(IDENTITY_REFUSED_NOTE).toContain('Restart')+ expect(IDENTITY_REFUSED_NOTE).toContain('Close and reopen this node')})- it('keeps the ordinary sentence for an ordinary node — the one a restart DOES fix', async () => {+ it('keeps the ordinary sentence for an ordinary node — the one reopening DOES fix', async () => {const res = await control('open-terminal', 'n-ordinary-refusal')expect(res.status).toBe(403)expect((await res.text()).trim()).toBe(IDENTITY_REFUSED_NOTE)@@ -579,7 +584,7 @@ describe('a node that can NEVER have an identity is told so, and not told to res* THE WINDOW IS WHERE THAT SENTENCE WAS NEEDED, AND IT WAS THE ONE PLACE IT COULD NOT REACH.** Measured against a real hook server on 2026-08-14: node `Term-X`, a refused case-fold collision- * member, was handed `IDENTITY_RESTART_NOTE` — "Restart this node… to pick one up" — for a node+ * member, was handed `IDENTITY_RESTART_NOTE` — "Close and reopen this node to pick one up" — for a node* that has nothing to pick up. `controlPolicy` answers `allow-with-warning` for exactly this* population until 2026-10-13, and the warn branch emitted one fixed string, so the unmintable* wording only ever appeared AFTER the cutoff (or for a latched node). For the whole warningdiff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 94c442a24..66d3a9bc0 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -376,7 +376,7 @@ class HookServer {* changes — today, the members of a case-folding collision group (`node-token-service.ts`).** It exists only to pick the right refusal SENTENCE. `IDENTITY_REFUSED_NOTE` tells the user to- * restart the node to pick up an identity; for these nodes there is nothing to pick up, so that+ * reopen the node to pick up an identity; for these nodes there is nothing to pick up, so that* advice sends them round a loop while the only other signal is a `console.warn` in a log they* are not reading. The other unmintable population — an id outside `isSafeNodeId`, which reaches* the canvas because `fileToProject` does not validate ids out of `project.json` — needs no@@ -420,8 +420,9 @@ class HookServer {* An unmintable node is `allow-with-warning` for the whole window — `controlPolicy` cannot see* that it is unmintable, and would not change its verdict if it could, because running is the* right answer there. So the window was the ONE period in which these nodes were guaranteed to be- * told to "Restart this node… to pick one up", which is the loop `IDENTITY_UNMINTABLE_NOTE` was- * written to end. The note was unreachable exactly while it was needed.+ * told to "Close and reopen this node to pick one up", which is the loop+ * `IDENTITY_UNMINTABLE_NOTE` was written to end. The note was unreachable exactly while it was+ * needed.*/private identityWarningNote(nodeId: string): string {return this.identityUnmintable(nodeId) ? IDENTITY_UNMINTABLE_WARN_NOTE : IDENTITY_RESTART_NOTEdiff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex bbbbe4b9e..5de118282 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -87,6 +87,7 @@import { codexThreadIdentityResolverSh } from '../../codex-thread-identity-sh'import { codexThreadIdentityRoot } from '../../codex-identity-proxy'import { HOOK_CURL_HEADERS_SH } from '../hook-curl-config-sh'+import { NODE_TOKEN_READ_SH } from '../node-token-sh'/*** Bumped by hand whenever this script's CONTRACT with the server changes. Not a git sha and not a@@ -107,9 +108,13 @@ import { HOOK_CURL_HEADERS_SH } from '../hook-curl-config-sh'* and any session the PHONE spawns on that host, which runs the host's installed script — stay* `legacy` until the project reconnects.*/-export const MANAGED_SCRIPT_REVISION = 3+export const MANAGED_SCRIPT_REVISION = 4/** The first revision that reads NODETERM_NODE_TOKEN_DIR and sends the node token (PR #195). */export const MIN_TOKEN_AWARE_REVISION = 3+/* rev 4 (issue #384): the token read moved to the shared resolver in `node-token-sh.ts`, which+ * falls back to the standard token dirs when the endpoint file advertises none. The floor stays 3+ * on purpose — rev 3 CAN read a token, which is the only question `MIN_TOKEN_AWARE_REVISION`+ * answers; calling it stale would tell a working session to reconnect for nothing. */function safeIdentityRoot(): string | null {try {@@ -172,13 +177,10 @@ export function buildManagedScript('# ever present its own. Absent (pre-v2 endpoint, pre-upgrade session, remote write that failed)','# leaves it EMPTY, and an empty header is exactly what the server reads as `legacy`: the POST','# still happens and nothing about it fails. Kept in a function because the failover below has to',- '# RE-read it against the dir of the endpoint it adopted.',- 'nt_read_node_token() {',- ' nt_node_token=""',- ' if [ -n "$NODETERM_NODE_TOKEN_DIR" ] && [ -n "$NODETERM_NODE_ID" ]; then',- ' nt_node_token=$(head -n 1 "$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID" 2>/dev/null)',- ' fi',- '}',+ '# RE-read it against the dir of the endpoint it adopted — which is why the resolver takes that',+ '# endpoint as an argument (see node-token-sh.ts, and issue #384 for the population its',+ '# fallbacks exist for: an endpoint file that is still LIVE but advertises no dir at all).',+ NODE_TOKEN_READ_SH,'nt_read_node_token',HOOK_CURL_HEADERS_SH,'payload=$(cat)',@@ -332,8 +334,10 @@ export function buildManagedScript(' # The token is re-read HERE, per candidate, not once at the top: it must come from the dir',' # the endpoint we just adopted advertises. Reusing the primary\'s (or the previous',' # candidate\'s) would send our kid to a server that cannot judge it — harmless, but also',- ' # pointless, and it would hide a real identity behind a legacy.',- ' nt_read_node_token',+ ' # pointless, and it would hide a real identity behind a legacy. The adopted path is passed',+ ' # in for the same reason: when that endpoint advertises no dir, the fallback must derive',+ ' # from ITS directory, never from the one we are walking away from.',+ ' nt_read_node_token "$nt_ep"',' nt_request_post && return 0',' done',' return 1',diff --git a/src/core/agents/node-identity-policy.test.ts b/src/core/agents/node-identity-policy.test.tsindex d36609f68..963e51350 100644--- a/src/core/agents/node-identity-policy.test.ts+++ b/src/core/agents/node-identity-policy.test.ts@@ -38,14 +38,33 @@ describe('the cutoff is a dated commitment, not a "later"', () => {expect(NODE_IDENTITY_STRICT_AFTER.toISOString().slice(0, 10)).toBe(NODE_IDENTITY_STRICT_DATE)})- it('names the action in both sentences, so the user is told what to do', () => {+ it('names an action that CAN work, in both sentences', () => {for (const note of [IDENTITY_RESTART_NOTE, IDENTITY_REFUSED_NOTE]) {- expect(note).toContain('Restart agent')+ expect(note).toContain('Close and reopen this node')// One line: both are PREFIXED onto a reply, and a multi-line prefix buries the reply.expect(note).not.toContain('\n')}})+ it('does NOT prescribe the in-place agent restart, which cannot fix this (#384)', () => {+ // `agent-restart.ts` re-launches the CLI INSIDE the same pane and leaves the pty, the tmux+ // session and therefore the session ENVIRONMENT untouched — and identity is read out of that+ // environment. So the old advice was guaranteed not to work for the population it was handed+ // to, which is the same loop IDENTITY_UNMINTABLE_NOTE was written to break.+ for (const note of [IDENTITY_RESTART_NOTE, IDENTITY_REFUSED_NOTE]) {+ expect(note).not.toContain('Restart agent')+ }+ })++ it('the refusal points at the escape hatch, since it has no date to wait for', () => {+ // IDENTITY_REFUSED_NOTE fires on BOTH sides of the cutoff (the latch does not wait for it), so+ // unlike the warning it cannot tell the user "this becomes strict on <date>". The Settings row+ // is the only thing that releases it without a working fix, and a stranded user's symptom+ // never says "identity", so the sentence has to name it.+ expect(IDENTITY_REFUSED_NOTE).toContain('Settings')+ expect(IDENTITY_REFUSED_NOTE).not.toContain(NODE_IDENTITY_STRICT_DATE)+ })+it('says, in the refusal, that the command did not run', () => {expect(IDENTITY_REFUSED_NOTE).toContain('did not run')})diff --git a/src/core/agents/node-identity-policy.ts b/src/core/agents/node-identity-policy.tsindex db85ea59b..9a91ee5a1 100644--- a/src/core/agents/node-identity-policy.ts+++ b/src/core/agents/node-identity-policy.ts@@ -100,11 +100,22 @@ export function isStrictInstant(now: Date): boolean {* It says what could not be established, that the command ran anyway, the exact action that fixes* it, and the date after which it stops being a note and starts being a refusal. One line, because* it is a prefix and a multi-line prefix buries the reply the agent actually asked for.+ *+ * THE ACTION IS "close and reopen", not "Restart agent" — issue #384. Both sentences used to name+ * the in-place restart, and that one is measurably incapable of fixing this: `agent-restart.ts`+ * types the CLI's exit line and re-launches it INSIDE the same pane, deliberately leaving the pty,+ * the tmux session and therefore the whole session ENVIRONMENT untouched. Identity is read out of+ * that environment (`$NODETERM_HOOK_ENDPOINT` → the token dir it advertises), so the restart+ * cannot change the answer, however many times it is run. Only a new tmux session picks up the+ * current `-e` env, and on an SSH host only a reconnect rewrites the endpoint file, the shim, the+ * hook script and the token files. Naming an action that cannot work is the exact loop+ * `IDENTITY_UNMINTABLE_NOTE` exists to break, and it was being handed to a far larger population.*/export const IDENTITY_RESTART_NOTE ='NodeTerm could not confirm which node sent this command: this session is not presenting its ' +- 'node identity, so it ran unverified. Restart this node (right-click it, "Restart agent") to ' +- `pick one up — from ${STRICT_DATE} commands from a session without one are refused.`+ 'node identity, so it ran unverified. Close and reopen this node to pick one up (on an SSH ' ++ `project, reconnect the project first) — from ${STRICT_DATE} commands from a session without ` ++ 'one are refused.'/*** The same situation once it is refused — after the cutoff, or once the node has proven itself and@@ -115,8 +126,9 @@ export const IDENTITY_RESTART_NOTE =*/export const IDENTITY_REFUSED_NOTE ='NodeTerm could not confirm which node sent this command, so it did not run: this session is ' +- 'not presenting its node identity. Restart this node (right-click it, "Restart agent") to pick ' +- 'one up.'+ 'not presenting its node identity. Close and reopen this node to pick one up — on an SSH ' ++ 'project, reconnect the project first — or turn off Settings → Agents → "Require verified node ' ++ 'identity for canvas control".'/*** The refusal for a node that can NEVER have an identity, however many times it is restarted.@@ -131,10 +143,11 @@ export const IDENTITY_REFUSED_NOTE =* `nodeAuthToken` returns '' for it forever.** Giving those `IDENTITY_REFUSED_NOTE` is the worst kind of wrong answer: it names an action- * ("Restart this node… to pick one up") that is guaranteed not to work, so the user restarts in a- * loop while the only real signal — a `console.warn` in the main-process log — sits somewhere they- * will never look. This sentence names the cause instead, refuses to advise a restart, and points- * at both real ways out: fix the id, or use the escape hatch, which does release this.+ * ("Close and reopen this node to pick one up") that is guaranteed not to work, so the user+ * reopens in a loop while the only real signal — a `console.warn` in the main-process log — sits+ * somewhere they will never look. This sentence names the cause instead, refuses to advise any+ * action on the node, and points at both real ways out: fix the id, or use the escape hatch,+ * which does release this.** It is one of a PAIR: this is the refusal, `IDENTITY_UNMINTABLE_WARN_NOTE` is the same cause said* during the warning window, where the command ran. The two differ in one clause and share thediff --git a/src/core/agents/node-token-sh.ts b/src/core/agents/node-token-sh.tsnew file mode 100644index 000000000..2eaeb9909--- /dev/null+++ b/src/core/agents/node-token-sh.ts@@ -0,0 +1,102 @@+/**+ * THE PER-NODE CAPABILITY, READ — one POSIX-sh resolver, every generated client.+ *+ * Four generated clients present this node's token: the managed hook script, the canvas-control+ * shim (`nodeterm.sh`), the context-link shim (`context.sh`) and the codex launcher. Three of them+ * carried the SAME two lines by copy — read `$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID`, or+ * nothing — and that copy is what issue #384 was:+ *+ * the dir is advertised ONLY by the endpoint file, and a session is pinned for life to the+ * endpoint PATH it was handed at tmux creation (`buildPtyEnv` / `remoteHookEnvArgs`).+ *+ * So a session whose endpoint file does not advertise a dir presents no token at all, forever,+ * while its token file sits in the standard place. Three populations land there, all measured:+ *+ * - **A pre-v2 endpoint file that is still LIVE.** SSH hosts used to share one+ * `~/.nodeterm/hook-endpoint.env`; the current build writes per-project+ * `hook-endpoint-<projectId>.env` and never rewrites the old path again. The old file names+ * `~/.nodeterm/hook-<projectId>.sock` — a path that is RE-BOUND on every connect of that+ * project — so it keeps reaching a live server while advertising no token dir. Reproduced on a+ * real host: a `VERSION=1` file dated a month earlier, pointing at a socket created minutes ago.+ * - **A session whose env carries the transport directly and no readable endpoint file** — what+ * the phone hands a session it spawns (see the managed script's own gate comment).+ * - **A partial read of an endpoint file** being rewritten under the reader.+ *+ * The failure this produces is not "unverified": it is a hard 403 with+ * `IDENTITY_REFUSED_NOTE`, because the node is LATCHED. The managed hook script has an endpoint+ * FAILOVER that adopts a live sibling endpoint and re-reads the token from ITS dir, so the same+ * node proves itself through the hook and is refused through the shim — trust-on-first-proof then+ * refuses every canvas-control call for the life of the session. The shims never learned the+ * failover, so the asymmetry was permanent and invisible.+ *+ * THE FIX, and why it can only ever help: the read falls back from the advertised dir to+ * `<dir of the endpoint file>/node-tokens` — which is the layout BY CONSTRUCTION on all three+ * surfaces (`<userData>/hook-endpoint.env` + `<userData>/node-tokens` on desktop and Server+ * Edition, `<home>/.nodeterm/hook-endpoint-<p>.env` + `<home>/.nodeterm/node-tokens` on an SSH+ * host) — and then to the same well-known data dirs the managed script already walks for endpoint+ * files.+ *+ * It is monotone, and that is the whole safety argument:+ *+ * - the ADVERTISED dir is always tried first, so nothing that verifies today stops verifying;+ * - the lookup is by `$NODETERM_NODE_ID` FILENAME in every candidate, so a session can still only+ * ever present its own node's token — the property `never presents ANOTHER node's token file`+ * is a property of the key, not of the directory;+ * - a dir belonging to a DIFFERENT instance mints under a different secret, so its token carries a+ * foreign `kid`, which `verifyNodeToken` reads as `legacy` — bit-for-bit what presenting nothing+ * already gave. It can never read as `forged` (that needs OUR kid over another node's mac, and+ * the filename forbids it) and it can never read as a different node.+ *+ * So each candidate can turn `legacy` into `verified` and nothing else. The happy path costs+ * exactly one `head`, as before: only a miss walks.+ *+ * NOT USED BY the codex launcher (`core/codex-identity-proxy.ts`), deliberately. That client+ * REFUSES outright when the endpoint file is unreadable (`nt_fail hook-endpoint-unavailable`) and+ * degrades to plain codex with a named reason, which is a different and already-honest contract;+ * folding it in here would change what it reports, not just what it reads. Its read is one line+ * beside a `case` gate on the wire shape — if it ever grows a fallback, it grows THIS one.+ */++/**+ * Defines `nt_read_node_token [endpoint-file]`, which sets `nt_node_token` to this node's+ * capability or to '' when there is none to present. Never fails: '' is an ordinary state (a+ * pre-token session, a remote write that did not land) that the server reads as `legacy`, and a+ * hook client must not be able to die over identity.+ *+ * The optional argument is for the managed script's failover, which must anchor the derivation to+ * the endpoint it JUST ADOPTED rather than to the primary it is walking away from. Omitted, it+ * anchors to `$NODETERM_HOOK_ENDPOINT`.+ */+export const NODE_TOKEN_READ_SH = [+ '# `<dir of $1>/node-tokens`, or nothing when $1 names no directory. The endpoint file and the',+ '# token dir are siblings on every surface we ship, so this needs no per-platform knowledge.',+ 'nt_token_dir_beside() {',+ ' case "$1" in */*) ;; *) return 0 ;; esac',+ ' nt_tdb=${1%/*}',+ ' [ -n "$nt_tdb" ] || return 0',+ " printf '%s/node-tokens' \"$nt_tdb\"",+ '}',+ '# nt_read_node_token [endpoint-file] — sets $nt_node_token. See node-token-sh.ts for why the',+ '# fallbacks below can only ever turn `legacy` into `verified`, and never anything into anything',+ '# worse. The lookup is by node-id FILENAME in every candidate, so a session can only ever',+ '# present its OWN token however many directories are searched.',+ 'nt_read_node_token() {',+ ' nt_node_token=""',+ ' [ -n "$NODETERM_NODE_ID" ] || return 0',+ ' nt_ntep="$1"',+ ' [ -n "$nt_ntep" ] || nt_ntep="$NODETERM_HOOK_ENDPOINT"',+ ' for nt_ntd in \\',+ ' "$NODETERM_NODE_TOKEN_DIR" \\',+ ' "$(nt_token_dir_beside "$nt_ntep")" \\',+ ' "$HOME/.nodeterm/node-tokens" \\',+ ' "$HOME/.nodeterm-server/node-tokens" \\',+ ' "$HOME/.config/node-terminal/node-tokens" \\',+ ' "$HOME/Library/Application Support/node-terminal/node-tokens"; do',+ ' [ -n "$nt_ntd" ] || continue',+ ' nt_node_token=$(head -n 1 "$nt_ntd/$NODETERM_NODE_ID" 2>/dev/null) || nt_node_token=""',+ ' [ -n "$nt_node_token" ] && return 0',+ ' done',+ ' nt_node_token=""',+ ' return 0',+ '}'+].join('\n')diff --git a/src/core/context-link-core.test.ts b/src/core/context-link-core.test.tsindex f3df00fa1..2daca8e88 100644--- a/src/core/context-link-core.test.ts+++ b/src/core/context-link-core.test.ts@@ -227,3 +227,33 @@ describe('buildLinkedContextInstructions', () => {expect(CONTEXT_SHIM_SCRIPT).toContain(`echo "${CONTEXT_UNREACHABLE_MSG}" >&2`)})})++// The context-link shim is generated source that no compiler ever checks, and it is the only+// context-link client. A quoting or `for`-list slip in it fails silently on the user's machine —+// and, for an SSH project, on a machine we cannot inspect. `sh -n` is the cheap half of the+// discipline the canvas-control shim gets in full (canvas-control-shim.test.ts runs that one for+// real); the two share `nt_read_node_token`, so the behaviour is covered there.+describe('the context-link shim', () => {+ it('is valid POSIX sh', async () => {+ const { execFile } = await import('node:child_process')+ const { promisify } = await import('node:util')+ const fs = await import('node:fs')+ const os = await import('node:os')+ const path = await import('node:path')+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-context-shim-'))+ const file = path.join(dir, 'context.sh')+ fs.writeFileSync(file, CONTEXT_SHIM_SCRIPT, { mode: 0o755 })+ try {+ await expect(promisify(execFile)('/bin/sh', ['-n', file])).resolves.toBeTruthy()+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })++ it('resolves the per-node token through the one shared reader (#384)', () => {+ // Not a second copy of `head -n 1 "$NODETERM_NODE_TOKEN_DIR/…"`: that copy is what left a+ // session pinned to a pre-v2 endpoint file presenting nothing for its whole life.+ expect(CONTEXT_SHIM_SCRIPT).toContain('nt_read_node_token')+ expect(CONTEXT_SHIM_SCRIPT).not.toContain('nt_node_token=$(head -n 1 "$NODETERM_NODE_TOKEN_DIR')+ })+})diff --git a/src/core/context-link-core.ts b/src/core/context-link-core.tsindex d7e04e2d2..99423f2ae 100644--- a/src/core/context-link-core.ts+++ b/src/core/context-link-core.ts@@ -5,6 +5,7 @@ import type { ContextLinkInfo } from '../shared/types'import { sessionName } from './tmux-naming'import { HOOK_CURL_HEADERS_SH } from './agents/hook-curl-config-sh'import { CODEX_SANDBOX_BLOCKED_LINE, CODEX_SANDBOX_HINT_SH } from './agents/hook-sandbox-hint-sh'+import { NODE_TOKEN_READ_SH } from './agents/node-token-sh'/** The shim's generic transport-failure sentence — exported so the agent-facing docs below can* quote it verbatim and the parity test holds the two ends together. */@@ -183,14 +184,13 @@ if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then. "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || :fi-# The PER-NODE capability: the endpoint file (v2) advertises the directory, the token is one file-# in it named for THIS node id — a lookup by name, never a scan, so a session can only ever present-# its own. Missing (pre-v2 endpoint, a node whose token was never materialised) leaves it empty,-# which the server reads as legacy — the request still goes, exactly as before.-nt_node_token=""-if [ -n "$NODETERM_NODE_TOKEN_DIR" ] && [ -n "$NODETERM_NODE_ID" ]; then- nt_node_token=$(head -n 1 "$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID" 2>/dev/null)-fi+# The PER-NODE capability, resolved by the one shared reader (see node-token-sh.ts): the token is+# one file named for THIS node id — a lookup by name, never a scan, so a session can only ever+# present its own. The endpoint file (v2) advertises the directory; when it does not — a pinned+# pre-v2 endpoint that is still live, a session whose transport came from the env — the resolver+# falls back to the standard locations rather than reading as \`legacy\` forever (issue #384).+${NODE_TOKEN_READ_SH}+nt_read_node_token${HOOK_CURL_HEADERS_SH}diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.tsindex 9f89bc037..1d20b107d 100644--- a/src/main/canvas-control-core.ts+++ b/src/main/canvas-control-core.ts@@ -4,6 +4,7 @@import { HOOK_CURL_HEADERS_SH } from '../core/agents/hook-curl-config-sh'import { CODEX_SANDBOX_HINT_SH } from '../core/agents/hook-sandbox-hint-sh'import { codexSandboxGuidanceLines } from '../core/context-link-core'+import { NODE_TOKEN_READ_SH } from '../core/agents/node-token-sh'import { AGENT_CONFIG, AGENT_HOOK_TARGETS, BUILTIN_AGENT_IDS } from '@shared/agents/config'import { RETRYABLE } from '../core/agents/agent-message-decide'import { FANOUT_PER_TURN, PAIR_MIN_INTERVAL_MS } from '../core/agents/agent-message-flow'@@ -426,14 +427,15 @@ if [ -n "$NODETERM_HOOK_ENDPOINT" ] && [ -r "$NODETERM_HOOK_ENDPOINT" ]; then. "$NODETERM_HOOK_ENDPOINT" 2>/dev/null || :fi-# The PER-NODE capability: the endpoint file (v2) advertises the directory, the token is one file-# in it named for THIS node id — a lookup by name, never a scan, so a session can only ever present-# its own. Missing (pre-v2 endpoint, a node whose token was never materialised) leaves it empty,-# which the server reads as legacy — the request still goes, exactly as before.-nt_node_token=""-if [ -n "$NODETERM_NODE_TOKEN_DIR" ] && [ -n "$NODETERM_NODE_ID" ]; then- nt_node_token=$(head -n 1 "$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID" 2>/dev/null)-fi+# The PER-NODE capability: the token is one file named for THIS node id — a lookup by name, never+# a scan, so a session can only ever present its own. The endpoint file (v2) advertises the+# directory; the resolver falls back to the standard locations when it does not, because a session+# is pinned for life to the endpoint PATH it was handed at tmux creation and an old file that is+# still live advertises none. That was issue #384: the node proved itself through the hook script+# (which fails over) and was then refused here, permanently, by the trust-on-first-proof latch.+# Missing everywhere leaves it empty, which the server reads as legacy — the request still goes.+${NODE_TOKEN_READ_SH}+nt_read_node_token${HOOK_CURL_HEADERS_SH}diff --git a/src/main/canvas-control-shim.test.ts b/src/main/canvas-control-shim.test.tsindex ae21f6427..cb0bea9d3 100644--- a/src/main/canvas-control-shim.test.ts+++ b/src/main/canvas-control-shim.test.ts@@ -19,7 +19,7 @@ const run = promisify(execFile)let dir = ''let shim = ''-let received: { verb: string; nodeId: string; args: Record<string, string> }[] = []+let received: { verb: string; nodeId: string; args: Record<string, string>; verified?: boolean }[] = []beforeAll(async () => {dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-shim-'))@@ -368,6 +368,71 @@ describe('canvas-control shim presents the per-node token', () => {})expect(seen).toEqual([{ path: '/control/list', nodeToken: '' }])})++ // ISSUE #384. The dir is advertised ONLY by the endpoint file, and a session is pinned for life+ // to the endpoint PATH it was handed at tmux creation — so an endpoint file that is still LIVE+ // but advertises no dir (SSH hosts used to share one `~/.nodeterm/hook-endpoint.env`, and the+ // per-project socket path it names is RE-BOUND on every connect) left the shim presenting nothing+ // for the life of the session. Reproduced against a real host before this test existed: the same+ // node proved itself through the managed hook script — which fails over and re-reads the token+ // from the endpoint it adopts — and was then refused here by the trust-on-first-proof latch.+ it('finds it BESIDE the endpoint file when the file advertises no dir (#384)', async () => {+ seen.length = 0+ const home = path.join(dir, 'pinned-home')+ const data = path.join(home, '.nodeterm')+ fs.mkdirSync(path.join(data, 'node-tokens'), { recursive: true })+ fs.writeFileSync(path.join(data, 'node-tokens', 'node-1'), 'BESIDE-TOKEN\n', { mode: 0o600 })+ const endpoint = path.join(data, 'hook-endpoint-oldproject.env')+ // A pre-v2 endpoint file: transport + bearer, no NODETERM_NODE_TOKEN_DIR line at all.+ fs.writeFileSync(endpoint, `NODETERM_HOOK_PORT=${tcpPort}\nNODETERM_HOOK_TOKEN=whatever\nNODETERM_HOOK_VERSION=1\n`)+ await callShim(['list'], {+ HOME: home,+ NODETERM_HOOK_PORT: '',+ NODETERM_HOOK_TOKEN: '',+ NODETERM_HOOK_ENDPOINT: endpoint+ })+ expect(seen).toEqual([{ path: '/control/list', nodeToken: 'BESIDE-TOKEN' }])+ })++ it('finds it in the standard data dir when there is no readable endpoint file at all', async () => {+ // The shape the phone hands a session it spawns: the transport rides the env and+ // NODETERM_HOOK_ENDPOINT is empty (no host process existed at spawn), so nothing ever+ // advertises a dir and there is no endpoint path to derive one from either.+ seen.length = 0+ const home = path.join(dir, 'phone-home')+ fs.mkdirSync(path.join(home, '.nodeterm', 'node-tokens'), { recursive: true })+ fs.writeFileSync(path.join(home, '.nodeterm', 'node-tokens', 'node-1'), 'HOME-TOKEN\n', { mode: 0o600 })+ await callShim(['list'], {+ HOME: home,+ NODETERM_HOOK_PORT: String(tcpPort),+ NODETERM_HOOK_ENDPOINT: ''+ })+ expect(seen).toEqual([{ path: '/control/list', nodeToken: 'HOME-TOKEN' }])+ })++ it('still prefers the ADVERTISED dir — a fallback can only fill a gap, never override', async () => {+ // The monotonicity claim in node-token-sh.ts made observable: nothing that verifies today may+ // start reading out of a different directory because a fallback exists.+ seen.length = 0+ const home = path.join(dir, 'both-home')+ fs.mkdirSync(path.join(home, '.nodeterm', 'node-tokens'), { recursive: true })+ fs.writeFileSync(path.join(home, '.nodeterm', 'node-tokens', 'node-1'), 'FALLBACK-TOKEN\n', { mode: 0o600 })+ await callShim(['list'], {+ HOME: home,+ NODETERM_HOOK_PORT: String(tcpPort),+ NODETERM_NODE_TOKEN_DIR: tokenDir+ })+ expect(seen).toEqual([{ path: '/control/list', nodeToken: 'CANVAS-NODE-TOKEN' }])+ })++ it('is keyed by node id in EVERY candidate, not only the advertised one', async () => {+ seen.length = 0+ const home = path.join(dir, 'other-home')+ fs.mkdirSync(path.join(home, '.nodeterm', 'node-tokens'), { recursive: true })+ fs.writeFileSync(path.join(home, '.nodeterm', 'node-tokens', 'node-9'), 'NODE-9-TOKEN\n', { mode: 0o600 })+ await callShim(['list'], { HOME: home, NODETERM_HOOK_PORT: String(tcpPort) })+ expect(seen).toEqual([{ path: '/control/list', nodeToken: '' }])+ })})// A command line is not private: `ps` and /proc/<pid>/cmdline are world-readable, so `curl -H@@ -675,3 +740,64 @@ describe('sticky through the shim (verified-only verb)', () => {expect(received.length).toBe(before)})})++// ISSUE #384, END TO END, through the real policy. The latch ("trust on first proof") refuses a+// node that HAS authenticated the moment a caller naming it cannot — immediately, on both sides of+// the dated cutoff — and `IDENTITY_REFUSED_NOTE` is the sentence the issue is titled after.+//+// The two halves only meet because the clients disagreed: the managed hook script fails over to a+// live sibling endpoint and re-reads the token from ITS dir, so the node proves itself; the shim+// had no failover and no fallback, so on a session pinned to an endpoint file that advertises no+// token dir it presented nothing for the rest of that session's life. Proven by one client,+// refused through the other, with "Restart agent" as the only advice — and an in-place agent+// restart re-launches the CLI in the same pane, with the same environment and the same endpoint+// file, so it could never have helped.+describe('a latched node is not refused just because its endpoint advertises no dir (#384)', () => {+ const SECRET = Buffer.alloc(32, 11)+ let home = ''+ let tokens = ''+ let pinned = ''++ beforeAll(() => {+ hookServer.setNodeAuthSecret(SECRET)+ hookServer.forgetProvenNode('node-1') // earlier describes share the id; start from unlatched+ home = path.join(dir, 'latched-home')+ tokens = path.join(home, '.nodeterm', 'node-tokens')+ fs.mkdirSync(tokens, { recursive: true })+ fs.writeFileSync(path.join(tokens, 'node-1'), `${nodeAuthToken(SECRET, 'node-1')}\n`, { mode: 0o600 })+ // The pinned endpoint: a LIVE transport (the per-project socket path is re-bound on every+ // connect, so an old file keeps reaching a current server) and no NODETERM_NODE_TOKEN_DIR line.+ pinned = path.join(home, '.nodeterm', 'hook-endpoint-oldproject.env')+ fs.writeFileSync(+ pinned,+ `NODETERM_HOOK_PORT=${hookServer.getPort()}\nNODETERM_HOOK_TOKEN=${hookServer.getToken()}\nNODETERM_HOOK_VERSION=1\n`+ )+ })++ afterAll(() => {+ hookServer.clearNodeAuthSecretForTests()+ hookServer.forgetProvenNode('node-1')+ })++ it('latches the node on its first verified call', async () => {+ expect(hookServer.isNodeProven('node-1')).toBe(false)+ await callShim(['list'], { HOME: home, NODETERM_NODE_TOKEN_DIR: tokens })+ expect(hookServer.isNodeProven('node-1')).toBe(true)+ })++ it('then still runs a mutation through the pinned endpoint, verified', async () => {+ const before = received.length+ const { stdout } = await callShim(['open-terminal'], {+ HOME: home,+ NODETERM_HOOK_PORT: '',+ NODETERM_HOOK_TOKEN: '',+ NODETERM_HOOK_ENDPOINT: pinned+ })+ // The exact string the issue is titled after, and the warning-window one beside it.+ expect(stdout).not.toContain('not presenting its node identity')+ expect(stdout.trim()).toBe('did open-terminal')+ expect(received.length).toBe(before + 1)+ // Not merely tolerated — actually identified, which is what the latch was protecting.+ expect(received.at(-1)?.verified).toBe(true)+ })+})