@miadi/tide 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -187,6 +187,32 @@ before it reads context or proposes a steer. The cockpit routes (`steer`, `peek`
187
187
  `terminals`) are still tmux-only — herdr reachability from `/api/tide/*` is tracked in
188
188
  jgwill/Miadi#494.
189
189
 
190
+ ### Annotate surface — `/api/tide/annotate/{resolve,mark,deliver}` (2026-09-12)
191
+
192
+ The web leg of the plannotator review loop that `tan <pane>` runs in a terminal. Verbs:
193
+ `fetchReply(pane, {pick, host})`, `listBlocks(doc)`, `mark(doc, {block | quote, text, kind})`,
194
+ `exportReview(doc)`, `deliver(pane, doc, {submit})`. An adapter over
195
+ `/opt/gaia/linux_migration/11-plannotator-tmux-review.sh` (jgwill/gaia#80) and a headless
196
+ `plannotator-tui` — no resolution or delivery logic of its own, so the two clients cannot drift.
197
+ Marks land in plannotator's store keyed by the vessel document, so a review begun in the browser
198
+ can be finished in the terminal TUI and the other way round. A block mark is always a comment;
199
+ `looks_good` / `delete` need a quote (plannotator-tui 0.6.0). tmux only.
200
+
201
+ Second pass (2026-09-12, Mia's marks, Episode 339): a vessel remembers the pane it was fetched
202
+ from (`source.json`) and `deliver` refuses any other pane, or a document with no source identity;
203
+ every mark made here carries `author` (a stable principal id) and `author_name` — required in
204
+ `mark()`, derived from a tailnet identity by the route when there is one — while marks made
205
+ earlier or in the TUI stay unattributed. Gates: `resolve` and `mark` are writer-tier
206
+ (`requireMiadiAuth({ write: true })`, as `/api/tide/peek`); `deliver` additionally needs the writer
207
+ token or a tailnet identity, as `/api/tide/steer`, and answers a pane-guard refusal as `held`, not
208
+ an error. Proven in `tests/annotate-routes.test.mjs` and `test/annotate-deliver.test.ts`.
209
+
210
+ Resolution: `PLANNOTATOR_TMUX_REVIEW_SCRIPT` → the gaia path above; `PLANNOTATOR_TUI_BIN` →
211
+ `which plannotator-tui` → `~/.cargo/bin/plannotator-tui` (the Next server's PATH lacks cargo's
212
+ bin); `PLANNOTATOR_TMUX_REVIEW_DIR` is the script's own vessel root, web runs sit under `web/`.
213
+ Grounding: `foundations/annotation-as-coordination/`. Routes: `app/api/tide/annotate/*`;
214
+ UI: `components/tide/reply-annotator.tsx` in the `/tide` pane inspector.
215
+
190
216
  ## Tests
191
217
 
192
218
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/tide",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Typed client boundary for the ironsilk `tide` runtime. Daemon Unix-socket transport with CLI fallback.",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -15,6 +15,7 @@
15
15
  "src"
16
16
  ],
17
17
  "dependencies": {
18
+ "@miadi/annotate-core": "^0.1.0",
18
19
  "@miadi/tide-contract": "0.3.0"
19
20
  },
20
21
  "keywords": [
@@ -24,6 +25,6 @@
24
25
  "operator-cockpit"
25
26
  ],
26
27
  "scripts": {
27
- "test": "d=$(mktemp -d \"${TMPDIR:-/tmp}/miadi-tide-test.XXXXXX\") && trap 'rm -rf \"$d\"' EXIT && ../../node_modules/.bin/tsc -p tsconfig.test.json --outDir \"$d\" && node --test \"$d\"/packages/tide/test/*.test.js"
28
+ "test": "d=$(mktemp -d \"${TMPDIR:-/tmp}/miadi-tide-test.XXXXXX\") && trap 'rm -rf \"$d\"' EXIT && ../../node_modules/.bin/tsc -p tsconfig.test.json --outDir \"$d\" && ln -s \"$PWD/node_modules\" \"$d/packages/tide/node_modules\" && node --test \"$d\"/packages/tide/test/*.test.js"
28
29
  }
29
30
  }
@@ -0,0 +1,768 @@
1
+ // Annotate an agent's last reply from a non-terminal client, and deliver the
2
+ // review into its tmux pane — the web leg of the plannotator review loop.
3
+ //
4
+ // This module owns NO resolution and NO delivery logic of its own. Both belong
5
+ // to /opt/gaia/linux_migration/11-plannotator-tmux-review.sh (jgwill/gaia#80),
6
+ // which already proves the reply belongs to the pane, keeps every run in a
7
+ // durable vessel, refuses to paste while a human is typing, and pastes with
8
+ // bracketed paste so a multi-line review does not submit itself line by line.
9
+ // A second implementation of any of that would drift from the first. So this
10
+ // is an adapter: it runs the script's two non-interactive legs (`--no-tui` to
11
+ // fetch, `--from-file … --no-tui` to deliver) and `plannotator-tui` headlessly
12
+ // for marks and exports, through execFile argument arrays (no shell).
13
+ //
14
+ // Marks made here land in the same store the terminal TUI reads
15
+ // (~/.plannotator/clients/plannotator-tui/annotations/…, keyed by document
16
+ // path), so a review begun in the browser can be finished in `tan`, and the
17
+ // other way round. Measured 2026-09-12 on gaia: `--annotate-block`,
18
+ // `--annotate` and `--export` all return 0 from a process with no TTY.
19
+ //
20
+ // Second pass, 2026-09-12, from Mia's marks on the first account (Episode 339):
21
+ // • A vessel remembers the pane it was fetched from (`source.json`), and
22
+ // deliver() refuses any other pane. Root containment and the pane guard
23
+ // never bound a document to its source, and the script's `--from-file` leg
24
+ // skips agent resolution — so before this, a reply read from pane A could
25
+ // be pasted into pane B by anyone holding the writer token.
26
+ // • Every mark made through this module carries a stable principal id and a
27
+ // readable name (`author` / `author_name` on the record — both fields exist
28
+ // in plannotator-tui 0.6.0's struct and survive export and further marks).
29
+ // Marks made earlier, or in the terminal TUI, stay unattributed; nothing
30
+ // here assigns an author after the fact.
31
+ //
32
+ // Ref: jgwill/gaia#80 · foundations/annotation-as-coordination/
33
+
34
+ import { execFile } from "node:child_process"
35
+ import { promisify } from "node:util"
36
+ import { mkdir, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises"
37
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"
38
+ import { homedir } from "node:os"
39
+ import { randomBytes } from "node:crypto"
40
+ import { TideError } from "./errors"
41
+ import { isMarkAuthor, MARK_KINDS, resolveQuote } from "@miadi/annotate-core"
42
+ import type {
43
+ AnnotateBlock,
44
+ AnnotateDocument,
45
+ DeliverOutcome,
46
+ MarkAuthor,
47
+ MarkKind,
48
+ QuoteSelector,
49
+ StoredMark,
50
+ } from "@miadi/annotate-core"
51
+
52
+ const pExecFile = promisify(execFile)
53
+
54
+ export const DEFAULT_REVIEW_SCRIPT = "/opt/gaia/linux_migration/11-plannotator-tmux-review.sh"
55
+ export const REVIEW_SCRIPT_ENV = "PLANNOTATOR_TMUX_REVIEW_SCRIPT"
56
+ /** The script's own override for where run vessels live. Same name, same meaning. */
57
+ export const VESSEL_ROOT_ENV = "PLANNOTATOR_TMUX_REVIEW_DIR"
58
+ export const PLANNOTATOR_BIN_ENV = "PLANNOTATOR_TUI_BIN"
59
+ /** Where plannotator-tui keeps its records; override for tests. */
60
+ export const STORE_ROOT_ENV = "PLANNOTATOR_STORE_DIR"
61
+ /** Web-made runs sit under `<root>/web/<stamp>/` so `cdtan` still lists terminal runs first. */
62
+ export const WEB_VESSEL_SUBDIR = "web"
63
+ /** The vessel's memory of where its document came from. */
64
+ export const SOURCE_FILE = "source.json"
65
+
66
+ /**
67
+ * Anything tmux accepts as a target, minus anything that could read as an
68
+ * option (no leading `-`) or reach a shell (there is no shell, but the script
69
+ * hands it to `tmux -t`). `%56`, `56`, `trading-gold`, `sess:1.0` all pass.
70
+ */
71
+ export const ANNOTATE_TARGET_PATTERN = /^[A-Za-z0-9%][A-Za-z0-9._:%-]{0,119}$/
72
+ export const ANNOTATE_HOSTS = ["claude", "codex", "pi", "omp", "copilot", "droid", "hermes", "opencode"] as const
73
+ export type AnnotateHost = (typeof ANNOTATE_HOSTS)[number]
74
+ // The vocabulary any annotated document shares lives in @miadi/annotate-core,
75
+ // so a page without this Node adapter (a browser, gmtermux) speaks the same
76
+ // types. The names this module always exported stay exported, as aliases.
77
+ export { AUTHOR_ID_PATTERN, MARK_KINDS, isMarkAuthor } from "@miadi/annotate-core"
78
+ export type { MarkAuthor, MarkKind, QuoteSelector } from "@miadi/annotate-core"
79
+
80
+ /** One block of the reply. `row` is its 0-based first line in the document. */
81
+ export type ReplyBlock = AnnotateBlock
82
+
83
+ /** The pane identity tmux itself reports for a target. `pane_id` is stable for the pane's lifetime. */
84
+ export interface PaneIdentity {
85
+ pane_id: string
86
+ session_name: string
87
+ window_index: string
88
+ pane_index: string
89
+ pane_pid: string
90
+ }
91
+
92
+ export interface SourceIdentity extends PaneIdentity {
93
+ /** The target as it was requested (`%64`, `56`, `session:0.0`). */
94
+ target: string
95
+ agent_pid: string | null
96
+ host: string | null
97
+ cwd: string | null
98
+ fetched_at: string
99
+ }
100
+
101
+ /** A reply fetched from a pane: core's document (`id` is the vessel's reply.md) plus where it came from. */
102
+ export interface FetchedReply extends AnnotateDocument {
103
+ target: string
104
+ vessel: string
105
+ doc: string
106
+ blocks: ReplyBlock[]
107
+ source: SourceIdentity
108
+ /** The script's stderr, ANSI stripped — the `ok agent N`, `ok transcript host` lines. */
109
+ log: string[]
110
+ }
111
+
112
+ /** A mark as this adapter takes it: the author is required here; a host resolves it first. */
113
+ export interface MarkInput {
114
+ block?: number
115
+ /** Exact words, or core's selector with context that names one occurrence. */
116
+ quote?: string | QuoteSelector
117
+ text: string
118
+ kind?: MarkKind
119
+ author: MarkAuthor
120
+ }
121
+
122
+ export interface ReviewExport {
123
+ doc: string
124
+ /** The numbered review exactly as `--export` prints it; empty when count is 0. */
125
+ review: string
126
+ count: number
127
+ }
128
+
129
+ export interface MarkResult extends ReviewExport {
130
+ /** How many new records received the author. 1 on the normal path. */
131
+ stamped: number
132
+ author: MarkAuthor
133
+ }
134
+
135
+ export interface DeliverResult extends DeliverOutcome {
136
+ target: string
137
+ doc: string
138
+ source: SourceIdentity
139
+ /** The exact terminal command that re-delivers this document later, to its source pane. */
140
+ redeliver: string
141
+ review: string
142
+ log: string[]
143
+ }
144
+
145
+ export function resolveReviewScript(env: NodeJS.ProcessEnv = process.env): string {
146
+ return env[REVIEW_SCRIPT_ENV]?.trim() || DEFAULT_REVIEW_SCRIPT
147
+ }
148
+
149
+ /** Mirrors the script: `$PLANNOTATOR_TMUX_REVIEW_DIR` → `$XDG_STATE_HOME/…` → `~/.local/state/…`. */
150
+ export function resolveVesselRoot(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
151
+ const fromEnv = env[VESSEL_ROOT_ENV]?.trim()
152
+ if (fromEnv) return fromEnv
153
+ const xdg = env.XDG_STATE_HOME?.trim()
154
+ return join(xdg || join(home, ".local", "state"), "plannotator-tmux-review")
155
+ }
156
+
157
+ /** plannotator-tui's record root: `$PLANNOTATOR_STORE_DIR` → `~/.plannotator/clients/plannotator-tui/annotations`. */
158
+ export function resolveStoreRoot(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
159
+ const fromEnv = env[STORE_ROOT_ENV]?.trim()
160
+ if (fromEnv) return fromEnv
161
+ return join(home, ".plannotator", "clients", "plannotator-tui", "annotations")
162
+ }
163
+
164
+ function resolveTmuxBin(env: NodeJS.ProcessEnv = process.env): string {
165
+ return env.TIDE_TMUX_BIN?.trim() || "tmux"
166
+ }
167
+
168
+ let cachedPlannotator: Promise<string> | null = null
169
+
170
+ /**
171
+ * `PLANNOTATOR_TUI_BIN` → `which plannotator-tui` → `~/.cargo/bin/plannotator-tui`.
172
+ * The last resort is real: the Next server on gaia is launched with a PATH that
173
+ * has pnpm and /usr/bin on it and not cargo's install dir (read from
174
+ * /proc/<pid>/environ, 2026-09-12), while the binary lives there for the same user.
175
+ */
176
+ export function resolvePlannotatorBin(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): Promise<string> {
177
+ if (cachedPlannotator) return cachedPlannotator
178
+ cachedPlannotator = (async () => {
179
+ const fromEnv = env[PLANNOTATOR_BIN_ENV]?.trim()
180
+ if (fromEnv) return fromEnv
181
+ try {
182
+ const { stdout } = await pExecFile("which", ["plannotator-tui"], { timeout: 3000 })
183
+ const found = stdout.trim().split("\n")[0]?.trim()
184
+ if (found) return found
185
+ } catch {
186
+ // not on PATH — fall through
187
+ }
188
+ return join(home, ".cargo", "bin", "plannotator-tui")
189
+ })()
190
+ return cachedPlannotator
191
+ }
192
+
193
+ export function resetPlannotatorBinCache(): void {
194
+ cachedPlannotator = null
195
+ }
196
+
197
+ export function stripAnsi(s: string): string {
198
+ return s.replace(/\x1b\[[0-9;]*[A-Za-z]/g, "")
199
+ }
200
+
201
+ function logLines(stderr: string): string[] {
202
+ return stripAnsi(stderr)
203
+ .split("\n")
204
+ .map(l => l.trimEnd())
205
+ .filter(l => l.trim().length > 0)
206
+ }
207
+
208
+ /**
209
+ * Turn `plannotator-tui --blocks` output plus the document into blocks that
210
+ * carry their FULL text.
211
+ *
212
+ * The tool's `row` is NOT a document line. It is a position on the tool's own
213
+ * rendered view: runs of blank lines collapse, and on 2026-09-13 a reply of
214
+ * three one-line paragraphs (document lines 0, 2, 4) came back as rows 0, 4, 8.
215
+ * Slicing the document by row put two paragraphs in block 0 and left block 2
216
+ * past the end of the file, empty. What the tool does keep exact is the ORDER
217
+ * of blocks and the first line of each block's source in its preview column
218
+ * (truncated). So each block starts at the first line, at or after the
219
+ * previous block, whose text begins with its preview, and runs to the next
220
+ * block's start. A fenced code block is skipped whole before the next search,
221
+ * so a matching line inside the code cannot be taken for the next block. A
222
+ * preview that matches nothing falls back to the next non-blank line.
223
+ *
224
+ * `row` on the result is the matched document line (0-based). Marks never use
225
+ * it; they address blocks by `index`.
226
+ */
227
+ export function parseBlocks(blocksOutput: string, docText: string): ReplyBlock[] {
228
+ const lines = docText.split("\n")
229
+ const heads: Array<{ index: number; kind: string; toolRow: number; preview: string }> = []
230
+ for (const line of blocksOutput.split("\n")) {
231
+ const m = /^\s*(\d+)\s+(\S+)\s+row\s+(\d+)(?: {2}(.*))?$/.exec(line)
232
+ if (m) heads.push({ index: Number(m[1]), kind: m[2], toolRow: Number(m[3]), preview: m[4] ?? "" })
233
+ }
234
+ heads.sort((a, b) => a.index - b.index)
235
+
236
+ const norm = (t: string) => t.replace(/\s+/g, " ").trim()
237
+ const starts: number[] = []
238
+ let cursor = 0
239
+ for (const h of heads) {
240
+ const want = norm(h.preview)
241
+ let at = -1
242
+ if (want) {
243
+ for (let i = cursor; i < lines.length; i++) {
244
+ if (norm(lines[i]).startsWith(want)) { at = i; break }
245
+ }
246
+ }
247
+ if (at === -1) {
248
+ at = cursor
249
+ while (at < lines.length - 1 && lines[at].trim() === "") at++
250
+ }
251
+ starts.push(at)
252
+ cursor = Math.min(at + 1, lines.length)
253
+ const fence = /^\s*(```|~~~)/.exec(lines[at] ?? "")
254
+ if (h.kind === "CodeBlock" && fence) {
255
+ for (let j = at + 1; j < lines.length; j++) {
256
+ if (lines[j].trimStart().startsWith(fence[1])) { cursor = j + 1; break }
257
+ }
258
+ }
259
+ }
260
+
261
+ return heads.map((h, i) => {
262
+ const start = starts[i]
263
+ const end = i + 1 < heads.length ? Math.max(starts[i + 1], start) : lines.length
264
+ return { index: h.index, kind: h.kind, row: start, text: lines.slice(start, end).join("\n").replace(/\s+$/, "") }
265
+ })
266
+ }
267
+
268
+ /** `--export` prints `No annotations.` for zero, else one `## Annotation N` per mark. */
269
+ export function countAnnotations(review: string): number {
270
+ return (review.match(/^## Annotation\b/gm) ?? []).length
271
+ }
272
+
273
+ export function buildFetchArgv(script: string, target: string, opts: { pick?: number; host?: AnnotateHost } = {}): string[] {
274
+ const argv = [script, target, "--no-tui", "--pick", String(opts.pick ?? 1)]
275
+ if (opts.host) argv.push("--host", opts.host)
276
+ return argv
277
+ }
278
+
279
+ export function buildDeliverArgv(script: string, target: string, doc: string, submit: boolean): string[] {
280
+ const argv = [script, target, "--from-file", doc, "--no-tui"]
281
+ if (submit) argv.push("--submit")
282
+ return argv
283
+ }
284
+
285
+ /**
286
+ * A quote mark carries a kind; a block mark is always a comment — plannotator-tui
287
+ * 0.6.0's `--annotate-block` takes no kind and ignores a fourth argument
288
+ * (measured 2026-09-12). Callers wanting looks_good/delete pass a quote.
289
+ */
290
+ export function buildMarkArgv(
291
+ bin: string,
292
+ doc: string,
293
+ input: Pick<MarkInput, "block" | "quote" | "text" | "kind">,
294
+ occurrence = 1,
295
+ ): string[] {
296
+ const kind = input.kind ?? "comment"
297
+ if (input.quote !== undefined) {
298
+ const argv = [bin, "--annotate", doc, quoteExact(input.quote), input.text, kind]
299
+ // plannotator-tui marks the first occurrence unless told otherwise.
300
+ if (occurrence > 1) argv.push("--occurrence", String(occurrence))
301
+ return argv
302
+ }
303
+ if (input.block !== undefined) return [bin, "--annotate-block", doc, String(input.block), input.text]
304
+ throw new TideError("a mark needs a block index or a quote")
305
+ }
306
+
307
+ function quoteExact(quote: string | QuoteSelector): string {
308
+ return typeof quote === "string" ? quote : quote.exact
309
+ }
310
+
311
+ /**
312
+ * For a plannotator-tui without `--occurrence`, which anchors a quote on its
313
+ * FIRST occurrence (`source.find(quote)`). A quote whose context names a later occurrence would
314
+ * be marked on the wrong sentence, so it is refused with a way forward. A
315
+ * phrase that appears once, or whose context names the first occurrence,
316
+ * passes. Ref: jgwill/Miadi#683 (D3).
317
+ */
318
+ export function assertQuoteAnchors(text: string, quote: string | QuoteSelector): void {
319
+ const selector: QuoteSelector = typeof quote === "string" ? { exact: quote } : quote
320
+ const r = resolveQuote(text, selector)
321
+ if ("missing" in r) throw new TideError("those words are not in the reply: select them again inside one block")
322
+ if ("ambiguous" in r) throw new TideError(`these words appear ${r.ambiguous} times in the reply; select a longer phrase`)
323
+ if (r.start !== text.indexOf(selector.exact)) {
324
+ throw new TideError(
325
+ `these words appear ${r.occurrences} times in the reply and only the first can be marked for now; select a longer phrase`,
326
+ )
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Which occurrence of its exact words a quote names, counted as plannotator-tui
332
+ * counts them (1-based, non-overlapping, `str::match_indices`), for
333
+ * `--annotate … --occurrence N`. Missing words and a phrase whose context
334
+ * cannot pick one occurrence are refused with a way forward.
335
+ */
336
+ export function quoteOccurrence(text: string, quote: string | QuoteSelector): number {
337
+ const selector: QuoteSelector = typeof quote === "string" ? { exact: quote } : quote
338
+ const r = resolveQuote(text, selector)
339
+ if ("missing" in r) throw new TideError("those words are not in the reply: select them again inside one block")
340
+ if ("ambiguous" in r) throw new TideError(`these words appear ${r.ambiguous} times in the reply; select a longer phrase`)
341
+ let n = 0
342
+ for (let at = text.indexOf(selector.exact); at !== -1; at = text.indexOf(selector.exact, at + selector.exact.length)) {
343
+ n++
344
+ if (at === r.start) return n
345
+ if (at > r.start) break
346
+ }
347
+ // The words overlap themselves ("haha" in "hahaha") and the match sits between two counted ones.
348
+ throw new TideError("these words overlap another occurrence of themselves; select a longer phrase")
349
+ }
350
+
351
+ /**
352
+ * Whether the installed plannotator-tui takes `--occurrence` (added in
353
+ * miadisabelle/mia-plannotator-tui#1). Its usage text says so. An older binary
354
+ * would ignore the flag and mark the first occurrence, so marks on a later one
355
+ * are refused there instead (`assertQuoteAnchors`).
356
+ */
357
+ const occurrenceSupport = new Map<string, Promise<boolean>>()
358
+ export function plannotatorTakesOccurrence(bin: string): Promise<boolean> {
359
+ let known = occurrenceSupport.get(bin)
360
+ if (!known) {
361
+ known = run([bin, "--usage-probe"], { timeoutMs: 10_000 })
362
+ .then(r => `${r.stdout}\n${r.stderr}`.includes("--occurrence"))
363
+ .catch(() => false)
364
+ occurrenceSupport.set(bin, known)
365
+ }
366
+ return known
367
+ }
368
+
369
+ /** Pure containment check; `assertVesselDoc` adds symlink resolution. */
370
+ export function isInsideRoot(doc: string, root: string): boolean {
371
+ const rel = relative(resolve(root), resolve(doc))
372
+ return rel.length > 0 && !rel.startsWith("..") && !isAbsolute(rel)
373
+ }
374
+
375
+ /**
376
+ * The only documents this module will mark or paste are Markdown files inside
377
+ * the review vessel root. `doc` arrives from an HTTP body and ends up in an argv
378
+ * that pastes the file's marks into a live pane; without this line any readable
379
+ * file on the host could be annotated and typed into a terminal.
380
+ */
381
+ export async function assertVesselDoc(doc: unknown, root: string = resolveVesselRoot()): Promise<string> {
382
+ if (typeof doc !== "string" || !doc.endsWith(".md") || !isAbsolute(doc)) {
383
+ throw new TideError("doc must be an absolute .md path inside the review vessel root")
384
+ }
385
+ let real: string
386
+ try {
387
+ real = await realpath(doc)
388
+ } catch {
389
+ throw new TideError(`doc not found: ${doc}`)
390
+ }
391
+ let realRoot: string
392
+ try {
393
+ realRoot = await realpath(root)
394
+ } catch {
395
+ throw new TideError(`review vessel root not found: ${root}`)
396
+ }
397
+ if (!isInsideRoot(real, realRoot)) throw new TideError("doc must live inside the review vessel root")
398
+ return real
399
+ }
400
+
401
+ // ------------------------------------------------------------ pane identity --
402
+
403
+ /** The `tmux display-message -p` format that yields one PaneIdentity per line. */
404
+ export const TMUX_IDENTITY_FORMAT = "#{pane_id}\t#{session_name}\t#{window_index}\t#{pane_index}\t#{pane_pid}"
405
+
406
+ export function parsePaneIdentity(line: string): PaneIdentity | null {
407
+ const parts = line.trim().split("\t")
408
+ if (parts.length !== 5 || !/^%\d+$/.test(parts[0])) return null
409
+ const [pane_id, session_name, window_index, pane_index, pane_pid] = parts
410
+ return { pane_id, session_name, window_index, pane_index, pane_pid }
411
+ }
412
+
413
+ /** The script names the agent it resolved; keep that beside the pane identity when present. */
414
+ export function parseAgentFromLog(log: string[]): { agent_pid: string | null; host: string | null; cwd: string | null } {
415
+ let agent_pid: string | null = null
416
+ let host: string | null = null
417
+ let cwd: string | null = null
418
+ for (const line of log) {
419
+ const a = /\bok agent (\d+) \(([^)]+)\)/.exec(line)
420
+ if (a) agent_pid = a[1]
421
+ const h = /\btranscript host (\S+), cwd (.+)$/.exec(line)
422
+ if (h) {
423
+ host = h[1]
424
+ cwd = h[2].trim()
425
+ }
426
+ }
427
+ return { agent_pid, host, cwd }
428
+ }
429
+
430
+ /** Identity equality is on `pane_id`: tmux never reuses one while the server runs. */
431
+ export function sourceMatches(source: Pick<SourceIdentity, "pane_id">, here: Pick<PaneIdentity, "pane_id">): boolean {
432
+ return source.pane_id === here.pane_id
433
+ }
434
+
435
+ export function describePane(p: PaneIdentity): string {
436
+ return `${p.pane_id} (${p.session_name}:${p.window_index}.${p.pane_index})`
437
+ }
438
+
439
+ /** Ask tmux who `target` is right now; null when there is no such pane. */
440
+ export async function resolvePaneIdentity(target: string): Promise<PaneIdentity | null> {
441
+ const r = await run([resolveTmuxBin(), "display-message", "-p", "-t", target, TMUX_IDENTITY_FORMAT], { timeoutMs: 5_000 })
442
+ if (r.code !== 0) return null
443
+ return parsePaneIdentity(r.stdout)
444
+ }
445
+
446
+ export async function readSourceIdentity(doc: string): Promise<SourceIdentity | null> {
447
+ try {
448
+ const raw = await readFile(join(dirname(doc), SOURCE_FILE), "utf8")
449
+ const s = JSON.parse(raw) as Partial<SourceIdentity>
450
+ if (typeof s.pane_id !== "string" || !/^%\d+$/.test(s.pane_id)) return null
451
+ return s as SourceIdentity
452
+ } catch {
453
+ return null
454
+ }
455
+ }
456
+
457
+ // ------------------------------------------------------------ author stamping --
458
+
459
+ /**
460
+ * Locate the plannotator record for `doc`: `<store>/<slug>/<doc-slug>/annotations.json`
461
+ * whose `path` is the document. The slug rule is the tool's own and not stable
462
+ * across versions, so the record is found by its content, not by rebuilding
463
+ * the slug.
464
+ */
465
+ export async function findStoreFile(doc: string, root: string = resolveStoreRoot()): Promise<string | null> {
466
+ let candidates: string[] = []
467
+ try {
468
+ const level1 = await readdir(root, { withFileTypes: true })
469
+ for (const a of level1) {
470
+ if (!a.isDirectory()) continue
471
+ const level2 = await readdir(join(root, a.name), { withFileTypes: true })
472
+ for (const b of level2) {
473
+ if (b.isDirectory()) candidates.push(join(root, a.name, b.name, "annotations.json"))
474
+ }
475
+ }
476
+ } catch {
477
+ return null
478
+ }
479
+ let realDoc = doc
480
+ try {
481
+ realDoc = await realpath(doc)
482
+ } catch {
483
+ // compare on the given path only
484
+ }
485
+ for (const file of candidates) {
486
+ try {
487
+ const rec = JSON.parse(await readFile(file, "utf8")) as { path?: unknown }
488
+ if (rec.path === doc || rec.path === realDoc) return file
489
+ } catch {
490
+ // not a record — skip
491
+ }
492
+ }
493
+ return null
494
+ }
495
+
496
+ interface StoreAnnotation {
497
+ id?: unknown
498
+ author?: unknown
499
+ author_name?: unknown
500
+ [k: string]: unknown
501
+ }
502
+ interface StoreRecord {
503
+ path?: unknown
504
+ annotations?: StoreAnnotation[]
505
+ [k: string]: unknown
506
+ }
507
+
508
+ export function recordIds(rec: StoreRecord): Set<string> {
509
+ return new Set((rec.annotations ?? []).map(a => (typeof a.id === "string" ? a.id : "")).filter(Boolean))
510
+ }
511
+
512
+ /**
513
+ * Write the author onto exactly the records in `ids` that have none. Returns how
514
+ * many were stamped. A record that already carries an author is left alone —
515
+ * the rule is no assignment after the fact, in either direction.
516
+ */
517
+ export function stampAuthor(rec: StoreRecord, ids: Set<string>, author: MarkAuthor): number {
518
+ let n = 0
519
+ for (const a of rec.annotations ?? []) {
520
+ if (typeof a.id !== "string" || !ids.has(a.id)) continue
521
+ if (a.author !== null && a.author !== undefined) continue
522
+ a.author = author.id
523
+ a.author_name = author.name
524
+ n++
525
+ }
526
+ return n
527
+ }
528
+
529
+ // --------------------------------------------------------------- processes --
530
+
531
+ interface RunResult {
532
+ code: number
533
+ stdout: string
534
+ stderr: string
535
+ }
536
+
537
+ async function run(argv: string[], opts: { env?: NodeJS.ProcessEnv; timeoutMs?: number } = {}): Promise<RunResult> {
538
+ const [file, ...args] = argv
539
+ const timeout = opts.timeoutMs ?? 60_000
540
+ try {
541
+ const { stdout, stderr } = await pExecFile(file, args, { env: opts.env, timeout, maxBuffer: 8 * 1024 * 1024 })
542
+ return { code: 0, stdout: String(stdout), stderr: String(stderr) }
543
+ } catch (err) {
544
+ const e = err as { code?: number | string | null; stdout?: string | Buffer; stderr?: string | Buffer; killed?: boolean; message?: string }
545
+ const command = argv.join(" ")
546
+ if (e.code === "ENOENT") throw new TideError(`not found: ${file}`, err, { kind: "binary_missing", command })
547
+ if (e.code === "EACCES") throw new TideError(`not executable: ${file}`, err, { kind: "binary_not_executable", command })
548
+ if (e.killed) throw new TideError(`timed out after ${timeout / 1000}s: ${file}`, err, { kind: "timeout", command, timeoutMs: timeout })
549
+ if (typeof e.code === "number") return { code: e.code, stdout: String(e.stdout ?? ""), stderr: String(e.stderr ?? "") }
550
+ throw new TideError(e.message ?? `failed: ${file}`, err, { kind: "spawn", command })
551
+ }
552
+ }
553
+
554
+ function exitError(what: string, r: RunResult): TideError {
555
+ const tail = logLines(r.stderr).slice(-3).join(" | ")
556
+ return new TideError(tail || `${what} exited ${r.code}`, undefined, { kind: "exit", exitCode: r.code, stderr: r.stderr })
557
+ }
558
+
559
+ /** The script finds `plannotator-tui` by name (`command -v`); put its directory on the child's PATH. */
560
+ async function childEnv(): Promise<NodeJS.ProcessEnv> {
561
+ const dir = dirname(await resolvePlannotatorBin())
562
+ const path = process.env.PATH ?? ""
563
+ return { ...process.env, PATH: path.split(":").includes(dir) ? path : `${dir}:${path}` }
564
+ }
565
+
566
+ function assertTarget(target: string): void {
567
+ if (typeof target !== "string" || !ANNOTATE_TARGET_PATTERN.test(target)) {
568
+ throw new TideError("target must be a tmux pane id (%56), a pane index, or session:window.pane")
569
+ }
570
+ }
571
+
572
+ // -------------------------------------------------------------------- verbs --
573
+
574
+ /**
575
+ * The newest earlier web vessel that holds this very reply from this very pane
576
+ * and has marks on it. Fetching reopens it instead of keeping a fresh copy, so
577
+ * marks another person made on the reply are there when it is fetched again
578
+ * (Episode 339: William opens an agent in the cockpit and finds Mia's marks).
579
+ * Null when the reply changed since, or nobody marked it.
580
+ */
581
+ export async function findMarkedVessel(
582
+ paneId: string,
583
+ text: string,
584
+ opts: { root?: string; storeRoot?: string; exclude?: string } = {},
585
+ ): Promise<{ vessel: string; doc: string; source: SourceIdentity } | null> {
586
+ const webDir = join(opts.root ?? resolveVesselRoot(), WEB_VESSEL_SUBDIR)
587
+ const dirs = async (dir: string) =>
588
+ (await readdir(dir, { withFileTypes: true })).filter(d => d.isDirectory()).map(d => d.name)
589
+ let runs: string[]
590
+ try {
591
+ // Run directories are stamped, so name order is time order.
592
+ runs = (await dirs(webDir)).sort().reverse().slice(0, 200)
593
+ } catch {
594
+ return null
595
+ }
596
+ for (const run of runs) {
597
+ const runDir = join(webDir, run)
598
+ if (runDir === opts.exclude) continue
599
+ for (const child of await dirs(runDir).catch(() => [] as string[])) {
600
+ const vessel = join(runDir, child)
601
+ const doc = join(vessel, "reply.md")
602
+ try {
603
+ const source = JSON.parse(await readFile(join(vessel, SOURCE_FILE), "utf8")) as SourceIdentity
604
+ if (source.pane_id !== paneId) continue
605
+ if ((await readFile(doc, "utf8")) !== text) continue
606
+ if ((await listMarks(doc, opts.storeRoot)).length > 0) return { vessel, doc, source }
607
+ } catch {
608
+ // not a complete web vessel — skip
609
+ }
610
+ }
611
+ }
612
+ return null
613
+ }
614
+
615
+ /**
616
+ * Resolve the agent under `target`, read its last reply, and keep it in a fresh
617
+ * vessel together with the pane's identity. When an earlier vessel already holds
618
+ * the same reply with marks on it, that vessel is returned (`reopened`) and the
619
+ * fresh copy is removed. Delivers nothing. The vessel root is
620
+ * set per call so the one directory the script creates is found by listing, not
621
+ * by parsing its stderr.
622
+ */
623
+ export async function fetchReply(target: string, opts: { pick?: number; host?: AnnotateHost } = {}): Promise<FetchedReply> {
624
+ assertTarget(target)
625
+ const here = await resolvePaneIdentity(target)
626
+ if (!here) throw new TideError(`no such tmux pane: ${target}`)
627
+ const script = resolveReviewScript()
628
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-")
629
+ const webRoot = join(resolveVesselRoot(), WEB_VESSEL_SUBDIR, `${stamp}-${randomBytes(3).toString("hex")}`)
630
+ await mkdir(webRoot, { recursive: true })
631
+ const env = { ...(await childEnv()), [VESSEL_ROOT_ENV]: webRoot }
632
+ const r = await run(buildFetchArgv(script, target, opts), { env, timeoutMs: 90_000 })
633
+ const log = logLines(r.stderr)
634
+ if (r.code !== 0) throw exitError("review script", r)
635
+ const children = (await readdir(webRoot, { withFileTypes: true })).filter(d => d.isDirectory()).map(d => d.name)
636
+ if (children.length !== 1) throw new TideError(`expected one run vessel under ${webRoot}, found ${children.length}`)
637
+ const vessel = join(webRoot, children[0])
638
+ const doc = join(vessel, "reply.md")
639
+ const source: SourceIdentity = { target, ...here, ...parseAgentFromLog(log), fetched_at: new Date().toISOString() }
640
+ await writeFile(join(vessel, SOURCE_FILE), JSON.stringify(source, null, 2) + "\n", "utf8")
641
+ const text = await readFile(doc, "utf8")
642
+ const earlier = await findMarkedVessel(here.pane_id, text, { exclude: webRoot })
643
+ if (earlier) {
644
+ await rm(webRoot, { recursive: true, force: true })
645
+ const blocks = await listBlocks(earlier.doc, text)
646
+ return { id: earlier.doc, target, vessel: earlier.vessel, doc: earlier.doc, text, blocks, source: earlier.source, log, reopened: true }
647
+ }
648
+ const blocks = await listBlocks(doc, text)
649
+ return { id: doc, target, vessel, doc, text, blocks, source, log }
650
+ }
651
+
652
+ export async function listBlocks(doc: string, text?: string): Promise<ReplyBlock[]> {
653
+ const bin = await resolvePlannotatorBin()
654
+ const r = await run([bin, "--blocks", doc], { timeoutMs: 20_000 })
655
+ if (r.code !== 0) throw exitError("plannotator-tui --blocks", r)
656
+ return parseBlocks(r.stdout, text ?? (await readFile(doc, "utf8")))
657
+ }
658
+
659
+ export async function exportReview(doc: string): Promise<ReviewExport> {
660
+ const bin = await resolvePlannotatorBin()
661
+ const r = await run([bin, "--export", doc], { timeoutMs: 20_000 })
662
+ if (r.code !== 0) throw exitError("plannotator-tui --export", r)
663
+ const count = countAnnotations(r.stdout)
664
+ return { doc, review: count > 0 ? r.stdout : "", count }
665
+ }
666
+
667
+ /** One mark as the store holds it. Marks made before attribution, or in the terminal TUI, answer null for their author. */
668
+ export type MarkRecord = StoredMark
669
+
670
+ /** The marks on a document with their authors, oldest first, so a reader can see whose each one is. */
671
+ export async function listMarks(doc: string, storeRoot?: string): Promise<MarkRecord[]> {
672
+ const file = await findStoreFile(doc, storeRoot)
673
+ if (!file) return []
674
+ const rec = JSON.parse(await readFile(file, "utf8")) as StoreRecord
675
+ const text = (v: unknown) => (typeof v === "string" ? v : "")
676
+ return (rec.annotations ?? [])
677
+ .map(a => ({
678
+ id: text(a.id),
679
+ author: typeof a.author === "string" && a.author ? a.author : null,
680
+ author_name: typeof a.author_name === "string" && a.author_name ? a.author_name : null,
681
+ text: text(a.body),
682
+ quote: text((a.anchor as { originalText?: unknown } | undefined)?.originalText),
683
+ created_at: typeof a.created_at === "string" ? a.created_at : null,
684
+ }))
685
+ .filter(m => m.id)
686
+ }
687
+
688
+ /**
689
+ * Add one mark, attributed. plannotator-tui has no author flag, so the record
690
+ * is stamped after the fact: the ids present before the call are read, the
691
+ * mark is made, and the ids that appeared receive `author` / `author_name`.
692
+ * Two clients marking the same document in the same instant could cross-stamp;
693
+ * the store is one file per document and this module holds no lock on it.
694
+ */
695
+ export async function mark(doc: string, input: MarkInput): Promise<MarkResult> {
696
+ if (typeof input.text !== "string" || input.text.trim().length === 0) throw new TideError("mark text required")
697
+ if (!isMarkAuthor(input.author)) throw new TideError("mark author required: { id, name } — a stable principal id and a readable name")
698
+ const kind = input.kind ?? "comment"
699
+ if (!MARK_KINDS.includes(kind)) throw new TideError(`kind must be one of ${MARK_KINDS.join(", ")}`)
700
+ if (input.quote === undefined && kind !== "comment") {
701
+ throw new TideError("looks_good and delete marks need a quote — a block mark is always a comment")
702
+ }
703
+ const bin = await resolvePlannotatorBin()
704
+ let occurrence = 1
705
+ if (input.quote !== undefined) {
706
+ const text = await readFile(doc, "utf8")
707
+ if (await plannotatorTakesOccurrence(bin)) occurrence = quoteOccurrence(text, input.quote)
708
+ else assertQuoteAnchors(text, input.quote)
709
+ }
710
+ const storeRoot = resolveStoreRoot()
711
+ const before = await findStoreFile(doc, storeRoot)
712
+ const idsBefore = before ? recordIds(JSON.parse(await readFile(before, "utf8")) as StoreRecord) : new Set<string>()
713
+
714
+ const r = await run(buildMarkArgv(bin, doc, { ...input, kind }, occurrence), { timeoutMs: 20_000 })
715
+ if (r.code !== 0) throw exitError("plannotator-tui --annotate", r)
716
+
717
+ const store = before ?? (await findStoreFile(doc, storeRoot))
718
+ if (!store) throw new TideError("the mark was written but its record was not found in the plannotator store; author not stamped")
719
+ const rec = JSON.parse(await readFile(store, "utf8")) as StoreRecord
720
+ const fresh = new Set([...recordIds(rec)].filter(id => !idsBefore.has(id)))
721
+ const stamped = stampAuthor(rec, fresh, input.author)
722
+ if (stamped > 0) await writeFile(store, JSON.stringify(rec, null, 2) + "\n", "utf8")
723
+ const exported = await exportReview(doc)
724
+ return { ...exported, stamped, author: input.author }
725
+ }
726
+
727
+ /**
728
+ * Paste the document's marks into `target` through the script's `--from-file`
729
+ * leg: it exports, runs the pane guard, pastes bracketed, and presses Enter only
730
+ * on `submit`. Before any of that, the target must BE the pane the document was
731
+ * fetched from: the vessel's `source.json` names it, tmux is asked who `target`
732
+ * is now, and the pane ids must agree. A document without a source identity was
733
+ * not fetched through this module and is not delivered by it. A guard refusal is
734
+ * a RESULT (`held`), not an error — the marks are safe in the vessel and
735
+ * `redeliver` is the command that sends them later.
736
+ */
737
+ export async function deliver(target: string, doc: string, opts: { submit?: boolean } = {}): Promise<DeliverResult> {
738
+ assertTarget(target)
739
+ const submit = opts.submit === true
740
+ const script = resolveReviewScript()
741
+ const source = await readSourceIdentity(doc)
742
+ if (!source) {
743
+ throw new TideError(
744
+ `refusing: ${basename(dirname(doc))}/reply.md carries no source identity — it was not fetched through this surface. ` +
745
+ `Deliver it from the terminal: ${script} <its pane> --from-file ${doc} --no-tui`,
746
+ )
747
+ }
748
+ const here = await resolvePaneIdentity(target)
749
+ if (!here) throw new TideError(`refusing: target ${target} is gone`)
750
+ if (!sourceMatches(source, here)) {
751
+ throw new TideError(`refusing: this reply was fetched from ${describePane(source)}; ${target} is ${describePane(here)}`)
752
+ }
753
+ const argv = buildDeliverArgv(script, source.pane_id, doc, submit)
754
+ const exported = await exportReview(doc)
755
+ const base = { target, doc, source, count: exported.count, submitted: false, review: exported.review, redeliver: argv.join(" ") }
756
+ if (exported.count === 0) {
757
+ return { ...base, delivered: false, held: null, log: ["no annotations on that document — nothing to deliver"] }
758
+ }
759
+ const r = await run(argv, { env: await childEnv(), timeoutMs: 60_000 })
760
+ const log = logLines(r.stderr)
761
+ if (r.code === 0) return { ...base, delivered: true, submitted: submit, held: null, log }
762
+ const heldLine = log.find(l => /pane-write-guard: .* is /.test(l))
763
+ if (r.code === 1 && heldLine) {
764
+ const held = heldLine.replace(/^.*pane-write-guard:\s*\S+\s+is\s+/, "").replace(/\.\s*Not writing\.?\s*$/, "")
765
+ return { ...base, delivered: false, held, log }
766
+ }
767
+ throw exitError("review script", r)
768
+ }
package/src/client.ts CHANGED
@@ -41,6 +41,7 @@ import {
41
41
  TideDaemonError,
42
42
  } from "./socket"
43
43
  import { TideError } from "./errors"
44
+ import type { TideFailureDetail } from "./errors"
44
45
  import {
45
46
  HERDR_PANE_ID_PATTERN,
46
47
  buildHerdrSendKeysPlan,
@@ -89,34 +90,145 @@ export function resetTideBinCache(): void {
89
90
  // TideError now lives in errors.ts (so herdr.ts can throw it without an import
90
91
  // cycle); re-exported here to keep the public surface unchanged.
91
92
  export { TideError }
93
+ export type { TideFailureKind, TideFailureDetail } from "./errors"
92
94
 
93
95
  export interface TideRunOptions {
94
96
  timeoutMs?: number
95
97
  cwd?: string
96
98
  }
97
99
 
100
+ /** The fields Node hangs off an `execFile` rejection. All optional — none is guaranteed. */
101
+ interface ExecFileFailure {
102
+ code?: number | string | null
103
+ killed?: boolean
104
+ signal?: string | null
105
+ stderr?: string | Buffer
106
+ message?: string
107
+ }
108
+
109
+ /** First `n` non-empty lines of stderr, trimmed — enough to name a cause, not a transcript. */
110
+ function stderrTail(raw: unknown, n = 3): string | null {
111
+ const s = typeof raw === "string" ? raw : Buffer.isBuffer(raw) ? raw.toString("utf8") : ""
112
+ const lines = s.split("\n").map(l => l.trimEnd()).filter(l => l.trim().length > 0)
113
+ if (lines.length === 0) return null
114
+ return lines.slice(-n).join(" | ")
115
+ }
116
+
117
+ const secs = (ms: number) => `${(ms / 1000).toFixed(1)}s`
118
+
119
+ /**
120
+ * Turn an `execFile` rejection into a sentence that names WHAT happened.
121
+ *
122
+ * Node's own message is `Command failed: <argv>` for a timeout kill exactly as
123
+ * it is for a non-zero exit, so the previous wrapper — `tide <args> failed:
124
+ * <that>` — asserted a failure that in the timeout case had not been observed
125
+ * at all. A timeout must say it is a timeout, and must carry elapsed AND limit
126
+ * together: either number alone is unactionable.
127
+ */
128
+ function classifyExecFailure(
129
+ bin: string,
130
+ args: string[],
131
+ err: unknown,
132
+ elapsedMs: number,
133
+ timeoutMs: number,
134
+ ): TideError {
135
+ const e = (err ?? {}) as ExecFileFailure
136
+ const argv = `${bin} ${args.join(" ")}`
137
+ const stderr = stderrTail(e.stderr)
138
+ const tail = stderr ? ` · stderr: ${stderr}` : ""
139
+ const base: Omit<TideFailureDetail, "kind"> = { command: argv, elapsedMs, timeoutMs, stderr }
140
+
141
+ if (e.code === "ENOENT") {
142
+ return new TideError(
143
+ `tide CLI not found at ${bin} — resolution is TIDE_BIN → \`which tide\` → the legacy path, ` +
144
+ `and every leg missed. This is our configuration, not the runtime.`,
145
+ err,
146
+ { ...base, kind: "binary_missing" },
147
+ )
148
+ }
149
+ if (e.code === "EACCES" || e.code === "EPERM") {
150
+ return new TideError(`tide CLI at ${bin} is not executable (${String(e.code)})`, err, {
151
+ ...base,
152
+ kind: "binary_not_executable",
153
+ })
154
+ }
155
+ if (e.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
156
+ return new TideError(
157
+ `\`${argv}\` produced more than the 8 MiB stdout budget after ${secs(elapsedMs)} — ` +
158
+ `the answer was real and too large to buffer, not a failure of the command.`,
159
+ err,
160
+ { ...base, kind: "output_too_large" },
161
+ )
162
+ }
163
+ // The timeout kill: `execFile` sets `killed` only when IT sent the signal
164
+ // (the maxBuffer kill is classified above), and leaves `code` null because
165
+ // the child never got to exit on its own terms.
166
+ if (e.killed === true) {
167
+ return new TideError(
168
+ `\`${argv}\` TIMED OUT: killed with ${e.signal ?? "SIGTERM"} after ${secs(elapsedMs)}, ` +
169
+ `limit ${secs(timeoutMs)}. It was not observed to fail — it was not given time to answer. ` +
170
+ `Raise the limit for this verb or serve a cached inventory.${tail}`,
171
+ err,
172
+ { ...base, kind: "timeout", signal: e.signal ?? "SIGTERM", exitCode: null },
173
+ )
174
+ }
175
+ // A signal that execFile did NOT send. On 2026-09-13 a phone peek read
176
+ // "TIMED OUT: killed with SIGTERM after 1.3s, limit 8.0s": `systemctl stop
177
+ // miadi-server` (KillMode=control-group) had sent SIGTERM to every child of
178
+ // the server, including this one. Calling that a timeout told the operator to
179
+ // raise a limit that was never reached. The command did not fail and did not
180
+ // run out of time, so the fix is to ask again.
181
+ if (e.signal != null && typeof e.code !== "number") {
182
+ return new TideError(
183
+ `\`${argv}\` was stopped by ${e.signal} after ${secs(elapsedMs)}, before its ` +
184
+ `${secs(timeoutMs)} limit. The signal came from outside this call, most often a restart ` +
185
+ `of the server that ran it. The command did not fail; ask again.${tail}`,
186
+ err,
187
+ { ...base, kind: "killed", signal: e.signal, exitCode: null },
188
+ )
189
+ }
190
+ if (typeof e.code === "number") {
191
+ return new TideError(
192
+ `\`${argv}\` exited ${e.code} after ${secs(elapsedMs)}${tail || " with no stderr"}`,
193
+ err,
194
+ { ...base, kind: "exit", exitCode: e.code },
195
+ )
196
+ }
197
+ return new TideError(
198
+ `\`${argv}\` could not be run after ${secs(elapsedMs)}: ${e.message ?? String(err)}${tail}`,
199
+ err,
200
+ { ...base, kind: "spawn" },
201
+ )
202
+ }
203
+
98
204
  /** Core helper: run `tide <args> --format json`, parse and return JSON, or throw `TideError`. */
99
205
  export async function runTideJson<T = unknown>(
100
206
  args: string[],
101
207
  opts: TideRunOptions = {},
102
208
  ): Promise<T> {
103
209
  const bin = await resolveTideBin()
210
+ const timeoutMs = opts.timeoutMs ?? 10_000
211
+ const startedAt = Date.now()
104
212
  let stdout: string
105
213
  try {
106
214
  const res = await pExecFile(bin, args, {
107
- timeout: opts.timeoutMs ?? 10_000,
215
+ timeout: timeoutMs,
108
216
  cwd: opts.cwd,
109
217
  maxBuffer: 8 * 1024 * 1024,
110
218
  })
111
219
  stdout = res.stdout
112
220
  } catch (err) {
113
- const msg = err instanceof Error ? err.message : String(err)
114
- throw new TideError(`tide ${args.join(" ")} failed: ${msg}`, err)
221
+ throw classifyExecFailure(bin, args, err, Date.now() - startedAt, timeoutMs)
115
222
  }
116
223
  try {
117
224
  return JSON.parse(stdout) as T
118
225
  } catch (err) {
119
- throw new TideError(`tide ${args.join(" ")} returned non-JSON output`, err)
226
+ throw new TideError(`tide ${args.join(" ")} returned non-JSON output`, err, {
227
+ kind: "non_json",
228
+ command: `${bin} ${args.join(" ")}`,
229
+ elapsedMs: Date.now() - startedAt,
230
+ timeoutMs,
231
+ })
120
232
  }
121
233
  }
122
234
 
@@ -189,13 +301,35 @@ export async function getContext(opts: GetContextOptions = {}): Promise<ContextS
189
301
  })
190
302
  }
191
303
 
304
+ /**
305
+ * How long `tide operator terminals` is given before it is killed.
306
+ *
307
+ * MEASURED, not guessed. On gaia, 2026-08-07, 52 live tmux panes:
308
+ * `/usr/bin/time` reported **113.79s**, exit 0, 29,225 bytes of correct JSON.
309
+ * The cost is per-pane and roughly linear — `TerminalInventory._target_from_row`
310
+ * calls `DomainDetector.detect` for every row, and each detect spawns
311
+ * `tmux display-message`, reads the pane env, and shells out to `git` in the
312
+ * pane's cwd. ~2.2s × panes. So the limit must scale with the herd, not with
313
+ * how long a cockpit request "ought" to take.
314
+ *
315
+ * 240s is 2.1× the measurement — headroom for roughly double today's pane count
316
+ * before the kill returns. The previous limit was **8s**, i.e. 7% of the time
317
+ * the command actually needs, which is why this verb had been reporting
318
+ * `Command failed` since the herd outgrew ~4 panes.
319
+ *
320
+ * A limit this long is only safe because the route in front of it caches and
321
+ * revalidates in the background (`app/api/tide/terminals/route.ts`); a cockpit
322
+ * must never block a person for two minutes on every load.
323
+ */
324
+ export const TERMINALS_TIMEOUT_MS = 240_000
325
+
192
326
  /** Operator cockpit — read-only inventory of tmux terminal targets. */
193
327
  export function getTerminals(opts: GetTerminalsOptions = {}): Promise<TideTerminalsResult> {
194
328
  const args = ["operator", "terminals"]
195
329
  const domain = opts.domain?.trim()
196
330
  if (domain) args.push("--domain", domain)
197
331
  args.push("--format", "json")
198
- return runTideJson<TideTerminalsResult>(args, { timeoutMs: 8_000, ...opts })
332
+ return runTideJson<TideTerminalsResult>(args, { timeoutMs: TERMINALS_TIMEOUT_MS, ...opts })
199
333
  }
200
334
 
201
335
  /**
package/src/errors.ts CHANGED
@@ -2,11 +2,65 @@
2
2
  // herdr transport (herdr.ts) can throw it without a client ↔ herdr import
3
3
  // cycle. Public surface is unchanged: client.ts re-exports TideError.
4
4
 
5
+ /**
6
+ * WHY A FAILURE HAS A KIND.
7
+ *
8
+ * Until 2026-08-07 every CLI failure collapsed into Node's own
9
+ * `Command failed: <argv>` string, which is the message `execFile` emits for a
10
+ * non-zero exit AND for a timeout kill AND for a maxBuffer overflow. On
11
+ * 2026-08-07 `/api/tide/terminals` had been answering 500 with that string for
12
+ * days while `tide operator terminals` was exiting 0 with correct JSON in
13
+ * 113.8s — the 8s `execFile` timeout was killing it, and the word "failed"
14
+ * sent two people hunting a broken binary that was never broken.
15
+ *
16
+ * The kinds below each have a DIFFERENT fix, which is the whole reason to keep
17
+ * them apart:
18
+ * • `timeout` — nothing failed; the limit was too small. Raise it or cache.
19
+ * • `killed` — nothing failed and the limit was not reached: a signal from
20
+ * outside (a server restart stops its children) ended it. Ask again.
21
+ * • `exit` — the CLI genuinely refused. Read `stderr`.
22
+ * • `binary_missing` — resolution is wrong (`TIDE_BIN`/PATH), not the runtime.
23
+ * • `binary_not_executable` — permissions on the resolved path.
24
+ * • `output_too_large` — the answer was real and bigger than `maxBuffer`.
25
+ * • `non_json` — exit 0, but stdout was not the `--format json` contract.
26
+ * • `spawn` — OS refused to start the process at all.
27
+ */
28
+ export type TideFailureKind =
29
+ | "timeout"
30
+ | "killed"
31
+ | "exit"
32
+ | "binary_missing"
33
+ | "binary_not_executable"
34
+ | "output_too_large"
35
+ | "non_json"
36
+ | "spawn"
37
+ | "unknown"
38
+
39
+ /** Machine-readable companion to the message, so callers branch on a field rather than a regex. */
40
+ export interface TideFailureDetail {
41
+ kind: TideFailureKind
42
+ /** The argv that was run, for the log. Never rendered into a public body verbatim. */
43
+ command?: string
44
+ /** Wall time actually spent before the failure was observed. */
45
+ elapsedMs?: number
46
+ /** The limit that was in force — meaningless without `elapsedMs` beside it. */
47
+ timeoutMs?: number
48
+ exitCode?: number | null
49
+ signal?: string | null
50
+ stderr?: string | null
51
+ }
52
+
5
53
  export class TideError extends Error {
6
54
  readonly cause?: unknown
7
- constructor(message: string, cause?: unknown) {
55
+ readonly detail?: TideFailureDetail
56
+ constructor(message: string, cause?: unknown, detail?: TideFailureDetail) {
8
57
  super(message)
9
58
  this.name = "TideError"
10
59
  this.cause = cause
60
+ this.detail = detail
61
+ }
62
+ /** Never "unknown" by accident: absent detail means the thrower did not classify. */
63
+ get kind(): TideFailureKind {
64
+ return this.detail?.kind ?? "unknown"
11
65
  }
12
66
  }
package/src/index.ts CHANGED
@@ -2,6 +2,7 @@ export * from "./types"
2
2
  export * from "./socket"
3
3
  export * from "./client"
4
4
  export * from "./herdr"
5
+ export * from "./annotate"
5
6
  // steer-gate: explicit exports — trustSteerGateProbes/acceptGateOverrides are
6
7
  // deliberately NOT on the package surface (W10a: the test seam must be a
7
8
  // direct-module import, never a consumer API).