decklight 0.5.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 (53) hide show
  1. package/README.md +20 -9
  2. package/SPEC.md +239 -17
  3. package/cli/agents.mjs +97 -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 +475 -0
  10. package/cli/decklight.mjs +95 -25
  11. package/cli/dev.mjs +193 -25
  12. package/cli/edit.mjs +1055 -39
  13. package/cli/git-tree.mjs +87 -0
  14. package/cli/git.mjs +370 -0
  15. package/cli/history.mjs +145 -0
  16. package/cli/init.mjs +199 -7
  17. package/cli/marketplace.mjs +123 -17
  18. package/cli/port-conflict.mjs +228 -22
  19. package/cli/present.mjs +297 -12
  20. package/cli/publish.mjs +15 -40
  21. package/cli/record.mjs +154 -0
  22. package/cli/restore.mjs +120 -4
  23. package/cli/review-remote.mjs +330 -0
  24. package/cli/review-store.mjs +107 -0
  25. package/cli/review-submit.mjs +292 -0
  26. package/cli/review.mjs +361 -0
  27. package/cli/serve.mjs +60 -1
  28. package/cli/skill-content.mjs +12 -1
  29. package/cli/theme.mjs +78 -11
  30. package/cli/units.mjs +2 -2
  31. package/cli/upstream.mjs +256 -0
  32. package/cli/util.mjs +59 -0
  33. package/dist/build-info.json +1 -0
  34. package/dist/decklight.css +534 -3
  35. package/dist/decklight.js +102 -76
  36. package/dist/decklight.js.map +4 -4
  37. package/docs/architecture.svg +7 -0
  38. package/package.json +2 -1
  39. package/tools/args.mjs +20 -0
  40. package/tools/deck-html.mjs +84 -0
  41. package/tools/elevenlabs-tts.mjs +1 -1
  42. package/tools/lipsync-server.mjs +64 -2
  43. package/tools/lipsync.mjs +40 -24
  44. package/tools/local-voice.mjs +170 -16
  45. package/tools/publish-voices.mjs +78 -18
  46. package/tools/recording-impact.mjs +110 -0
  47. package/tools/review-anchor.mjs +180 -0
  48. package/tools/test-impact.mjs +259 -0
  49. package/tools/tts-engines.mjs +211 -12
  50. package/tools/tts-setup.mjs +2 -9
  51. package/tools/video.mjs +56 -12
  52. package/tools/voiceover-server.mjs +262 -11
  53. package/tools/voiceover.mjs +32 -13
@@ -9,7 +9,7 @@
9
9
  // --bucket gs://decklight-voices/showcase --sign 7d
10
10
  //
11
11
  // What ships next to the deck afterwards is manifest.signed.json — a few KB of
12
- // JSON naming one URL per slide. The runtime plays those URLs verbatim, which
12
+ // JSON naming one URL per slide, plus one per ⟨CLICK⟩ beat. The runtime plays those URLs verbatim, which
13
13
  // is the entire reason this exists: a presigned URL carries its signature in
14
14
  // the query string, and the older `dir:` form has nowhere to put one. A PUBLIC
15
15
  // bucket never needed this and still doesn't (`dir: 'https://storage.googleapis.com/…'`
@@ -27,7 +27,8 @@ import { argReader, isMain } from './args.mjs';
27
27
 
28
28
  const USAGE = `usage: node tools/publish-voices.mjs <voice-dir> --bucket gs://bucket/prefix [--sign 7d]
29
29
  uploads a recorded track's audio to Cloud Storage and writes a manifest of
30
- per-slide URLs to deploy next to the deck
30
+ URLs to deploy next to the deck — one per slide, plus one per ⟨CLICK⟩ beat,
31
+ which is what lets a cloud-hosted track pace the builds and not just the slides
31
32
 
32
33
  --bucket gs://… destination; the track's own folder name is appended
33
34
  --sign <dur> mint V4 signed URLs valid this long (max 7d, the V4 cap)
@@ -83,6 +84,24 @@ export function parseBucket(dest) {
83
84
  export const trackPrefix = ({ bucket, prefix }, dirName) =>
84
85
  `gs://${bucket}/${[prefix, dirName].filter(Boolean).join('/')}`;
85
86
 
87
+ /**
88
+ * Every audio file this track has, in play order: the whole-slide file, then
89
+ * its ⟨CLICK⟩ beats.
90
+ *
91
+ * A slide is more than one file now. `tools/voiceover.mjs` has always written
92
+ * `slide-NN-KK.m4a` per beat and listed them under `segments`, and the runtime
93
+ * plays them to pace the builds (SPEC PRESENTING) — so publishing a track
94
+ * without them publishes a track that cannot do the thing it was recorded for.
95
+ */
96
+ export function manifestFiles(manifest) {
97
+ const out = [];
98
+ for (const s of (manifest?.slides ?? []).filter(Boolean)) {
99
+ if (s.file) out.push(s.file);
100
+ for (const sg of s.segments ?? []) if (sg?.file) out.push(sg.file);
101
+ }
102
+ return out;
103
+ }
104
+
86
105
  /**
87
106
  * Which files this run has to upload.
88
107
  *
@@ -91,12 +110,33 @@ export const trackPrefix = ({ bucket, prefix }, dirName) =>
91
110
  * manifest.signed.json is a record of exactly which bytes are already up
92
111
  * there. No bucket listing, no re-hashing: files whose hash moved, plus any
93
112
  * the last publish never saw.
113
+ *
114
+ * Keyed by FILE rather than by slide, because a slide is several files. A beat
115
+ * has no hash of its own (voiceover.mjs writes `{file}` and nothing else) so it
116
+ * inherits its slide's, which is the right answer anyway: the beats are cut
117
+ * from the same synthesis as the slide file, and move exactly when it moves.
94
118
  */
95
119
  export function changedFiles(manifest, previous, { all = false } = {}) {
96
- const was = new Map((previous?.slides ?? []).filter(Boolean).map((s) => [s.file, s.hash]));
97
- return (manifest?.slides ?? [])
98
- .filter(Boolean)
99
- .filter((s) => all || was.get(s.file) !== s.hash);
120
+ const was = new Map();
121
+ for (const s of (previous?.slides ?? []).filter(Boolean)) {
122
+ was.set(s.file, s.hash);
123
+ for (const sg of s.segments ?? []) {
124
+ // A beat carried through an earlier publish WITHOUT a url of its own was
125
+ // never uploaded: this tool walked slides[i].file only and spread the
126
+ // rest of the entry through untouched, so the entry travelled while the
127
+ // bytes stayed on the author's disk. Treating it as already-published
128
+ // would skip precisely the tracks this fix exists for.
129
+ if (sg?.file && sg.url) was.set(sg.file, s.hash);
130
+ }
131
+ }
132
+ const out = [];
133
+ for (const s of (manifest?.slides ?? []).filter(Boolean)) {
134
+ for (const file of [s.file, ...(s.segments ?? []).map((sg) => sg?.file)]) {
135
+ if (!file) continue;
136
+ if (all || was.get(file) !== s.hash) out.push({ file, hash: s.hash });
137
+ }
138
+ }
139
+ return out;
100
140
  }
101
141
 
102
142
  /**
@@ -112,7 +152,18 @@ export function signedManifest(manifest, {
112
152
  source,
113
153
  bucket,
114
154
  ...(signDuration ? { signDuration } : {}),
115
- slides: (manifest.slides ?? []).map((s) => (s ? { ...s, url: urls.get(s.file) ?? s.url } : null)),
155
+ slides: (manifest.slides ?? []).map((s) => {
156
+ if (!s) return null;
157
+ const out = { ...s, url: urls.get(s.file) ?? s.url };
158
+ // Each beat gets its OWN url, and it has to: the runtime refuses to
159
+ // believe a segment on a signed manifest unless it carries one, because
160
+ // for as long as this tool did not write them, an entry without a url
161
+ // named audio that was never in the bucket.
162
+ if (s.segments) {
163
+ out.segments = s.segments.map((sg) => (sg?.file ? { ...sg, url: urls.get(sg.file) ?? sg.url } : sg));
164
+ }
165
+ return out;
166
+ }),
116
167
  };
117
168
  }
118
169
 
@@ -192,27 +243,33 @@ export async function publishVoicesMain(args = []) {
192
243
  }
193
244
  }
194
245
 
195
- // EVERY slide is signed, not only the changed ones: signatures expire on
246
+ // EVERY file is signed, not only the changed ones: signatures expire on
196
247
  // their own schedule, so a re-sign that skipped the untouched files would
197
- // publish a manifest where most slides had already lapsed.
198
- const all = (manifest.slides ?? []).filter(Boolean);
248
+ // publish a manifest where most of it had already lapsed.
249
+ const all = manifestFiles(manifest);
250
+ const slideCount = (manifest.slides ?? []).filter((s) => s?.file).length;
251
+ const beats = all.length - slideCount;
252
+ // Said out loud, because it is the difference between a cloud track that
253
+ // paces the builds and one that only changes slides — and the count is the
254
+ // only place a publisher can notice the beats were never recorded.
255
+ const tally = `${all.length} URL(s)` + (beats ? ` (${slideCount} slides + ${beats} ⟨CLICK⟩ beats)` : '');
199
256
  const urls = new Map();
200
257
  let expires = null;
201
258
  if (signSeconds === null) {
202
- for (const s of all) urls.set(s.file, `https://storage.googleapis.com/${dest.bucket}/${[dest.prefix, dirName, s.file].filter(Boolean).join('/')}`);
203
- console.log(`wrote ${all.length} public URL(s) — no signature, no expiry`);
259
+ for (const f of all) urls.set(f, `https://storage.googleapis.com/${dest.bucket}/${[dest.prefix, dirName, f].filter(Boolean).join('/')}`);
260
+ console.log(`wrote ${tally} public — no signature, no expiry`);
204
261
  } else if (dry) {
205
- console.log(`would sign ${all.length} slide URL(s) for ${signArg}`);
262
+ console.log(`would sign ${tally} for ${signArg}`);
206
263
  } else {
207
- for (const s of all) {
208
- const out = gcloud(['storage', 'sign-url', `${at}/${s.file}`,
264
+ for (const f of all) {
265
+ const out = gcloud(['storage', 'sign-url', `${at}/${f}`,
209
266
  `--duration=${signSeconds}s`, '--format=json']);
210
267
  const url = signedUrlFrom(JSON.parse(out));
211
- if (!url) { console.error(`publish-voices: gcloud signed nothing for ${s.file}`); return 1; }
212
- urls.set(s.file, url);
268
+ if (!url) { console.error(`publish-voices: gcloud signed nothing for ${f}`); return 1; }
269
+ urls.set(f, url);
213
270
  }
214
271
  expires = new Date(Date.now() + signSeconds * 1000).toISOString();
215
- console.log(`signed ${all.length} slide URL(s) · valid until ${expires}`
272
+ console.log(`signed ${tally} · valid until ${expires}`
216
273
  + (signSeconds === V4_MAX_SECONDS ? ' (7 days — the V4 maximum)' : ''));
217
274
  }
218
275
 
@@ -224,6 +281,9 @@ export async function publishVoicesMain(args = []) {
224
281
  writeFileSync(outPath, JSON.stringify(out, null, 1));
225
282
  console.log(`wrote ${outPath} — deploy it next to the deck`);
226
283
  console.log(` narration: { files: [{ label: '${manifest.voice ?? dirName}', manifest: '${dir}/manifest.signed.json' }] }`);
284
+ // A manifest track needs no `segments: true` — the manifest IS the list of
285
+ // what exists — so the only thing left to say is that the beats are in it.
286
+ if (beats) console.log(` ${beats} ⟨CLICK⟩ beat(s) signed too — this track paces the builds, not just the slides`);
227
287
  return 0;
228
288
  }
229
289
 
@@ -0,0 +1,110 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // What an edit does to the recordings a deck carries — SPEC NARRATION.
5
+ //
6
+ // A recorded track is minutes of somebody's own voice, and it lives in two
7
+ // places that an edit can silently pull apart: the AUDIO on disk, and the
8
+ // deck's `narration.files` config that points at it and the NOTES the audio
9
+ // reads. An agent asked to "rewrite the voiceover" reasonably rewrote the
10
+ // whole `Decklight.init` call and dropped the config with it — every
11
+ // recording orphaned, the WAVs still on disk but nothing playing them, and no
12
+ // sign until you press V and the track is gone. That actually happened.
13
+ //
14
+ // So an edit that changes what recordings mean is worth a word. Three shapes:
15
+ //
16
+ // orphaned — a track configured before is gone from the config after, and
17
+ // it has audio on disk. The whole track stops playing.
18
+ // stale — a track still configured, but a slide's NOTES changed and that
19
+ // slide has a recording: the voice now reads something the slide
20
+ // no longer says.
21
+ // reshaped — a track still configured, but the slide COUNT changed. Recorded
22
+ // files map to slides by position (slide-NN.wav), so an insert or
23
+ // delete shifts every recording after it onto the wrong slide.
24
+ //
25
+ // Pure, over injected `dirsOf` (parse the config — the caller owns the init
26
+ // walkers) and `recordedSlides` (read the disk). The notes diff is the one
27
+ // thing done here, because deck-html is importable and the runtime is not.
28
+
29
+ import { sectionBodies, NOTES_ASIDE, cleanNotes } from './deck-html.mjs';
30
+
31
+ /** Each slide's notes as plain compared text, index-aligned to the deck. */
32
+ function notesPerSlide(html) {
33
+ return sectionBodies(html).map((body) => {
34
+ const m = body.match(NOTES_ASIDE);
35
+ return m ? cleanNotes(m[1]) : '';
36
+ });
37
+ }
38
+
39
+ /**
40
+ * The recordings an edit would orphan, stale, or reshape.
41
+ *
42
+ * `dirsOf(html)` → the track dirs the deck's config names (a manifest/cloud
43
+ * entry has no local dir and is not one). `recordedSlides(dir)` → the 1-based
44
+ * slide numbers with audio in that dir, `[]` for a dir with none. Both are
45
+ * injected so this stays testable without a filesystem or the init walkers.
46
+ */
47
+ export function recordingImpact(before, after, { dirsOf, recordedSlides }) {
48
+ const beforeDirs = dirsOf(before);
49
+ const afterDirs = new Set(dirsOf(after));
50
+ const nb = notesPerSlide(before);
51
+ const na = notesPerSlide(after);
52
+
53
+ const orphaned = [];
54
+ const stale = [];
55
+ const reshaped = [];
56
+ for (const dir of beforeDirs) {
57
+ const recorded = recordedSlides(dir);
58
+ if (!recorded.length) continue; // nothing on disk → nothing to lose
59
+ if (!afterDirs.has(dir)) { orphaned.push({ dir, slides: recorded.length }); continue; }
60
+ // still configured — did the slides move or change under it?
61
+ if (nb.length !== na.length) { reshaped.push({ dir, before: nb.length, after: na.length }); continue; }
62
+ const has = new Set(recorded);
63
+ const slides = [];
64
+ for (let i = 0; i < nb.length; i++) {
65
+ if (nb[i] !== na[i] && has.has(i + 1)) slides.push(i + 1);
66
+ }
67
+ if (slides.length) stale.push({ dir, slides });
68
+ }
69
+ return { orphaned, stale, reshaped };
70
+ }
71
+
72
+ /** True when there is anything worth saying. */
73
+ export function hasImpact(impact) {
74
+ return !!(impact && (impact.orphaned.length || impact.stale.length || impact.reshaped.length));
75
+ }
76
+
77
+ /**
78
+ * One line a person reads — or null when nothing changed.
79
+ *
80
+ * Says which track and how much, and ends with the one fact that turns a
81
+ * scare into a fix: Z takes the edit back, the audio never left the disk.
82
+ */
83
+ export function impactWarning(impact) {
84
+ if (!hasImpact(impact)) return null;
85
+ const parts = [];
86
+ for (const o of impact.orphaned) {
87
+ parts.push(`${o.dir} (${o.slides} recorded slide${o.slides === 1 ? '' : 's'}) is no longer played`);
88
+ }
89
+ for (const r of impact.reshaped) {
90
+ parts.push(`${r.dir}’s recordings no longer line up — the deck went from ${r.before} slides to ${r.after}`);
91
+ }
92
+ for (const s of impact.stale) {
93
+ const list = s.slides.join(', ');
94
+ parts.push(`${s.dir}: the recording no longer matches the notes on slide${s.slides.length === 1 ? '' : 's'} ${list}`);
95
+ }
96
+ return `🎙 heads up — ${parts.join('; ')}. Z takes the edit back; the audio is still on disk.`;
97
+ }
98
+
99
+ /**
100
+ * Slide numbers with audio under `dir`, from its filenames — the default
101
+ * `recordedSlides`. `slide-07.wav` and `slide-07-02.wav` both count slide 7.
102
+ */
103
+ export function slidesFromFiles(names) {
104
+ const out = new Set();
105
+ for (const name of names ?? []) {
106
+ const m = /^slide-(\d{2,})(?:-\d+)?\.(?:wav|m4a|mp3)$/i.exec(String(name));
107
+ if (m) out.add(Number(m[1]));
108
+ }
109
+ return [...out].sort((a, b) => a - b);
110
+ }
@@ -0,0 +1,180 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // The review anchor — SPEC REVIEW.
5
+ //
6
+ // SHARED BY THE BROWSER AND THE CLI, which is the whole reason it lives here.
7
+ // `src/core/review.js` shows comments in the deck and `cli/comments.mjs` prints
8
+ // them in a terminal, and the two must agree exactly about which slide a
9
+ // comment belongs to — a disagreement is invisible and costs somebody their
10
+ // review.
11
+ //
12
+ // It cannot live in `src/`: that directory is the browser runtime and is NOT in
13
+ // the published package (`files` ships cli/, tools/, dist/, themes/, docs/), so
14
+ // a CLI reaching into it works in a checkout and fails on every install. The
15
+ // soak caught exactly that, which is what the soak is for.
16
+ //
17
+ // THIS FILE IMPORTS NOTHING, and must not start. `src/core/review.js` imports
18
+ // it and esbuild inlines it into the browser bundle, so a single `node:`
19
+ // require here would break a runtime whose whole claim is zero dependencies.
20
+ // test/review.test.mjs asserts the file has no imports at all rather than
21
+ // trusting this paragraph.
22
+
23
+ /**
24
+ * A slide's content fingerprint.
25
+ *
26
+ * Over the slide's TEXT, not its markup, so re-indenting the file or changing a
27
+ * class does not orphan every comment on it. Notes are already excluded by the
28
+ * caller's `slideBody` — a comment is about what the audience sees, and an
29
+ * author rewriting their own speaker notes has not changed the slide the
30
+ * reviewer was looking at.
31
+ *
32
+ * WHITESPACE IS REMOVED, not collapsed, and that is the load-bearing bit. The
33
+ * browser reads a slide through the DOM (`textContent` of each child, joined)
34
+ * and a tool reads it out of the FILE (tags stripped), and the two disagree
35
+ * about spacing in ways that are invisible and endless: `<p>a</p><p>b</p>` is
36
+ * "a b" to one and "ab" to the other, `<ul><li>x</li><li>y</li></ul>` is the
37
+ * reverse, and source indentation between tags shows up in one and not the
38
+ * other. Every one of those would silently orphan a comment. Dropping
39
+ * whitespace entirely makes the question not arise — the cost is that "the cat"
40
+ * and "thecat" hash alike, which is not a thing anchoring cares about.
41
+ *
42
+ * FNV-1a, 32-bit, hex. Not a security boundary — nobody is attacking a comment
43
+ * anchor — so the cheapest stable hash that fits in a JSON line and can be
44
+ * computed identically in Node and a browser with no dependency.
45
+ */
46
+ export function fingerprint(text) {
47
+ let h = 0x811c9dc5;
48
+ const s = String(text ?? '').replace(/\s+/g, '');
49
+ for (let i = 0; i < s.length; i++) {
50
+ h ^= s.charCodeAt(i);
51
+ h = Math.imul(h, 0x01000193) >>> 0;
52
+ }
53
+ return h.toString(16).padStart(8, '0');
54
+ }
55
+
56
+ /**
57
+ * Where a comment belongs in the deck as it is NOW.
58
+ *
59
+ * `slides` is `[{ slide, title, fp }]` for the current deck — one entry per
60
+ * section, in order.
61
+ *
62
+ * Returns `{ verdict, slide, movedFrom }`:
63
+ *
64
+ * exact the fingerprint matches — this is the slide, wherever it now
65
+ * sits. `movedFrom` is set when the index changed.
66
+ * stale the content changed, but exactly one slide still carries the
67
+ * title. Probably right, and worth saying it may not be.
68
+ * unanchored the comment recorded no fingerprint (hand-written, or written by
69
+ * an older version) and its index is still in range. Shown, with
70
+ * the warning that it is a guess.
71
+ * orphaned the slide is gone. Listed at the end rather than dropped — a
72
+ * comment about a slide somebody deleted is often the most
73
+ * interesting one in the file.
74
+ *
75
+ * A title match is required to be UNIQUE. Two slides called "Agenda" is an
76
+ * ordinary deck, and picking the first would be a coin flip presented as an
77
+ * answer.
78
+ *
79
+ * THE POSITIONAL FALLBACK IS NOT A FALLBACK FOR A KNOWN SLIDE. A comment that
80
+ * recorded a fingerprint and whose fingerprint is nowhere in the deck is a
81
+ * comment whose slide is gone — falling back to "whatever is twelfth now" puts
82
+ * somebody's objection under a slide that never said the thing, which is worse
83
+ * than admitting the slide is missing. So the index is consulted only when
84
+ * there was nothing better to consult: no fingerprint was ever recorded.
85
+ */
86
+ export function resolveAnchor(comment, slides) {
87
+ const list = Array.isArray(slides) ? slides : [];
88
+ const was = Number(comment?.slide);
89
+
90
+ if (comment?.fp) {
91
+ const hit = list.find((s) => s.fp === comment.fp);
92
+ if (hit) {
93
+ return { verdict: 'exact', slide: hit.slide, movedFrom: hit.slide === was ? null : was };
94
+ }
95
+ }
96
+
97
+ const title = String(comment?.title ?? '').trim();
98
+ if (title) {
99
+ const named = list.filter((s) => String(s.title ?? '').trim() === title);
100
+ if (named.length === 1) {
101
+ return { verdict: 'stale', slide: named[0].slide, movedFrom: named[0].slide === was ? null : was };
102
+ }
103
+ }
104
+
105
+ if (!comment?.fp && Number.isInteger(was) && was >= 1 && was <= list.length) {
106
+ return { verdict: 'unanchored', slide: was, movedFrom: null };
107
+ }
108
+ return { verdict: 'orphaned', slide: null, movedFrom: null };
109
+ }
110
+
111
+ /** What a reader is told about each verdict, in one place so it reads alike. */
112
+ export const VERDICT_NOTE = {
113
+ exact: null,
114
+ stale: 'this slide changed since the comment was written',
115
+ unanchored: 'could not find the slide this was written on — showing it where it used to be',
116
+ orphaned: 'the slide this was written on is gone',
117
+ };
118
+
119
+ /**
120
+ * The deck as the anchor resolver wants it: one entry per slide.
121
+ *
122
+ * `title` and `body` come from the finder's own helpers, so the title a comment
123
+ * remembers is the same string the finder shows for that slide and the two can
124
+ * never disagree about what a slide is called.
125
+ */
126
+ export function indexSlides(sections, { titleOf, bodyOf }) {
127
+ return sections.map((section, i) => {
128
+ const body = bodyOf(section);
129
+ return { slide: i + 1, title: titleOf(section, i, body), fp: fingerprint(body) };
130
+ });
131
+ }
132
+
133
+ /**
134
+ * Fold the records into what a reader wants: comments, each with its replies and
135
+ * whether it has been resolved.
136
+ *
137
+ * The fold is the whole reason `op:"resolve"` is a separate line — state is
138
+ * DERIVED from the log rather than stored, so two people resolving the same
139
+ * comment is two harmless lines rather than a conflict, and a resolve that
140
+ * arrives before the comment it refers to (which `merge=union` can do, since it
141
+ * does not reorder) still lands once both are present.
142
+ */
143
+ export function foldReview(records) {
144
+ const byId = new Map();
145
+ const replies = [];
146
+ const resolves = [];
147
+ const anchors = [];
148
+ for (const r of records) {
149
+ if (r.op === 'resolve') { resolves.push(r); continue; }
150
+ if (r.op === 'anchor') { anchors.push(r); continue; }
151
+ if (r.re) { replies.push(r); continue; }
152
+ // A duplicate id is the same comment arriving twice (an import, a union
153
+ // merge that saw both sides). First one wins; it is the same text.
154
+ if (!byId.has(r.id)) byId.set(r.id, { ...r, replies: [], resolved: null });
155
+ }
156
+ for (const r of replies) byId.get(r.re)?.replies.push(r);
157
+ for (const r of resolves) {
158
+ const c = byId.get(r.re);
159
+ // Last resolve wins, but only over another resolve — a comment resolved and
160
+ // then resolved again by somebody else is still resolved.
161
+ if (c) c.resolved = { at: r.at ?? null, by: r.by ?? null };
162
+ }
163
+ // An anchor op MOVES a comment: the author, standing where the content
164
+ // lives now, re-pins a comment whose slide was deleted or rewritten past
165
+ // recognition. Applied after the fold and last-wins like a resolve, it
166
+ // replaces the anchor triple wholesale — slide, title, fingerprint — so
167
+ // resolveAnchor sees the comment as if it had been written there, while the
168
+ // original line is never edited (that would break merge=union). `movedFrom`
169
+ // keeps pointing at where the REVIEWER wrote it: that history is the
170
+ // comment's, not the anchor's.
171
+ for (const r of anchors) {
172
+ const c = byId.get(r.re);
173
+ if (!c || !Number.isInteger(r.slide)) continue;
174
+ c.slide = r.slide;
175
+ c.title = r.title ?? null;
176
+ c.fp = r.fp ?? null;
177
+ c.anchored = { at: r.at ?? null, by: r.by ?? null };
178
+ }
179
+ return [...byId.values()];
180
+ }