decklight 0.6.0 → 0.7.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.
Files changed (47) hide show
  1. package/README.md +16 -8
  2. package/SPEC.md +166 -10
  3. package/cli/agents.mjs +52 -2
  4. package/cli/banner.mjs +125 -0
  5. package/cli/bundle.mjs +14 -4
  6. package/cli/{rec.mjs → cast.mjs} +25 -8
  7. package/cli/comments.mjs +389 -0
  8. package/cli/commit-flow.mjs +157 -0
  9. package/cli/commit-message.mjs +125 -0
  10. package/cli/decklight.mjs +88 -25
  11. package/cli/dev.mjs +159 -13
  12. package/cli/edit.mjs +927 -39
  13. package/cli/git-tree.mjs +87 -0
  14. package/cli/git.mjs +22 -0
  15. package/cli/init.mjs +37 -5
  16. package/cli/port-conflict.mjs +187 -16
  17. package/cli/publish.mjs +15 -40
  18. package/cli/record.mjs +154 -0
  19. package/cli/review-remote.mjs +330 -0
  20. package/cli/review-store.mjs +107 -0
  21. package/cli/review-submit.mjs +292 -0
  22. package/cli/review.mjs +361 -0
  23. package/cli/serve.mjs +36 -1
  24. package/cli/skill-content.mjs +3 -1
  25. package/cli/units.mjs +2 -2
  26. package/cli/util.mjs +59 -0
  27. package/dist/build-info.json +1 -0
  28. package/dist/decklight.css +244 -1
  29. package/dist/decklight.js +102 -79
  30. package/dist/decklight.js.map +4 -4
  31. package/docs/architecture.svg +7 -0
  32. package/package.json +2 -1
  33. package/tools/args.mjs +20 -0
  34. package/tools/deck-html.mjs +50 -0
  35. package/tools/elevenlabs-tts.mjs +1 -1
  36. package/tools/lipsync-server.mjs +64 -2
  37. package/tools/lipsync.mjs +40 -24
  38. package/tools/local-voice.mjs +170 -16
  39. package/tools/publish-voices.mjs +78 -18
  40. package/tools/recording-impact.mjs +110 -0
  41. package/tools/review-anchor.mjs +180 -0
  42. package/tools/test-impact.mjs +259 -0
  43. package/tools/tts-engines.mjs +26 -4
  44. package/tools/tts-setup.mjs +1 -1
  45. package/tools/video.mjs +15 -3
  46. package/tools/voiceover-server.mjs +167 -7
  47. package/tools/voiceover.mjs +30 -1
@@ -0,0 +1,330 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // What reviews are waiting — SPEC REVIEW.
5
+ //
6
+ // `review submit` pushes a reviewer's comments to `review/<who>-<date>`. This is
7
+ // the other end: the one reader that finds those branches and says how many
8
+ // comments are on each. Three surfaces share it — `decklight author` at startup,
9
+ // `M` in the deck, and `decklight comments --incoming` — and they share it so
10
+ // that none of them can drift into a different answer.
11
+ //
12
+ // THE FETCH DOCTRINE, AND WHY THIS IS ALLOWED TO CROSS IT.
13
+ //
14
+ // cli/git.mjs states NEVER A FETCH YOU DID NOT ASK FOR, and cli/edit.mjs asserts
15
+ // that opening the history touches no network. That rule is about the PRESENTER:
16
+ // nothing may reach for a remote in the middle of a talk. An author opening
17
+ // their own editor is a different person in a different moment, and "somebody
18
+ // reviewed your deck" is only useful if it arrives without being asked for.
19
+ //
20
+ // The crossing is kept narrow, and the shape is `update-check.mjs`'s:
21
+ // - once, at startup, never on a timer, never from a request handler
22
+ // - detached and never awaited, so nothing waits on a remote that is down
23
+ // - off by three switches, each of which reports the REASON it was skipped
24
+ // - never reachable from the SIGINT path (cli/edit.mjs:604 says why)
25
+ //
26
+ // AND THE REFSPEC DOCTRINE. `cli/upstream.mjs` states that no name, path or
27
+ // refspec derived from anything ever becomes a git argument. The GLOB halves
28
+ // of the refspec below are frozen constants in this source file; the remote's
29
+ // NAME is the one interpolation, the same user-typed `--remote` flag `publish`
30
+ // already passes to git, and it is gated by `remoteNameProblem` before it can
31
+ // reach an argument. What varies on the wire — which branches came back, what
32
+ // is in them — is filtered to the `refs/heads/review/` namespace before any of
33
+ // it is read back, so nothing a reviewer chose can begin with a `-` by the
34
+ // time it is an argument.
35
+
36
+ import { basename, dirname, resolve } from 'node:path';
37
+ import { execFileSync } from 'node:child_process';
38
+
39
+ import { runGit, classifyFailure } from './upstream.mjs';
40
+ import { existsSync, readFileSync } from 'node:fs';
41
+
42
+ import { parseReview, mergeById, reviewPathFor } from './review-store.mjs';
43
+ import { foldReview } from '../tools/review-anchor.mjs';
44
+
45
+ /** Every review branch a remote has. A literal, not built from anything. */
46
+ const REVIEW_GLOB = 'refs/heads/review/*';
47
+ /** …and where they land locally: exactly where a plain `git fetch <remote>` would put them. */
48
+ const refspecFor = (remote) => `+refs/heads/review/*:refs/remotes/${remote}/review/*`;
49
+
50
+ /** Refuse a remote name git could misread, rather than repairing it. */
51
+ export function remoteNameProblem(remote) {
52
+ const r = String(remote ?? '');
53
+ if (!r) return 'is empty';
54
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(r)) return 'is not a remote name';
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * Why the check did not run, or `false` if it should.
60
+ *
61
+ * A reason string rather than a boolean, `upstreamSuppressed`'s shape: the
62
+ * caller prints "not checked — CI" instead of nothing, because a silent skip
63
+ * and "no reviews waiting" look identical to the reader and mean opposite
64
+ * things. UNCHECKED IS ITS OWN ANSWER AND NEVER A PASS.
65
+ *
66
+ * `ci: false` is the ON-DEMAND surface's setting (the M overlay's route):
67
+ * the explicit switches mean "never touch the network for reviews" and kill
68
+ * every surface, but `CI` exists to silence the UNASKED startup fetch — a
69
+ * route somebody exercises deliberately, from a test or a script, must still
70
+ * answer there, or "works on my machine" becomes literal.
71
+ */
72
+ export function reviewCheckSuppressed({ args = [], env = process.env, ci = true } = {}) {
73
+ if (args.includes('--no-review-check')) return '--no-review-check';
74
+ if (env.DECKLIGHT_NO_REVIEW_CHECK) return 'DECKLIGHT_NO_REVIEW_CHECK is set';
75
+ if (ci && env.CI) return 'CI';
76
+ return false;
77
+ }
78
+
79
+ /** `review/ana-2026-08-24` → who and when, for a line a human reads. */
80
+ export function describeBranch(branch) {
81
+ const tail = String(branch).replace(/^review\//, '');
82
+ const m = /^(.*)-(\d{4}-\d{2}-\d{2})$/.exec(tail);
83
+ return m ? { who: m[1], when: m[2] } : { who: tail, when: null };
84
+ }
85
+
86
+ /**
87
+ * The reviews waiting on `remote` for this deck.
88
+ *
89
+ * Two network calls no matter how many reviews there are — one `ls-remote` to
90
+ * see whether any exist at all, one `fetch` to bring them in — and then every
91
+ * count is a local read. A per-branch fetch would be the obvious shape and
92
+ * would put a talk's worth of round trips behind an editor's startup.
93
+ *
94
+ * Returns `{ state, reviews, reason }`. `state` is one of:
95
+ * `ok` — the list is authoritative, and may be empty
96
+ * `none` — the remote has no review branches
97
+ * `no-repo` / `untracked` / `no-remote` — the feature does not apply here
98
+ * `offline` / `no-credential` / `timeout` / `error` — COULD NOT ASK
99
+ *
100
+ * The last group is the reason this returns a state rather than an array: a
101
+ * failed check must never render as "no reviews waiting".
102
+ */
103
+ export async function reviewsWaiting(deckPath, { remote = 'origin', run = runGit } = {}) {
104
+ const full = resolve(deckPath);
105
+ const cwd = dirname(full);
106
+ const no = (state, reason = null) => ({ state, reviews: [], reason });
107
+ const badRemote = remoteNameProblem(remote);
108
+ if (badRemote) return no('error', `the remote name ${JSON.stringify(remote)} ${badRemote}`);
109
+
110
+ const top = await run(['rev-parse', '--show-toplevel'], { cwd });
111
+ if (!top.ok || !top.stdout) return no('no-repo');
112
+ // The deck must be a file this repository versions — resolveUpstream's gate,
113
+ // for its reasons: without it every deck in ~/Downloads is "in a clone" for
114
+ // anyone whose home directory happens to be one. Asked by basename from the
115
+ // deck's own directory so no two spellings of one path are ever compared.
116
+ const tracked = await run(['ls-files', '--error-unmatch', '--', basename(full)], { cwd });
117
+ if (!tracked.ok) return no('untracked');
118
+
119
+ const url = await run(['remote', 'get-url', remote], { cwd });
120
+ if (!url.ok || !url.stdout) return no('no-remote');
121
+
122
+ const listed = await run(['ls-remote', '--heads', remote, REVIEW_GLOB], { cwd });
123
+ if (!listed.ok) return no(classifyFailure(listed), listed.stderr || null);
124
+ const branches = listed.stdout.split('\n').filter(Boolean)
125
+ .map((l) => l.split('\t')[1])
126
+ .filter((r) => typeof r === 'string' && r.startsWith('refs/heads/review/'))
127
+ .map((r) => r.slice('refs/heads/'.length));
128
+ if (!branches.length) return { state: 'none', reviews: [], reason: null };
129
+
130
+ const fetched = await run(['fetch', '--quiet', remote, refspecFor(remote)], { cwd });
131
+ if (!fetched.ok) return no(classifyFailure(fetched), fetched.stderr || null);
132
+
133
+ // Which file to read out of each branch. `--show-prefix` rather than a
134
+ // relative path computed here: git answers in forward slashes, and macOS
135
+ // resolves /tmp and /var through symlinks, so comparing two absolute paths
136
+ // for one file disagrees more often than it looks.
137
+ const prefix = await run(['rev-parse', '--show-prefix'], { cwd });
138
+ const storeName = basename(full).replace(/\.html?$/i, '') + '.review.jsonl';
139
+ const inRepo = `${prefix.ok ? prefix.stdout : ''}${storeName}`;
140
+
141
+ // "Waiting" used to mean "holds records your sidecar does not", because the
142
+ // overlay MERGED a review into that sidecar and the by-id merge was the
143
+ // arbiter of doneness. Nothing is copied any more, so that test would call
144
+ // every review waiting forever. A review is an inbox item now: it waits until
145
+ // you mark it done, and `--import` still ends it the old way — a review whose
146
+ // records all sit in the local file has plainly been dealt with.
147
+ const storePath = reviewPathFor(full);
148
+ const mine = existsSync(storePath) ? parseReview(readFileSync(storePath, 'utf8')).records : [];
149
+
150
+ const reviews = [];
151
+ for (const branch of branches) {
152
+ // `<ref>:<path>` is one argument and both halves are DATA here — the ref
153
+ // came from the remote, so it goes after `--`… except `git show` takes no
154
+ // `--` before a `rev:path`. What protects this instead is that the ref was
155
+ // filtered to `refs/heads/review/` above and can therefore never begin with
156
+ // a `-`, which is the only way an argument turns into an option.
157
+ const ref = `refs/remotes/${remote}/${branch}`;
158
+ const blob = await run(['show', `${ref}:${inRepo}`], { cwd });
159
+ // A review branch with no sidecar for THIS deck is a review of another deck
160
+ // in the same repository. Skipped, not reported: an author opening one deck
161
+ // does not want to hear about comments on a different one.
162
+ if (!blob.ok) continue;
163
+ const { records, skipped } = parseReview(blob.stdout);
164
+ // The same fold `decklight comments` renders with. A raw line count calls
165
+ // a resolved comment "waiting" and counts a union-merge duplicate twice —
166
+ // and then this line disagrees with the very command it points at.
167
+ const folded = foldReview(records);
168
+ const open = folded.filter((c) => !c.resolved);
169
+ // Nothing OPEN means nothing waiting: a branch of resolves is history, not
170
+ // a review the author still owes attention.
171
+ if (!open.length) continue;
172
+ // …nor does a review whose every record the local sidecar already holds:
173
+ // that is `--import`, or a real merge, and it has plainly been dealt with.
174
+ if (!mergeById(mine, records).added) continue;
175
+ // Which of ITS comments this clone has marked done. Carried per comment
176
+ // rather than per branch: finishing half a long review has to leave the
177
+ // other half on screen, which a single branch-level flag cannot express.
178
+ const doneIds = doneComments(cwd, branch, { records });
179
+ const stamp = await run(['log', '-1', '--format=%aI', ref], { cwd });
180
+ reviews.push({
181
+ branch,
182
+ ...describeBranch(branch),
183
+ // The comments themselves ride along: the overlay renders them — the
184
+ // records ARE the review, and a count was only ever a placeholder.
185
+ records,
186
+ comments: open.length,
187
+ // Raw, unlike `comments`: a reply here may answer a comment living in
188
+ // ANOTHER branch (each reviewer clones from main), and the fold — scoped
189
+ // to this one sidecar — would drop it as parentless.
190
+ replies: records.filter((r) => r.re && !r.op).length,
191
+ unreadable: skipped,
192
+ at: stamp.ok ? stamp.stdout : null,
193
+ // The ids the overlay strikes through, and the count that decides whether
194
+ // this review still wants attention. `done` stays as a summary — every
195
+ // open comment marked — so a caller asking "am I finished with this?"
196
+ // does not have to do the arithmetic itself.
197
+ doneIds: [...doneIds],
198
+ done: open.every((c) => doneIds.has(c.id)),
199
+ waiting: open.filter((c) => !doneIds.has(c.id)).length,
200
+ });
201
+ }
202
+ // Newest first: an author wants the review that just arrived, not the one from
203
+ // three weeks ago they already read. The commit date is the real recency; the
204
+ // branch's own date breaks ties, which is not a rare case — two reviewers
205
+ // finishing within the same second of each other tie on `%aI` exactly, and
206
+ // without the tiebreak the order falls through to whatever ls-remote listed,
207
+ // which is alphabetical by reviewer and means nothing at all.
208
+ const key = (r) => [String(r.at ?? ''), String(r.when ?? '')];
209
+ reviews.sort((a, b) => {
210
+ const [aAt, aWhen] = key(a); const [bAt, bWhen] = key(b);
211
+ return bAt.localeCompare(aAt) || bWhen.localeCompare(aWhen);
212
+ });
213
+ // `state` is about what still WANTS attention. Done reviews stay in the list
214
+ // — the overlay strikes them through so they can be unmarked — but a session
215
+ // where every review is done is a session with nothing waiting, and must say
216
+ // so rather than nagging about work already finished.
217
+ return { state: reviews.some((r) => !r.done) ? 'ok' : 'none', reviews, reason: null };
218
+ }
219
+
220
+ /**
221
+ * One line for a terminal, or `null` when there is nothing worth saying.
222
+ *
223
+ * `null` for the states where the feature simply does not apply (no repo, no
224
+ * remote, an untracked deck) — an author who has never used this should not be
225
+ * told about a thing that is not happening. Every FAILURE, though, gets a line:
226
+ * that is the distinction the state machine exists to make.
227
+ */
228
+ export function reviewLine(result, { deck = '' } = {}) {
229
+ const { state, reviews } = result ?? {};
230
+ if (state === 'ok') {
231
+ // Only what is not marked done: the line is the nag, and a review you have
232
+ // finished with must not appear in it.
233
+ const open = reviews.filter((r) => !r.done);
234
+ const n = open.length;
235
+ // What is still WAITING, comment by comment: a review you are halfway
236
+ // through should say so rather than counting from the top again.
237
+ const total = open.reduce((sum, r) => sum + (r.waiting ?? r.comments), 0);
238
+ const who = open.slice(0, 3).map((r) => r.who).join(', ');
239
+ return `reviews: ${total} comment${total === 1 ? '' : 's'} waiting`
240
+ + ` from ${who}${n > 3 ? ` +${n - 3} more` : ''}`
241
+ + `${deck ? ` — decklight comments ${deck} --incoming` : ''}`;
242
+ }
243
+ if (state === 'none' || state === 'no-repo' || state === 'untracked' || state === 'no-remote') return null;
244
+ const how = {
245
+ offline: 'no network',
246
+ 'no-credential': 'the remote asked for credentials',
247
+ timeout: 'the remote did not answer',
248
+ }[state] ?? 'git could not read the remote';
249
+ // NOT "no reviews": this is the sentence that keeps a failed check from
250
+ // reading like an all-clear.
251
+ return `reviews: not checked — ${how}`;
252
+ }
253
+
254
+ // ── a comment you are finished with ──────────────────────────────────────
255
+ //
256
+ // Doneness is PER COMMENT, and where the mark lives follows who owns the
257
+ // comment rather than any wish for uniform storage:
258
+ //
259
+ // your own comments already have one — `{op:'resolve'}` in the sidecar,
260
+ // append-only and shared, so a reviewer can see you dealt with their
261
+ // point. "Done" is not a second state beside it; it IS that record.
262
+ //
263
+ // a reviewer's comments live on their branch, which is not yours to write.
264
+ // So the mark is kept HERE, in this clone's git config: private, never
265
+ // pushed, and reversible with `git config --unset`.
266
+ //
267
+ // A review branch stops waiting when every one of its open comments is marked,
268
+ // which is the same sentence as before — it is just counted a comment at a time
269
+ // now, so finishing half of a long review leaves the other half visible.
270
+
271
+ /** The config key one comment's mark lives under. */
272
+ export const doneKey = (branch, id) => `decklight-review.${branch}.done-${id}`;
273
+
274
+ /**
275
+ * A comment id is half of a git config KEY, so it has to be shaped like one.
276
+ *
277
+ * Keys are `[a-zA-Z][a-zA-Z0-9-]*` — and ids are minted as `[a-z0-9]{1,12}`
278
+ * (cli/review-store.mjs `newId`), so `done-<id>` is always valid. Anything else
279
+ * arrived from a file somebody else wrote, and is refused rather than handed to
280
+ * git, where it would be a silent no-op at best.
281
+ */
282
+ export const usableId = (id) => typeof id === 'string' && /^[a-z0-9]{1,12}$/.test(id);
283
+
284
+ /**
285
+ * Which comments of this review are marked done in THIS clone.
286
+ *
287
+ * One `--get-regexp` rather than a lookup per comment: a review can carry
288
+ * dozens, and forty git invocations to draw one overlay is the kind of cost
289
+ * that only shows up on somebody else's machine.
290
+ *
291
+ * A legacy WHOLE-REVIEW mark (`[decklight-review "<branch>"] done`, which is
292
+ * what the first version of this wrote) is honoured as "all of them": the
293
+ * feature shipped, somebody may have marked a review with it, and silently
294
+ * un-marking their work to simplify this function would be a poor trade.
295
+ */
296
+ export function doneComments(cwd, branch, { run = null, exec = execFileSync, records = [] } = {}) {
297
+ const g = run ?? ((args) => exec('git', args, { cwd, encoding: 'utf8' }).trim());
298
+ const ids = new Set();
299
+ // `--get-regexp` returns "<key> <value>" lines; the key is lower-cased by git
300
+ // (sections and keys are case-insensitive), so match on the tail after
301
+ // `.done-`, which is where the id is.
302
+ let out = '';
303
+ try { out = g(['config', '--get-regexp', `^decklight-review\\.${escapeRe(branch)}\\.done`]) ?? ''; }
304
+ catch { return ids; }
305
+ let legacyAll = false;
306
+ for (const line of out.split('\n')) {
307
+ if (!line.trim()) continue;
308
+ const [key, value] = [line.slice(0, line.indexOf(' ')), line.slice(line.indexOf(' ') + 1)];
309
+ if (value.trim() !== 'true') continue;
310
+ const m = /\.done-([a-z0-9]{1,12})$/.exec(key);
311
+ if (m) ids.add(m[1]);
312
+ else if (/\.done$/.test(key)) legacyAll = true;
313
+ }
314
+ if (legacyAll) for (const r of records) if (r?.id) ids.add(r.id);
315
+ return ids;
316
+ }
317
+
318
+ /** Mark one comment done, or take the mark off. Never fatal: a mark is a convenience. */
319
+ export function setCommentDone(cwd, branch, id, done, { run = null, exec = execFileSync } = {}) {
320
+ if (!usableId(id)) return false;
321
+ const g = run ?? ((args) => exec('git', args, { cwd, encoding: 'utf8' }).trim());
322
+ try {
323
+ if (done) g(['config', doneKey(branch, id), 'true']);
324
+ else g(['config', '--unset', doneKey(branch, id)]);
325
+ return true;
326
+ } catch { return false; }
327
+ }
328
+
329
+ /** git config takes a REGEX, and a branch name is full of characters one means. */
330
+ function escapeRe(s) { return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); }
@@ -0,0 +1,107 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The review-comment store — SPEC REVIEW.
5
+ //
6
+ // A reviewer's comments on a deck live in `<deck>.review.jsonl` beside it: one
7
+ // JSON object per line, APPEND-ONLY, never rewritten.
8
+ //
9
+ // Append-only is not tidiness, it is the merge strategy. `.gitattributes`
10
+ // declares `*.review.jsonl merge=union`, so two reviewers commenting on the same
11
+ // deck at the same time produce two sets of added lines and no conflict. That
12
+ // only holds while every operation is a NEW LINE: resolving a comment and
13
+ // replying to one are records of their own (`op:"resolve"`, `re:"<id>"`), never
14
+ // edits to the line they refer to. A store that mutated a line would conflict on
15
+ // exactly the deck that two people were reviewing, which is every deck worth
16
+ // reviewing.
17
+ //
18
+ // It is also why the format is JSONL rather than JSON: an appended line is a
19
+ // diff of one line, so a reviewer's push reads in a pull request with no tooling
20
+ // at all. `body` is written last for the same reason — the eye lands on the
21
+ // prose, not the bookkeeping.
22
+ //
23
+ // Nothing here touches git or the filesystem. The store is the shape; who reads
24
+ // and writes it is cli/review.mjs (the reviewer) and cli/comments.mjs (the
25
+ // author).
26
+ //
27
+ // `foldReview` — turning the log into comments-with-replies — lives in
28
+ // src/core/review.js instead, because the BROWSER needs it too and the runtime
29
+ // may never import from cli/. The dependency only ever points one way.
30
+
31
+ /** The sidecar that belongs to a deck: `talk.html` → `talk.review.jsonl`. */
32
+ export const reviewPathFor = (deckPath) => String(deckPath).replace(/\.html?$/i, '') + '.review.jsonl';
33
+
34
+ /**
35
+ * Parse the store. A malformed line is SKIPPED, never fatal.
36
+ *
37
+ * This file is hand-mergeable text that arrives over email and through
38
+ * `merge=union`, so a half-written line is a thing that will happen. Refusing to
39
+ * read the whole file because of one is how a reviewer loses forty comments to a
40
+ * truncated forty-first — and the one line nobody can parse is also the one line
41
+ * nobody can act on, so dropping it costs nothing that was recoverable.
42
+ *
43
+ * Returns `{ records, skipped }` — `skipped` counted rather than swallowed, so a
44
+ * caller can say so out loud instead of quietly showing fewer comments than the
45
+ * file contains.
46
+ */
47
+ export function parseReview(text) {
48
+ const records = [];
49
+ let skipped = 0;
50
+ for (const line of String(text ?? '').split('\n')) {
51
+ if (!line.trim()) continue;
52
+ let rec;
53
+ try { rec = JSON.parse(line); } catch { skipped++; continue; }
54
+ // An object with no id and no `re` is not a record of anything — it cannot
55
+ // be replied to, resolved, or pointed at a slide.
56
+ if (!rec || typeof rec !== 'object' || Array.isArray(rec) || (!rec.id && !rec.re)) { skipped++; continue; }
57
+ records.push(rec);
58
+ }
59
+ return { records, skipped };
60
+ }
61
+
62
+ /** One record as the line it will be appended as — `body` last, on purpose. */
63
+ export function serializeRecord(rec) {
64
+ const { body, ...rest } = rec;
65
+ return JSON.stringify(body === undefined ? rest : { ...rest, body });
66
+ }
67
+
68
+ /**
69
+ * Merge an incoming store into an existing one, by id.
70
+ *
71
+ * The no-repo reviewer's return path: they were sent a deck, they commented, and
72
+ * they send back a file. Every record carries an id, so merging is a set union
73
+ * and importing the same file twice is a no-op — which matters, because the
74
+ * person doing it has no way to know whether they already did.
75
+ *
76
+ * Order is preserved and incoming records go on the END, so the file stays an
77
+ * append-only log and the diff of an import reads like any other reviewer's
78
+ * push.
79
+ */
80
+ export function mergeById(existing, incoming) {
81
+ // ops carry no id of their own — the tuple is their identity, so the same
82
+ // resolve or re-anchor arriving twice (an import replayed) stays one line
83
+ const key = (r) => (r.op ? `${r.op}:${r.re}:${r.at ?? ''}:${r.by ?? ''}` : r.id);
84
+ const seen = new Set(existing.map(key));
85
+ const added = [];
86
+ for (const r of incoming) {
87
+ const k = key(r);
88
+ if (seen.has(k)) continue;
89
+ seen.add(k);
90
+ added.push(r);
91
+ }
92
+ return { records: [...existing, ...added], added: added.length };
93
+ }
94
+
95
+ /**
96
+ * A short, collision-resistant id for a new comment.
97
+ *
98
+ * Not a UUID: this appears in `re:` fields a human may type in a terminal, and
99
+ * in a diff a human reads. Four bytes of the caller's randomness, base36 — the
100
+ * store dedupes by id anyway, so a collision costs one dropped comment rather
101
+ * than corruption, and at four bytes it will not happen.
102
+ *
103
+ * `rand` is injected so a test is not a coin flip.
104
+ */
105
+ export function newId(rand = () => Math.random()) {
106
+ return Math.floor(rand() * 0xffffffff).toString(36).padStart(6, '0').slice(-6);
107
+ }