@miadi/tide 0.5.0 → 0.5.2

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.
Files changed (3) hide show
  1. package/README.md +14 -18
  2. package/package.json +1 -1
  3. package/src/annotate.ts +89 -29
package/README.md CHANGED
@@ -3,8 +3,8 @@
3
3
  Typed client boundary between Miadi and the **ironsilk `tide`** runtime. The single place the web app talks to `tide` — replacing the per-route
4
4
  `exec("/home/jgi/anaconda3/bin/tide …")` calls.
5
5
 
6
- Grounded in `foundations/terminal-workspace-orchestration/` (Decision C) and
7
- `rispecs/tide-runtime/05-ui-surface.spec.md` (daemon-socket transport).
6
+ Grounding, specs, issues and episodes behind this package are listed in `AGENTS.md` in the
7
+ source repository.
8
8
 
9
9
  ## Runtime dependency — install `tide`
10
10
 
@@ -18,8 +18,7 @@ pip install -U ironsilk # provides the `tide` CLI (0.9.27+)
18
18
  tide --help # verify
19
19
  ```
20
20
 
21
- Source for the runtime lives at `/usr/local/src/ironsilk/runtime/` (editable:
22
- `pip install -e .`). `@miadi/tide` resolves the binary via `TIDE_BIN` →
21
+ `@miadi/tide` resolves the binary via `TIDE_BIN` →
23
22
  `which tide` → legacy `/home/jgi/anaconda3/bin/tide`; set `TIDE_BIN` when `tide`
24
23
  is outside the server's `PATH`. The daemon socket is resolved separately via
25
24
  `TIDE_SOCKET` (see below).
@@ -74,12 +73,12 @@ one-call snapshot (`TideHerdrInventory`: workspaces + panes, tabs on request) be
74
73
  reads herdr scrollback through the stable peek verb. Pane-id segments are alphanumeric
75
74
  (`w2:pE` past `p9`). Binary resolution: `TIDE_HERDR_BIN` → `herdr` on `PATH`.
76
75
 
77
- > **Readiness: `live-verified`.** Smoked against a real herdr 0.7.4 instance (EP137
78
- > herdr-smoke lane, 2026-07-16) — inventory parsing, send-text/send-keys, pane run, read,
76
+ > **Readiness: `live-verified`.** Smoked against a real herdr 0.7.4 instance
77
+ > (2026-07-16) — inventory parsing, send-text/send-keys, pane run, read,
79
78
  > wait output (hit + timeout exit codes), agent-status, and label→id resolution — in
80
79
  > addition to the injected-runner tests in `test/herdr.test.ts`.
81
80
 
82
- #### Observer inventory + capability advertisement (EP152, live-verified)
81
+ #### Observer inventory + capability advertisement (live-verified)
83
82
 
84
83
  ```ts
85
84
  import { getHerdrSnapshot, describeHerdrCapabilities } from "@miadi/tide"
@@ -101,14 +100,14 @@ const caps = await describeHerdrCapabilities()
101
100
  // reason } — safe for /api/tide/health.
102
101
  ```
103
102
 
104
- Live receipts (herdr 0.7.4, protocol 16, EP152 2026-07-18): 85 advertised socket
103
+ Live receipts (herdr 0.7.4, protocol 16, 2026-07-18): 85 advertised socket
105
104
  methods, all seven derived flags true, snapshot of 7 workspaces / 22 tabs / 44
106
105
  panes / 21 agents. That smoke also showed pane ids go **alphanumeric** past `p9`
107
106
  (`w2:pE`, `w7:pA`) — herdr's own schema types `pane_id` as a plain string — so the
108
107
  client id pattern accepts the family agreed with `@miadi/tide-contract` 0.2.3:
109
108
  `w[0-9A-Za-z]+:p[0-9A-Za-z]+` (the dashed legacy form stays digits-only).
110
109
 
111
- #### Steer gate — ACTIVE_CONTROLLER + TTY + live target (EP152 wave-2)
110
+ #### Steer gate — ACTIVE_CONTROLLER + TTY + live target
112
111
 
113
112
  Every steer **execution** (`sendKeys` tmux + herdr, `sendKeysViaHerdr`,
114
113
  `runInHerdrPane`) passes the 3-part gate ported from the Python runtime's
@@ -141,7 +140,7 @@ loudly in both directions (a herdr-shaped id on the tmux path and vice versa).
141
140
 
142
141
  `getTerminals` and `detect` are the read-only surface behind `GET /api/tide/terminals`
143
142
  and `GET /api/tide/detect` — the typed half of operator-terminal triage and manual
144
- domain assignment (jgwill/Miadi#382). The write-back half (assign a pane to a domain)
143
+ domain assignment. The write-back half (assign a pane to a domain)
145
144
  is deferred to the runtime + a guarded route.
146
145
 
147
146
  ## Transport status
@@ -150,7 +149,7 @@ is deferred to the runtime + a guarded route.
150
149
  |---|---|
151
150
  | One-shot CLI (`tide … --format json`, `execFile` arg-arrays, no shell) | **implemented** |
152
151
  | Daemon + Unix-domain-socket transport (`miadi.tide.daemon.v2`) | **implemented** (`src/socket.ts`) |
153
- | herdr CLI transport (`src/herdr.ts`, `multiplexer: "herdr"`) | **live-verified** (herdr 0.7.4, EP137 smoke + runner-mocked tests) |
152
+ | herdr CLI transport (`src/herdr.ts`, `multiplexer: "herdr"`) | **live-verified** (herdr 0.7.4, live smoke + runner-mocked tests) |
154
153
  | Schema-first contract (`tide-api.schema.json` → generated types) | planned |
155
154
 
156
155
  ### How transport selection works
@@ -184,34 +183,31 @@ Newline-delimited JSON over a Unix socket. Request
184
183
  `describeTransport()` + `pingDaemon()` back the shipped `GET /api/tide/health` route, so a
185
184
  Hermes/Ava/Miadi session can see *which transport is live and whether the daemon is answering*
186
185
  before it reads context or proposes a steer. The cockpit routes (`steer`, `peek`, `detect`,
187
- `terminals`) are still tmux-only — herdr reachability from `/api/tide/*` is tracked in
188
- jgwill/Miadi#494.
186
+ `terminals`) are still tmux-only; herdr reachability from `/api/tide/*` is not wired yet.
189
187
 
190
188
  ### Annotate surface — `/api/tide/annotate/{resolve,mark,deliver}` (2026-09-12)
191
189
 
192
190
  The web leg of the plannotator review loop that `tan <pane>` runs in a terminal. Verbs:
193
191
  `fetchReply(pane, {pick, host})`, `listBlocks(doc)`, `mark(doc, {block | quote, text, kind})`,
194
192
  `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
193
+ `/opt/gaia/linux_migration/11-plannotator-tmux-review.sh` and a headless
196
194
  `plannotator-tui` — no resolution or delivery logic of its own, so the two clients cannot drift.
197
195
  Marks land in plannotator's store keyed by the vessel document, so a review begun in the browser
198
196
  can be finished in the terminal TUI and the other way round. A block mark is always a comment;
199
197
  `looks_good` / `delete` need a quote (plannotator-tui 0.6.0). tmux only.
200
198
 
201
- Second pass (2026-09-12, Mia's marks, Episode 339): a vessel remembers the pane it was fetched
199
+ A vessel remembers the pane it was fetched
202
200
  from (`source.json`) and `deliver` refuses any other pane, or a document with no source identity;
203
201
  every mark made here carries `author` (a stable principal id) and `author_name` — required in
204
202
  `mark()`, derived from a tailnet identity by the route when there is one — while marks made
205
203
  earlier or in the TUI stay unattributed. Gates: `resolve` and `mark` are writer-tier
206
204
  (`requireMiadiAuth({ write: true })`, as `/api/tide/peek`); `deliver` additionally needs the writer
207
205
  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`.
206
+ an error. Proven in `test/annotate-deliver.test.ts`.
209
207
 
210
208
  Resolution: `PLANNOTATOR_TMUX_REVIEW_SCRIPT` → the gaia path above; `PLANNOTATOR_TUI_BIN` →
211
209
  `which plannotator-tui` → `~/.cargo/bin/plannotator-tui` (the Next server's PATH lacks cargo's
212
210
  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
211
 
216
212
  ## Tests
217
213
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/tide",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
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"
package/src/annotate.ts CHANGED
@@ -287,9 +287,19 @@ export function buildDeliverArgv(script: string, target: string, doc: string, su
287
287
  * 0.6.0's `--annotate-block` takes no kind and ignores a fourth argument
288
288
  * (measured 2026-09-12). Callers wanting looks_good/delete pass a quote.
289
289
  */
290
- export function buildMarkArgv(bin: string, doc: string, input: Pick<MarkInput, "block" | "quote" | "text" | "kind">): string[] {
290
+ export function buildMarkArgv(
291
+ bin: string,
292
+ doc: string,
293
+ input: Pick<MarkInput, "block" | "quote" | "text" | "kind">,
294
+ occurrence = 1,
295
+ ): string[] {
291
296
  const kind = input.kind ?? "comment"
292
- if (input.quote !== undefined) return [bin, "--annotate", doc, quoteExact(input.quote), input.text, kind]
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
+ }
293
303
  if (input.block !== undefined) return [bin, "--annotate-block", doc, String(input.block), input.text]
294
304
  throw new TideError("a mark needs a block index or a quote")
295
305
  }
@@ -299,8 +309,8 @@ function quoteExact(quote: string | QuoteSelector): string {
299
309
  }
300
310
 
301
311
  /**
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
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
304
314
  * be marked on the wrong sentence, so it is refused with a way forward. A
305
315
  * phrase that appears once, or whose context names the first occurrence,
306
316
  * passes. Ref: jgwill/Miadi#683 (D3).
@@ -317,6 +327,45 @@ export function assertQuoteAnchors(text: string, quote: string | QuoteSelector):
317
327
  }
318
328
  }
319
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
+
320
369
  /** Pure containment check; `assertVesselDoc` adds symlink resolution. */
321
370
  export function isInsideRoot(doc: string, root: string): boolean {
322
371
  const rel = relative(resolve(root), resolve(doc))
@@ -523,10 +572,14 @@ function assertTarget(target: string): void {
523
572
  // -------------------------------------------------------------------- verbs --
524
573
 
525
574
  /**
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
575
+ * The newest earlier vessel that holds this very reply from this very pane and
576
+ * has marks on it. Fetching reopens it instead of keeping a fresh copy, so
528
577
  * marks another person made on the reply are there when it is fetched again
529
578
  * (Episode 339: William opens an agent in the cockpit and finds Mia's marks).
579
+ * Two layouts are searched: web runs at `<root>/web/<run>/<vessel>/` and
580
+ * terminal `tan` runs at `<root>/<stamp>-<target>/`, which the review script
581
+ * gives a `source.json` since jgwill/gaia#87. Their stamps are not comparable
582
+ * (UTC vs local time), so matches are ordered by `fetched_at`.
530
583
  * Null when the reply changed since, or nobody marked it.
531
584
  */
532
585
  export async function findMarkedVessel(
@@ -534,32 +587,34 @@ export async function findMarkedVessel(
534
587
  text: string,
535
588
  opts: { root?: string; storeRoot?: string; exclude?: string } = {},
536
589
  ): Promise<{ vessel: string; doc: string; source: SourceIdentity } | null> {
537
- const webDir = join(opts.root ?? resolveVesselRoot(), WEB_VESSEL_SUBDIR)
590
+ const root = opts.root ?? resolveVesselRoot()
591
+ const webDir = join(root, WEB_VESSEL_SUBDIR)
538
592
  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) {
593
+ (await readdir(dir, { withFileTypes: true }).catch(() => [])).filter(d => d.isDirectory()).map(d => d.name)
594
+ // Run directories are stamped, so within one layout name order is time order.
595
+ const newest = (names: string[]) => names.sort().reverse().slice(0, 200)
596
+ const vessels: string[] = []
597
+ for (const run of newest(await dirs(webDir))) {
548
598
  const runDir = join(webDir, run)
549
599
  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
- }
600
+ for (const child of await dirs(runDir)) vessels.push(join(runDir, child))
601
+ }
602
+ for (const run of newest((await dirs(root)).filter(name => name !== WEB_VESSEL_SUBDIR))) vessels.push(join(root, run))
603
+ const matches: { vessel: string; doc: string; source: SourceIdentity }[] = []
604
+ for (const vessel of vessels) {
605
+ const doc = join(vessel, "reply.md")
606
+ try {
607
+ const source = JSON.parse(await readFile(join(vessel, SOURCE_FILE), "utf8")) as SourceIdentity
608
+ if (source.pane_id !== paneId) continue
609
+ if ((await readFile(doc, "utf8")) !== text) continue
610
+ matches.push({ vessel, doc, source })
611
+ } catch {
612
+ // not a complete vessel (a terminal run from before source.json) — skip
561
613
  }
562
614
  }
615
+ // Stable: vessels without fetched_at keep their name order.
616
+ matches.sort((a, b) => String(b.source.fetched_at ?? "").localeCompare(String(a.source.fetched_at ?? "")))
617
+ for (const m of matches) if ((await listMarks(m.doc, opts.storeRoot)).length > 0) return m
563
618
  return null
564
619
  }
565
620
 
@@ -651,13 +706,18 @@ export async function mark(doc: string, input: MarkInput): Promise<MarkResult> {
651
706
  if (input.quote === undefined && kind !== "comment") {
652
707
  throw new TideError("looks_good and delete marks need a quote — a block mark is always a comment")
653
708
  }
654
- if (input.quote !== undefined) assertQuoteAnchors(await readFile(doc, "utf8"), input.quote)
655
709
  const bin = await resolvePlannotatorBin()
710
+ let occurrence = 1
711
+ if (input.quote !== undefined) {
712
+ const text = await readFile(doc, "utf8")
713
+ if (await plannotatorTakesOccurrence(bin)) occurrence = quoteOccurrence(text, input.quote)
714
+ else assertQuoteAnchors(text, input.quote)
715
+ }
656
716
  const storeRoot = resolveStoreRoot()
657
717
  const before = await findStoreFile(doc, storeRoot)
658
718
  const idsBefore = before ? recordIds(JSON.parse(await readFile(before, "utf8")) as StoreRecord) : new Set<string>()
659
719
 
660
- const r = await run(buildMarkArgv(bin, doc, { ...input, kind }), { timeoutMs: 20_000 })
720
+ const r = await run(buildMarkArgv(bin, doc, { ...input, kind }, occurrence), { timeoutMs: 20_000 })
661
721
  if (r.code !== 0) throw exitError("plannotator-tui --annotate", r)
662
722
 
663
723
  const store = before ?? (await findStoreFile(doc, storeRoot))