@miadi/tide 0.4.0 → 0.5.0
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 +26 -0
- package/package.json +3 -2
- package/src/annotate.ts +714 -0
- package/src/client.ts +139 -5
- package/src/errors.ts +55 -1
- package/src/index.ts +1 -0
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.
|
|
3
|
+
"version": "0.5.0",
|
|
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
|
}
|
package/src/annotate.ts
ADDED
|
@@ -0,0 +1,714 @@
|
|
|
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(bin: string, doc: string, input: Pick<MarkInput, "block" | "quote" | "text" | "kind">): string[] {
|
|
291
|
+
const kind = input.kind ?? "comment"
|
|
292
|
+
if (input.quote !== undefined) return [bin, "--annotate", doc, quoteExact(input.quote), input.text, kind]
|
|
293
|
+
if (input.block !== undefined) return [bin, "--annotate-block", doc, String(input.block), input.text]
|
|
294
|
+
throw new TideError("a mark needs a block index or a quote")
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function quoteExact(quote: string | QuoteSelector): string {
|
|
298
|
+
return typeof quote === "string" ? quote : quote.exact
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* plannotator-tui 0.6.0 anchors a quote on its FIRST occurrence
|
|
303
|
+
* (`source.find(quote)`). A quote whose context names a later occurrence would
|
|
304
|
+
* be marked on the wrong sentence, so it is refused with a way forward. A
|
|
305
|
+
* phrase that appears once, or whose context names the first occurrence,
|
|
306
|
+
* passes. Ref: jgwill/Miadi#683 (D3).
|
|
307
|
+
*/
|
|
308
|
+
export function assertQuoteAnchors(text: string, quote: string | QuoteSelector): void {
|
|
309
|
+
const selector: QuoteSelector = typeof quote === "string" ? { exact: quote } : quote
|
|
310
|
+
const r = resolveQuote(text, selector)
|
|
311
|
+
if ("missing" in r) throw new TideError("those words are not in the reply: select them again inside one block")
|
|
312
|
+
if ("ambiguous" in r) throw new TideError(`these words appear ${r.ambiguous} times in the reply; select a longer phrase`)
|
|
313
|
+
if (r.start !== text.indexOf(selector.exact)) {
|
|
314
|
+
throw new TideError(
|
|
315
|
+
`these words appear ${r.occurrences} times in the reply and only the first can be marked for now; select a longer phrase`,
|
|
316
|
+
)
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Pure containment check; `assertVesselDoc` adds symlink resolution. */
|
|
321
|
+
export function isInsideRoot(doc: string, root: string): boolean {
|
|
322
|
+
const rel = relative(resolve(root), resolve(doc))
|
|
323
|
+
return rel.length > 0 && !rel.startsWith("..") && !isAbsolute(rel)
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* The only documents this module will mark or paste are Markdown files inside
|
|
328
|
+
* the review vessel root. `doc` arrives from an HTTP body and ends up in an argv
|
|
329
|
+
* that pastes the file's marks into a live pane; without this line any readable
|
|
330
|
+
* file on the host could be annotated and typed into a terminal.
|
|
331
|
+
*/
|
|
332
|
+
export async function assertVesselDoc(doc: unknown, root: string = resolveVesselRoot()): Promise<string> {
|
|
333
|
+
if (typeof doc !== "string" || !doc.endsWith(".md") || !isAbsolute(doc)) {
|
|
334
|
+
throw new TideError("doc must be an absolute .md path inside the review vessel root")
|
|
335
|
+
}
|
|
336
|
+
let real: string
|
|
337
|
+
try {
|
|
338
|
+
real = await realpath(doc)
|
|
339
|
+
} catch {
|
|
340
|
+
throw new TideError(`doc not found: ${doc}`)
|
|
341
|
+
}
|
|
342
|
+
let realRoot: string
|
|
343
|
+
try {
|
|
344
|
+
realRoot = await realpath(root)
|
|
345
|
+
} catch {
|
|
346
|
+
throw new TideError(`review vessel root not found: ${root}`)
|
|
347
|
+
}
|
|
348
|
+
if (!isInsideRoot(real, realRoot)) throw new TideError("doc must live inside the review vessel root")
|
|
349
|
+
return real
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// ------------------------------------------------------------ pane identity --
|
|
353
|
+
|
|
354
|
+
/** The `tmux display-message -p` format that yields one PaneIdentity per line. */
|
|
355
|
+
export const TMUX_IDENTITY_FORMAT = "#{pane_id}\t#{session_name}\t#{window_index}\t#{pane_index}\t#{pane_pid}"
|
|
356
|
+
|
|
357
|
+
export function parsePaneIdentity(line: string): PaneIdentity | null {
|
|
358
|
+
const parts = line.trim().split("\t")
|
|
359
|
+
if (parts.length !== 5 || !/^%\d+$/.test(parts[0])) return null
|
|
360
|
+
const [pane_id, session_name, window_index, pane_index, pane_pid] = parts
|
|
361
|
+
return { pane_id, session_name, window_index, pane_index, pane_pid }
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** The script names the agent it resolved; keep that beside the pane identity when present. */
|
|
365
|
+
export function parseAgentFromLog(log: string[]): { agent_pid: string | null; host: string | null; cwd: string | null } {
|
|
366
|
+
let agent_pid: string | null = null
|
|
367
|
+
let host: string | null = null
|
|
368
|
+
let cwd: string | null = null
|
|
369
|
+
for (const line of log) {
|
|
370
|
+
const a = /\bok agent (\d+) \(([^)]+)\)/.exec(line)
|
|
371
|
+
if (a) agent_pid = a[1]
|
|
372
|
+
const h = /\btranscript host (\S+), cwd (.+)$/.exec(line)
|
|
373
|
+
if (h) {
|
|
374
|
+
host = h[1]
|
|
375
|
+
cwd = h[2].trim()
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return { agent_pid, host, cwd }
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Identity equality is on `pane_id`: tmux never reuses one while the server runs. */
|
|
382
|
+
export function sourceMatches(source: Pick<SourceIdentity, "pane_id">, here: Pick<PaneIdentity, "pane_id">): boolean {
|
|
383
|
+
return source.pane_id === here.pane_id
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
export function describePane(p: PaneIdentity): string {
|
|
387
|
+
return `${p.pane_id} (${p.session_name}:${p.window_index}.${p.pane_index})`
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** Ask tmux who `target` is right now; null when there is no such pane. */
|
|
391
|
+
export async function resolvePaneIdentity(target: string): Promise<PaneIdentity | null> {
|
|
392
|
+
const r = await run([resolveTmuxBin(), "display-message", "-p", "-t", target, TMUX_IDENTITY_FORMAT], { timeoutMs: 5_000 })
|
|
393
|
+
if (r.code !== 0) return null
|
|
394
|
+
return parsePaneIdentity(r.stdout)
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export async function readSourceIdentity(doc: string): Promise<SourceIdentity | null> {
|
|
398
|
+
try {
|
|
399
|
+
const raw = await readFile(join(dirname(doc), SOURCE_FILE), "utf8")
|
|
400
|
+
const s = JSON.parse(raw) as Partial<SourceIdentity>
|
|
401
|
+
if (typeof s.pane_id !== "string" || !/^%\d+$/.test(s.pane_id)) return null
|
|
402
|
+
return s as SourceIdentity
|
|
403
|
+
} catch {
|
|
404
|
+
return null
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// ------------------------------------------------------------ author stamping --
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Locate the plannotator record for `doc`: `<store>/<slug>/<doc-slug>/annotations.json`
|
|
412
|
+
* whose `path` is the document. The slug rule is the tool's own and not stable
|
|
413
|
+
* across versions, so the record is found by its content, not by rebuilding
|
|
414
|
+
* the slug.
|
|
415
|
+
*/
|
|
416
|
+
export async function findStoreFile(doc: string, root: string = resolveStoreRoot()): Promise<string | null> {
|
|
417
|
+
let candidates: string[] = []
|
|
418
|
+
try {
|
|
419
|
+
const level1 = await readdir(root, { withFileTypes: true })
|
|
420
|
+
for (const a of level1) {
|
|
421
|
+
if (!a.isDirectory()) continue
|
|
422
|
+
const level2 = await readdir(join(root, a.name), { withFileTypes: true })
|
|
423
|
+
for (const b of level2) {
|
|
424
|
+
if (b.isDirectory()) candidates.push(join(root, a.name, b.name, "annotations.json"))
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
} catch {
|
|
428
|
+
return null
|
|
429
|
+
}
|
|
430
|
+
let realDoc = doc
|
|
431
|
+
try {
|
|
432
|
+
realDoc = await realpath(doc)
|
|
433
|
+
} catch {
|
|
434
|
+
// compare on the given path only
|
|
435
|
+
}
|
|
436
|
+
for (const file of candidates) {
|
|
437
|
+
try {
|
|
438
|
+
const rec = JSON.parse(await readFile(file, "utf8")) as { path?: unknown }
|
|
439
|
+
if (rec.path === doc || rec.path === realDoc) return file
|
|
440
|
+
} catch {
|
|
441
|
+
// not a record — skip
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
return null
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
interface StoreAnnotation {
|
|
448
|
+
id?: unknown
|
|
449
|
+
author?: unknown
|
|
450
|
+
author_name?: unknown
|
|
451
|
+
[k: string]: unknown
|
|
452
|
+
}
|
|
453
|
+
interface StoreRecord {
|
|
454
|
+
path?: unknown
|
|
455
|
+
annotations?: StoreAnnotation[]
|
|
456
|
+
[k: string]: unknown
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
export function recordIds(rec: StoreRecord): Set<string> {
|
|
460
|
+
return new Set((rec.annotations ?? []).map(a => (typeof a.id === "string" ? a.id : "")).filter(Boolean))
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Write the author onto exactly the records in `ids` that have none. Returns how
|
|
465
|
+
* many were stamped. A record that already carries an author is left alone —
|
|
466
|
+
* the rule is no assignment after the fact, in either direction.
|
|
467
|
+
*/
|
|
468
|
+
export function stampAuthor(rec: StoreRecord, ids: Set<string>, author: MarkAuthor): number {
|
|
469
|
+
let n = 0
|
|
470
|
+
for (const a of rec.annotations ?? []) {
|
|
471
|
+
if (typeof a.id !== "string" || !ids.has(a.id)) continue
|
|
472
|
+
if (a.author !== null && a.author !== undefined) continue
|
|
473
|
+
a.author = author.id
|
|
474
|
+
a.author_name = author.name
|
|
475
|
+
n++
|
|
476
|
+
}
|
|
477
|
+
return n
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// --------------------------------------------------------------- processes --
|
|
481
|
+
|
|
482
|
+
interface RunResult {
|
|
483
|
+
code: number
|
|
484
|
+
stdout: string
|
|
485
|
+
stderr: string
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
async function run(argv: string[], opts: { env?: NodeJS.ProcessEnv; timeoutMs?: number } = {}): Promise<RunResult> {
|
|
489
|
+
const [file, ...args] = argv
|
|
490
|
+
const timeout = opts.timeoutMs ?? 60_000
|
|
491
|
+
try {
|
|
492
|
+
const { stdout, stderr } = await pExecFile(file, args, { env: opts.env, timeout, maxBuffer: 8 * 1024 * 1024 })
|
|
493
|
+
return { code: 0, stdout: String(stdout), stderr: String(stderr) }
|
|
494
|
+
} catch (err) {
|
|
495
|
+
const e = err as { code?: number | string | null; stdout?: string | Buffer; stderr?: string | Buffer; killed?: boolean; message?: string }
|
|
496
|
+
const command = argv.join(" ")
|
|
497
|
+
if (e.code === "ENOENT") throw new TideError(`not found: ${file}`, err, { kind: "binary_missing", command })
|
|
498
|
+
if (e.code === "EACCES") throw new TideError(`not executable: ${file}`, err, { kind: "binary_not_executable", command })
|
|
499
|
+
if (e.killed) throw new TideError(`timed out after ${timeout / 1000}s: ${file}`, err, { kind: "timeout", command, timeoutMs: timeout })
|
|
500
|
+
if (typeof e.code === "number") return { code: e.code, stdout: String(e.stdout ?? ""), stderr: String(e.stderr ?? "") }
|
|
501
|
+
throw new TideError(e.message ?? `failed: ${file}`, err, { kind: "spawn", command })
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function exitError(what: string, r: RunResult): TideError {
|
|
506
|
+
const tail = logLines(r.stderr).slice(-3).join(" | ")
|
|
507
|
+
return new TideError(tail || `${what} exited ${r.code}`, undefined, { kind: "exit", exitCode: r.code, stderr: r.stderr })
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** The script finds `plannotator-tui` by name (`command -v`); put its directory on the child's PATH. */
|
|
511
|
+
async function childEnv(): Promise<NodeJS.ProcessEnv> {
|
|
512
|
+
const dir = dirname(await resolvePlannotatorBin())
|
|
513
|
+
const path = process.env.PATH ?? ""
|
|
514
|
+
return { ...process.env, PATH: path.split(":").includes(dir) ? path : `${dir}:${path}` }
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function assertTarget(target: string): void {
|
|
518
|
+
if (typeof target !== "string" || !ANNOTATE_TARGET_PATTERN.test(target)) {
|
|
519
|
+
throw new TideError("target must be a tmux pane id (%56), a pane index, or session:window.pane")
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// -------------------------------------------------------------------- verbs --
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* The newest earlier web vessel that holds this very reply from this very pane
|
|
527
|
+
* and has marks on it. Fetching reopens it instead of keeping a fresh copy, so
|
|
528
|
+
* marks another person made on the reply are there when it is fetched again
|
|
529
|
+
* (Episode 339: William opens an agent in the cockpit and finds Mia's marks).
|
|
530
|
+
* Null when the reply changed since, or nobody marked it.
|
|
531
|
+
*/
|
|
532
|
+
export async function findMarkedVessel(
|
|
533
|
+
paneId: string,
|
|
534
|
+
text: string,
|
|
535
|
+
opts: { root?: string; storeRoot?: string; exclude?: string } = {},
|
|
536
|
+
): Promise<{ vessel: string; doc: string; source: SourceIdentity } | null> {
|
|
537
|
+
const webDir = join(opts.root ?? resolveVesselRoot(), WEB_VESSEL_SUBDIR)
|
|
538
|
+
const dirs = async (dir: string) =>
|
|
539
|
+
(await readdir(dir, { withFileTypes: true })).filter(d => d.isDirectory()).map(d => d.name)
|
|
540
|
+
let runs: string[]
|
|
541
|
+
try {
|
|
542
|
+
// Run directories are stamped, so name order is time order.
|
|
543
|
+
runs = (await dirs(webDir)).sort().reverse().slice(0, 200)
|
|
544
|
+
} catch {
|
|
545
|
+
return null
|
|
546
|
+
}
|
|
547
|
+
for (const run of runs) {
|
|
548
|
+
const runDir = join(webDir, run)
|
|
549
|
+
if (runDir === opts.exclude) continue
|
|
550
|
+
for (const child of await dirs(runDir).catch(() => [] as string[])) {
|
|
551
|
+
const vessel = join(runDir, child)
|
|
552
|
+
const doc = join(vessel, "reply.md")
|
|
553
|
+
try {
|
|
554
|
+
const source = JSON.parse(await readFile(join(vessel, SOURCE_FILE), "utf8")) as SourceIdentity
|
|
555
|
+
if (source.pane_id !== paneId) continue
|
|
556
|
+
if ((await readFile(doc, "utf8")) !== text) continue
|
|
557
|
+
if ((await listMarks(doc, opts.storeRoot)).length > 0) return { vessel, doc, source }
|
|
558
|
+
} catch {
|
|
559
|
+
// not a complete web vessel — skip
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
return null
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* Resolve the agent under `target`, read its last reply, and keep it in a fresh
|
|
568
|
+
* vessel together with the pane's identity. When an earlier vessel already holds
|
|
569
|
+
* the same reply with marks on it, that vessel is returned (`reopened`) and the
|
|
570
|
+
* fresh copy is removed. Delivers nothing. The vessel root is
|
|
571
|
+
* set per call so the one directory the script creates is found by listing, not
|
|
572
|
+
* by parsing its stderr.
|
|
573
|
+
*/
|
|
574
|
+
export async function fetchReply(target: string, opts: { pick?: number; host?: AnnotateHost } = {}): Promise<FetchedReply> {
|
|
575
|
+
assertTarget(target)
|
|
576
|
+
const here = await resolvePaneIdentity(target)
|
|
577
|
+
if (!here) throw new TideError(`no such tmux pane: ${target}`)
|
|
578
|
+
const script = resolveReviewScript()
|
|
579
|
+
const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-")
|
|
580
|
+
const webRoot = join(resolveVesselRoot(), WEB_VESSEL_SUBDIR, `${stamp}-${randomBytes(3).toString("hex")}`)
|
|
581
|
+
await mkdir(webRoot, { recursive: true })
|
|
582
|
+
const env = { ...(await childEnv()), [VESSEL_ROOT_ENV]: webRoot }
|
|
583
|
+
const r = await run(buildFetchArgv(script, target, opts), { env, timeoutMs: 90_000 })
|
|
584
|
+
const log = logLines(r.stderr)
|
|
585
|
+
if (r.code !== 0) throw exitError("review script", r)
|
|
586
|
+
const children = (await readdir(webRoot, { withFileTypes: true })).filter(d => d.isDirectory()).map(d => d.name)
|
|
587
|
+
if (children.length !== 1) throw new TideError(`expected one run vessel under ${webRoot}, found ${children.length}`)
|
|
588
|
+
const vessel = join(webRoot, children[0])
|
|
589
|
+
const doc = join(vessel, "reply.md")
|
|
590
|
+
const source: SourceIdentity = { target, ...here, ...parseAgentFromLog(log), fetched_at: new Date().toISOString() }
|
|
591
|
+
await writeFile(join(vessel, SOURCE_FILE), JSON.stringify(source, null, 2) + "\n", "utf8")
|
|
592
|
+
const text = await readFile(doc, "utf8")
|
|
593
|
+
const earlier = await findMarkedVessel(here.pane_id, text, { exclude: webRoot })
|
|
594
|
+
if (earlier) {
|
|
595
|
+
await rm(webRoot, { recursive: true, force: true })
|
|
596
|
+
const blocks = await listBlocks(earlier.doc, text)
|
|
597
|
+
return { id: earlier.doc, target, vessel: earlier.vessel, doc: earlier.doc, text, blocks, source: earlier.source, log, reopened: true }
|
|
598
|
+
}
|
|
599
|
+
const blocks = await listBlocks(doc, text)
|
|
600
|
+
return { id: doc, target, vessel, doc, text, blocks, source, log }
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
export async function listBlocks(doc: string, text?: string): Promise<ReplyBlock[]> {
|
|
604
|
+
const bin = await resolvePlannotatorBin()
|
|
605
|
+
const r = await run([bin, "--blocks", doc], { timeoutMs: 20_000 })
|
|
606
|
+
if (r.code !== 0) throw exitError("plannotator-tui --blocks", r)
|
|
607
|
+
return parseBlocks(r.stdout, text ?? (await readFile(doc, "utf8")))
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
export async function exportReview(doc: string): Promise<ReviewExport> {
|
|
611
|
+
const bin = await resolvePlannotatorBin()
|
|
612
|
+
const r = await run([bin, "--export", doc], { timeoutMs: 20_000 })
|
|
613
|
+
if (r.code !== 0) throw exitError("plannotator-tui --export", r)
|
|
614
|
+
const count = countAnnotations(r.stdout)
|
|
615
|
+
return { doc, review: count > 0 ? r.stdout : "", count }
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** One mark as the store holds it. Marks made before attribution, or in the terminal TUI, answer null for their author. */
|
|
619
|
+
export type MarkRecord = StoredMark
|
|
620
|
+
|
|
621
|
+
/** The marks on a document with their authors, oldest first, so a reader can see whose each one is. */
|
|
622
|
+
export async function listMarks(doc: string, storeRoot?: string): Promise<MarkRecord[]> {
|
|
623
|
+
const file = await findStoreFile(doc, storeRoot)
|
|
624
|
+
if (!file) return []
|
|
625
|
+
const rec = JSON.parse(await readFile(file, "utf8")) as StoreRecord
|
|
626
|
+
const text = (v: unknown) => (typeof v === "string" ? v : "")
|
|
627
|
+
return (rec.annotations ?? [])
|
|
628
|
+
.map(a => ({
|
|
629
|
+
id: text(a.id),
|
|
630
|
+
author: typeof a.author === "string" && a.author ? a.author : null,
|
|
631
|
+
author_name: typeof a.author_name === "string" && a.author_name ? a.author_name : null,
|
|
632
|
+
text: text(a.body),
|
|
633
|
+
quote: text((a.anchor as { originalText?: unknown } | undefined)?.originalText),
|
|
634
|
+
created_at: typeof a.created_at === "string" ? a.created_at : null,
|
|
635
|
+
}))
|
|
636
|
+
.filter(m => m.id)
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* Add one mark, attributed. plannotator-tui has no author flag, so the record
|
|
641
|
+
* is stamped after the fact: the ids present before the call are read, the
|
|
642
|
+
* mark is made, and the ids that appeared receive `author` / `author_name`.
|
|
643
|
+
* Two clients marking the same document in the same instant could cross-stamp;
|
|
644
|
+
* the store is one file per document and this module holds no lock on it.
|
|
645
|
+
*/
|
|
646
|
+
export async function mark(doc: string, input: MarkInput): Promise<MarkResult> {
|
|
647
|
+
if (typeof input.text !== "string" || input.text.trim().length === 0) throw new TideError("mark text required")
|
|
648
|
+
if (!isMarkAuthor(input.author)) throw new TideError("mark author required: { id, name } — a stable principal id and a readable name")
|
|
649
|
+
const kind = input.kind ?? "comment"
|
|
650
|
+
if (!MARK_KINDS.includes(kind)) throw new TideError(`kind must be one of ${MARK_KINDS.join(", ")}`)
|
|
651
|
+
if (input.quote === undefined && kind !== "comment") {
|
|
652
|
+
throw new TideError("looks_good and delete marks need a quote — a block mark is always a comment")
|
|
653
|
+
}
|
|
654
|
+
if (input.quote !== undefined) assertQuoteAnchors(await readFile(doc, "utf8"), input.quote)
|
|
655
|
+
const bin = await resolvePlannotatorBin()
|
|
656
|
+
const storeRoot = resolveStoreRoot()
|
|
657
|
+
const before = await findStoreFile(doc, storeRoot)
|
|
658
|
+
const idsBefore = before ? recordIds(JSON.parse(await readFile(before, "utf8")) as StoreRecord) : new Set<string>()
|
|
659
|
+
|
|
660
|
+
const r = await run(buildMarkArgv(bin, doc, { ...input, kind }), { timeoutMs: 20_000 })
|
|
661
|
+
if (r.code !== 0) throw exitError("plannotator-tui --annotate", r)
|
|
662
|
+
|
|
663
|
+
const store = before ?? (await findStoreFile(doc, storeRoot))
|
|
664
|
+
if (!store) throw new TideError("the mark was written but its record was not found in the plannotator store; author not stamped")
|
|
665
|
+
const rec = JSON.parse(await readFile(store, "utf8")) as StoreRecord
|
|
666
|
+
const fresh = new Set([...recordIds(rec)].filter(id => !idsBefore.has(id)))
|
|
667
|
+
const stamped = stampAuthor(rec, fresh, input.author)
|
|
668
|
+
if (stamped > 0) await writeFile(store, JSON.stringify(rec, null, 2) + "\n", "utf8")
|
|
669
|
+
const exported = await exportReview(doc)
|
|
670
|
+
return { ...exported, stamped, author: input.author }
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* Paste the document's marks into `target` through the script's `--from-file`
|
|
675
|
+
* leg: it exports, runs the pane guard, pastes bracketed, and presses Enter only
|
|
676
|
+
* on `submit`. Before any of that, the target must BE the pane the document was
|
|
677
|
+
* fetched from: the vessel's `source.json` names it, tmux is asked who `target`
|
|
678
|
+
* is now, and the pane ids must agree. A document without a source identity was
|
|
679
|
+
* not fetched through this module and is not delivered by it. A guard refusal is
|
|
680
|
+
* a RESULT (`held`), not an error — the marks are safe in the vessel and
|
|
681
|
+
* `redeliver` is the command that sends them later.
|
|
682
|
+
*/
|
|
683
|
+
export async function deliver(target: string, doc: string, opts: { submit?: boolean } = {}): Promise<DeliverResult> {
|
|
684
|
+
assertTarget(target)
|
|
685
|
+
const submit = opts.submit === true
|
|
686
|
+
const script = resolveReviewScript()
|
|
687
|
+
const source = await readSourceIdentity(doc)
|
|
688
|
+
if (!source) {
|
|
689
|
+
throw new TideError(
|
|
690
|
+
`refusing: ${basename(dirname(doc))}/reply.md carries no source identity — it was not fetched through this surface. ` +
|
|
691
|
+
`Deliver it from the terminal: ${script} <its pane> --from-file ${doc} --no-tui`,
|
|
692
|
+
)
|
|
693
|
+
}
|
|
694
|
+
const here = await resolvePaneIdentity(target)
|
|
695
|
+
if (!here) throw new TideError(`refusing: target ${target} is gone`)
|
|
696
|
+
if (!sourceMatches(source, here)) {
|
|
697
|
+
throw new TideError(`refusing: this reply was fetched from ${describePane(source)}; ${target} is ${describePane(here)}`)
|
|
698
|
+
}
|
|
699
|
+
const argv = buildDeliverArgv(script, source.pane_id, doc, submit)
|
|
700
|
+
const exported = await exportReview(doc)
|
|
701
|
+
const base = { target, doc, source, count: exported.count, submitted: false, review: exported.review, redeliver: argv.join(" ") }
|
|
702
|
+
if (exported.count === 0) {
|
|
703
|
+
return { ...base, delivered: false, held: null, log: ["no annotations on that document — nothing to deliver"] }
|
|
704
|
+
}
|
|
705
|
+
const r = await run(argv, { env: await childEnv(), timeoutMs: 60_000 })
|
|
706
|
+
const log = logLines(r.stderr)
|
|
707
|
+
if (r.code === 0) return { ...base, delivered: true, submitted: submit, held: null, log }
|
|
708
|
+
const heldLine = log.find(l => /pane-write-guard: .* is /.test(l))
|
|
709
|
+
if (r.code === 1 && heldLine) {
|
|
710
|
+
const held = heldLine.replace(/^.*pane-write-guard:\s*\S+\s+is\s+/, "").replace(/\.\s*Not writing\.?\s*$/, "")
|
|
711
|
+
return { ...base, delivered: false, held, log }
|
|
712
|
+
}
|
|
713
|
+
throw exitError("review script", r)
|
|
714
|
+
}
|
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:
|
|
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
|
-
|
|
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:
|
|
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
|
-
|
|
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).
|