@miadi/companion-ui 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/dialogue.tsx CHANGED
@@ -1,19 +1,27 @@
1
1
  "use client"
2
2
 
3
3
  /**
4
- * The conversation with a companion seat, as React: the person's takes and the seat's
5
- * replies in the order they happened, each with its playback, and the card an episode
4
+ * The conversation with a companion seat, as React: the person's takes, the seat's
5
+ * replies and the marks on the episode's drawings (each with the thread the seat answered
6
+ * in) in the order they happened, each reply with its playback, and the card an episode
6
7
  * room shows for it.
7
8
  *
8
9
  * Data in, intent out. The host builds the thread (`buildCompanionThread`), decides who
9
- * hears a take (`takeAudioUrl` answers null for a reader who may not), and says where a
10
- * related card leads (`relatedHref`). No component fetches, holds a URL or knows a root.
10
+ * hears a take (`takeAudioUrl` answers null for a reader who may not), says where a
11
+ * related card leads (`relatedHref`) and opens a mark on its board (`onOpenMark`). No
12
+ * component fetches, holds a URL or knows a root.
11
13
  */
12
14
 
13
15
  import { useRef, useState, type CSSProperties, type ReactNode } from "react"
14
16
  import {
17
+ drawingLabel,
18
+ markElementNames,
19
+ markOf,
20
+ markState,
15
21
  personaLabel,
22
+ sayMarks,
16
23
  stampOf,
24
+ type CompanionMarkTurn,
17
25
  type CompanionReplyTurn,
18
26
  type CompanionTakeTurn,
19
27
  type CompanionThread,
@@ -62,6 +70,21 @@ export interface CompanionTurnOptions {
62
70
  * steps reads as its words, and no walk is offered.
63
71
  */
64
72
  onWalk?: (turn: CompanionReplyTurn) => void
73
+ /**
74
+ * Open a mark on the host's board: its drawing, with the mark's thread. Absent: a mark
75
+ * reads as its words and its thread, and no button is offered.
76
+ */
77
+ onOpenMark?: (turn: CompanionMarkTurn) => void
78
+ /** False for a mark whose drawing the host's board does not draw: no button is offered for it. */
79
+ canOpenMark?: (turn: CompanionMarkTurn) => boolean
80
+ /**
81
+ * True when the reader is the person who marks the drawings (the episode's writer): a
82
+ * person's mark reads "You marked …" and a reply "answers your mark …". Otherwise each
83
+ * reads under its author's name.
84
+ */
85
+ readerMarks?: boolean
86
+ /** The companion a mark waits on, by name. Default `Mia`. */
87
+ companionName?: string
65
88
  theme?: Partial<CompanionTheme>
66
89
  }
67
90
 
@@ -109,6 +132,7 @@ function usePlayer() {
109
132
  }
110
133
 
111
134
  function sourcesOf(turn: CompanionTurn, options: CompanionTurnOptions): string[] {
135
+ if (turn.kind === "mark") return []
112
136
  if (turn.kind === "take") {
113
137
  const url = options.takeAudioUrl?.(turn)
114
138
  return url ? [url] : []
@@ -142,6 +166,8 @@ export interface CompanionTurnViewProps extends CompanionTurnOptions {
142
166
  turn: CompanionTurn
143
167
  /** The take this reply answers, when it is not the turn just before. */
144
168
  answers?: CompanionTakeTurn
169
+ /** The mark this reply answers, when it is in the thread. */
170
+ answersMark?: CompanionMarkTurn
145
171
  playing?: Playing | null
146
172
  onPlay?: (turn: CompanionTurn, srcs: string[]) => void
147
173
  /** Show the whole text at once. */
@@ -149,7 +175,143 @@ export interface CompanionTurnViewProps extends CompanionTurnOptions {
149
175
  anchorPrefix?: string
150
176
  }
151
177
 
152
- export function CompanionTurnView({ turn, answers, playing, onPlay, open = false, anchorPrefix = "turn-", ...options }: CompanionTurnViewProps) {
178
+ /** A pin, drawn: the mark's sign on the board. */
179
+ function PinIcon({ size = 14 }: { size?: number }) {
180
+ return (
181
+ <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true" focusable="false" style={{ flex: "none" }}>
182
+ <path d="M12 21.5s-6.5-6-6.5-11.5a6.5 6.5 0 1 1 13 0c0 5.5-6.5 11.5-6.5 11.5z" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinejoin="round" />
183
+ <circle cx="12" cy="10" r="2.3" fill="none" stroke="currentColor" strokeWidth="1.8" />
184
+ </svg>
185
+ )
186
+ }
187
+
188
+ /** A frame around a point, drawn: where on the drawing. */
189
+ function LocateIcon() {
190
+ return (
191
+ <svg width="13" height="13" viewBox="0 0 24 24" aria-hidden="true" focusable="false" style={{ flex: "none" }}>
192
+ <circle cx="12" cy="12" r="6.5" fill="none" stroke="currentColor" strokeWidth="1.8" />
193
+ <path d="M12 2.5v4M12 17.5v4M2.5 12h4M17.5 12h4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
194
+ </svg>
195
+ )
196
+ }
197
+
198
+ /** Who wrote a mark or a word in its thread, as this reader is told. */
199
+ function markWho(author: { name: string; role: string }, options: CompanionTurnOptions, subject: boolean): string {
200
+ if (options.readerMarks && author.role === "person") return subject ? "You" : "you"
201
+ return author.name
202
+ }
203
+
204
+ /** A mark on a drawing, its words, the thread under it, where it stands, and the way to it on the board. */
205
+ function MarkTurnView({ turn, open, anchorPrefix, options }: { turn: CompanionMarkTurn; open: boolean; anchorPrefix: string; options: CompanionTurnOptions }) {
206
+ const t = { ...COMPANION_THEME, ...options.theme }
207
+ const [expanded, setExpanded] = useState(open)
208
+ const byPerson = turn.author.role === "person"
209
+ const state = markState(turn)
210
+ const names = markElementNames(turn)
211
+ const drawing = drawingLabel(turn)
212
+ const companion = options.companionName ?? "Mia"
213
+ const long = turn.text.length + turn.replies.reduce((n, r) => n + r.text.length, 0) > LONG
214
+ const openable = !!options.onOpenMark && (options.canOpenMark?.(turn) ?? true)
215
+ const standing =
216
+ state === "answered" ? "answered" : state === "waiting" ? `waits for ${companion}` : state === "resolved" ? "resolved" : "waits for an answer"
217
+
218
+ const bubble: CSSProperties = {
219
+ alignSelf: byPerson ? "flex-end" : "flex-start",
220
+ width: "min(100%, 680px)",
221
+ boxSizing: "border-box",
222
+ background: t.card,
223
+ border: `1px solid ${byPerson ? `${t.accent}55` : t.border}`,
224
+ borderRadius: byPerson ? "12px 12px 4px 12px" : "12px 12px 12px 4px",
225
+ padding: "10px 12px",
226
+ display: "flex",
227
+ flexDirection: "column",
228
+ gap: 6,
229
+ }
230
+
231
+ return (
232
+ <article id={`${anchorPrefix}${turn.id}`} data-turn="mark" data-turn-id={turn.id} data-mark-state={state} style={bubble}>
233
+ <header style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 12, lineHeight: 1.45 }}>
234
+ <span style={{ color: byPerson ? t.accent : t.textDim, display: "inline-flex", marginTop: 1 }}><PinIcon /></span>
235
+ <span style={{ flex: "1 1 auto", minWidth: 0, display: "flex", flexWrap: "wrap", alignItems: "baseline", gap: "2px 10px" }}>
236
+ <span style={{ color: t.text, overflowWrap: "anywhere" }}>
237
+ <strong style={{ color: byPerson ? t.accent : t.text }}>{markWho(turn.author, options, true)}</strong> marked{" "}
238
+ <strong>{names}</strong> on <strong>{drawing}</strong>
239
+ </span>
240
+ <span style={{ color: t.muted, fontFamily: t.mono, fontSize: 11 }}>{stampOf(turn.at)}</span>
241
+ </span>
242
+ </header>
243
+
244
+ <div
245
+ style={{
246
+ display: "flex", flexDirection: "column", gap: 8,
247
+ ...(long && !expanded ? { maxHeight: "13em", overflow: "hidden", WebkitMaskImage: "linear-gradient(#000 70%, transparent)", maskImage: "linear-gradient(#000 70%, transparent)" } : {}),
248
+ }}
249
+ >
250
+ <div style={{ fontSize: 13.5, lineHeight: 1.55 }}>
251
+ <Prose text={turn.text} color={t.text} />
252
+ </div>
253
+ {turn.replies.length > 0 && (
254
+ <ol aria-label="the mark's thread" style={{ listStyle: "none", margin: 0, padding: "0 0 0 10px", borderLeft: `2px solid ${t.border}`, display: "flex", flexDirection: "column", gap: 8 }}>
255
+ {turn.replies.map((reply, i) => (
256
+ <li key={i} data-mark-reply={reply.author.role}>
257
+ <div style={{ display: "flex", flexWrap: "wrap", alignItems: "baseline", gap: "2px 8px", fontSize: 12 }}>
258
+ <strong style={{ color: reply.author.role === "agent" ? t.text : t.accent }}>{markWho(reply.author, options, true)}</strong>
259
+ <span style={{ color: t.muted, fontFamily: t.mono, fontSize: 11 }}>{stampOf(reply.at)}</span>
260
+ </div>
261
+ <div style={{ fontSize: 13, lineHeight: 1.5 }}>
262
+ <Prose text={reply.text} color={reply.author.role === "agent" ? t.text : t.textDim} />
263
+ </div>
264
+ </li>
265
+ ))}
266
+ </ol>
267
+ )}
268
+ </div>
269
+ {long && (
270
+ <button
271
+ type="button"
272
+ onClick={() => setExpanded(!expanded)}
273
+ style={{ alignSelf: "flex-start", background: "none", border: "none", padding: 0, cursor: "pointer", color: t.accent, fontSize: 12, fontFamily: "inherit" }}
274
+ >
275
+ {expanded ? "Show less" : "Read all"}
276
+ </button>
277
+ )}
278
+
279
+ <footer style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: "6px 12px", fontSize: 11.5 }}>
280
+ <span data-mark-standing="" style={{ color: state === "waiting" ? t.warning : t.muted }}>{standing}</span>
281
+ {turn.voiced.length > 0 && (
282
+ <a href={`#${anchorPrefix}${turn.voiced[0]}`} style={{ color: t.textDim }}>
283
+ also answered by voice
284
+ </a>
285
+ )}
286
+ {openable && (
287
+ <button
288
+ type="button"
289
+ onClick={() => options.onOpenMark?.(turn)}
290
+ title={`Opens ${drawing} on the board, with this mark's thread`}
291
+ style={{
292
+ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 6, minHeight: 32, padding: "4px 12px", borderRadius: 999, cursor: "pointer",
293
+ border: `1px solid ${t.accent}`, background: "transparent", color: t.accent, fontSize: 12, fontWeight: 700, fontFamily: "inherit",
294
+ }}
295
+ >
296
+ <LocateIcon />
297
+ See it on the drawing
298
+ </button>
299
+ )}
300
+ </footer>
301
+ </article>
302
+ )
303
+ }
304
+
305
+ export function CompanionTurnView(props: CompanionTurnViewProps) {
306
+ if (props.turn.kind === "mark") {
307
+ const { turn, open = false, anchorPrefix = "turn-", answers: _a, answersMark: _m, playing: _p, onPlay: _o, ...options } = props
308
+ return <MarkTurnView turn={turn} open={open} anchorPrefix={anchorPrefix} options={options} />
309
+ }
310
+ return <SpokenTurnView {...props} turn={props.turn} />
311
+ }
312
+
313
+ /** A take or a reply: what was said, with its playback. */
314
+ function SpokenTurnView({ turn, answers, answersMark, playing, onPlay, open = false, anchorPrefix = "turn-", ...options }: CompanionTurnViewProps & { turn: CompanionTakeTurn | CompanionReplyTurn }) {
153
315
  const t = { ...COMPANION_THEME, ...options.theme }
154
316
  const [expanded, setExpanded] = useState(open)
155
317
  const take = turn.kind === "take"
@@ -198,6 +360,18 @@ export function CompanionTurnView({ turn, answers, playing, onPlay, open = false
198
360
  answers the take of {stampOf(answers.at)}
199
361
  </a>
200
362
  )}
363
+ {!take && answersMark && (
364
+ <a href={`#${anchorPrefix}${answersMark.id}`} data-answers-mark={answersMark.id} style={{ color: t.textDim, fontSize: 11, display: "inline-flex", alignItems: "center", gap: 4 }}>
365
+ <PinIcon size={11} />
366
+ answers {options.readerMarks && answersMark.author.role === "person" ? "your" : `${answersMark.author.name}'s`} mark on {markElementNames(answersMark)}
367
+ </a>
368
+ )}
369
+ {!take && !answersMark && turn.mark && (
370
+ <span data-answers-mark={turn.mark.id} style={{ color: t.textDim, fontSize: 11, display: "inline-flex", alignItems: "center", gap: 4 }}>
371
+ <PinIcon size={11} />
372
+ answers a mark on the drawings
373
+ </span>
374
+ )}
201
375
  {!take && turn.feedback && (
202
376
  <span title={turn.feedback === "up" ? "marked as working" : "marked as not working"} style={{ fontSize: 12 }}>
203
377
  {turn.feedback === "up" ? "👍" : "👎"}
@@ -254,8 +428,10 @@ export function CompanionTurnView({ turn, answers, playing, onPlay, open = false
254
428
  {turn.related.map((card) => {
255
429
  const href = options.relatedHref ? options.relatedHref(card.href) : card.href
256
430
  const chip: CSSProperties = { fontSize: 11.5, padding: "3px 8px", borderRadius: 999, border: `1px solid ${t.border}`, color: t.textDim, textDecoration: "none" }
431
+ // Named by its label: a reading tool names a link by its title when it has one and cuts a long one,
432
+ // which turned a review's address into a prefix an agent completed by guessing (jgwill/Miadi#1032).
257
433
  return href ? (
258
- <a key={`${card.label}-${card.href}`} href={href} style={{ ...chip, color: t.accent }} title={card.href}>{card.label}</a>
434
+ <a key={`${card.label}-${card.href}`} href={href} style={{ ...chip, color: t.accent }} title={card.href} aria-label={card.label}>{card.label}</a>
259
435
  ) : (
260
436
  <span key={`${card.label}-${card.href}`} style={chip} title={card.href}>{card.label}</span>
261
437
  )
@@ -310,11 +486,13 @@ export function CompanionDialogue({ thread, initialTurns = 12, note, anchorPrefi
310
486
  const answers = turn.kind === "reply" && turn.take && !(before?.kind === "take" && before.id === turn.take)
311
487
  ? (thread.turns.find((x) => x.kind === "take" && x.id === turn.take) as CompanionTakeTurn | undefined)
312
488
  : undefined
489
+ const answersMark = turn.kind === "reply" ? markOf(thread, turn) : undefined
313
490
  return (
314
491
  <CompanionTurnView
315
492
  key={`${turn.kind}-${turn.id}`}
316
493
  turn={turn}
317
494
  answers={answers}
495
+ answersMark={answersMark}
318
496
  playing={playing}
319
497
  onPlay={(x, srcs) => play(x.id, srcs)}
320
498
  anchorPrefix={anchorPrefix}
@@ -351,12 +529,21 @@ export interface CompanionCardProps extends CompanionTurnOptions {
351
529
  export function CompanionCard({ thread, conversationHref, links = [], children, latest = 2, title = "Companion", ...options }: CompanionCardProps) {
352
530
  const t = { ...COMPANION_THEME, ...options.theme }
353
531
  const { audio, playing, play, events } = usePlayer()
354
- const personas = [...new Set(thread.turns.flatMap((x) => (x.kind === "reply" ? [personaLabel(x.persona)] : [])))]
532
+ const personas = [
533
+ ...new Set([
534
+ ...thread.turns.flatMap((x) => (x.kind === "reply" ? [personaLabel(x.persona)] : [])),
535
+ ...(thread.markCounts ?? []).flatMap((c) => c.answeredBy),
536
+ ]),
537
+ ]
355
538
  const turns = thread.turns.slice(-latest)
539
+ const marks = thread.marks ?? 0
356
540
  const counts = [
357
541
  thread.takes ? `${thread.takes} take${thread.takes === 1 ? "" : "s"}` : "",
358
542
  thread.replies ? `${thread.replies} repl${thread.replies === 1 ? "y" : "ies"}` : "",
543
+ marks ? `${marks} mark${marks === 1 ? "" : "s"}` : "",
359
544
  ].filter(Boolean).join(" · ")
545
+ // What the drawings hold, said even when the latest turns are takes and replies.
546
+ const onDrawings = thread.markCounts?.length ? sayMarks(thread, options.companionName ?? "Mia") : ""
360
547
 
361
548
  return (
362
549
  <section data-companion-card={thread.turns.length} style={{ background: t.card, border: `1px solid ${t.border}`, borderRadius: 10, padding: 15, display: "flex", flexDirection: "column", gap: 10 }}>
@@ -367,14 +554,21 @@ export function CompanionCard({ thread, conversationHref, links = [], children,
367
554
  )}
368
555
  </div>
369
556
  <audio ref={audio} {...events} controls preload="none" style={{ width: "100%", height: 32, display: playing ? "block" : "none" }} />
557
+ {onDrawings && (
558
+ <div data-companion-marks={marks} style={{ display: "flex", alignItems: "flex-start", gap: 6, fontSize: 12.5, color: t.textDim, lineHeight: 1.45 }}>
559
+ <span style={{ color: t.accent, display: "inline-flex", marginTop: 2 }}><PinIcon size={13} /></span>
560
+ <span>{onDrawings}</span>
561
+ </div>
562
+ )}
370
563
  {turns.length === 0 ? (
371
- <div style={{ fontSize: 12.5, color: t.textDim, fontStyle: "italic" }}>No conversation with a companion yet.</div>
564
+ onDrawings ? null : <div style={{ fontSize: 12.5, color: t.textDim, fontStyle: "italic" }}>No conversation with a companion yet.</div>
372
565
  ) : (
373
566
  <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
374
567
  {turns.map((turn) => (
375
568
  <CompanionTurnView
376
569
  key={`${turn.kind}-${turn.id}`}
377
570
  turn={turn}
571
+ answersMark={turn.kind === "reply" ? markOf(thread, turn) : undefined}
378
572
  playing={playing}
379
573
  onPlay={(x, srcs) => play(x.id, srcs)}
380
574
  anchorPrefix="companion-card-"
package/src/index.ts CHANGED
@@ -2,8 +2,9 @@
2
2
  * @miadi/companion-ui — an episode's companion seat, as React.
3
3
  *
4
4
  * - The conversation: `buildCompanionThread` joins the person's takes, the seat's
5
- * replies and the voices cut from them; `CompanionDialogue` shows it with each
6
- * turn's playback; `CompanionCard` is the short form an episode room shows.
5
+ * replies, the voices cut from them and the marks on the episode's drawings with
6
+ * their threads; `CompanionDialogue` shows it with each turn's playback;
7
+ * `CompanionCard` is the short form an episode room shows.
7
8
  * - The seat: `CompanionOpener` plans and opens a seat for an episode through a
8
9
  * transport the host gives it (`httpCompanionTransport`). `CompanionGlyphBar`
9
10
  * draws one glyph per agent with a seat, and the host shows the opener of the
@@ -20,13 +21,25 @@
20
21
  export {
21
22
  COMPANION_VOICE_SOURCE,
22
23
  buildCompanionThread,
24
+ drawingLabel,
23
25
  isCompanionVoice,
26
+ markAnswerer,
27
+ markElementNames,
28
+ markOf,
29
+ markState,
24
30
  personaLabel,
31
+ sayMarks,
25
32
  seatOfSession,
26
33
  speakable,
27
34
  stampOf,
28
35
  takeOf,
29
36
  type CompanionFeedback,
37
+ type CompanionMark,
38
+ type CompanionMarkAuthor,
39
+ type CompanionMarkCount,
40
+ type CompanionMarkRef,
41
+ type CompanionMarkReply,
42
+ type CompanionMarkTurn,
30
43
  type CompanionRelated,
31
44
  type CompanionReply,
32
45
  type CompanionReplyTurn,
package/src/node.ts CHANGED
@@ -11,19 +11,35 @@
11
11
  * `claude/mia-episode-companion/phone-capture`). Only id, take, text, seat, session,
12
12
  * time, related cards and the thumb leave this module. The reply's origin (user, host,
13
13
  * pane, cwd) and its loop record stay on the host.
14
+ * - Marks are the drawing sidecars under the episode's `diagrams/` folder
15
+ * (`<name>.<kind>.marks.json`, jgwill/smcraft Spec 83): what a person pointed at and
16
+ * wrote, and the thread an agent answered in. A reply that answers a mark keeps
17
+ * `mark: { id, doc }`.
14
18
  * - Forks are the episode's `branches/<name>/` folders that hold a brief: the trunk
15
19
  * seat writes the brief when it forks a session to work a branch.
16
20
  *
17
21
  * Every reader answers an empty list when its folder or file is absent or unreadable.
18
22
  */
19
23
 
20
- import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
24
+ import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs"
21
25
  import { homedir } from "node:os"
22
26
  import { join } from "node:path"
23
- import type { CompanionFeedback, CompanionRelated, CompanionReply, CompanionStep, CompanionTake } from "./thread.js"
27
+ import type {
28
+ CompanionFeedback,
29
+ CompanionMark,
30
+ CompanionMarkAuthor,
31
+ CompanionMarkRef,
32
+ CompanionMarkReply,
33
+ CompanionRelated,
34
+ CompanionReply,
35
+ CompanionStep,
36
+ CompanionTake,
37
+ } from "./thread.js"
24
38
 
25
39
  const TAKE_ID = /^\d{12}$/
26
40
  const EPISODE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
41
+ /** The loom's mark id (`newMarkId` in `@miadi/stateloom-protocol`). */
42
+ const MARK_ID = /^m-[0-9a-z]+$/
27
43
 
28
44
  function readJson(file: string): Record<string, unknown> | null {
29
45
  try {
@@ -154,6 +170,15 @@ function steps(value: unknown): CompanionStep[] {
154
170
  return out
155
171
  }
156
172
 
173
+ /** A reply's mark, kept only when its id is the loom's and its drawing an absolute `.json` path. */
174
+ function markRef(value: unknown): CompanionMarkRef | undefined {
175
+ const m = (value && typeof value === "object" ? value : {}) as Record<string, unknown>
176
+ const id = str(m.id)
177
+ const doc = str(m.doc)
178
+ if (!id || !MARK_ID.test(id) || !doc || !doc.startsWith("/") || !doc.endsWith(".json") || doc.split("/").includes("..")) return undefined
179
+ return { id, doc }
180
+ }
181
+
157
182
  export function readCompanionReplies(repliesDir: string, episode: string): CompanionReply[] {
158
183
  if (!EPISODE_NAME.test(episode)) return []
159
184
  const thumbs = new Map<string, CompanionFeedback | "">()
@@ -173,6 +198,7 @@ export function readCompanionReplies(repliesDir: string, episode: string): Compa
173
198
  const cards = related(r.related)
174
199
  const thumb = thumbs.get(id)
175
200
  const walk = steps(r.steps)
201
+ const mark = markRef(r.mark)
176
202
  replies.push({
177
203
  id,
178
204
  take: take && TAKE_ID.test(take) ? take : null,
@@ -183,11 +209,130 @@ export function readCompanionReplies(repliesDir: string, episode: string): Compa
183
209
  ...(cards.length ? { related: cards } : {}),
184
210
  ...(thumb ? { feedback: thumb } : {}),
185
211
  ...(walk.length ? { steps: walk } : {}),
212
+ ...(mark ? { mark } : {}),
186
213
  })
187
214
  }
188
215
  return replies.sort((a, b) => a.at.localeCompare(b.at))
189
216
  }
190
217
 
218
+ /** A drawing's sidecar: `<name>.<smdf|erdf|sqdf>.marks.json` (the loom's `marksPathOf`). */
219
+ const MARKS_FILE = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(smdf|erdf|sqdf)\.marks\.json$/
220
+ const FOLDER = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
221
+ /** Folders under `diagrams/` a sidecar may sit in: `diagrams/a/b/c/`. */
222
+ const MARKS_DEPTH = 3
223
+ const MAX_MARKS = 40
224
+ const MAX_TEXT = 4000
225
+ const MAX_FILE_BYTES = 1_500_000
226
+
227
+ /** A file under `diagrams/` as JSON, when it is a plain file of a readable size. */
228
+ function readSmallJson(file: string): Record<string, unknown> | null {
229
+ try {
230
+ const stat = lstatSync(file)
231
+ if (!stat.isFile() || stat.size > MAX_FILE_BYTES) return null
232
+ } catch {
233
+ return null
234
+ }
235
+ return readJson(file)
236
+ }
237
+
238
+ function clip(text: string): string {
239
+ return text.length > MAX_TEXT ? `${text.slice(0, MAX_TEXT - 1)}…` : text
240
+ }
241
+
242
+ function markAuthor(value: unknown): CompanionMarkAuthor | null {
243
+ const a = (value && typeof value === "object" ? value : {}) as Record<string, unknown>
244
+ const name = str(a.name)
245
+ const role = a.role
246
+ return name && (role === "person" || role === "agent") ? { name, role } : null
247
+ }
248
+
249
+ /** The drawing's own name: `settings.name`, the machine's when it is written wrapped (`{ stateMachine }`). */
250
+ function drawingTitle(file: string): string | undefined {
251
+ const raw = readSmallJson(file)
252
+ if (!raw) return undefined
253
+ const def = (raw.stateMachine ?? raw.definition ?? raw) as Record<string, unknown>
254
+ const settings = (def && typeof def === "object" ? def.settings : undefined) as Record<string, unknown> | undefined
255
+ return str(settings?.name)
256
+ }
257
+
258
+ /** One drawing's marks, read defensively: a mark that does not say who, when and what is left out. */
259
+ function marksOf(diagrams: string, folder: string, sidecar: string): CompanionMark[] {
260
+ const raw = readSmallJson(join(diagrams, folder, sidecar))
261
+ if (!raw || !Array.isArray(raw.marks)) return []
262
+ const drawing = `${folder ? `${folder}/` : ""}${sidecar.replace(/\.marks\.json$/i, ".json")}`
263
+ const doc = join(diagrams, drawing)
264
+ const title = drawingTitle(doc)
265
+ const out: CompanionMark[] = []
266
+ for (const value of raw.marks as unknown[]) {
267
+ const m = (value && typeof value === "object" ? value : {}) as Record<string, unknown>
268
+ const id = str(m.id)
269
+ const text = str(m.text)
270
+ const at = str(m.at)
271
+ const author = markAuthor(m.author)
272
+ if (!id || !MARK_ID.test(id) || !text || !at || !author) continue
273
+ const elements = Array.isArray(m.elements)
274
+ ? m.elements.filter((e): e is string => typeof e === "string" && e.includes(":")).slice(0, 48)
275
+ : []
276
+ const r = m.region as Record<string, unknown> | undefined
277
+ const area = !!r && [r.width, r.height].every((v) => typeof v === "number" && Number.isFinite(v) && v > 0)
278
+ const replies: CompanionMarkReply[] = []
279
+ for (const rv of Array.isArray(m.replies) ? (m.replies as unknown[]) : []) {
280
+ const reply = (rv && typeof rv === "object" ? rv : {}) as Record<string, unknown>
281
+ const who = markAuthor(reply.author)
282
+ const said = str(reply.text)
283
+ const when = str(reply.at)
284
+ if (who && said && when) replies.push({ author: who, text: clip(said), at: when })
285
+ }
286
+ const status = m.status === "answered" || m.status === "resolved" ? m.status : "open"
287
+ const lastAt = replies.reduce((latest, x) => (x.at > latest ? x.at : latest), at)
288
+ out.push({
289
+ id,
290
+ doc,
291
+ drawing,
292
+ ...(title ? { title } : {}),
293
+ elements,
294
+ ...(area ? { area: true } : {}),
295
+ text: clip(text),
296
+ author,
297
+ at,
298
+ lastAt,
299
+ status,
300
+ replies,
301
+ })
302
+ }
303
+ return out
304
+ }
305
+
306
+ /**
307
+ * The marks on an episode's drawings, with their threads: every drawing sidecar under
308
+ * `<episodeDir>/diagrams/`, at most three folders deep, symbolic links and hidden folders
309
+ * left alone. A sidecar that does not parse is skipped. The latest 40 marks by when they
310
+ * were made, each text cut at 4000 characters, oldest first.
311
+ */
312
+ export function readCompanionMarks(episodeDir: string): CompanionMark[] {
313
+ const diagrams = join(episodeDir, "diagrams")
314
+ try {
315
+ if (!lstatSync(diagrams).isDirectory()) return []
316
+ } catch {
317
+ return []
318
+ }
319
+ const marks: CompanionMark[] = []
320
+ const visit = (folder: string, depth: number) => {
321
+ let entries
322
+ try {
323
+ entries = readdirSync(join(diagrams, folder), { withFileTypes: true })
324
+ } catch {
325
+ return
326
+ }
327
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
328
+ if (e.isFile() && MARKS_FILE.test(e.name)) marks.push(...marksOf(diagrams, folder, e.name))
329
+ else if (e.isDirectory() && depth < MARKS_DEPTH && FOLDER.test(e.name)) visit(folder ? `${folder}/${e.name}` : e.name, depth + 1)
330
+ }
331
+ }
332
+ visit("", 0)
333
+ return marks.sort((a, b) => a.at.localeCompare(b.at)).slice(-MAX_MARKS)
334
+ }
335
+
191
336
  export interface CompanionFork {
192
337
  /** The branch folder's name: `plot-threads`. */
193
338
  name: string