@miadi/tide 0.6.13 → 0.6.14

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/tide",
3
- "version": "0.6.13",
3
+ "version": "0.6.14",
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"
@@ -43,6 +43,14 @@
43
43
  # so a reply reviewed with `tan` is a vessel tide can recognise and deliver. Plan:
44
44
  # jgwill/gaia#87.
45
45
  #
46
+ # WHO THE MARKS ARE BY. plannotator-tui asks nobody who is at the keyboard, so this script
47
+ # does, before it opens the TUI: the token is MIADI_PERSON_TOKEN (who this shell acts for),
48
+ # else MIADI_ACCOUNT_TOKEN (who this Unix account acts for), else the one in
49
+ # ~/.miadi/person.env. The Miadi app says whose token it is, and the TUI writes that id and
50
+ # name on each mark as it saves it, with author_basis "signed". With no token, a refused one,
51
+ # or no app answering, the review still opens, its marks are unsigned, and this script says
52
+ # why before the TUI opens and again after it closes. Ref: jgwill/Miadi#937.
53
+ #
46
54
  # A RUN SURVIVES EDITS TO THIS FILE: it re-execs a snapshot of itself, because bash reads
47
55
  # a script by byte offset and an edit under a live run makes it resume mid-statement.
48
56
  # Earned 2026-09-08, twice: `syntax error near unexpected token`, then `line 239: e:
@@ -114,7 +122,7 @@ while [ $# -gt 0 ]; do
114
122
  --no-tui) OPEN_TUI=0 ;;
115
123
  --print) PRINT_ONLY=1 ;;
116
124
  --submit) SUBMIT=1 ;;
117
- -h|--help) sed -n '2,44p' "$SELF"; exit 0 ;;
125
+ -h|--help) sed -n '2,52p' "$SELF"; exit 0 ;;
118
126
  -*) fail "unknown option: $1" ;;
119
127
  *) [ -z "$TARGET" ] || fail "more than one tmux target given"; TARGET="$1" ;;
120
128
  esac
@@ -319,11 +327,78 @@ $FOUND" ;; esac
319
327
  fi
320
328
  fi
321
329
 
330
+ # ------------------------------------------------------- who is reviewing --
331
+
332
+ # Sets REVIEWER_ID and REVIEWER_NAME, or REVIEWER_WHY when the marks will be unsigned.
333
+ # A token goes only to https or to this machine, and through curl's stdin so ps cannot
334
+ # show it. Probes the same apps as @miadi/chronicle-tui: the local one, then the tailnet one.
335
+ REVIEWER_ID=""
336
+ REVIEWER_NAME=""
337
+ REVIEWER_WHY=""
338
+ resolve_reviewer() {
339
+ local token source base answer code body
340
+ token="${MIADI_PERSON_TOKEN:-}"
341
+ source="MIADI_PERSON_TOKEN"
342
+ if [ -z "$token" ]; then token="${MIADI_ACCOUNT_TOKEN:-}"; source="MIADI_ACCOUNT_TOKEN"; fi
343
+ if [ -z "$token" ] && [ -r "$HOME/.miadi/person.env" ]; then
344
+ token="$(sed -n 's/^\(export \)\{0,1\}MIADI_ACCOUNT_TOKEN=//p' "$HOME/.miadi/person.env" | tail -1 | tr -d "\"'")"
345
+ source="$HOME/.miadi/person.env"
346
+ fi
347
+ if [ -z "$token" ]; then
348
+ REVIEWER_WHY="no person: set MIADI_PERSON_TOKEN, or write ~/.miadi/person.env, then check with miadi-config check"
349
+ return 0
350
+ fi
351
+ command -v curl >/dev/null 2>&1 || { REVIEWER_WHY="curl is not installed, so nobody can say whose $source this is"; return 0; }
352
+ command -v jq >/dev/null 2>&1 || { REVIEWER_WHY="jq is not installed, so the app's answer cannot be read"; return 0; }
353
+ REVIEWER_WHY="no Miadi app answered, so nobody could say whose $source this is"
354
+ for base in "${MIADI_WEB_URL:-http://127.0.0.1:3335}" "${MIADI_URL_BASE_INTERNAL:-}"; do
355
+ base="${base%/}"
356
+ case "$base" in
357
+ https://*|http://127.0.0.1|http://127.0.0.1:*|http://localhost|http://localhost:*|http://\[::1\]|http://\[::1\]:*) ;;
358
+ *) continue ;;
359
+ esac
360
+ answer="$(printf 'header = "Authorization: Bearer %s"\n' "$token" \
361
+ | curl -sS -m 4 -K - -w '\n%{http_code}' "$base/api/identity/me" 2>/dev/null || true)"
362
+ code="${answer##*$'\n'}"
363
+ body="${answer%$'\n'*}"
364
+ case "$code" in
365
+ 200)
366
+ REVIEWER_ID="$(jq -r '.person.id // empty' <<<"$body" 2>/dev/null || true)"
367
+ REVIEWER_NAME="$(jq -r '.person.name // empty' <<<"$body" 2>/dev/null || true)"
368
+ if [ -n "$REVIEWER_ID" ] && [ -n "$REVIEWER_NAME" ]; then REVIEWER_WHY=""; return 0; fi
369
+ REVIEWER_ID=""; REVIEWER_NAME=""
370
+ REVIEWER_WHY="$base accepted $source and named no person"
371
+ return 0 ;;
372
+ 401|403)
373
+ REVIEWER_WHY="$base refused $source: it is expired, revoked or for another app"
374
+ return 0 ;;
375
+ esac
376
+ done
377
+ return 0
378
+ }
379
+
322
380
  # ------------------------------------------------------------- annotate it --
323
381
 
324
382
  if [ "$OPEN_TUI" = 1 ]; then
383
+ AUTHOR_ENV=()
384
+ # A caller that names the author itself keeps its word.
385
+ if [ -z "${PLANNOTATOR_TUI_AUTHOR:-}" ]; then
386
+ resolve_reviewer
387
+ TUI_BIN="$(command -v plannotator-tui)"
388
+ if [ -n "$REVIEWER_ID" ] && ! grep -q PLANNOTATOR_TUI_AUTHOR "$TUI_BIN"; then
389
+ REVIEWER_WHY="$TUI_BIN cannot write an author: apt install --only-upgrade miadi-tide, and remove any older copy that comes first on PATH"
390
+ REVIEWER_ID=""
391
+ fi
392
+ if [ -n "$REVIEWER_ID" ]; then
393
+ AUTHOR_ENV=("PLANNOTATOR_TUI_AUTHOR=$REVIEWER_ID" "PLANNOTATOR_TUI_AUTHOR_NAME=$REVIEWER_NAME" "PLANNOTATOR_TUI_AUTHOR_BASIS=signed")
394
+ ok "marks are signed as $REVIEWER_NAME"
395
+ else
396
+ warn "marks will be unsigned: $REVIEWER_WHY"
397
+ fi
398
+ fi
325
399
  info "Opening plannotator-tui — mark blocks, then q. Delivery happens on exit."
326
- plannotator-tui "$DOC" || true
400
+ env "${AUTHOR_ENV[@]}" plannotator-tui "$DOC" || true
401
+ [ -z "$REVIEWER_WHY" ] || warn "the marks made here are unsigned: $REVIEWER_WHY"
327
402
  else
328
403
  ok "TUI skipped (--no-tui)"
329
404
  fi
package/src/annotate.ts CHANGED
@@ -27,8 +27,9 @@
27
27
  // • Every mark made through this module carries a stable principal id and a
28
28
  // readable name (`author` / `author_name` on the record — both fields exist
29
29
  // in plannotator-tui 0.6.0's struct and survive export and further marks).
30
- // Marks made earlier, or in the terminal TUI, stay unattributed; nothing
31
- // here assigns an author after the fact.
30
+ // Marks made earlier stay unattributed; nothing here assigns an author
31
+ // after the fact. A mark made in the terminal TUI through the review script
32
+ // carries the person the script verified (jgwill/Miadi#937).
32
33
  //
33
34
  // Ref: jgwill/gaia#80 · foundations/annotation-as-coordination/
34
35
 
@@ -86,7 +87,7 @@ export type { MarkAuthor, MarkKind, QuoteSelector } from "@miadi/annotate-core"
86
87
  /** One block of the reply. `row` is its 0-based first line in the document. */
87
88
  export type ReplyBlock = AnnotateBlock
88
89
 
89
- /** The pane identity tmux itself reports for a target. `pane_id` is stable for the pane's lifetime. */
90
+ /** The pane identity tmux itself reports for a target. `pane_id` holds for one tmux server: a restart gives the ids out again. */
90
91
  export interface PaneIdentity {
91
92
  pane_id: string
92
93
  session_name: string
@@ -466,9 +467,24 @@ export function parseAgentFromLog(log: string[]): { agent_pid: string | null; ho
466
467
  return { agent_pid, host, cwd }
467
468
  }
468
469
 
469
- /** Identity equality is on `pane_id`: tmux never reuses one while the server runs. */
470
- export function sourceMatches(source: Pick<SourceIdentity, "pane_id">, here: Pick<PaneIdentity, "pane_id">): boolean {
471
- return source.pane_id === here.pane_id
470
+ /**
471
+ * One tmux pane, unbroken: the same id and the same first process. It holds through a renamed
472
+ * session or a moved pane, and whatever the agent answered since. An id alone proves nothing:
473
+ * tmux gives the ids out again after a restart, and %115 went from one agent to another
474
+ * (jgwill/Miadi#938).
475
+ */
476
+ export function samePaneLife(a: Pick<PaneIdentity, "pane_id" | "pane_pid">, b: Pick<PaneIdentity, "pane_id" | "pane_pid">): boolean {
477
+ return a.pane_id === b.pane_id && Boolean(a.pane_pid) && a.pane_pid === b.pane_pid
478
+ }
479
+
480
+ type PanePlace = Pick<PaneIdentity, "session_name" | "window_index" | "pane_index">
481
+
482
+ /**
483
+ * The same session, window and pane index: where a tmux restore puts a pane back, under a new id
484
+ * and a new process. It says where, not who: only the reply the agent there holds can say that.
485
+ */
486
+ export function samePanePlace(a: PanePlace, b: PanePlace): boolean {
487
+ return Boolean(a.session_name) && a.session_name === b.session_name && a.window_index === b.window_index && a.pane_index === b.pane_index
472
488
  }
473
489
 
474
490
  export function describePane(p: PaneIdentity): string {
@@ -626,9 +642,13 @@ function assertTarget(target: string): void {
626
642
 
627
643
  // -------------------------------------------------------------------- verbs --
628
644
 
629
- /** Earlier vessels of a pane holding exactly this reply, newest fetch first (the search findMarkedVessel describes). */
645
+ /**
646
+ * Earlier vessels of a pane holding exactly this reply, newest fetch first (the search
647
+ * findMarkedVessel describes). The pane is the one unbroken pane, or the same place after a
648
+ * restart: the reply is compared here, so a place holding this very reply is that pane.
649
+ */
630
650
  async function sameReplyVessels(
631
- paneId: string,
651
+ here: PaneIdentity,
632
652
  text: string,
633
653
  opts: { root?: string; exclude?: string } = {},
634
654
  ): Promise<{ vessel: string; doc: string; source: SourceIdentity }[]> {
@@ -650,7 +670,7 @@ async function sameReplyVessels(
650
670
  const doc = join(vessel, "reply.md")
651
671
  try {
652
672
  const source = JSON.parse(await readFile(join(vessel, SOURCE_FILE), "utf8")) as SourceIdentity
653
- if (source.pane_id !== paneId) continue
673
+ if (!samePaneLife(source, here) && !samePanePlace(source, here)) continue
654
674
  if ((await readFile(doc, "utf8")) !== text) continue
655
675
  matches.push({ vessel, doc, source })
656
676
  } catch {
@@ -674,11 +694,11 @@ async function sameReplyVessels(
674
694
  * Null when the reply changed since, or nobody marked it.
675
695
  */
676
696
  export async function findMarkedVessel(
677
- paneId: string,
697
+ here: PaneIdentity,
678
698
  text: string,
679
699
  opts: { root?: string; storeRoot?: string; exclude?: string } = {},
680
700
  ): Promise<{ vessel: string; doc: string; source: SourceIdentity } | null> {
681
- for (const m of await sameReplyVessels(paneId, text, opts)) if ((await listMarks(m.doc, opts.storeRoot)).length > 0) return m
701
+ for (const m of await sameReplyVessels(here, text, opts)) if ((await listMarks(m.doc, opts.storeRoot)).length > 0) return m
682
702
  return null
683
703
  }
684
704
 
@@ -690,11 +710,11 @@ export async function findMarkedVessel(
690
710
  * Null when nobody fetched this reply from this pane before.
691
711
  */
692
712
  export async function findReplyVessel(
693
- paneId: string,
713
+ here: PaneIdentity,
694
714
  text: string,
695
715
  opts: { root?: string; storeRoot?: string; exclude?: string } = {},
696
716
  ): Promise<{ vessel: string; doc: string; source: SourceIdentity; marked: boolean } | null> {
697
- const matches = await sameReplyVessels(paneId, text, opts)
717
+ const matches = await sameReplyVessels(here, text, opts)
698
718
  for (const m of matches) if ((await listMarks(m.doc, opts.storeRoot)).length > 0) return { ...m, marked: true }
699
719
  return matches[0] ? { ...matches[0], marked: false } : null
700
720
  }
@@ -711,32 +731,71 @@ export async function fetchReply(target: string, opts: { pick?: number; host?: A
711
731
  assertTarget(target)
712
732
  const here = await resolvePaneIdentity(target)
713
733
  if (!here) throw new TideError(`no such tmux pane: ${target}`)
714
- const script = resolveReviewScript()
715
- const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-")
716
- const webRoot = join(resolveVesselRoot(), WEB_VESSEL_SUBDIR, `${stamp}-${randomBytes(3).toString("hex")}`)
717
- await mkdir(webRoot, { recursive: true })
718
- const env = { ...(await childEnv()), [VESSEL_ROOT_ENV]: webRoot }
719
- const r = await run(buildFetchArgv(script, target, opts), { env, timeoutMs: 90_000 })
720
- const log = logLines(r.stderr)
721
- if (r.code !== 0) throw exitError("review script", r)
722
- const children = (await readdir(webRoot, { withFileTypes: true })).filter(d => d.isDirectory()).map(d => d.name)
723
- if (children.length !== 1) throw new TideError(`expected one run vessel under ${webRoot}, found ${children.length}`)
724
- const vessel = join(webRoot, children[0])
725
- const doc = join(vessel, "reply.md")
734
+ const { webRoot, vessel, doc, log } = await readReplyIntoVessel(target, opts)
726
735
  const source: SourceIdentity = { target, ...here, ...parseAgentFromLog(log), fetched_at: new Date().toISOString() }
727
736
  await writeFile(join(vessel, SOURCE_FILE), JSON.stringify(source, null, 2) + "\n", "utf8")
728
737
  const text = await readFile(doc, "utf8")
729
738
  // The same reply fetched before keeps its document: everyone's marks and presence meet on one copy.
730
- const earlier = await findReplyVessel(here.pane_id, text, { exclude: webRoot })
739
+ const earlier = await findReplyVessel(here, text, { exclude: webRoot })
731
740
  if (earlier) {
732
741
  await rm(webRoot, { recursive: true, force: true })
733
742
  const blocks = await listBlocks(earlier.doc, text)
734
- return { id: earlier.doc, target, vessel: earlier.vessel, doc: earlier.doc, text, blocks, source: earlier.source, log, ...(earlier.marked ? { reopened: true } : {}) }
743
+ // A restart moved the pane: the vessel now names it, so a delivery needs no further proof.
744
+ const bound = samePaneLife(earlier.source, here) ? earlier.source : await rebindVessel(earlier.vessel, earlier.source, here, target)
745
+ return { id: earlier.doc, target, vessel: earlier.vessel, doc: earlier.doc, text, blocks, source: bound, log, ...(earlier.marked ? { reopened: true } : {}) }
735
746
  }
736
747
  const blocks = await listBlocks(doc, text)
737
748
  return { id: doc, target, vessel, doc, text, blocks, source, log }
738
749
  }
739
750
 
751
+ /** Run the script's fetch leg in a fresh directory of its own. A failed fetch leaves nothing behind. */
752
+ async function readReplyIntoVessel(
753
+ target: string,
754
+ opts: { pick?: number; host?: AnnotateHost } = {},
755
+ ): Promise<{ webRoot: string; vessel: string; doc: string; log: string[] }> {
756
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+$/, "").replace("T", "-")
757
+ const webRoot = join(resolveVesselRoot(), WEB_VESSEL_SUBDIR, `${stamp}-${randomBytes(3).toString("hex")}`)
758
+ await mkdir(webRoot, { recursive: true })
759
+ try {
760
+ const env = { ...(await childEnv()), [VESSEL_ROOT_ENV]: webRoot }
761
+ const r = await run(buildFetchArgv(resolveReviewScript(), target, opts), { env, timeoutMs: 90_000 })
762
+ if (r.code !== 0) throw exitError("review script", r)
763
+ const children = (await readdir(webRoot, { withFileTypes: true })).filter(d => d.isDirectory()).map(d => d.name)
764
+ if (children.length !== 1) throw new TideError(`expected one run vessel under ${webRoot}, found ${children.length}`)
765
+ const vessel = join(webRoot, children[0])
766
+ return { webRoot, vessel, doc: join(vessel, "reply.md"), log: logLines(r.stderr) }
767
+ } catch (err) {
768
+ await rm(webRoot, { recursive: true, force: true })
769
+ throw err
770
+ }
771
+ }
772
+
773
+ /** How far back a pane's replies are read to prove a restart: the agent may have answered again since. */
774
+ export const RESTART_PROOF_REPLIES = 5
775
+
776
+ /** Does the agent now in `target` hold this reply among its latest? No agent there answers false. */
777
+ async function paneHoldsReply(target: string, text: string): Promise<boolean> {
778
+ for (let pick = 1; pick <= RESTART_PROOF_REPLIES; pick++) {
779
+ let fetched: { webRoot: string; doc: string }
780
+ try {
781
+ fetched = await readReplyIntoVessel(target, { pick })
782
+ } catch {
783
+ return false
784
+ }
785
+ const held = await readFile(fetched.doc, "utf8")
786
+ await rm(fetched.webRoot, { recursive: true, force: true })
787
+ if (held === text) return true
788
+ }
789
+ return false
790
+ }
791
+
792
+ /** The vessel names the pane as it is now. When it was fetched stays as it was. */
793
+ async function rebindVessel(vessel: string, source: SourceIdentity, here: PaneIdentity, target: string): Promise<SourceIdentity> {
794
+ const bound: SourceIdentity = { ...source, ...here, target }
795
+ await writeFile(join(vessel, SOURCE_FILE), JSON.stringify(bound, null, 2) + "\n", "utf8")
796
+ return bound
797
+ }
798
+
740
799
  export async function listBlocks(doc: string, text?: string): Promise<ReplyBlock[]> {
741
800
  const bin = await resolvePlannotatorBin()
742
801
  const r = await run([bin, "--blocks", doc], { timeoutMs: 20_000 })
@@ -752,7 +811,7 @@ export async function exportReview(doc: string): Promise<ReviewExport> {
752
811
  return { doc, review: count > 0 ? r.stdout : "", count }
753
812
  }
754
813
 
755
- /** One mark as the store holds it. Marks made before attribution, or in the terminal TUI, answer null for their author. */
814
+ /** One mark as the store holds it. A mark made before attribution, or in a TUI nobody named a person to, answers null for its author. */
756
815
  export type MarkRecord = StoredMark
757
816
 
758
817
  /** The block index plannotator-tui stored with a mark (`anchor.plannotator_tui.block`), or null. */
@@ -828,8 +887,10 @@ export async function mark(doc: string, input: MarkInput): Promise<MarkResult> {
828
887
  * Paste the document's marks into `target` through the script's `--from-file`
829
888
  * leg: it exports, runs the pane guard, pastes bracketed, and presses Enter only
830
889
  * on `submit`. Before any of that, the target must BE the pane the document was
831
- * fetched from: the vessel's `source.json` names it, tmux is asked who `target`
832
- * is now, and the pane ids must agree. A document without a source identity was
890
+ * fetched from: the vessel's `source.json` names it and tmux is asked who `target`
891
+ * is now. The same id and process is that pane. After a tmux restart, the same
892
+ * session, window and pane index is that pane when the agent there still holds this
893
+ * reply, and the vessel is rebound to it. A document without a source identity was
833
894
  * not fetched through this module and is not delivered by it. A guard refusal is
834
895
  * a RESULT (`held`), not an error — the marks are safe in the vessel and
835
896
  * `redeliver` is the command that sends them later.
@@ -847,12 +908,22 @@ export async function deliver(target: string, doc: string, opts: { submit?: bool
847
908
  }
848
909
  const here = await resolvePaneIdentity(target)
849
910
  if (!here) throw new TideError(`refusing: target ${target} is gone`)
850
- if (!sourceMatches(source, here)) {
851
- throw new TideError(`refusing: this reply was fetched from ${describePane(source)}; ${target} is ${describePane(here)}`)
911
+ let bound = source
912
+ if (!samePaneLife(source, here)) {
913
+ if (!samePanePlace(source, here)) {
914
+ throw new TideError(`refusing: this reply was fetched from ${describePane(source)}; ${target} is ${describePane(here)}`)
915
+ }
916
+ if (!(await paneHoldsReply(here.pane_id, await readFile(doc, "utf8")))) {
917
+ throw new TideError(
918
+ `refusing: ${describePane(here)} is where this reply was fetched, and the agent there does not hold it among its last ${RESTART_PROOF_REPLIES} replies. ` +
919
+ `If it is the same agent, deliver from the terminal: ${script} ${here.pane_id} --from-file ${doc} --no-tui`,
920
+ )
921
+ }
922
+ bound = await rebindVessel(dirname(doc), source, here, target)
852
923
  }
853
- const argv = buildDeliverArgv(script, source.pane_id, doc, submit)
924
+ const argv = buildDeliverArgv(script, here.pane_id, doc, submit)
854
925
  const exported = await exportReview(doc)
855
- const base = { target, doc, source, count: exported.count, submitted: false, review: exported.review, redeliver: argv.join(" ") }
926
+ const base = { target, doc, source: bound, count: exported.count, submitted: false, review: exported.review, redeliver: argv.join(" ") }
856
927
  if (exported.count === 0) {
857
928
  return { ...base, delivered: false, held: null, log: ["no annotations on that document — nothing to deliver"] }
858
929
  }