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.

feat(messaging): a per-pair rate limit and a per-turn fan-out cap

Claude Code9c6edb4284ff
diff --git a/src/core/agents/agent-message-flow.test.ts b/src/core/agents/agent-message-flow.test.ts
new file mode 100644
index 000000000..2d13e0178
--- /dev/null
+++ b/src/core/agents/agent-message-flow.test.ts
@@ -0,0 +1,365 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import {
+ PAIR_MIN_INTERVAL_MS,
+ FANOUT_PER_TURN,
+ FANOUT_RETRY_AFTER_MS,
+ TURN_STALE_MS,
+ checkFanOut,
+ checkFlowLimits,
+ checkPairRate,
+ flowStats,
+ noteNewTurn,
+ noteSent,
+ pairKey,
+ resetMessageFlow,
+ type FlowVerdict
+} from './agent-message-flow'
+import { decidePreProbe, RETRYABLE } from './agent-message-decide'
+import { deliverAgentMessage, type DeliveryDeps } from './agent-message'
+import { MANAGED_SCRIPT_REVISION } from './hooks/managed-script'
+import type { MirrorEntry } from '../agent-status-mirror'
+
+const T0 = 1_700_000_000_000
+
+/** The `retryAfterMs` of a refusal, or `null` when the verdict was `ok`. Asserted by RUNNING the
+ * checks — nothing in this file reads the module's source. */
+const wait = (v: FlowVerdict): number | null => ('ok' in v ? null : v.retryAfterMs)
+
+beforeEach(() => resetMessageFlow())
+
+describe('the per-pair rate limit', () => {
+ it('lets the first delivery of a pair through', () => {
+ expect(wait(checkPairRate('a', 'b', T0))).toBeNull()
+ })
+
+ it('refuses the second inside the window, and the wait is the exact remainder', () => {
+ noteSent('a', 'b', T0)
+ expect(wait(checkPairRate('a', 'b', T0 + 1))).toBe(PAIR_MIN_INTERVAL_MS - 1)
+ expect(wait(checkPairRate('a', 'b', T0 + 4000))).toBe(PAIR_MIN_INTERVAL_MS - 4000)
+ expect(wait(checkPairRate('a', 'b', T0 + PAIR_MIN_INTERVAL_MS - 1))).toBe(1)
+ })
+
+ it('opens again exactly AT the interval, not one tick later', () => {
+ noteSent('a', 'b', T0)
+ expect(wait(checkPairRate('a', 'b', T0 + PAIR_MIN_INTERVAL_MS - 1))).toBe(1)
+ expect(wait(checkPairRate('a', 'b', T0 + PAIR_MIN_INTERVAL_MS))).toBeNull()
+ })
+
+ it('throttles the PAIR, not the sender: A→B says nothing about A→C', () => {
+ // The failure this pins: keyed by sender alone, an orchestrator fanning out to four workers
+ // starves itself — three of its four sends are refused for being correct behaviour.
+ noteSent('a', 'b', T0)
+ expect(wait(checkPairRate('a', 'c', T0 + 1))).toBeNull()
+ expect(wait(checkPairRate('a', 'b', T0 + 1))).toBe(PAIR_MIN_INTERVAL_MS - 1)
+ })
+
+ it('throttles the PAIR, not the target: A→B says nothing about C→B', () => {
+ // The failure this pins: keyed by target alone, one node's window is held shut by whoever
+ // wrote to it last, and every other conversation with that node pays for it.
+ noteSent('a', 'b', T0)
+ expect(wait(checkPairRate('c', 'b', T0 + 1))).toBeNull()
+ })
+
+ it('the REVERSE pair is a different pair — a reply is never throttled by the message it answers', () => {
+ noteSent('a', 'b', T0)
+ expect(wait(checkPairRate('b', 'a', T0 + 1))).toBeNull()
+ // …and the reply's own window is likewise the reply's own.
+ noteSent('b', 'a', T0 + 1)
+ expect(wait(checkPairRate('b', 'a', T0 + 2))).toBe(PAIR_MIN_INTERVAL_MS - 1)
+ expect(wait(checkPairRate('a', 'b', T0 + 2))).toBe(PAIR_MIN_INTERVAL_MS - 2)
+ })
+
+ it('the key composes both ids so no two distinct conversations share one', () => {
+ // The separator is a NUL because a node id cannot contain one. A hyphen or a space could:
+ // 'a-b'\u2192'c' and 'a'\u2192'b-c' would be the SAME key under either, and one conversation
+ // would silently throttle another.
+ // The set must contain ids that DO collide under a weaker key, or this proves nothing: 'ab'+'c'
+ // and 'a'+'bc' are the same string once the separator is dropped. (Found by mutation: without
+ // these four the whole test stayed green with the separator removed entirely.)
+ const ids = ['a', 'b', 'c', 'ab', 'bc', 'a-b', 'b-c', 'a b', 'b c']
+ const seen = new Map<string, string>()
+ for (const src of ids)
+ for (const dst of ids) {
+ const key = pairKey(src, dst)
+ const pair = `${src}\u2192${dst}`
+ expect(seen.get(key) ?? pair, `${seen.get(key)} collided with ${pair}`).toBe(pair)
+ seen.set(key, pair)
+ }
+ expect(seen.size).toBe(ids.length * ids.length)
+ // The reverse pair in particular — the one people get wrong.
+ expect(pairKey('a', 'b')).not.toBe(pairKey('b', 'a'))
+ })
+
+ it('a CHECK never starts a window — only a delivered message does', () => {
+ // Otherwise a delivery refused for any other reason (a busy target, an unverified identity —
+ // the two commonest refusals there are) would burn the budget it never used, and the caller
+ // told to retry would be rate-limited for doing what it was told.
+ expect(wait(checkPairRate('a', 'b', T0))).toBeNull()
+ expect(wait(checkPairRate('a', 'b', T0 + 1))).toBeNull()
+ expect(flowStats().pairs).toBe(0)
+ })
+})
+
+describe('the per-turn fan-out cap', () => {
+ it('passes FANOUT_PER_TURN deliveries in one turn and refuses the next', () => {
+ // Four DIFFERENT targets, so nothing here can be the per-pair limiter firing.
+ for (let i = 0; i < FANOUT_PER_TURN; i++) {
+ expect(wait(checkFanOut('a', T0 + i)), `send ${i + 1} of the turn`).toBeNull()
+ noteSent('a', `dst-${i}`, T0 + i)
+ }
+ expect(wait(checkFanOut('a', T0 + FANOUT_PER_TURN))).toBe(FANOUT_RETRY_AFTER_MS)
+ })
+
+ it("resets on the SOURCE's own newTurn", () => {
+ for (let i = 0; i < FANOUT_PER_TURN; i++) noteSent('a', `dst-${i}`, T0 + i)
+ expect(wait(checkFanOut('a', T0 + 10))).toBe(FANOUT_RETRY_AFTER_MS)
+ noteNewTurn('a')
+ expect(wait(checkFanOut('a', T0 + 10))).toBeNull()
+ })
+
+ it("another node's newTurn does not reset it", () => {
+ // If it did, every delivery would refill the budget that sent it: a delivery is precisely what
+ // starts the TARGET's next turn.
+ for (let i = 0; i < FANOUT_PER_TURN; i++) noteSent('a', `dst-${i}`, T0 + i)
+ noteNewTurn('b')
+ noteNewTurn('dst-0')
+ expect(wait(checkFanOut('a', T0 + 10))).toBe(FANOUT_RETRY_AFTER_MS)
+ })
+
+ it('a tool-event burst does not reset it — nothing but a newTurn does', () => {
+ // The renderer's own per-turn fan-out is keyed on `newTurn` for this reason: a working→done→
+ // working cycle happens many times inside one turn. This module is given no state signal at
+ // all, so the assertion is that everything else it accepts leaves the budget standing.
+ for (let i = 0; i < FANOUT_PER_TURN; i++) noteSent('a', `dst-${i}`, T0 + i)
+ for (let t = 1; t < 60; t++) {
+ checkFanOut('a', T0 + t * 1000)
+ checkPairRate('a', 'dst-0', T0 + t * 1000)
+ noteNewTurn('someone-else')
+ }
+ // Still inside the same turn (well under TURN_STALE_MS), still capped.
+ expect(wait(checkFanOut('a', T0 + 60_000))).toBe(FANOUT_RETRY_AFTER_MS)
+ })
+
+ it('the budget is per SENDER: one node using it up does not silence another', () => {
+ for (let i = 0; i < FANOUT_PER_TURN; i++) noteSent('a', `dst-${i}`, T0 + i)
+ expect(wait(checkFanOut('a', T0 + 10))).toBe(FANOUT_RETRY_AFTER_MS)
+ expect(wait(checkFanOut('b', T0 + 10))).toBeNull()
+ })
+
+ it('expires on its own if the turn signal never arrives — the stuck-limiter backstop', () => {
+ // A shell that never wires `noteNewTurn` would otherwise silence every sender after four
+ // messages, for the rest of the run, with no way to wait it out.
+ for (let i = 0; i < FANOUT_PER_TURN; i++) noteSent('a', `dst-${i}`, T0 + i)
+ const lastSend = T0 + FANOUT_PER_TURN - 1
+ expect(wait(checkFanOut('a', lastSend + TURN_STALE_MS - 1))).toBe(FANOUT_RETRY_AFTER_MS)
+ expect(wait(checkFanOut('a', lastSend + TURN_STALE_MS))).toBeNull()
+ })
+
+ it('the backstop measures the LAST send, not the first — a slow turn is still capped', () => {
+ noteSent('a', 'dst-0', T0)
+ for (let i = 1; i < FANOUT_PER_TURN; i++) noteSent('a', `dst-${i}`, T0 + i * (TURN_STALE_MS - 1))
+ const last = T0 + (FANOUT_PER_TURN - 1) * (TURN_STALE_MS - 1)
+ expect(wait(checkFanOut('a', last + 1))).toBe(FANOUT_RETRY_AFTER_MS)
+ })
+})
+
+describe('the refusals are the union member, and they refuse for real', () => {
+ it('a fan-out refusal survives the trip through decidePreProbe', () => {
+ // The trap: `decidePreProbe` refuses on `retryAfterMs > 0`, so a cap reporting 0 would be a cap
+ // that silently stopped existing. Asserted by running the decider on the number this module
+ // actually produces.
+ for (let i = 0; i < FANOUT_PER_TURN; i++) noteSent('a', `dst-${i}`, T0 + i)
+ const v = checkFanOut('a', T0 + 10)
+ expect('ok' in v).toBe(false)
+ const outcome = decidePreProbe({
+ targetLive: true,
+ tokenFilePresent: true,
+ target: { state: 'done', updatedAt: T0, stateVerified: true, clientRevision: MANAGED_SCRIPT_REVISION },
+ retryAfterMs: (v as { retryAfterMs: number }).retryAfterMs
+ })
+ expect(outcome).toEqual({ kind: 'rateLimited', retryAfterMs: FANOUT_RETRY_AFTER_MS })
+ expect(RETRYABLE.rateLimited).toBe(true)
+ })
+
+ it('a pair refusal likewise, with its own remaining wait', () => {
+ noteSent('a', 'b', T0)
+ const v = checkPairRate('a', 'b', T0 + 2500)
+ const outcome = decidePreProbe({
+ targetLive: true,
+ tokenFilePresent: true,
+ target: { state: 'done', updatedAt: T0, stateVerified: true, clientRevision: MANAGED_SCRIPT_REVISION },
+ retryAfterMs: (v as { retryAfterMs: number }).retryAfterMs
+ })
+ expect(outcome).toEqual({ kind: 'rateLimited', retryAfterMs: PAIR_MIN_INTERVAL_MS - 2500 })
+ })
+})
+
+describe('checkFlowLimits — both budgets in one call', () => {
+ it('passes when both do', () => {
+ expect(checkFlowLimits('a', 'b', T0)).toEqual({ ok: true })
+ })
+
+ it('names the pair limit when only the pair is over', () => {
+ noteSent('a', 'b', T0)
+ expect(checkFlowLimits('a', 'b', T0 + 1)).toEqual({
+ ok: false,
+ limit: 'pair',
+ outcome: { kind: 'rateLimited', retryAfterMs: PAIR_MIN_INTERVAL_MS - 1 }
+ })
+ })
+
+ it('names the fan-out cap when only the cap is over', () => {
+ for (let i = 0; i < FANOUT_PER_TURN; i++) noteSent('a', `dst-${i}`, T0 + i)
+ expect(checkFlowLimits('a', 'fresh-target', T0 + 10)).toEqual({
+ ok: false,
+ limit: 'fan-out',
+ outcome: { kind: 'rateLimited', retryAfterMs: FANOUT_RETRY_AFTER_MS }
+ })
+ })
+
+ it('reports the FAN-OUT cap when both refuse — its wait is never the shorter one', () => {
+ for (let i = 0; i < FANOUT_PER_TURN; i++) noteSent('a', `dst-${i}`, T0 + i)
+ // dst-0's pair window has 2 ms left; the fan-out floor is the whole interval. Reporting the
+ // smaller of two live limits would invite a retry that is already known to fail.
+ const nearlyOpen = T0 + PAIR_MIN_INTERVAL_MS - 2
+ expect(checkFlowLimits('a', 'dst-0', nearlyOpen)).toEqual({
+ ok: false,
+ limit: 'fan-out',
+ outcome: { kind: 'rateLimited', retryAfterMs: FANOUT_RETRY_AFTER_MS }
+ })
+ })
+
+ it('and the precedence is only sound while the fan-out floor is the longer wait', () => {
+ // The invariant behind the branch above, pinned so that changing either constant fails here
+ // rather than silently telling a caller to come back before it can be served.
+ expect(FANOUT_RETRY_AFTER_MS).toBeGreaterThanOrEqual(PAIR_MIN_INTERVAL_MS)
+ })
+})
+
+describe('eviction — the entries go away, not just the verdicts', () => {
+ it('drops a pair entry once its window has passed', () => {
+ // Asserted on the MAP, not through a read that shares the window's bound: a limiter that
+ // decides expiry at read time while the map keeps growing passes every verdict test and leaks.
+ noteSent('a', 'b', T0)
+ noteSent('c', 'd', T0)
+ expect(flowStats().pairs).toBe(2)
+ checkPairRate('x', 'y', T0 + PAIR_MIN_INTERVAL_MS)
+ expect(flowStats().pairs).toBe(0)
+ })
+
+ it('keeps a pair entry that is still inside its window', () => {
+ noteSent('a', 'b', T0)
+ checkPairRate('x', 'y', T0 + PAIR_MIN_INTERVAL_MS - 1)
+ expect(flowStats().pairs).toBe(1)
+ })
+
+ it('drops a sender budget once it goes stale, and on a newTurn', () => {
+ noteSent('a', 'b', T0)
+ expect(flowStats().senders).toBe(1)
+ noteNewTurn('a')
+ expect(flowStats().senders).toBe(0)
+ noteSent('a', 'b', T0)
+ checkFanOut('z', T0 + TURN_STALE_MS)
+ expect(flowStats().senders).toBe(0)
+ })
+
+ it('a clock that jumps BACKWARDS drops the entry instead of parking it in the future', () => {
+ // An NTP step back would otherwise leave `PAIR_MIN_INTERVAL_MS - (now - at)` refusing for as
+ // long as the step was large — an agent silenced for an hour by a time correction. Over-sending
+ // by one message is the direction this module always takes.
+ noteSent('a', 'b', T0)
+ expect(wait(checkPairRate('a', 'b', T0 - 60 * 60_000))).toBeNull()
+ expect(flowStats().pairs).toBe(0)
+ for (let i = 0; i < FANOUT_PER_TURN; i++) noteSent('a', `dst-${i}`, T0 + i)
+ expect(wait(checkFanOut('a', T0 - 60 * 60_000))).toBeNull()
+ expect(flowStats().senders).toBe(0)
+ })
+
+ it('resetMessageFlow really empties both maps', () => {
+ noteSent('a', 'b', T0)
+ resetMessageFlow()
+ expect(flowStats()).toEqual({ pairs: 0, senders: 0 })
+ expect(wait(checkPairRate('a', 'b', T0 + 1))).toBeNull()
+ })
+})
+
+describe('the limiter is consulted BEFORE any pane probe', () => {
+ // The point of a pre-probe refusal: on an SSH project whose ControlMaster has died, a probe is a
+ // real login, and a busy-looping sender turns that into the 72k-logins/day shape this repo has
+ // already lived through. Asserted by RUNNING a delivery with a probe that counts its calls.
+ const idle: MirrorEntry = {
+ state: 'done',
+ updatedAt: T0,
+ stateVerified: true,
+ clientRevision: MANAGED_SCRIPT_REVISION
+ }
+
+ function countingDeps(): { deps: DeliveryDeps; probes: number[]; writes: number[] } {
+ const probes: number[] = []
+ const writes: number[] = []
+ return {
+ probes,
+ writes,
+ deps: {
+ paneOwner: async () => {
+ probes.push(1)
+ return null
+ },
+ bracketPasteRequested: async () => true,
+ sendFramed: async () => {
+ writes.push(1)
+ return true
+ },
+ mirrorEntry: () => idle,
+ tokenFilePresent: () => true,
+ lock: async (_id, fn) => fn(),
+ now: () => T0,
+ nonce: () => 'NONCE0123456',
+ trace: async () => ({ traceId: 't-1', traced: 'memory' as const }),
+ subscribeEvents: () => () => {}
+ }
+ }
+ }
+
+ it('a rate-limited delivery touches no pane and writes nothing', async () => {
+ noteSent('n-src', 'n-dst', T0)
+ const check = checkFlowLimits('n-src', 'n-dst', T0 + 1)
+ expect(check.ok).toBe(false)
+ const { deps, probes, writes } = countingDeps()
+ const outcome = await deliverAgentMessage(
+ {
+ targetNodeId: 'n-dst',
+ sourceNodeId: 'n-src',
+ sourceTitle: 'Alpha',
+ body: 'do the thing',
+ targetAgentId: 'claude',
+ retryAfterMs: (check as { outcome: { retryAfterMs: number } }).outcome.retryAfterMs
+ },
+ deps
+ )
+ expect(outcome).toEqual({ kind: 'rateLimited', retryAfterMs: PAIR_MIN_INTERVAL_MS - 1 })
+ expect(probes).toEqual([])
+ expect(writes).toEqual([])
+ })
+
+ it('and the same delivery DOES probe once the budget is clear — the counter is real', async () => {
+ // The control. Without it the assertion above would pass just as well against a delivery that
+ // never probes anything, which would make it evidence of nothing.
+ expect(wait(checkPairRate('n-src', 'n-dst', T0))).toBeNull()
+ const { deps, probes, writes } = countingDeps()
+ const outcome = await deliverAgentMessage(
+ {
+ targetNodeId: 'n-dst',
+ sourceNodeId: 'n-src',
+ sourceTitle: 'Alpha',
+ body: 'do the thing',
+ targetAgentId: 'claude'
+ },
+ deps
+ )
+ expect(probes.length).toBe(1)
+ // An unreadable pane is refused, so still no write — the probe is the thing being counted.
+ expect(outcome).toEqual({ kind: 'targetNotAgentPane', observed: 'unknown' })
+ expect(writes).toEqual([])
+ })
+})
diff --git a/src/core/agents/agent-message-flow.ts b/src/core/agents/agent-message-flow.ts
new file mode 100644
index 000000000..402194b3e
--- /dev/null
+++ b/src/core/agents/agent-message-flow.ts
@@ -0,0 +1,261 @@
+import type { AgentMessageOutcome } from './agent-message-decide'
+
+/**
+ * FLOW CONTROL — the first throttle the control surface has ever had.
+ *
+ * What exists today is timeouts (`SLOWLORIS_MS` → `CONTROL_CEILING_MS`, the 120 s `pendingControl`
+ * bound) and a one-at-a-time confirmation serializer (`confirmBusy()`). A timeout is not a throttle
+ * and a modal is not a budget — and messaging skips the modal entirely once the per-project switch
+ * is on, so even the accidental brake is gone. These two limits are the replacement.
+ *
+ * Both are PRE-PROBE by construction: they answer from a `Map` lookup, so a refusal costs no tmux
+ * round-trip and — on an SSH project whose ControlMaster has died — no real login. That is not a
+ * micro-optimisation; `-o ControlMaster=auto` turned exactly this shape into 72k logins/day once
+ * already (memory: ssh-controlmaster-fallback). Both refusals are the EXISTING `rateLimited` member
+ * of `AgentMessageOutcome`, never a new ad-hoc shape, so `RETRYABLE` already answers for them.
+ *
+ * ── THREE SURFACES ──────────────────────────────────────────────────────────────────────────────
+ *
+ * - **Desktop (Electron):** the only surface with the messaging verbs, so the only surface that
+ * consumes budget. The state below is main-process memory, next to `deliverAgentMessage`.
+ * - **Server Edition:** this module ships (everything in `src/core` ships on both shells) and has
+ * no consumer — messaging does not exist there, and Task 5.3 makes that a named, terminal
+ * refusal rather than a throttle-shaped one. Nothing here needs a second wiring.
+ * - **Mobile (phone):** never a sender — it drives the canvas over relay→IPC, not `/control/*` —
+ * so a phone action never calls `noteSent` and never consumes anyone's budget. It IS a valid
+ * target (Correction C1), and as a target it is covered like any other: the pair budget belongs
+ * to the PAIR, so a phone-spawned node being messaged by two different orchestrators gets two
+ * independent windows, which is the correct answer for two independent conversations.
+ *
+ * ── WHERE THE STATE LIVES, AND WHICH WAY IT FAILS ───────────────────────────────────────────────
+ *
+ * Process memory, module scope, for the lifetime of the shell that owns the delivery. Nothing is
+ * persisted, and that is a decision rather than an omission:
+ *
+ * - **A LOST limiter is a brief over-send.** After a restart every pair starts clean, so a pair
+ * that had just been written to could receive one extra message inside its 10 s window, and every
+ * sender starts its next turn with a full fan-out budget. Bounded, self-healing, invisible.
+ * - **A STUCK limiter is a permanently silent agent** — an entry that outlives its meaning and
+ * refuses every future delivery with a number nobody can wait out. That is the failure mode this
+ * module refuses to have, so every path that could produce it fails OPEN: entries are evicted on
+ * read (`sweep`), a clock that jumps BACKWARDS drops the entry instead of parking it in the
+ * future, and a fan-out budget whose reset signal never arrives expires on its own after
+ * `TURN_STALE_MS`.
+ *
+ * Nothing here reads the clock, the filesystem or a socket; `now` is injected exactly as it is in
+ * `decideDelivery`, so the whole thing is testable without fake timers.
+ */
+
+/** #98's 10 s, kept: the same number, now enforced. */
+export const PAIR_MIN_INTERVAL_MS = 10_000
+
+/** How many DIFFERENT deliveries one sender may make inside a single turn. */
+export const FANOUT_PER_TURN = 4
+
+/**
+ * The fan-out backstop, and the reason it exists is the failure direction above.
+ *
+ * The cap's real reset is the sender's own `newTurn`. If that signal never arrives — a shell that
+ * forgot to wire `noteNewTurn`, a normalizer that stopped flagging turn starts — the counter would
+ * stand forever and the sender would be silent for the rest of the run, which is precisely the
+ * stuck-limiter failure. So a budget that has seen no send for this long is treated as belonging to
+ * a turn that is over.
+ *
+ * It does not make the cap leaky: a burst is by definition sends seconds apart, and this window
+ * never elapses inside one. The worst case it admits is four extra messages per five idle minutes
+ * per sender — and each of those still has to clear the per-pair window.
+ */
+export const TURN_STALE_MS = 5 * 60_000
+
+/**
+ * What a fan-out refusal reports as `retryAfterMs`, and it is a FLOOR, not a promise.
+ *
+ * The budget resets on a turn boundary, which is not a clock event, so no number here is exactly
+ * right. The two obviously-wrong choices are worse than a floor: `0` would be read as "no limit at
+ * all" by `decidePreProbe`, whose refusal is `retryAfterMs > 0` — the cap would silently stop
+ * existing — and something enormous would tell a caller to abandon a budget that clears the moment
+ * its turn ends. The per-pair interval is the honest lower bound: nothing this sender does can land
+ * sooner than that anyway.
+ */
+export const FANOUT_RETRY_AFTER_MS = PAIR_MIN_INTERVAL_MS
+
+/** The `rateLimited` member of the delivery outcome union — reused, never re-declared. */
+export type RateLimited = Extract<AgentMessageOutcome, { kind: 'rateLimited' }>
+
+export type FlowVerdict = { ok: true } | RateLimited
+
+/** Which of the two budgets refused, for the trace. Deliberately NOT on the outcome: the sender is
+ * told `rateLimited` and a number, because that is all it can act on. */
+export type FlowLimit = 'pair' | 'fan-out'
+
+export type FlowCheck = { ok: true } | { ok: false; limit: FlowLimit; outcome: RateLimited }
+
+/**
+ * The map key, and the separator is written as the ESCAPE `\u0000` — never as a raw byte.
+ *
+ * A raw NUL in a source file makes git, grep and ripgrep skip the ENTIRE file in silence. This
+ * repo has been bitten twice (commit 4c0e8c3); the plan this task comes from was written with a raw
+ * one and was itself invisible to grep until it was caught.
+ */
+export function pairKey(src: string, dst: string): string {
+ return `${src}\u0000${dst}`
+}
+
+/**
+ * WHY THE KEY IS THE PAIR, and what each of the two obvious alternatives breaks.
+ *
+ * - Keyed by SENDER alone, one budget covers everything an orchestrator does: a fan-out to four
+ * workers is four sends inside a second, so three of them are refused and the orchestrator is
+ * starved by its own correct behaviour. (A per-sender budget is the right shape for a *turn*
+ * cap — which is what `checkFanOut` is, with a much larger allowance.)
+ * - Keyed by TARGET alone, one busy node throttles every conversation it is part of, and a sender
+ * is refused for something another sender did. Worse, it is trivially abusable: a flooder holds
+ * one target's window shut and nobody else can reach it.
+ * - Keyed by the PAIR, the budget belongs to the conversation. A→B being throttled says nothing
+ * about A→C, and — asserted explicitly, because it is the one people get wrong — nothing about
+ * B→A. A reply must never be throttled by the message it answers.
+ */
+const pairLastSentAt = new Map<string, number>()
+
+/**
+ * WHAT IDENTIFIES A TURN: the existence of this entry, delimited by the sender's own `newTurn`.
+ *
+ * There is no turn id to key on, and the three candidates that look like one are each wrong in a
+ * way that matters:
+ *
+ * - **A state transition (`working` → `done`)** would reset the cap several times inside one turn:
+ * a tool-event burst flips the mirror repeatedly, which is exactly why the renderer's own
+ * per-turn fan-out is keyed on `newTurn` and not on state (`normalize.ts` — *"true only for a
+ * genuine new turn … so the renderer can clear per-turn fan-out without clearing on every
+ * mid-turn tool event"*). A cap that resets mid-turn is not a cap.
+ * - **The session id** spans an entire session — hours, hundreds of turns. A cap keyed on it never
+ * resets in practice: four messages per session is a permanent block wearing a budget's clothes.
+ * - **Wall-clock windows** refill in the middle of a long turn and refuse at the start of a short
+ * one, which is the same objection as the first, plus arbitrariness.
+ *
+ * So the entry IS the turn: it is created by the turn's first send, incremented by each subsequent
+ * one, and destroyed by `noteNewTurn(src)` — the same edge `normalize.ts` already flags for exactly
+ * this purpose. `TURN_STALE_MS` is its only other exit, and that exit exists to fail open.
+ */
+interface TurnBudget {
+ /** Sends recorded in the current turn. */
+ sent: number
+ /** When the last of them was recorded — the staleness backstop's input, nothing else. */
+ lastSentAt: number
+}
+const senderTurns = new Map<string, TurnBudget>()
+
+/**
+ * EVICTION, not a read cap.
+ *
+ * Both maps are swept here and the checks below read whatever survives — so an entry that is still
+ * present is, by construction, still in force. There is deliberately no "is it expired?" branch in
+ * the readers: a limiter that decides expiry at read time while the map keeps growing looks correct
+ * from every test that reads through the same bound, and leaks. `flowStats()` exists so a test can
+ * assert the eviction directly instead of inferring it from a verdict.
+ *
+ * The `at > now` arm is the clock-jump guard. An NTP step backwards would otherwise leave an entry
+ * dated in the future, and `PAIR_MIN_INTERVAL_MS - (now - at)` would then refuse for as long as the
+ * step was large — an agent silenced for an hour by a time correction, with no way to wait it out.
+ * Dropping it over-sends by at most one message per pair. That is the direction this module always
+ * takes.
+ */
+function sweep(now: number): void {
+ for (const [key, at] of pairLastSentAt)
+ if (at > now || now - at >= PAIR_MIN_INTERVAL_MS) pairLastSentAt.delete(key)
+ for (const [id, b] of senderTurns)
+ if (b.lastSentAt > now || now - b.lastSentAt >= TURN_STALE_MS) senderTurns.delete(id)
+}
+
+/**
+ * May `src` write into `dst` right now? Pure read — a check NEVER starts a window.
+ *
+ * That matters: if merely asking extended the window, a delivery refused for any other reason (a
+ * busy target, an unverified identity — the two most common refusals in an orchestration session)
+ * would consume the budget it never used, and a caller told to retry would be rate-limited for
+ * doing what it was told. Only `noteSent` records, and only a delivery that actually reached the
+ * pane calls it.
+ */
+export function checkPairRate(src: string, dst: string, now: number): FlowVerdict {
+ sweep(now)
+ const last = pairLastSentAt.get(pairKey(src, dst))
+ if (last === undefined) return { ok: true }
+ return { kind: 'rateLimited', retryAfterMs: PAIR_MIN_INTERVAL_MS - (now - last) }
+}
+
+/** Has `src` used up this turn's fan-out budget? Pure read, same contract as `checkPairRate`. */
+export function checkFanOut(src: string, now: number): FlowVerdict {
+ sweep(now)
+ const budget = senderTurns.get(src)
+ if (!budget || budget.sent < FANOUT_PER_TURN) return { ok: true }
+ return { kind: 'rateLimited', retryAfterMs: FANOUT_RETRY_AFTER_MS }
+}
+
+/**
+ * Both budgets in one call, because two of them is one too many to remember.
+ *
+ * A caller that consults the pair limit and forgets the fan-out cap has shipped half a feature that
+ * looks whole, and nothing would fail.
+ *
+ * When BOTH refuse, the fan-out cap is the one reported, because its wait is never the shorter of
+ * the two: a pair remainder is at most `PAIR_MIN_INTERVAL_MS`, which is what the fan-out floor is.
+ * Reporting the smaller of two live limits would invite a retry already known to fail. The test
+ * pins that relationship between the constants, so weakening either one fails there rather than
+ * quietly turning this precedence into the wrong answer.
+ */
+export function checkFlowLimits(src: string, dst: string, now: number): FlowCheck {
+ const pair = checkPairRate(src, dst, now)
+ const fanOut = checkFanOut(src, now)
+ if (!('ok' in fanOut)) return { ok: false, limit: 'fan-out', outcome: fanOut }
+ if (!('ok' in pair)) return { ok: false, limit: 'pair', outcome: pair }
+ return { ok: true }
+}
+
+/**
+ * Record a delivery that ACTUALLY reached the pane — the single write path for both budgets.
+ *
+ * Called after the write, not before the gate. A refusal puts nothing in anybody's pane, so it
+ * costs nobody's budget; the cost of that choice is that refusals are unthrottled, which is
+ * acceptable precisely because they are pre-probe and free. The cost of the alternative is not: a
+ * sender whose four attempts were all refused as `targetBusy` — a RETRYABLE outcome it was told to
+ * come back from — would find itself silent for the rest of its turn, blocked by the retries the
+ * feature asked it to make.
+ */
+export function noteSent(src: string, dst: string, now: number): void {
+ sweep(now)
+ pairLastSentAt.set(pairKey(src, dst), now)
+ const budget = senderTurns.get(src)
+ if (budget) {
+ budget.sent += 1
+ budget.lastSentAt = now
+ } else {
+ senderTurns.set(src, { sent: 1, lastSentAt: now })
+ }
+}
+
+/**
+ * The sender started a new turn — its fan-out budget is gone with the old one.
+ *
+ * Wired (in Task 5.1) to the same `newTurn` edge the renderer's own per-turn fan-out uses. Deleting
+ * rather than zeroing keeps the map bounded by "senders with an in-flight turn" instead of "senders
+ * seen this run", and makes an absent entry mean exactly one thing.
+ *
+ * Only the SOURCE's own turn resets it. A `newTurn` on the target is another node's business — if
+ * it reset the sender's budget, every message would refill the budget that sent it, because a
+ * delivery is what starts the target's turn.
+ */
+export function noteNewTurn(nodeId: string): void {
+ senderTurns.delete(nodeId)
+}
+
+/** Live entry counts, so a test can assert EVICTION rather than infer it from a verdict. */
+export function flowStats(): { pairs: number; senders: number } {
+ return { pairs: pairLastSentAt.size, senders: senderTurns.size }
+}
+
+/** Drop every budget. Test isolation, and the honest teardown for a shell that is shutting down —
+ * forgetting is always the safe direction here (see the failure directions above). */
+export function resetMessageFlow(): void {
+ pairLastSentAt.clear()
+ senderTurns.clear()
+}