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): every delivery leaves a trace, and the board log stops growing forever
Claude Codebafeba6eef38
diff --git a/src/core/agents/agent-message-trace.test.ts b/src/core/agents/agent-message-trace.test.tsnew file mode 100644index 000000000..f1c95a593--- /dev/null+++ b/src/core/agents/agent-message-trace.test.ts@@ -0,0 +1,185 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import {+ recordDelivery,+ recentDeliveries,+ resetAgentMessageTraceForTests,+ TRACE_RING_CAPACITY+} from './agent-message-trace'+import { BoardLogStore, MAX_BOARD_LOG_BYTES, parseLines } from '../board-log'+import type { BoardLogEntry } from '../../shared/types'++let work: string++beforeEach(() => {+ resetAgentMessageTraceForTests()+ work = fs.mkdtempSync(path.join(os.tmpdir(), 'ntmsgtrace-'))+})+afterEach(() => {+ fs.rmSync(work, { recursive: true, force: true })+})++const input = (over: Partial<Parameters<typeof recordDelivery>[0]> = {}): Parameters<typeof recordDelivery>[0] => ({+ sourceNodeId: 'n-src',+ sourceTitle: 'Alpha',+ targetNodeId: 'n-dst',+ outcome: 'delivered',+ receipt: 'newTurn',+ bodyChars: 12,+ ...over+})++describe('recordDelivery — the durable leg', () => {+ it('a cwd-bearing project appends ONE line to <cwd>/.nodeterm/board-log.jsonl', async () => {+ const store = new BoardLogStore({})+ const r = await recordDelivery(input(), {+ appendBoardLog: (e: BoardLogEntry) => store.append(work, e),+ now: () => 1_700_000_000_000+ })+ expect(r.traced).toBe('board-log')+ const raw = fs.readFileSync(path.join(work, '.nodeterm', 'board-log.jsonl'), 'utf8')+ expect(raw.split('\n').filter(Boolean).length).toBe(1)+ const [entry] = parseLines(raw)+ expect(entry.event).toEqual({+ type: 'agent-message',+ from: 'n-src',+ to: 'n-dst',+ title: 'delivered'+ })+ expect(entry.id).toBe(r.traceId)+ expect(entry.nodeId).toBe('n-dst')+ })++ it('records the OUTCOME, not the attempt — a refused-after-write delivery says so', async () => {+ const lines: BoardLogEntry[] = []+ for (const outcome of ['delivered', 'stalled', 'deliveredToReplacedTarget'] as const) {+ await recordDelivery(input({ outcome }), {+ appendBoardLog: async (e) => {+ lines.push(e)+ return true+ },+ now: () => 1+ })+ }+ expect(lines.map((l) => l.event?.title)).toEqual([+ 'delivered',+ 'stalled',+ 'deliveredToReplacedTarget'+ ])+ })++ it('never traces the BODY — only its size', async () => {+ let seen: BoardLogEntry | undefined+ await recordDelivery(input({ bodyChars: 4096 }), {+ appendBoardLog: async (e) => {+ seen = e+ return true+ },+ now: () => 1+ })+ expect(JSON.stringify(seen)).not.toMatch(/body/i)+ expect(recentDeliveries(1)[0].bodyChars).toBe(4096)+ })+})++describe('recordDelivery — the memory leg (Global Constraint 10)', () => {+ it('an UNSUPPORTED project still records, into the ring, and reports traced: memory', async () => {+ // board-log-handlers answers `unsupported` for an inline/no-cwd canvas, a disconnected SSH+ // project, and any SSH project on the Server Edition. The delivery is NOT refused there.+ const r = await recordDelivery(input(), { appendBoardLog: async () => false, now: () => 7 })+ expect(r.traced).toBe('memory')+ expect(recentDeliveries()).toEqual([+ {+ traceId: r.traceId,+ ts: 7,+ sourceNodeId: 'n-src',+ targetNodeId: 'n-dst',+ outcome: 'delivered',+ receipt: 'newTurn',+ bodyChars: 12,+ traced: 'memory'+ }+ ])+ })++ it('a THROWING appender is the same fact as a false one — never a failed delivery', async () => {+ const r = await recordDelivery(input(), {+ appendBoardLog: async () => {+ throw new Error('ssh master went away')+ },+ now: () => 9+ })+ expect(r.traced).toBe('memory')+ expect(recentDeliveries()).toHaveLength(1)+ })++ it('the ring is bounded and evicts the OLDEST', async () => {+ for (let i = 0; i < TRACE_RING_CAPACITY + 25; i++) {+ await recordDelivery(input({ targetNodeId: `n-${i}` }), {+ appendBoardLog: async () => false,+ now: () => i+ })+ }+ // Ask for MORE than the capacity, deliberately. `recentDeliveries()`'s default limit is the+ // capacity itself, so reading with it cannot tell an evicting ring from an unbounded array —+ // that read would slice the last 200 of 225 and look identical. It is the same shape as the+ // board-log's 500 (`slice` after `reverse`, a read cap mistaken for eviction) which this very+ // file rotates around, and this assertion was green with the eviction removed until it asked+ // the question properly.+ const all = recentDeliveries(10_000)+ expect(all).toHaveLength(TRACE_RING_CAPACITY)+ expect(all[0].targetNodeId).toBe(`n-${TRACE_RING_CAPACITY + 24}`) // newest first+ expect(all.at(-1)!.targetNodeId).toBe('n-25') // 0..24 evicted+ })++ it('the ring is written even when the board log took it — Settings reads the ring', async () => {+ const r = await recordDelivery(input(), { appendBoardLog: async () => true, now: () => 3 })+ expect(r.traced).toBe('board-log')+ expect(recentDeliveries(1)[0].traced).toBe('board-log')+ })+})++describe('board-log truncation — the 500 was a READ cap, not an eviction', () => {+ it('rotates to board-log.jsonl.1 past MAX_BOARD_LOG_BYTES and starts a fresh file', async () => {+ const store = new BoardLogStore({})+ const dir = path.join(work, '.nodeterm')+ fs.mkdirSync(dir, { recursive: true })+ const file = path.join(dir, 'board-log.jsonl')+ // One byte under the bound: the next append must rotate.+ fs.writeFileSync(file, 'x'.repeat(MAX_BOARD_LOG_BYTES - 1))+ expect(await store.append(work, entry('after-rotate'))).toBe(true)+ expect(fs.existsSync(`${file}.1`)).toBe(true)+ expect(fs.statSync(`${file}.1`).size).toBe(MAX_BOARD_LOG_BYTES - 1)+ const fresh = fs.readFileSync(file, 'utf8')+ expect(fresh.split('\n').filter(Boolean).length).toBe(1)+ expect(parseLines(fresh)[0].text).toBe('after-rotate')+ })++ it('does NOT rotate below the bound', async () => {+ const store = new BoardLogStore({})+ await store.append(work, entry('one'))+ await store.append(work, entry('two'))+ const file = path.join(work, '.nodeterm', 'board-log.jsonl')+ expect(fs.existsSync(`${file}.1`)).toBe(false)+ expect(parseLines(fs.readFileSync(file, 'utf8')).map((e) => e.text)).toEqual(['two', 'one'])+ })++ it('keeps exactly ONE generation — a second rotation replaces the first', async () => {+ const store = new BoardLogStore({})+ const dir = path.join(work, '.nodeterm')+ fs.mkdirSync(dir, { recursive: true })+ const file = path.join(dir, 'board-log.jsonl')+ fs.writeFileSync(file, 'a'.repeat(MAX_BOARD_LOG_BYTES))+ await store.append(work, entry('gen-1'))+ fs.appendFileSync(file, 'b'.repeat(MAX_BOARD_LOG_BYTES))+ await store.append(work, entry('gen-2'))+ expect(fs.existsSync(`${file}.2`)).toBe(false)+ expect(fs.readFileSync(`${file}.1`, 'utf8')).toContain('gen-1')+ })+})++function entry(text: string): BoardLogEntry {+ return { id: `id-${text}`, ts: 1, author: { name: 'a', color: '#fff' }, kind: 'comment', text }+}diff --git a/src/core/agents/agent-message-trace.ts b/src/core/agents/agent-message-trace.tsnew file mode 100644index 000000000..4b7021928--- /dev/null+++ b/src/core/agents/agent-message-trace.ts@@ -0,0 +1,131 @@+import { randomUUID } from 'crypto'+import type { BoardLogEntry } from '../../shared/types'+import type { AgentMessageOutcomeKind, ReceiptSignal, TraceKind } from './agent-message-decide'++/**+ * EVERY DELIVERY LEAVES A TRACE — and the trace records the OUTCOME, not the attempt.+ *+ * A trace that says "a message was sent" and cannot say whether it landed answers the only question+ * anyone ever asks it with silence. So the entry is written after the outcome is known, and carries+ * the outcome kind.+ *+ * ── WHY THERE ARE TWO PLACES IT CAN LAND ────────────────────────────────────────────────────────+ *+ * The board log is `<cwd>/.nodeterm/board-log.jsonl`, so a cwd-less inline project, a disconnected+ * SSH project, and any SSH project on the Server Edition have NONE (`board-log-handlers.ts` answers+ * `unsupported` for exactly those three). Refusing to deliver there would make messaging+ * unavailable on precisely the inline canvases orchestration is most used on, so delivery is NOT+ * refused: the entry goes into a bounded in-memory ring instead, and the reply says+ * `traced: 'memory'`.+ *+ * The sender is therefore never told a durable trace exists when it does not. That distinction is+ * the whole reason `traced` is on the wire rather than implied.+ *+ * Neither `nodeterm:toast` (a GLOBAL banner, consumed only for clipboard errors) nor the node-scoped+ * copy pill (explicit "one pill, one owner" contract) is a delivery-trace mechanism. They were+ * considered and rejected; this module is what replaced them.+ */++/** How many deliveries the in-memory ring keeps. Bounded because it is a process-lifetime+ * singleton: an orchestration session can deliver for hours, and an unbounded array in the main+ * process is a leak with a nice name. */+export const TRACE_RING_CAPACITY = 200++export interface DeliveryTraceEntry {+ traceId: string+ ts: number+ sourceNodeId: string+ targetNodeId: string+ /** The OUTCOME, not the attempt. */+ outcome: AgentMessageOutcomeKind+ /** Which signal satisfied the receipt, when one did. */+ receipt?: ReceiptSignal+ /** Body size only — the body itself is never traced. A trace that copies the message would put+ * one agent's payload into another project's on-disk history, where nothing expires it. */+ bodyChars: number+ /** Where the durable copy went. `memory` means there is no durable copy. */+ traced: TraceKind+}++/** Everything `recordDelivery` needs that is not a pure value. Injected, so the ring and the board+ * log can both be exercised without a filesystem. */+export interface TraceDeps {+ /** Append to the project's board log. `false` = no reachable log (or the write failed) ⇒ ring+ * only. Wired by the shell to `BoardLogStore.append` / the boardLogAppend handler. */+ appendBoardLog(entry: BoardLogEntry): Promise<boolean>+ now(): number+ /** Overridable so a test can pin the id. */+ traceId?(): string+}++export interface DeliveryTraceInput {+ sourceNodeId: string+ sourceTitle: string+ targetNodeId: string+ outcome: AgentMessageOutcomeKind+ receipt?: ReceiptSignal+ bodyChars: number+}++const ring: DeliveryTraceEntry[] = []++/** The author stamped on a board-log line. A delivery is the app's own action, not a person's. */+const TRACE_AUTHOR = { name: 'nodeterm', color: '#8b8b8b' } as const++/**+ * Record one delivery. Never throws and never refuses: a trace failure must not fail a delivery+ * that has already put bytes into somebody's pane.+ *+ * The ring is written ALWAYS, board log or not, because it is what Settings → Agents reads (Task+ * 6.3) and a durable line in one project's file is not a live view of this process's deliveries.+ * `traced` reports only whether a DURABLE copy exists.+ */+export async function recordDelivery(+ input: DeliveryTraceInput,+ deps: TraceDeps+): Promise<{ traceId: string; traced: TraceKind }> {+ const traceId = (deps.traceId ?? randomUUID)()+ const ts = deps.now()+ let traced: TraceKind = 'memory'+ try {+ const ok = await deps.appendBoardLog({+ id: traceId,+ ts,+ author: TRACE_AUTHOR,+ nodeId: input.targetNodeId,+ kind: 'event',+ event: {+ type: 'agent-message',+ from: input.sourceNodeId,+ to: input.targetNodeId,+ title: input.outcome+ }+ })+ if (ok) traced = 'board-log'+ } catch {+ traced = 'memory' // an exception from the shell's appender is the same fact as `false`+ }+ ring.push({+ traceId,+ ts,+ sourceNodeId: input.sourceNodeId,+ targetNodeId: input.targetNodeId,+ outcome: input.outcome,+ ...(input.receipt ? { receipt: input.receipt } : {}),+ bodyChars: input.bodyChars,+ traced+ })+ while (ring.length > TRACE_RING_CAPACITY) ring.shift()+ return { traceId, traced }+}++/** The most recent deliveries, NEWEST FIRST — the same order `parseLines` hands the board log back,+ * so a UI can concatenate the two without re-sorting. */+export function recentDeliveries(limit = TRACE_RING_CAPACITY): DeliveryTraceEntry[] {+ const n = Math.max(0, Math.min(limit, ring.length))+ return ring.slice(ring.length - n).reverse()+}++export function resetAgentMessageTraceForTests(): void {+ ring.length = 0+}diff --git a/src/core/board-log.ts b/src/core/board-log.tsindex aeefc8864..db2e42ceb 100644--- a/src/core/board-log.ts+++ b/src/core/board-log.ts@@ -16,6 +16,24 @@ const LOG_DIR = '.nodeterm'const LOG_FILE = 'board-log.jsonl'const DEFAULT_CAP = 500+/**+ * Rotate the log once it passes this size, keeping ONE previous generation+ * (`board-log.jsonl.1`).+ *+ * The 500 in `DEFAULT_CAP` is not, and never was, an eviction: `parseLines` applies+ * `out.slice(0, cap)` AFTER `out.reverse()`, so it is a READ cap — nothing was ever removed, real+ * history was hidden below the fold, and `appendFileSync` grew the file UNBOUNDED inside the user's+ * repo. That was survivable while entries were human board actions; a feature that writes one entry+ * per agent-to-agent delivery must not ship without a bound.+ *+ * 4 MiB is ~40k entries at the size these lines actually are, and one generation means the worst+ * case on disk is 8 MiB + one line. Rotation is LOCAL ONLY: `RemoteLogExec` exposes `append`/`tail`+ * and nothing that can stat or rename, and inventing a third remote verb to run `mv` over a+ * ControlMaster is a bigger change than this defect justifies. An SSH project's log therefore still+ * grows — documented here rather than silently unbounded in two places.+ */+export const MAX_BOARD_LOG_BYTES = 4 * 1024 * 1024+/** Clamp an entry's `text` to `BOARD_LOG_TEXT_MAX` chars (+ '…' when truncated). Returns the* same entry when nothing changes, else a shallow copy with the shortened text. */export function clampEntryText(entry: BoardLogEntry): BoardLogEntry {@@ -115,6 +133,7 @@ export class BoardLogStore {}try {fs.mkdirSync(path.join(cwd, LOG_DIR), { recursive: true })+ this.rotateIfLarge(this.localPath(cwd), line.length)fs.appendFileSync(this.localPath(cwd), line)return true} catch {@@ -122,6 +141,27 @@ export class BoardLogStore {}}+ /**+ * Move the log aside when this append would take it past `MAX_BOARD_LOG_BYTES`.+ *+ * Rotates BEFORE the write, so the bound holds for the file as it exists on disk rather than one+ * entry late. `renameSync` over an existing `.1` replaces it — one generation, deliberately: two+ * would double the worst case for a file that lives inside the user's repository.+ *+ * Never throws: a log that cannot be rotated must still be APPENDED to (the caller's `try` then+ * decides), because losing a board entry to a failed housekeeping step is a worse outcome than a+ * file that is briefly too large.+ */+ private rotateIfLarge(file: string, incoming: number): void {+ try {+ const size = fs.statSync(file).size+ if (size + incoming <= MAX_BOARD_LOG_BYTES) return+ fs.renameSync(file, `${file}.1`)+ } catch {+ // No file yet (the common case), or an unstattable/unrenamable one — append regardless.+ }+ }+/** Read the log, newest-first (see parseLines). Missing file / failed read → []. */async read(cwd: string, opts: ParseOpts = {}): Promise<BoardLogEntry[]> {if (this.remote) {diff --git a/src/renderer/components/kanban/BoardLogPanel.tsx b/src/renderer/components/kanban/BoardLogPanel.tsxindex cdb92f04f..4bc9c3ce6 100644--- a/src/renderer/components/kanban/BoardLogPanel.tsx+++ b/src/renderer/components/kanban/BoardLogPanel.tsx@@ -40,6 +40,8 @@ function eventBody(e: BoardLogEvent): string {return `set priority → ${e.to ?? ''}`.trimEnd()case 'priority-cleared':return `removed the priority`+ case 'agent-message':+ return `sent a message to ${e.to ?? 'another node'} (${e.title ?? 'unknown outcome'})`default:// A newer peer may write event types this build doesn't know — show them neutrally.return `updated this card`diff --git a/src/shared/types.ts b/src/shared/types.tsindex dccd02d93..c1ae09023 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -397,9 +397,13 @@ export interface BoardLogEvent {| 'due-cleared'| 'priority-set'| 'priority-cleared'+ /** An agent-to-agent message delivery. `from`/`to` are NODE IDS (not column names) and `title`+ * is the delivery's outcome kind — a trace that cannot answer "did it land?" answers the only+ * question anyone asks it with silence. Written by `agent-message-trace.recordDelivery`. */+ | 'agent-message'from?: stringto?: string- /** Column title for column-added/deleted; card title for card-created. */+ /** Column title for column-added/deleted; card title for card-created; outcome for agent-message. */title?: string}