@miadi/companion-ui 0.0.0-stage → 0.1.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.
@@ -0,0 +1,381 @@
1
+ "use client"
2
+
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
6
+ * room shows for it.
7
+ *
8
+ * 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.
11
+ */
12
+
13
+ import { useRef, useState, type CSSProperties, type ReactNode } from "react"
14
+ import {
15
+ personaLabel,
16
+ stampOf,
17
+ type CompanionReplyTurn,
18
+ type CompanionTakeTurn,
19
+ type CompanionThread,
20
+ type CompanionTurn,
21
+ } from "./thread.js"
22
+
23
+ /** The fields `@miadi/episode-ui`'s `EpisodeUITheme` carries, so `CHRONICLE_THEME` fits as it is. */
24
+ export interface CompanionTheme {
25
+ background: string
26
+ card: string
27
+ text: string
28
+ textDim: string
29
+ muted: string
30
+ accent: string
31
+ border: string
32
+ success: string
33
+ warning: string
34
+ mono: string
35
+ }
36
+
37
+ /** The Chronicle's surface (the values of `@miadi/episode-ui/chronicle-theme`), every text colour at 4.5:1 or better. */
38
+ export const COMPANION_THEME: CompanionTheme = {
39
+ background: "#151515",
40
+ card: "#242424",
41
+ text: "#f9f9f9",
42
+ textDim: "#c8c8c8",
43
+ muted: "#959595",
44
+ accent: "#d4a843",
45
+ border: "#404040",
46
+ success: "#5ac37d",
47
+ warning: "#e0a458",
48
+ mono: "'JetBrains Mono', ui-monospace, monospace",
49
+ }
50
+
51
+ export interface CompanionTurnOptions {
52
+ /** A take's audio URL, or null when this reader does not hear takes. */
53
+ takeAudioUrl?: (take: CompanionTakeTurn) => string | null
54
+ /** The name a take is shown under. */
55
+ takeSpeaker?: string
56
+ /** Where a related card leads; the card's own href when absent, text when it answers null. */
57
+ relatedHref?: (href: string) => string | null
58
+ /** False when the host could not read the voices, so a reply without one is not called unvoiced. */
59
+ voicesRead?: boolean
60
+ theme?: Partial<CompanionTheme>
61
+ }
62
+
63
+ // ---------- playback ----------
64
+
65
+ interface Playing {
66
+ turn: string
67
+ part: number
68
+ parts: number
69
+ paused: boolean
70
+ }
71
+
72
+ /** One audio element per surface; a reply plays its voices one after another. */
73
+ function usePlayer() {
74
+ const audio = useRef<HTMLAudioElement>(null)
75
+ const queue = useRef<string[]>([])
76
+ const [playing, setPlaying] = useState<Playing | null>(null)
77
+
78
+ const start = (turn: string, srcs: string[], part = 0) => {
79
+ const a = audio.current
80
+ const src = srcs[part]
81
+ if (!a || !src) return
82
+ queue.current = srcs
83
+ setPlaying({ turn, part, parts: srcs.length, paused: false })
84
+ a.src = src
85
+ a.play().catch(() => {})
86
+ }
87
+ const play = (turn: string, srcs: string[]) => {
88
+ const a = audio.current
89
+ if (playing?.turn === turn && a) {
90
+ if (a.paused) a.play().catch(() => {})
91
+ else a.pause()
92
+ return
93
+ }
94
+ start(turn, srcs)
95
+ }
96
+ const onEnded = () => {
97
+ if (!playing) return
98
+ if (playing.part + 1 < queue.current.length) start(playing.turn, queue.current, playing.part + 1)
99
+ else setPlaying(null)
100
+ }
101
+ const onPause = () => setPlaying((p) => (p && !p.paused ? { ...p, paused: true } : p))
102
+ const onResume = () => setPlaying((p) => (p && p.paused ? { ...p, paused: false } : p))
103
+ return { audio, playing, play, events: { onEnded, onPause, onPlay: onResume } }
104
+ }
105
+
106
+ function sourcesOf(turn: CompanionTurn, options: CompanionTurnOptions): string[] {
107
+ if (turn.kind === "take") {
108
+ const url = options.takeAudioUrl?.(turn)
109
+ return url ? [url] : []
110
+ }
111
+ return turn.audio.map((v) => v.src).filter((src): src is string => Boolean(src))
112
+ }
113
+
114
+ // ---------- text ----------
115
+
116
+ /** Paragraphs, with `**bold**` kept as emphasis and every other character as written. */
117
+ function Prose({ text, color }: { text: string; color: string }) {
118
+ const paragraphs = text.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean)
119
+ return (
120
+ <>
121
+ {paragraphs.map((p, i) => (
122
+ <p key={i} style={{ margin: i === 0 ? 0 : "8px 0 0", whiteSpace: "pre-wrap", overflowWrap: "anywhere", color }}>
123
+ {p.split(/(\*\*[^*]+\*\*)/g).map((piece, j) =>
124
+ /^\*\*[^*]+\*\*$/.test(piece) ? <strong key={j}>{piece.slice(2, -2)}</strong> : <span key={j}>{piece}</span>,
125
+ )}
126
+ </p>
127
+ ))}
128
+ </>
129
+ )
130
+ }
131
+
132
+ const LONG = 520
133
+
134
+ // ---------- one turn ----------
135
+
136
+ export interface CompanionTurnViewProps extends CompanionTurnOptions {
137
+ turn: CompanionTurn
138
+ /** The take this reply answers, when it is not the turn just before. */
139
+ answers?: CompanionTakeTurn
140
+ playing?: Playing | null
141
+ onPlay?: (turn: CompanionTurn, srcs: string[]) => void
142
+ /** Show the whole text at once. */
143
+ open?: boolean
144
+ anchorPrefix?: string
145
+ }
146
+
147
+ export function CompanionTurnView({ turn, answers, playing, onPlay, open = false, anchorPrefix = "turn-", ...options }: CompanionTurnViewProps) {
148
+ const t = { ...COMPANION_THEME, ...options.theme }
149
+ const [expanded, setExpanded] = useState(open)
150
+ const take = turn.kind === "take"
151
+ const srcs = sourcesOf(turn, options)
152
+ const on = playing?.turn === turn.id
153
+ const sounding = on && !playing?.paused
154
+ const long = turn.text.length > LONG
155
+ const who = take ? (options.takeSpeaker ?? "Take") : personaLabel(turn.persona)
156
+
157
+ const bubble: CSSProperties = {
158
+ alignSelf: take ? "flex-end" : "flex-start",
159
+ width: "min(100%, 680px)",
160
+ boxSizing: "border-box",
161
+ background: t.card,
162
+ border: `1px solid ${on ? t.accent : take ? `${t.accent}55` : t.border}`,
163
+ borderRadius: take ? "12px 12px 4px 12px" : "12px 12px 12px 4px",
164
+ padding: "10px 12px",
165
+ display: "flex",
166
+ flexDirection: "column",
167
+ gap: 6,
168
+ }
169
+
170
+ return (
171
+ <article id={`${anchorPrefix}${turn.id}`} data-turn={turn.kind} data-turn-id={turn.id} style={bubble}>
172
+ <header style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: "4px 10px", fontSize: 12 }}>
173
+ {srcs.length > 0 && (
174
+ <button
175
+ type="button"
176
+ onClick={() => onPlay?.(turn, srcs)}
177
+ aria-label={`${sounding ? "Pause" : "Play"} ${who} ${stampOf(turn.at)}`}
178
+ style={{
179
+ width: 26, height: 26, flex: "none", borderRadius: 999, border: "none", cursor: "pointer",
180
+ background: on ? t.accent : t.muted, color: t.background, fontSize: 11, display: "flex", alignItems: "center", justifyContent: "center",
181
+ }}
182
+ >
183
+ {sounding ? "❚❚" : "▶"}
184
+ </button>
185
+ )}
186
+ <strong style={{ color: take ? t.accent : t.text }}>{who}</strong>
187
+ <span style={{ color: t.muted, fontFamily: t.mono, fontSize: 11 }}>{stampOf(turn.at)}</span>
188
+ {on && playing && playing.parts > 1 && (
189
+ <span style={{ color: t.accent, fontFamily: t.mono, fontSize: 11 }}>part {playing.part + 1} of {playing.parts}</span>
190
+ )}
191
+ {!take && answers && (
192
+ <a href={`#${anchorPrefix}${answers.id}`} style={{ color: t.textDim, fontSize: 11 }}>
193
+ answers the take of {stampOf(answers.at)}
194
+ </a>
195
+ )}
196
+ {!take && turn.feedback && (
197
+ <span title={turn.feedback === "up" ? "marked as working" : "marked as not working"} style={{ fontSize: 12 }}>
198
+ {turn.feedback === "up" ? "👍" : "👎"}
199
+ </span>
200
+ )}
201
+ </header>
202
+
203
+ {turn.text ? (
204
+ <div
205
+ style={{
206
+ fontSize: 13.5, lineHeight: 1.55,
207
+ ...(long && !expanded ? { maxHeight: "9.5em", overflow: "hidden", WebkitMaskImage: "linear-gradient(#000 70%, transparent)", maskImage: "linear-gradient(#000 70%, transparent)" } : {}),
208
+ }}
209
+ >
210
+ <Prose text={turn.text} color={t.text} />
211
+ </div>
212
+ ) : (
213
+ <div style={{ fontSize: 12.5, fontStyle: "italic", color: t.textDim }}>{take ? "No transcript yet." : "No text."}</div>
214
+ )}
215
+ {long && (
216
+ <button
217
+ type="button"
218
+ onClick={() => setExpanded(!expanded)}
219
+ style={{ alignSelf: "flex-start", background: "none", border: "none", padding: 0, cursor: "pointer", color: t.accent, fontSize: 12, fontFamily: "inherit" }}
220
+ >
221
+ {expanded ? "Show less" : "Read all"}
222
+ </button>
223
+ )}
224
+
225
+ {!take && turn.related?.length ? (
226
+ <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
227
+ {turn.related.map((card) => {
228
+ const href = options.relatedHref ? options.relatedHref(card.href) : card.href
229
+ const chip: CSSProperties = { fontSize: 11.5, padding: "3px 8px", borderRadius: 999, border: `1px solid ${t.border}`, color: t.textDim, textDecoration: "none" }
230
+ return href ? (
231
+ <a key={`${card.label}-${card.href}`} href={href} style={{ ...chip, color: t.accent }} title={card.href}>{card.label}</a>
232
+ ) : (
233
+ <span key={`${card.label}-${card.href}`} style={chip} title={card.href}>{card.label}</span>
234
+ )
235
+ })}
236
+ </div>
237
+ ) : null}
238
+
239
+ {!take && turn.fromVoices && (
240
+ <div style={{ fontSize: 11, color: t.muted }}>Shown from its voice: the reply's own record is not on this host.</div>
241
+ )}
242
+ {!take && srcs.length === 0 && !turn.fromVoices && (
243
+ <div style={{ fontSize: 11, color: t.muted }}>{options.voicesRead === false ? "Its voice could not be read just now." : "Not voiced."}</div>
244
+ )}
245
+ </article>
246
+ )
247
+ }
248
+
249
+ // ---------- the whole conversation ----------
250
+
251
+ export interface CompanionDialogueProps extends CompanionTurnOptions {
252
+ thread: CompanionThread
253
+ /** How many of the latest turns show before "show earlier". Default 12; 0 shows all. */
254
+ initialTurns?: number
255
+ /** A line above the turns, for instance why the takes are not shown to this reader. */
256
+ note?: ReactNode
257
+ anchorPrefix?: string
258
+ }
259
+
260
+ export function CompanionDialogue({ thread, initialTurns = 12, note, anchorPrefix = "turn-", ...options }: CompanionDialogueProps) {
261
+ const t = { ...COMPANION_THEME, ...options.theme }
262
+ const { audio, playing, play, events } = usePlayer()
263
+ const [shown, setShown] = useState(initialTurns > 0 ? initialTurns : thread.turns.length)
264
+ const from = Math.max(0, thread.turns.length - shown)
265
+ const turns = thread.turns.slice(from)
266
+
267
+ return (
268
+ <section data-companion-dialogue={thread.turns.length} style={{ display: "flex", flexDirection: "column", gap: 10 }}>
269
+ <audio ref={audio} {...events} controls preload="none" style={{ width: "100%", height: 36, display: playing ? "block" : "none" }} />
270
+ {note ? <div style={{ fontSize: 12.5, color: t.textDim }}>{note}</div> : null}
271
+ {thread.turns.length === 0 && <div style={{ fontSize: 13, color: t.textDim, fontStyle: "italic" }}>No conversation with a companion yet.</div>}
272
+ {from > 0 && (
273
+ <button
274
+ type="button"
275
+ onClick={() => setShown(thread.turns.length)}
276
+ style={{ alignSelf: "center", background: "transparent", border: `1px solid ${t.border}`, borderRadius: 999, color: t.accent, padding: "6px 14px", cursor: "pointer", fontSize: 12.5, fontFamily: "inherit" }}
277
+ >
278
+ Show {from} earlier turn{from === 1 ? "" : "s"}
279
+ </button>
280
+ )}
281
+ {turns.map((turn, i) => {
282
+ const before = i > 0 ? turns[i - 1] : from > 0 ? thread.turns[from - 1] : undefined
283
+ const answers = turn.kind === "reply" && turn.take && !(before?.kind === "take" && before.id === turn.take)
284
+ ? (thread.turns.find((x) => x.kind === "take" && x.id === turn.take) as CompanionTakeTurn | undefined)
285
+ : undefined
286
+ return (
287
+ <CompanionTurnView
288
+ key={`${turn.kind}-${turn.id}`}
289
+ turn={turn}
290
+ answers={answers}
291
+ playing={playing}
292
+ onPlay={(x, srcs) => play(x.id, srcs)}
293
+ anchorPrefix={anchorPrefix}
294
+ {...options}
295
+ />
296
+ )
297
+ })}
298
+ </section>
299
+ )
300
+ }
301
+
302
+ // ---------- the card an episode room shows ----------
303
+
304
+ export interface CompanionLink {
305
+ label: string
306
+ href: string
307
+ /** Opens in a new tab. */
308
+ external?: boolean
309
+ }
310
+
311
+ export interface CompanionCardProps extends CompanionTurnOptions {
312
+ thread: CompanionThread
313
+ /** The page that shows the whole conversation. */
314
+ conversationHref?: string
315
+ /** Other places the reader may go: the seat's pane, the page that records a take. */
316
+ links?: CompanionLink[]
317
+ /** Shown under the links, for instance `<CompanionOpener>` for a person who may open a seat. */
318
+ children?: ReactNode
319
+ /** How many of the latest turns the card shows. Default 2. */
320
+ latest?: number
321
+ title?: string
322
+ }
323
+
324
+ export function CompanionCard({ thread, conversationHref, links = [], children, latest = 2, title = "Companion", ...options }: CompanionCardProps) {
325
+ const t = { ...COMPANION_THEME, ...options.theme }
326
+ const { audio, playing, play, events } = usePlayer()
327
+ const personas = [...new Set(thread.turns.flatMap((x) => (x.kind === "reply" ? [personaLabel(x.persona)] : [])))]
328
+ const turns = thread.turns.slice(-latest)
329
+ const counts = [
330
+ thread.takes ? `${thread.takes} take${thread.takes === 1 ? "" : "s"}` : "",
331
+ thread.replies ? `${thread.replies} repl${thread.replies === 1 ? "y" : "ies"}` : "",
332
+ ].filter(Boolean).join(" · ")
333
+
334
+ return (
335
+ <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 }}>
336
+ <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 8, flexWrap: "wrap" }}>
337
+ <div style={{ fontSize: 11.5, fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.06em", color: t.muted }}>{title}</div>
338
+ {(personas.length > 0 || counts) && (
339
+ <div style={{ fontSize: 11.5, color: t.textDim }}>{[personas.join(", "), counts].filter(Boolean).join(" · ")}</div>
340
+ )}
341
+ </div>
342
+ <audio ref={audio} {...events} controls preload="none" style={{ width: "100%", height: 32, display: playing ? "block" : "none" }} />
343
+ {turns.length === 0 ? (
344
+ <div style={{ fontSize: 12.5, color: t.textDim, fontStyle: "italic" }}>No conversation with a companion yet.</div>
345
+ ) : (
346
+ <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
347
+ {turns.map((turn) => (
348
+ <CompanionTurnView
349
+ key={`${turn.kind}-${turn.id}`}
350
+ turn={turn}
351
+ playing={playing}
352
+ onPlay={(x, srcs) => play(x.id, srcs)}
353
+ anchorPrefix="companion-card-"
354
+ {...options}
355
+ />
356
+ ))}
357
+ </div>
358
+ )}
359
+ {(conversationHref || links.length > 0) && (
360
+ <nav style={{ display: "flex", flexDirection: "column", gap: 6, fontSize: 13 }}>
361
+ {conversationHref && thread.turns.length > 0 && (
362
+ <a href={conversationHref} style={{ color: t.accent, fontWeight: 700, textDecoration: "none" }}>
363
+ Open the whole conversation →
364
+ </a>
365
+ )}
366
+ {links.map((link) => (
367
+ <a
368
+ key={link.href}
369
+ href={link.href}
370
+ {...(link.external ? { target: "_blank", rel: "noreferrer" } : {})}
371
+ style={{ color: t.accent, textDecoration: "none" }}
372
+ >
373
+ {link.label}{link.external ? " ↗" : " →"}
374
+ </a>
375
+ ))}
376
+ </nav>
377
+ )}
378
+ {children}
379
+ </section>
380
+ )
381
+ }
package/src/index.ts ADDED
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @miadi/companion-ui — an episode's companion seat, as React.
3
+ *
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.
7
+ * - The seat: `CompanionOpener` plans and opens a seat for an episode through a
8
+ * transport the host gives it (`httpCompanionTransport`).
9
+ *
10
+ * Data and a transport in, intent out. No component holds a URL, a token or a
11
+ * chronicle root, and none decides who may hear a take or open a seat: the host
12
+ * decides, and passes or withholds. `@miadi/companion-ui/node` reads the files.
13
+ *
14
+ * The React modules are client modules. A server component imports the data from
15
+ * `@miadi/companion-ui/thread` and `@miadi/companion-ui/seat`, which hold no React.
16
+ */
17
+
18
+ export {
19
+ COMPANION_VOICE_SOURCE,
20
+ buildCompanionThread,
21
+ isCompanionVoice,
22
+ personaLabel,
23
+ seatOfSession,
24
+ speakable,
25
+ stampOf,
26
+ takeOf,
27
+ type CompanionFeedback,
28
+ type CompanionRelated,
29
+ type CompanionReply,
30
+ type CompanionReplyTurn,
31
+ type CompanionTake,
32
+ type CompanionTakeTurn,
33
+ type CompanionThread,
34
+ type CompanionTurn,
35
+ type CompanionVoice,
36
+ } from "./thread.js"
37
+ export {
38
+ COMPANION_SEATS,
39
+ LISTENING,
40
+ NOTHING_TO_RUN,
41
+ companionSessionName,
42
+ httpCompanionTransport,
43
+ sayFault,
44
+ sayPlan,
45
+ seatLabel,
46
+ type CompanionAnswer,
47
+ type CompanionOpenRequest,
48
+ type CompanionPlan,
49
+ type CompanionTransport,
50
+ } from "./seat.js"
51
+ export {
52
+ COMPANION_THEME,
53
+ CompanionCard,
54
+ CompanionDialogue,
55
+ CompanionTurnView,
56
+ type CompanionCardProps,
57
+ type CompanionDialogueProps,
58
+ type CompanionLink,
59
+ type CompanionTheme,
60
+ type CompanionTurnOptions,
61
+ type CompanionTurnViewProps,
62
+ } from "./dialogue.js"
63
+ export { CompanionOpener, OPENER_THEME, type CompanionOpenerProps, type CompanionOpenerTheme } from "./opener.js"
package/src/node.ts ADDED
@@ -0,0 +1,202 @@
1
+ /**
2
+ * `@miadi/companion-ui/node` — reads what the companion wrote, on the host that holds it.
3
+ *
4
+ * - Takes are capture bundles in the episode folder: `captures/<take>/capture.json`
5
+ * (`miadi.episode-capture.v1`) and `transcription_<take>_EN.txt` beside it. Only the
6
+ * descriptor and the transcript are read, never the audio and never a digest, so a
7
+ * room with twenty takes of twenty megabytes stays quick.
8
+ * - Replies are the companion phone page's records, one JSON line per reply in
9
+ * `<state>/replies/<episode>.jsonl`, with the person's thumbs in
10
+ * `<state>/replies/feedback/<episode>.jsonl` (jgwill/miadi-orchestration-kit,
11
+ * `claude/mia-episode-companion/phone-capture`). Only id, take, text, seat, session,
12
+ * time, related cards and the thumb leave this module. The reply's origin (user, host,
13
+ * pane, cwd) and its loop record stay on the host.
14
+ * - Forks are the episode's `branches/<name>/` folders that hold a brief: the trunk
15
+ * seat writes the brief when it forks a session to work a branch.
16
+ *
17
+ * Every reader answers an empty list when its folder or file is absent or unreadable.
18
+ */
19
+
20
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"
21
+ import { homedir } from "node:os"
22
+ import { join } from "node:path"
23
+ import type { CompanionFeedback, CompanionRelated, CompanionReply, CompanionTake } from "./thread.js"
24
+
25
+ const TAKE_ID = /^\d{12}$/
26
+ const EPISODE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/
27
+
28
+ function readJson(file: string): Record<string, unknown> | null {
29
+ try {
30
+ const value = JSON.parse(readFileSync(file, "utf8")) as unknown
31
+ return value && typeof value === "object" ? (value as Record<string, unknown>) : null
32
+ } catch {
33
+ return null
34
+ }
35
+ }
36
+
37
+ function str(value: unknown): string | undefined {
38
+ return typeof value === "string" && value.trim() ? value.trim() : undefined
39
+ }
40
+
41
+ /** The takes filed in one episode folder, oldest first. */
42
+ export function readCompanionTakes(episodeDir: string): CompanionTake[] {
43
+ const captures = join(episodeDir, "captures")
44
+ let names: string[]
45
+ try {
46
+ names = readdirSync(captures, { withFileTypes: true }).filter((e) => e.isDirectory() && TAKE_ID.test(e.name)).map((e) => e.name)
47
+ } catch {
48
+ return []
49
+ }
50
+ const takes: CompanionTake[] = []
51
+ for (const id of names) {
52
+ const folder = join(captures, id)
53
+ const capture = readJson(join(folder, "capture.json"))
54
+ const audio = (capture?.audio ?? null) as Record<string, unknown> | null
55
+ const outputs = Array.isArray((capture?.transcription as Record<string, unknown> | undefined)?.outputs)
56
+ ? ((capture!.transcription as Record<string, unknown>).outputs as Record<string, unknown>[])
57
+ : []
58
+ const english = outputs.find((o) => str(o.language)?.toLowerCase() === "en")
59
+ const transcriptName = str(english?.filename) ?? `transcription_${id}_EN.txt`
60
+ let text = ""
61
+ try {
62
+ text = readFileSync(join(folder, transcriptName.replace(/^.*\//, "")), "utf8").trim()
63
+ } catch {
64
+ text = ""
65
+ }
66
+ let at = str(capture?.storedAt) ?? ""
67
+ if (!at) {
68
+ try {
69
+ at = statSync(folder).mtime.toISOString()
70
+ } catch {
71
+ at = ""
72
+ }
73
+ }
74
+ const purpose = str(readJson(join(folder, "purpose.json"))?.purpose)
75
+ const audioName = str(audio?.filename)
76
+ const audioPath = str(audio?.relativePath) ?? (audioName ? `captures/${id}/${audioName}` : undefined)
77
+ takes.push({
78
+ id,
79
+ at,
80
+ text,
81
+ ...(audioPath && !audioPath.includes("..") && audioPath.startsWith(`captures/${id}/`) ? { audioPath } : {}),
82
+ ...(purpose ? { purpose } : {}),
83
+ })
84
+ }
85
+ return takes.sort((a, b) => a.at.localeCompare(b.at))
86
+ }
87
+
88
+ /**
89
+ * Where the companion phone page keeps its replies: `MIADI_PHONE_CAPTURE_STATE_DIR`,
90
+ * else `$XDG_STATE_HOME/miadi-phone-capture`, else `~/.local/state/miadi-phone-capture`,
91
+ * the same order the page itself reads, plus `/replies`.
92
+ */
93
+ export function companionRepliesDir(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
94
+ const state = env.MIADI_PHONE_CAPTURE_STATE_DIR?.trim()
95
+ || join(env.XDG_STATE_HOME?.trim() || join(home, ".local", "state"), "miadi-phone-capture")
96
+ return join(state, "replies")
97
+ }
98
+
99
+ function jsonLines(file: string): Record<string, unknown>[] {
100
+ let raw: string
101
+ try {
102
+ raw = readFileSync(file, "utf8")
103
+ } catch {
104
+ return []
105
+ }
106
+ const out: Record<string, unknown>[] = []
107
+ for (const line of raw.split("\n")) {
108
+ if (!line.trim()) continue
109
+ try {
110
+ const value = JSON.parse(line) as unknown
111
+ if (value && typeof value === "object") out.push(value as Record<string, unknown>)
112
+ } catch {
113
+ // a torn line
114
+ }
115
+ }
116
+ return out
117
+ }
118
+
119
+ function related(value: unknown): CompanionRelated[] {
120
+ if (!Array.isArray(value)) return []
121
+ return value
122
+ .map((r) => (r && typeof r === "object" ? (r as Record<string, unknown>) : {}))
123
+ .map((r) => ({ label: str(r.label) ?? "", href: str(r.href) ?? "", kind: str(r.kind) }))
124
+ .filter((r) => r.label && /^https?:\/\/\S+$/.test(r.href))
125
+ .map((r) => (r.kind ? { label: r.label, href: r.href, kind: r.kind } : { label: r.label, href: r.href }))
126
+ }
127
+
128
+ /** One episode's replies with the person's latest thumb on each, oldest first. */
129
+ export function readCompanionReplies(repliesDir: string, episode: string): CompanionReply[] {
130
+ if (!EPISODE_NAME.test(episode)) return []
131
+ const thumbs = new Map<string, CompanionFeedback | "">()
132
+ for (const entry of jsonLines(join(repliesDir, "feedback", `${episode}.jsonl`))) {
133
+ const reply = str(entry.reply)
134
+ const value = entry.value
135
+ if (reply && (value === "up" || value === "down" || value === "")) thumbs.set(reply, value)
136
+ }
137
+ const replies: CompanionReply[] = []
138
+ for (const r of jsonLines(join(repliesDir, `${episode}.jsonl`))) {
139
+ const id = str(r.id)
140
+ const text = str(r.text)
141
+ const at = str(r.at)
142
+ if (!id || !text || !at || (r.episode !== undefined && r.episode !== episode)) continue
143
+ const origin = (r.origin && typeof r.origin === "object" ? r.origin : {}) as Record<string, unknown>
144
+ const take = str(r.take)
145
+ const cards = related(r.related)
146
+ const thumb = thumbs.get(id)
147
+ replies.push({
148
+ id,
149
+ take: take && TAKE_ID.test(take) ? take : null,
150
+ text,
151
+ seat: str(r.seat) ?? "",
152
+ ...(str(origin.session) ? { session: str(origin.session)! } : {}),
153
+ at,
154
+ ...(cards.length ? { related: cards } : {}),
155
+ ...(thumb ? { feedback: thumb } : {}),
156
+ })
157
+ }
158
+ return replies.sort((a, b) => a.at.localeCompare(b.at))
159
+ }
160
+
161
+ export interface CompanionFork {
162
+ /** The branch folder's name: `plot-threads`. */
163
+ name: string
164
+ /** Its files, relative to the episode folder, the brief first. */
165
+ brief: string
166
+ /** The latest report, when the fork returned one. */
167
+ report?: string
168
+ }
169
+
170
+ /** The forks the companion drove, read from the episode's `branches/<name>/` folders that hold a brief. */
171
+ export function readCompanionForks(episodeDir: string): CompanionFork[] {
172
+ const branches = join(episodeDir, "branches")
173
+ if (!existsSync(branches)) return []
174
+ const forks: CompanionFork[] = []
175
+ let names: string[]
176
+ try {
177
+ names = readdirSync(branches, { withFileTypes: true }).filter((e) => e.isDirectory() && EPISODE_NAME.test(e.name)).map((e) => e.name)
178
+ } catch {
179
+ return []
180
+ }
181
+ const byNumber = (prefix: string) => (a: string, b: string) => {
182
+ const n = (name: string) => Number(new RegExp(`^${prefix}(?:-(\\d+))?\\.md$`).exec(name)?.[1] ?? 1)
183
+ return n(a) - n(b)
184
+ }
185
+ for (const name of names.sort()) {
186
+ let files: string[]
187
+ try {
188
+ files = readdirSync(join(branches, name))
189
+ } catch {
190
+ continue
191
+ }
192
+ const briefs = files.filter((f) => /^brief(?:-\d+)?\.md$/.test(f)).sort(byNumber("brief"))
193
+ if (briefs.length === 0) continue
194
+ const reports = files.filter((f) => /^report(?:-\d+)?\.md$/.test(f)).sort(byNumber("report"))
195
+ forks.push({
196
+ name,
197
+ brief: `branches/${name}/${briefs[0]}`,
198
+ ...(reports.length ? { report: `branches/${name}/${reports.at(-1)}` } : {}),
199
+ })
200
+ }
201
+ return forks
202
+ }