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
feat(messaging): the pure decider and a 16-outcome typed result
Claude Code4437c99eb26b
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.tsindex 5191eb9af..3d968287b 100644--- a/src/core/agent-status-mirror.test.ts+++ b/src/core/agent-status-mirror.test.ts@@ -1620,6 +1620,35 @@ describe('idle_prompt rescue (Esc that ran no Stop hook)', () => {expect(next.state).toBe('done')expect(next.updatedAt).toBe(1000)})++ it('marks the RESCUED done as inferred, so a consumer can tell it from a turn end', () => {+ // A node blocked on an approval is also "idle at its prompt". Messaging's gate 2 refuses this+ // shape, and it can only refuse what the entry remembers.+ const working = reduceEntry(undefined, ev({ state: 'working' }), 1000)+ const rescued = reduceEntry(working, ev({ state: 'done', idle: true }), 2000)+ expect(rescued).toMatchObject({ state: 'done', idleInferred: true })+ const genuine = reduceEntry(undefined, ev({ state: 'done' }), 1000)+ expect(genuine.idleInferred).toBeUndefined()+ })++ it('a later genuine turn-end CLEARS the marker — it describes the current state only', () => {+ const working = reduceEntry(undefined, ev({ state: 'working' }), 1000)+ const rescued = reduceEntry(working, ev({ state: 'done', idle: true }), 2000)+ expect(rescued.idleInferred).toBe(true)+ const nextTurn = reduceEntry(rescued, ev({ state: 'working', newTurn: true }), 3000)+ expect(nextTurn.idleInferred).toBeUndefined()+ const ended = reduceEntry(nextTurn, ev({ state: 'done' }), 4000)+ expect(ended.idleInferred).toBeUndefined()+ })++ it('an idle event that commits NOTHING leaves the marker alone', () => {+ // The rescue may only move a node that is still `working`; on a blocked node it returns early+ // and must not stamp a state it did not commit.+ const blocked = reduceEntry(undefined, ev({ state: 'blocked' }), 1000)+ const next = reduceEntry(blocked, ev({ state: 'done', idle: true }), 2000)+ expect(next.state).toBe('blocked')+ expect(next.idleInferred).toBeUndefined()+ })})diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex e93f4855b..d7ece2f6b 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -95,6 +95,22 @@ export interface MirrorEntry {* safest. Cleared by the first live event.*/restored?: true+ /**+ * The CURRENT `done` was inferred from the CLI going idle at its prompt (Claude's `idle_prompt`+ * notification, `normalize.ts` `idle`), not from a turn-end hook.+ *+ * `normalize.ts` already calls that a RESCUE signal, and `reduceEntry` already honours it as one+ * — it may only move a node that is still `working`. What was missing is that the resulting entry+ * did not remember WHICH kind of `done` it holds, so a consumer downstream could not tell a turn+ * that ended from a CLI that merely went quiet. Gate 2 of agent messaging is the consumer that+ * must: a node blocked on an approval is also "idle at its prompt", and delivering into it is+ * delivering into a modal. `Canvas.tsx` already discards the idle rescue for an `undefined` node+ * for the same reason; messaging must not be the one consumer that trusts it.+ *+ * Written on the SAME edge as `state`/`stateVerified` (inside `commitState`), so it can never+ * describe a state it did not arrive with.+ */+ idleInferred?: true}/** This host's Server-Edition install metadata (spec: server-update). Written by the installer@@ -365,6 +381,11 @@ export function reduceEntry(next.stateVerified = proofif (proof) next.verifiedAt = nownext.clientRevision = ev.clientRevision+ // Which KIND of `done` this is, recorded on the same edge as the state itself. `idle` is only+ // ever meaningful on a `done`; assigning (not merging) is the point — a later, genuine turn-end+ // `done` must clear the marker, or a node would stay tainted for the rest of its session.+ if (state === 'done' && ev.idle) next.idleInferred = true+ else delete next.idleInferred// The entry's STATE now comes from this run, so it is no longer the one restored off disk.// Cleared HERE and only here: an event that commits no state — a context/usage event, a// held-off late `working`, the idle rescue — leaves a restored `done` exactly as restored asdiff --git a/src/core/agents/agent-message-decide.test.ts b/src/core/agents/agent-message-decide.test.tsnew file mode 100644index 000000000..2d05aeb43--- /dev/null+++ b/src/core/agents/agent-message-decide.test.ts@@ -0,0 +1,283 @@+import { describe, it, expect } from 'vitest'+import {+ decideDelivery,+ type AgentMessageOutcome,+ type Proceed,+ DECISION_ORDER,+ RETRYABLE,+ NO_TOKEN_FILE_NOTE,+ type AgentMessageOutcomeKind,+ type DeliveryFacts+} from './agent-message-decide'+import { MANAGED_SCRIPT_REVISION, MIN_TOKEN_AWARE_REVISION } from './hooks/managed-script'+import type { MirrorEntry } from '../agent-status-mirror'++/** `RETRYABLE` for a decision, once it is established that the decision is a refusal. */+const retryable = (o: AgentMessageOutcome | Proceed): boolean => {+ expect(o.kind).not.toBe('proceed')+ return RETRYABLE[o.kind as AgentMessageOutcomeKind]+}++/** A verified, idle, current-script target: every gate passing. */+const readyEntry = (over: Partial<MirrorEntry> = {}): MirrorEntry => ({+ state: 'done',+ updatedAt: 1000,+ stateVerified: true,+ clientRevision: MANAGED_SCRIPT_REVISION,+ ...over+})++const ready = (over: Partial<DeliveryFacts> = {}): DeliveryFacts => ({+ targetLive: true,+ pane: 'agent',+ target: readyEntry(),+ tokenFilePresent: true,+ pasteAware: true,+ ...over+})++describe('decideDelivery — the happy path', () => {+ it('proceeds when every gate passes', () => {+ expect(decideDelivery(ready()).kind).toBe('proceed')+ })+})++describe('decideDelivery — one case per refusal', () => {+ it.each(['switch-off', 'cross-project', 'self-send', 'unsupported-edition'] as const)(+ 'notPermitted carries the reason %s',+ (reason) => {+ const o = decideDelivery(ready({ notPermitted: reason }))+ expect(o).toEqual({ kind: 'notPermitted', reason })+ expect(retryable(o)).toBe(false)+ }+ )++ it('rateLimited says when, and is retryable', () => {+ const o = decideDelivery(ready({ retryAfterMs: 1500 }))+ expect(o).toEqual({ kind: 'rateLimited', retryAfterMs: 1500 })+ expect(retryable(o)).toBe(true)+ })++ it('a zero/absent retryAfterMs is not a rate limit', () => {+ expect(decideDelivery(ready({ retryAfterMs: 0 })).kind).toBe('proceed')+ })++ it('targetGone when there is no live session', () => {+ expect(decideDelivery(ready({ targetLive: false })).kind).toBe('targetGone')+ })++ it('targetNotAgentPane on a kernel NO, naming what was observed', () => {+ const o = decideDelivery(ready({ pane: 'not-agent', paneObserved: 'zsh' }))+ expect(o).toEqual({ kind: 'targetNotAgentPane', observed: 'zsh' })+ expect(retryable(o)).toBe(false)+ })++ it('targetNotAgentPane on an UNKNOWN pane too — an unreadable pane is never admitted', () => {+ // `unknown` is not a shade of `not-agent` for the predicate, but for DELIVERY both refuse:+ // the one thing neither may do is write into a pane we could not read.+ expect(decideDelivery(ready({ pane: 'unknown' }))).toEqual({+ kind: 'targetNotAgentPane',+ observed: 'unknown'+ })+ })++ it.each(['working', 'waiting', 'blocked'] as const)('targetBusy for state %s, retryable', (state) => {+ const o = decideDelivery(ready({ target: readyEntry({ state }) }))+ expect(o).toEqual({ kind: 'targetBusy', state })+ expect(retryable(o)).toBe(true)+ })++ it('targetNotIdleUnknown when the node has never posted', () => {+ const o = decideDelivery(ready({ target: undefined, tokenFilePresent: true }))+ // …but only once its identity question is answered: an unposted node is `targetStatusStale`+ // first, because that is the more permanent fact. Verified-and-absent cannot happen, so the+ // never-posted branch of gate 2 is reached through a target that HAS proof for a cleared state.+ expect(o.kind).toBe('targetStatusStale')+ expect(decideDelivery(ready({ target: readyEntry({ state: undefined }) }))).toEqual({+ kind: 'targetNotIdleUnknown',+ reason: 'the node is between sessions (no current state)'+ })+ })++ it('targetNotIdleUnknown for a RESTORED entry — 6-hour-old evidence is not evidence', () => {+ const o = decideDelivery(+ ready({ target: readyEntry({ restored: true, stateVerified: true }) })+ )+ expect(o.kind).toBe('targetNotIdleUnknown')+ expect((o as { reason: string }).reason).toMatch(/restored from disk/i)+ })++ it('targetNotIdleUnknown for a `done` inferred from idle_prompt', () => {+ // A node blocked on an approval is ALSO idle at its prompt. Canvas.tsx already discards the+ // idle rescue for an `undefined` node; messaging must not be the one consumer that trusts it.+ const o = decideDelivery(ready({ target: readyEntry({ idleInferred: true }) }))+ expect(o.kind).toBe('targetNotIdleUnknown')+ expect((o as { reason: string }).reason).toMatch(/idle at its prompt/i)+ })++ it('targetNotPasteAware is decided LAST, and only when explicitly probed false', () => {+ expect(decideDelivery(ready({ pasteAware: false })).kind).toBe('targetNotPasteAware')+ // undefined means "not probed yet" (the probe is a second round-trip, paid only after the+ // gate passes), not "no".+ expect(decideDelivery(ready({ pasteAware: undefined })).kind).toBe('proceed')+ })+})++describe('the THREE unverified refusals — Correction C1 + Finding F2', () => {+ const unverified = (over: Partial<MirrorEntry> = {}): MirrorEntry =>+ readyEntry({ stateVerified: false, ...over })++ it('an OLD hook script is named as such, and is NOT retryable', () => {+ // The trap this closes: the token file IS present here, so a token-file check alone would say+ // "retry after its next turn", and it would never clear because the script cannot read the file.+ const o = decideDelivery(ready({ target: unverified({ clientRevision: 2 }), tokenFilePresent: true }))+ expect(o.kind).toBe('targetHookScriptStale')+ expect(retryable(o)).toBe(false)+ expect((o as { note: string }).note).toMatch(/reconnect|restart/i)+ expect((o as { observedRevision?: number }).observedRevision).toBe(2)+ })++ it('an ABSENT client stamp is treated as an old script, not as a current one', () => {+ const o = decideDelivery(+ ready({ target: unverified({ clientRevision: undefined }), tokenFilePresent: true })+ )+ expect(o.kind).toBe('targetHookScriptStale')+ expect((o as { observedRevision?: number }).observedRevision).toBeUndefined()+ })++ it('the note names the action for the SURFACE the target is on', () => {+ const local = decideDelivery(+ ready({ target: unverified({ clientRevision: 2 }), tokenFilePresent: true, targetIsRemote: false })+ )+ const remote = decideDelivery(+ ready({ target: unverified({ clientRevision: 2 }), tokenFilePresent: true, targetIsRemote: true })+ )+ expect((local as { note: string }).note).toMatch(/restart the nodeterm app/i)+ expect((remote as { note: string }).note).toMatch(/reconnect the SSH project/i)+ })++ it('a CURRENT script with a token file but no verified event yet is RETRYABLE', () => {+ const o = decideDelivery(+ ready({ target: unverified({ clientRevision: MANAGED_SCRIPT_REVISION }), tokenFilePresent: true })+ )+ expect(o).toEqual({ kind: 'targetStatusStale' })+ expect(retryable(o)).toBe(true)+ })++ it('a current script with NO token file is not retryable and says what to do', () => {+ const o = decideDelivery(+ ready({ target: unverified({ clientRevision: MANAGED_SCRIPT_REVISION }), tokenFilePresent: false })+ )+ expect(o.kind).toBe('targetStatusUnverified')+ expect(retryable(o)).toBe(false)+ expect((o as { note: string }).note).toBe(NO_TOKEN_FILE_NOTE)+ expect((o as { note: string }).note).toMatch(/relaunch|open its project/i)+ })++ it('script staleness is decided BEFORE token presence — the script is the outer cause', () => {+ // Both wrong at once: report the one whose fix unblocks the other.+ expect(+ decideDelivery(ready({ target: unverified({ clientRevision: 2 }), tokenFilePresent: false })).kind+ ).toBe('targetHookScriptStale')+ })++ it('exactly MIN_TOKEN_AWARE_REVISION is current, one below it is stale', () => {+ const at = decideDelivery(+ ready({ target: unverified({ clientRevision: MIN_TOKEN_AWARE_REVISION }), tokenFilePresent: true })+ )+ const below = decideDelivery(+ ready({ target: unverified({ clientRevision: MIN_TOKEN_AWARE_REVISION - 1 }), tokenFilePresent: true })+ )+ expect(at.kind).toBe('targetStatusStale')+ expect(below.kind).toBe('targetHookScriptStale')+ })++ it('a NEVER-POSTED node is not accused of running an old script', () => {+ // No observation ⇒ no evidence about its script. It falls through to the answerable question.+ expect(decideDelivery(ready({ target: undefined, tokenFilePresent: true })).kind).toBe(+ 'targetStatusStale'+ )+ expect(decideDelivery(ready({ target: undefined, tokenFilePresent: false })).kind).toBe(+ 'targetStatusUnverified'+ )+ })++ it('a RESTORED entry is not accused of running an old script either', () => {+ // `buildFile` never persists clientRevision, so a restored entry has none — accusing it would+ // be an accusation with no evidence behind it.+ expect(+ decideDelivery(ready({ target: unverified({ restored: true, clientRevision: undefined }), tokenFilePresent: true }))+ .kind+ ).toBe('targetStatusStale')+ })+})++describe('the decision ORDER is load-bearing', () => {+ it('walks DECISION_ORDER as each gate is cleared, one at a time', () => {+ // Start with EVERY gate failing, then clear exactly the gate that was just reported and assert+ // the next reason is the next entry in DECISION_ORDER. Asserted by RUNNING the decider — no+ // source text is matched anywhere in this file.+ let f: DeliveryFacts = {+ notPermitted: 'switch-off',+ retryAfterMs: 5000,+ targetLive: false,+ pane: 'unknown',+ target: { state: 'working', updatedAt: 0, stateVerified: false, clientRevision: 1 },+ tokenFilePresent: false,+ pasteAware: false+ }+ const clears: Array<(prev: DeliveryFacts) => DeliveryFacts> = [+ (p) => ({ ...p, notPermitted: undefined }),+ (p) => ({ ...p, retryAfterMs: undefined }),+ (p) => ({ ...p, targetLive: true }),+ (p) => ({ ...p, pane: 'agent' }),+ (p) => ({ ...p, target: { ...p.target!, clientRevision: MANAGED_SCRIPT_REVISION } }),+ (p) => ({ ...p, tokenFilePresent: true }),+ (p) => ({ ...p, target: { ...p.target!, stateVerified: true, state: undefined } }),+ (p) => ({ ...p, target: { ...p.target!, state: 'working' } }),+ (p) => ({ ...p, target: { ...p.target!, state: 'done' } }),+ (p) => ({ ...p, pasteAware: true })+ ]+ const walked: string[] = []+ for (const clear of clears) {+ walked.push(decideDelivery(f).kind)+ f = clear(f)+ }+ expect(walked).toEqual([...DECISION_ORDER])+ expect(decideDelivery(f).kind).toBe('proceed')+ })++ it('every reason in DECISION_ORDER is a real outcome kind with a RETRYABLE entry', () => {+ for (const kind of DECISION_ORDER) expect(typeof RETRYABLE[kind]).toBe('boolean')+ })+})++describe('RETRYABLE', () => {+ it('answers for every outcome kind the union declares', () => {+ // Runtime half. The compile-time half is below and is enforced by `npm run typecheck`.+ const kinds = Object.keys(RETRYABLE) as AgentMessageOutcomeKind[]+ expect(kinds.length).toBe(16)+ for (const k of kinds) expect(typeof RETRYABLE[k]).toBe('boolean')+ })++ it('a missing key is a COMPILE error, not a runtime undefined that reads as "do not retry"', () => {+ const { delivered: _delivered, ...incomplete } = RETRYABLE+ // @ts-expect-error — `delivered` is missing, and Record<Kind, boolean> refuses it. If this+ // line ever stops erroring, the exhaustiveness guarantee has been lost.+ const table: Record<AgentMessageOutcomeKind, boolean> = incomplete+ expect(table).toBeDefined()+ })++ it('the permanent refusals say NOT retryable and the transient ones say retryable', () => {+ expect(RETRYABLE.targetStatusUnverified).toBe(false)+ expect(RETRYABLE.targetHookScriptStale).toBe(false)+ expect(RETRYABLE.targetNotAgentPane).toBe(false)+ expect(RETRYABLE.targetNotPasteAware).toBe(false)+ expect(RETRYABLE.targetGone).toBe(false)+ expect(RETRYABLE.notPermitted).toBe(false)+ expect(RETRYABLE.targetStatusStale).toBe(true)+ expect(RETRYABLE.targetBusy).toBe(true)+ expect(RETRYABLE.targetNotIdleUnknown).toBe(true)+ expect(RETRYABLE.rateLimited).toBe(true)+ })+})diff --git a/src/core/agents/agent-message-decide.ts b/src/core/agents/agent-message-decide.tsnew file mode 100644index 000000000..508b016ce--- /dev/null+++ b/src/core/agents/agent-message-decide.ts@@ -0,0 +1,310 @@+import type { MirrorEntry } from '../agent-status-mirror'+import type { AgentPaneVerdict } from '../../shared/agents/pane-owner-predicate'+import { MIN_TOKEN_AWARE_REVISION } from './hooks/managed-script'++/**+ * THE PURE DECIDER — every reason a delivery may not happen, decided without a single side effect.+ *+ * The control surface is a boolean all the way down today: `sendText` returns `Promise<boolean>`,+ * the handler turns it into `{ ok, 'sent' | 'failed' }`, the route into 200/400, the shim into+ * exit 1. The caller here is a LANGUAGE MODEL, and an agent that cannot tell "not allowed" from+ * "target busy" retries the wrong one — with a per-pair rate limiter in front of it (PR 4), that is+ * a busy-loop that burns tokens and produces nothing.+ *+ * So the result is a discriminated union, and whether to retry is DATA (`RETRYABLE`), not prose.+ *+ * Nothing in this module reads the clock, the filesystem, a pane or a socket. Every fact arrives in+ * `DeliveryFacts`, which is what lets Task 3.3 test the sequencing without a pty and this file test+ * the policy without either.+ */++export type NotPermittedReason = 'switch-off' | 'cross-project' | 'self-send' | 'unsupported-edition'++/** Which signal satisfied the delivery receipt (Task 3.4). */+export type ReceiptSignal = 'newTurn' | 'working'++/** Where a delivery's trace landed. `memory` is a bounded ring, not a durable log — see Task 3.5. */+export type TraceKind = 'board-log' | 'memory'++export type AgentMessageOutcome =+ | { kind: 'delivered'; traceId: string; traced: TraceKind; receipt: 'observed'; signal: ReceiptSignal }+ | { kind: 'queued'; traceId: string; position: number; ttlMs: number }+ | { kind: 'stalled'; traceId: string; traced: TraceKind; waitedMs: number }+ | {+ kind: 'deliveredToReplacedTarget'+ traceId: string+ traced: TraceKind+ wasPane: string+ nowPane: string+ }+ | { kind: 'expired'; traceId: string; queuedForMs: number }+ | { kind: 'rateLimited'; retryAfterMs: number }+ | { kind: 'queueFull'; capacity: number }+ | { kind: 'targetBusy'; state: string }+ | { kind: 'targetNotIdleUnknown'; reason: string }+ | { kind: 'targetStatusUnverified'; note: string } // no token file — needs a human. NOT retryable.+ | { kind: 'targetStatusStale' } // token file exists, no verified event yet. Retryable.+ | { kind: 'targetHookScriptStale'; note: string; observedRevision?: number } // Finding F2. NOT retryable.+ | { kind: 'targetNotAgentPane'; observed: string }+ | { kind: 'targetNotPasteAware' }+ | { kind: 'targetGone' }+ | { kind: 'notPermitted'; reason: NotPermittedReason }++export type AgentMessageOutcomeKind = AgentMessageOutcome['kind']++/**+ * The retry column, as data.+ *+ * The caller is a LANGUAGE MODEL: an outcome that is not retryable must SAY so, or it will try+ * again — and with a per-pair rate limiter in front of it, "try again" on a permanent refusal is a+ * busy-loop that burns tokens and produces nothing. A boolean return could not carry this, which is+ * the whole reason the surface stopped being a boolean.+ *+ * `Record<AgentMessageOutcomeKind, boolean>` makes the table exhaustive BY THE TYPE: a new union+ * member that is not listed here is a compile error, not a runtime `undefined` that reads as+ * "not retryable" and silently strands a whole class of caller.+ */+export const RETRYABLE: Record<AgentMessageOutcomeKind, boolean> = {+ delivered: false,+ queued: false,+ stalled: false,+ deliveredToReplacedTarget: false,+ expired: true,+ rateLimited: true,+ queueFull: true,+ targetBusy: true,+ targetNotIdleUnknown: true,+ targetStatusUnverified: false,+ targetStatusStale: true,+ targetHookScriptStale: false,+ targetNotAgentPane: false,+ targetNotPasteAware: false,+ targetGone: false,+ notPermitted: false+}++/**+ * Order is load-bearing, and it is cheapest-and-most-permanent first.+ *+ * A caller that cannot be helped is told so WITHOUT a pane round-trip and WITHOUT burning+ * rate-limit budget. The two identity refusals sit ahead of the idle gate because an identity a+ * node cannot present is a more permanent fact than a turn it happens to be in the middle of.+ */+export const DECISION_ORDER = [+ 'notPermitted',+ 'rateLimited',+ 'targetGone',+ 'targetNotAgentPane',+ 'targetHookScriptStale',+ 'targetStatusUnverified',+ 'targetStatusStale',+ 'targetNotIdleUnknown',+ 'targetBusy',+ 'targetNotPasteAware'+] as const++export interface DeliveryFacts {+ /** Set by PR 5/PR 6 (the verbs and the per-project switch). Cheapest gate: pure caller state. */+ notPermitted?: NotPermittedReason+ /** Set by PR 4's per-pair limiter. `> 0` means refuse now and say when. */+ retryAfterMs?: number+ /** Is there a live session for this node at all? False ⇒ `targetGone`. */+ targetLive: boolean+ /**+ * Gate 1, from `isAgentPane` over `PtyManager.paneOwner` — kernel truth, three-valued.+ *+ * ── WHAT THIS VERDICT DOES NOT PROVE (carried from `pane-owner-predicate.ts` deliberately) ────+ *+ * `agent` proves the agent is IN the pane's foreground process group. It does NOT prove the agent+ * is the thing READING the tty. `sh -c "sleep 600 | claude"` answers `agent`, correctly — claude+ * really is in the group — but claude's stdin is the PIPE, so bytes written to the pane sit in+ * the tty buffer until the shell reads them after the pipeline exits. That is the+ * "rename splice = lost launch" shape: the write succeeds and the payload surfaces later,+ * somewhere else. The delivery RECEIPT (Task 3.4) is what makes that case observable rather than+ * silent — it is the only thing in this feature that can tell "B read it" from "the bytes are+ * sitting in a buffer" — and it is why a `stalled` outcome exists at all.+ *+ * Two false negatives are expected here and are NOT papered over: an agent script path containing+ * a SPACE (the argv split cannot tell it from two tokens) and a differently-named SYMLINK to the+ * agent binary (argv carries the name it was invoked as, not the target). Both answer `not-agent`+ * ⇒ `targetNotAgentPane`, a refusal, which is the safe direction. Do not "fix" either by matching+ * a substring of the command line: `vim /etc/claude.conf` would then be a claude pane.+ */+ pane: AgentPaneVerdict+ /** `#{pane_current_command}` (or 'unknown'), reported back so a refusal names what was seen. */+ paneObserved?: string+ /** The target's mirror entry — gate 2's entire input. `undefined` = this node has never posted. */+ target: MirrorEntry | undefined+ /** `nodeTokenFilePresent(targetNodeId)` — injected, so the decider stays pure. */+ tokenFilePresent: boolean+ /** Is the target on an SSH project? Only affects which ACTION a stale-script note names. */+ targetIsRemote?: boolean+ /**+ * Did the target's pane request bracketed paste? Deliberately OPTIONAL and deliberately last.+ *+ * `deliverAgentMessage` probes this only AFTER the gate passes, because the probe is a second+ * tmux round-trip and there is no point paying for it to tell a rate-limited caller something it+ * cannot act on. `undefined` therefore means "not asked yet", not "no".+ */+ pasteAware?: boolean+}++/** The one non-refusal. Kept out of `AgentMessageOutcome` so no caller can return it as a result. */+export interface Proceed {+ kind: 'proceed'+}++/**+ * Gate 2 — the target must be KNOWN idle on a VERIFIED status, and unknown is NOT idle.+ *+ * Modelled on `hibernation-policy.planHibernation` (`c.state === 'done'`, plus a never-seen node+ * being permanently ineligible), NOT on `restartEligibility`, whose `BUSY_STATES` is only+ * `{working, blocked}` — so `waiting` and `undefined` pass it. That is acceptable for a+ * user-initiated restart with a human watching the pane. It is not acceptable for an autonomous+ * write into somebody else's session.+ *+ * Refused, each with its own reason:+ * - `undefined` (post-relaunch, or right after a `sessionPhase:'start'` reset — a CLI that has+ * just launched is the most fragile moment a pane has),+ * - `working` / `blocked` / `waiting` (busy, and retryable),+ * - a RESTORED entry: 6-hour-old evidence off disk about a pane that has since done anything at+ * all, including being replaced,+ * - a `done` inferred from `idle_prompt` (`idleInferred`): a node blocked on an approval is also+ * "idle at the prompt",+ * - any `done` whose evidence was `stateVerified: false` — handled EARLIER, by the three identity+ * refusals, because an unprovable identity is the more permanent fact.+ */+function idleRefusal(e: MirrorEntry | undefined): AgentMessageOutcome | null {+ if (!e) return { kind: 'targetNotIdleUnknown', reason: 'no status has ever been posted for this node' }+ if (e.restored)+ return {+ kind: 'targetNotIdleUnknown',+ reason: 'the last known status was restored from disk at startup, not observed this run'+ }+ if (e.state === undefined)+ return { kind: 'targetNotIdleUnknown', reason: 'the node is between sessions (no current state)' }+ if (e.state !== 'done') return { kind: 'targetBusy', state: e.state }+ if (e.idleInferred)+ return {+ kind: 'targetNotIdleUnknown',+ reason: 'the last `done` was inferred from the CLI going idle at its prompt, which a node ' ++ 'waiting on an approval also does'+ }+ return null+}++/** The action a stale hook script needs, named per surface — because they genuinely differ. */+export function hookScriptStaleNote(targetIsRemote: boolean | undefined): string {+ return targetIsRemote+ ? 'the target runs a hook script that predates per-node identity; reconnect the SSH project ' ++ 'from the desktop that owns it (RemoteHooks.setup() is the only writer of a remote script)'+ : 'the target runs a hook script that predates per-node identity; restart the nodeterm app on ' ++ 'that host (the boot install rewrites the script unconditionally)'+}++/** The action an unmintable node needs — `IDENTITY_RESTART_NOTE`'s shape, never a bare code. */+export const NO_TOKEN_FILE_NOTE =+ 'the target has no per-node identity on this host: relaunch the node from the desktop, or open ' ++ 'its project so its token is materialised, then try again'++/**+ * The THREE unverified refusals — three populations, three ACTIONS. Collapsing them is worse than a+ * bare refusal, because two of the three would otherwise be told to retry something that can never+ * succeed.+ *+ * 1. STALE SCRIPT (`clientRevision` absent or `< MIN_TOKEN_AWARE_REVISION`). The session runs a+ * hook script that predates per-node identity and cannot read the token dir at all — the token+ * file may well be sitting right there. Checked FIRST because it is the OUTER CAUSE: fixing it+ * is what makes the other two checks mean anything. The action differs by surface — a local+ * host's script is rewritten unconditionally at every boot (`install-helper.ts`), a remote+ * host's only inside `RemoteHooks.setup()` on CONNECT, so an already-connected project needs a+ * reconnect. NOT retryable: no number of retries reinstalls a script.+ * 2. NO TOKEN FILE. The node cannot prove itself at all. NOT retryable — it needs a human.+ * 3. TOKEN FILE PRESENT, CURRENT SCRIPT, no verified event yet. It simply has not posted since the+ * file appeared. Retryable — wait for its next turn.+ *+ * The trap #1 closes: before the script stamped itself (`X-Nodeterm-Hook-Client`), an old script+ * POSTing `version=2` with no token header was byte-identical on the wire to a current script whose+ * token file was merely missing. A token-file check alone would answer "retry after its next turn"+ * for the old-script case — forever, because the script cannot read the file. A permanently wrong+ * retry is worse than a refusal.+ *+ * Measured 2026-08-15: a PHONE-SPAWNED session lands in NONE of these on a host running nodeterm.+ * It sources the 0600 endpoint file it was handed, reads `$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID`+ * and presents it, and verifies. rev. 3 of the design claimed the opposite; it was wrong, and the+ * reason it is wrong is the PERSIST-TIME token sweep (`refreshNodeTokens` on `onPersist`), NOT+ * `ptyManager.create` — which a phone-spawned session never touches.+ */+function identityRefusal(f: DeliveryFacts): AgentMessageOutcome | null {+ const e = f.target+ if (e?.stateVerified === true) return null+ // "Observed this run" is the precondition for reading a client revision at all: a restored entry+ // and a never-seen node carry no observation, so calling their script stale would be an+ // accusation we have no evidence for. They fall through to the token-file question, which is+ // answerable without an event.+ const observed = !!e && e.restored !== true+ if (observed && !(typeof e.clientRevision === 'number' && e.clientRevision >= MIN_TOKEN_AWARE_REVISION))+ return {+ kind: 'targetHookScriptStale',+ note: hookScriptStaleNote(f.targetIsRemote),+ ...(typeof e.clientRevision === 'number' ? { observedRevision: e.clientRevision } : {})+ }+ if (!f.tokenFilePresent) return { kind: 'targetStatusUnverified', note: NO_TOKEN_FILE_NOTE }+ return { kind: 'targetStatusStale' }+}++/**+ * The gates that cost NOTHING to evaluate — decided before any pane is touched.+ *+ * This split is the reason `DECISION_ORDER` is ordered the way it is, made real: a caller that is+ * not permitted, or that is over its rate budget, must be told so WITHOUT a tmux (or, on an SSH+ * project, an `ssh`) round-trip. Without the split the order would be a comment — the refusal text+ * would be right and the cost would be paid anyway, which is exactly the kind of gap a+ * source-reading test cannot see.+ *+ * `null` means "nothing decidable yet"; the caller probes and then calls `decideDelivery`.+ */+export function decidePreProbe(+ f: Pick<DeliveryFacts, 'notPermitted' | 'retryAfterMs' | 'targetLive'>+): AgentMessageOutcome | null {+ if (f.notPermitted) return { kind: 'notPermitted', reason: f.notPermitted }+ if (typeof f.retryAfterMs === 'number' && f.retryAfterMs > 0)+ return { kind: 'rateLimited', retryAfterMs: f.retryAfterMs }+ if (!f.targetLive) return { kind: 'targetGone' }+ return null+}++/**+ * Decide whether a delivery may proceed. Pure.+ *+ * The sequence below IS `DECISION_ORDER`, and the ordering test walks it by clearing one fact at a+ * time — asserted by RUNNING this function, never by reading its source.+ */+export function decideDelivery(f: DeliveryFacts): AgentMessageOutcome | Proceed {+ const cheap = decidePreProbe(f)+ if (cheap) return cheap+ // Gate 1. `unknown` is NOT a shade of `not-agent` — but for DELIVERY both refuse, because the one+ // thing neither may do is admit a pane we could not read.+ //+ // ── DO NOT RETRY AN `unknown` VERDICT ON A FIXED SHORT TIMER WITHOUT A CIRCUIT BREAKER ────────+ //+ // Measured: `probeWithin` answers at 2s, but the `ssh` child it started lives until `runAsync`'s+ // own 15s reap, so a 2s retry loop stacks ~7 overlapping children per pane. And `childArgs`+ // carries `-o ControlMaster=auto`, so against a DEAD master each of those children does not+ // multiplex — it opens a full connection, i.e. a REAL LOGIN. A pane that is unreadable *because*+ // its master died is therefore the worst case, and it is the same shape this repo already lived+ // through at 72k logins/day (memory: ssh-controlmaster-fallback). `targetNotAgentPane` is marked+ // NOT retryable in `RETRYABLE` partly for this reason: the honest advice to a language model+ // holding an unreadable pane is not "try again in a moment".+ if (f.pane !== 'agent')+ return { kind: 'targetNotAgentPane', observed: f.paneObserved ?? (f.pane === 'unknown' ? 'unknown' : 'not-agent') }+ const identity = identityRefusal(f)+ if (identity) return identity+ const idle = idleRefusal(f.target)+ if (idle) return idle+ // Last, and only when everything else passed: the pane must have ASKED for bracketed paste.+ // herdr :260 — a multi-line envelope on the unframed fallback would be submitted line-by-line as+ // separate turns. It is refused, never sent and hoped for.+ if (f.pasteAware === false) return { kind: 'targetNotPasteAware' }+ return { kind: 'proceed' }+}