decklight 0.8.1 → 0.10.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 (138) hide show
  1. package/PLATFORM.md +707 -0
  2. package/README.md +226 -150
  3. package/SPEC.md +803 -888
  4. package/cli/agent-review.mjs +246 -0
  5. package/cli/agents.mjs +35 -9
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +190 -0
  10. package/cli/bundle-module.mjs +95 -0
  11. package/cli/bundle.mjs +439 -35
  12. package/cli/cast.mjs +48 -12
  13. package/cli/check-fixes.mjs +186 -0
  14. package/cli/check.mjs +988 -0
  15. package/cli/clone-deck.mjs +179 -0
  16. package/cli/commands.mjs +345 -0
  17. package/cli/comments.mjs +64 -18
  18. package/cli/commit-flow.mjs +51 -22
  19. package/cli/commit-message.mjs +51 -74
  20. package/cli/commit-split.mjs +601 -0
  21. package/cli/deck-refs.mjs +64 -0
  22. package/cli/deck-routes.mjs +67 -0
  23. package/cli/deckfile.mjs +3 -5
  24. package/cli/decklight.mjs +68 -289
  25. package/cli/design-system-deps.mjs +209 -0
  26. package/cli/design-system-edit.mjs +194 -0
  27. package/cli/design-system-refs.mjs +666 -0
  28. package/cli/design-system.mjs +497 -0
  29. package/cli/doctor.mjs +115 -0
  30. package/cli/edit-git.mjs +353 -0
  31. package/cli/edit-handover.mjs +551 -0
  32. package/cli/edit-look.mjs +631 -0
  33. package/cli/edit-slides.mjs +683 -0
  34. package/cli/edit.mjs +2585 -855
  35. package/cli/enhance.mjs +485 -0
  36. package/cli/extension.mjs +10 -10
  37. package/cli/font-refs.mjs +273 -0
  38. package/cli/font.mjs +246 -0
  39. package/cli/git-tree.mjs +1 -1
  40. package/cli/git.mjs +78 -11
  41. package/cli/import.mjs +56 -10
  42. package/cli/init.mjs +407 -236
  43. package/cli/library.mjs +127 -0
  44. package/cli/loader.mjs +3 -1
  45. package/cli/marketplace-autocheck.mjs +200 -0
  46. package/cli/marketplace.mjs +460 -29
  47. package/cli/narrate.mjs +251 -0
  48. package/cli/open-browser.mjs +63 -0
  49. package/cli/open.mjs +961 -0
  50. package/cli/pdf.mjs +64 -17
  51. package/cli/pkg.mjs +44 -2
  52. package/cli/plugin.mjs +43 -41
  53. package/cli/port-conflict.mjs +53 -23
  54. package/cli/pptx-export.mjs +63 -27
  55. package/cli/publish.mjs +8 -4
  56. package/cli/qr.mjs +1 -1
  57. package/cli/record.mjs +85 -23
  58. package/cli/remote.mjs +43 -17
  59. package/cli/restore.mjs +11 -4
  60. package/cli/review-ref.mjs +125 -0
  61. package/cli/review-remote.mjs +92 -48
  62. package/cli/review-routes.mjs +254 -0
  63. package/cli/review-store.mjs +47 -7
  64. package/cli/review-submit.mjs +47 -57
  65. package/cli/runtime-link.mjs +560 -0
  66. package/cli/serve.mjs +236 -45
  67. package/cli/setup.mjs +112 -0
  68. package/cli/sign.mjs +1 -1
  69. package/cli/skill-content.mjs +229 -35
  70. package/cli/skills.mjs +353 -26
  71. package/cli/start.mjs +110 -0
  72. package/cli/supervise.mjs +6 -6
  73. package/cli/theme-refs.mjs +527 -0
  74. package/cli/theme.mjs +181 -137
  75. package/cli/trust.mjs +83 -0
  76. package/cli/units.mjs +112 -47
  77. package/cli/update-check.mjs +1 -5
  78. package/cli/upgrade.mjs +194 -28
  79. package/cli/upstream.mjs +4 -3
  80. package/cli/util.mjs +4 -4
  81. package/cli/wizard.mjs +6 -6
  82. package/dist/build-info.json +1 -1
  83. package/dist/decklight.css +1533 -59
  84. package/dist/decklight.js +258 -115
  85. package/dist/decklight.js.map +4 -4
  86. package/docs/GLOSSARY.md +141 -0
  87. package/docs/architecture.svg +17 -17
  88. package/package.json +4 -2
  89. package/themes/README.md +9 -8
  90. package/themes/reveal-solarized.css +10 -0
  91. package/tools/args.mjs +20 -0
  92. package/tools/atomic-write.mjs +48 -0
  93. package/tools/brand-palette.mjs +717 -0
  94. package/tools/bridge.mjs +1 -1
  95. package/tools/build-groups.mjs +42 -0
  96. package/tools/color.mjs +48 -0
  97. package/tools/deck-html.mjs +396 -11
  98. package/tools/design-system-format.mjs +778 -0
  99. package/tools/design-system-migrations.mjs +207 -0
  100. package/tools/elevenlabs-tts.mjs +110 -17
  101. package/tools/exec.mjs +11 -3
  102. package/tools/extension-check.mjs +31 -7
  103. package/tools/font-format.mjs +190 -0
  104. package/tools/font-stacks.mjs +24 -0
  105. package/tools/gemini-tts.mjs +3 -0
  106. package/tools/lipsync-config.mjs +103 -0
  107. package/tools/lipsync-engines.mjs +205 -2
  108. package/tools/lipsync-server.mjs +264 -41
  109. package/tools/lipsync.mjs +37 -18
  110. package/tools/local-voice.mjs +32 -42
  111. package/tools/narration-manifest.mjs +270 -0
  112. package/tools/narration-synth.mjs +416 -0
  113. package/tools/pptx.mjs +776 -19
  114. package/tools/publish-targets.mjs +1 -1
  115. package/tools/publish-voices.mjs +3 -3
  116. package/tools/recording-impact.mjs +7 -3
  117. package/tools/render-theme.mjs +33 -0
  118. package/tools/review-anchor.mjs +28 -12
  119. package/tools/semver.mjs +40 -0
  120. package/tools/sentences.mjs +180 -0
  121. package/tools/shot.mjs +14 -7
  122. package/tools/site-clip.mjs +114 -0
  123. package/tools/site-voices.mjs +232 -0
  124. package/tools/template-theme.mjs +1 -1
  125. package/tools/test-impact.mjs +17 -10
  126. package/tools/theme-check.mjs +30 -3
  127. package/tools/tts-cache.mjs +4 -3
  128. package/tools/tts-engines.mjs +38 -20
  129. package/tools/tts-setup.mjs +7 -7
  130. package/tools/video-options.mjs +34 -0
  131. package/tools/video.mjs +530 -54
  132. package/tools/voiceover-server.mjs +185 -104
  133. package/tools/voiceover.mjs +119 -261
  134. package/tools/zip.mjs +1 -1
  135. package/cli/dev.mjs +0 -623
  136. package/cli/present.mjs +0 -853
  137. package/cli/review.mjs +0 -361
  138. package/tools/publish-site-voices.mjs +0 -75
@@ -0,0 +1,416 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The machine-narration core: a deck's notes in, a track's audio and manifest
6
+ * entries out (#555). Every path that synthesizes a track calls THIS —
7
+ * `decklight narrate`, the export that voices a range before rendering it,
8
+ * and whatever refreshes one stale slide later — so a track produced by one of
9
+ * them can be refreshed by another without its format, voice or manifest
10
+ * drifting.
11
+ *
12
+ * It sits BESIDE the identity layer, not over it: tools/narration-manifest.mjs
13
+ * says what a slide's text is and what its hash is, tools/tts-cache.mjs whether
14
+ * anyone has paid for the words. This owns the rest — sentence synthesis
15
+ * through that cache, the ⟨CLICK⟩ beat files, stitching a slide from its beats,
16
+ * encoding into the TRACK's format, and the skip-by-hash that makes a rerun
17
+ * free.
18
+ *
19
+ * The format is the track's. Before this, `voiceover` always wrote m4a, so
20
+ * pointing it at a track the deck's own recorder had made (wav) re-voiced it in
21
+ * piper, wrote m4a beside the wav and rewrote the header — one stale slide
22
+ * could not be refreshed in place. wav is the synthesis intermediate anyway, so
23
+ * a wav track is written directly; only an m4a or mp3 track is encoded.
24
+ *
25
+ * A human voice is out of scope: a microphone is the browser's, and the deck's
26
+ * recorder keeps that path.
27
+ */
28
+
29
+ import { readFileSync, writeFileSync, mkdirSync, rmSync, existsSync } from 'node:fs';
30
+ import { createHash } from 'node:crypto';
31
+ import { join, extname } from 'node:path';
32
+ import { clipKey, extFor } from './tts-cache.mjs';
33
+ import { cleanNotes, notesSegments } from './deck-html.mjs';
34
+ import { slideNotes, priorSlideTexts, manifestHash, markerPauses } from './narration-manifest.mjs';
35
+ import { PAUSE_MARK, speechRuns, hasWords, canonMarks, writtenMarks, forEngine, voicedPauses } from './sentences.mjs';
36
+ import { run as runBounded, PROBE_MS, CODEC_MS } from './exec.mjs';
37
+
38
+ /** The formats a track can be in — what a manifest's `file` names end with. */
39
+ export const TRACK_FORMATS = ['wav', 'm4a', 'mp3'];
40
+
41
+ /** A fresh track's format, as `decklight narrate` has always written it. */
42
+ export const DEFAULT_FORMAT = 'm4a';
43
+
44
+ /** The manifest header's own keys — everything else in a header is carried. */
45
+ const HEADER_KEYS = ['engine', 'model', 'voice', 'style', 'format', 'slides'];
46
+
47
+ /**
48
+ * The format an existing track is in: the extension its slide files carry,
49
+ * or null for a track with nothing in it yet. A track is one format — the
50
+ * first file says which, and a refresh keeps to it.
51
+ */
52
+ export function trackFormat(manifest) {
53
+ for (const entry of manifest?.slides ?? []) {
54
+ const ext = entry?.file ? extname(entry.file).slice(1).toLowerCase() : '';
55
+ if (TRACK_FORMATS.includes(ext)) return ext;
56
+ }
57
+ return null;
58
+ }
59
+
60
+ /** A manifest.json in `dir`, or null — absent, unreadable, or the old array form. */
61
+ export function readTrack(dir) {
62
+ try {
63
+ const m = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8'));
64
+ return m && Array.isArray(m.slides) ? m : null;
65
+ } catch { return null; }
66
+ }
67
+
68
+ /**
69
+ * Why a RANGED run into this track would leave it in two voices, or null.
70
+ *
71
+ * A header can describe one voice. A run over slides 3–4 in another engine,
72
+ * voice or model would write their audio and a header naming the new voice —
73
+ * and every slide outside the range would then be "stale" against a header
74
+ * it was never voiced under. Refused rather than resolved: the fix is to voice
75
+ * the whole track, or to put the other voice in its own folder.
76
+ */
77
+ export function voiceDrift(prev, { engine, model, voice }, { modelIsVoice = true } = {}) {
78
+ if (!prev?.slides?.some(Boolean)) return null;
79
+ const was = [];
80
+ if (prev.engine != null && prev.engine !== engine) was.push(`engine ${prev.engine}`);
81
+ if (prev.voice != null && voice != null && prev.voice !== voice) was.push(`voice ${prev.voice}`);
82
+ // a header written before `model` was recorded has none to disagree with;
83
+ // and for say/sapi the "model" is only the voice a bridge booted with — the
84
+ // voice that spoke is `voice` — so it has nothing to say about identity
85
+ if (modelIsVoice && prev.model != null && model != null && prev.model !== model) was.push(`model ${prev.model}`);
86
+ return was.length ? was.join(', ') : null;
87
+ }
88
+
89
+ /**
90
+ * A WAV's sample format and its PCM, or null for anything that is not one.
91
+ * The chunks are WALKED rather than a 44-byte header assumed: an engine that
92
+ * writes a LIST chunk before `data` would otherwise have its metadata spliced
93
+ * into the audio as a click.
94
+ */
95
+ export function readWav(buf) {
96
+ const b = Buffer.from(buf);
97
+ if (b.length < 12 || b.toString('ascii', 0, 4) !== 'RIFF' || b.toString('ascii', 8, 12) !== 'WAVE') return null;
98
+ let fmt = null;
99
+ for (let at = 12; at + 8 <= b.length;) {
100
+ const id = b.toString('ascii', at, at + 4);
101
+ const body = at + 8;
102
+ let size = b.readUInt32LE(at + 4);
103
+ if (id === 'fmt ' && size >= 16) {
104
+ fmt = { format: b.readUInt16LE(body), channels: b.readUInt16LE(body + 2), rate: b.readUInt32LE(body + 4), bits: b.readUInt16LE(body + 14) };
105
+ }
106
+ if (id === 'data') {
107
+ // a streamed WAV says 0 or 0xFFFFFFFF: its data runs to the end
108
+ if (!size || body + size > b.length) size = b.length - body;
109
+ return fmt ? { ...fmt, data: b.subarray(body, body + size) } : null;
110
+ }
111
+ at = body + size + (size & 1);
112
+ }
113
+ return null;
114
+ }
115
+
116
+ /**
117
+ * WAV clips joined into one, `lead` seconds of silence before the first and
118
+ * `gaps[j]` after clip j — how a ⟨PAUSE⟩ is baked into a take (#560). Null
119
+ * when the clips do not share one sample format, which one engine never does.
120
+ */
121
+ export function joinWav(clips, gaps = [], lead = 0) {
122
+ const wavs = clips.map(readWav);
123
+ const f = wavs[0];
124
+ const same = (w) => w && w.format === f.format && w.channels === f.channels && w.rate === f.rate && w.bits === f.bits;
125
+ if (!f || !wavs.every(same)) return null;
126
+ const align = f.channels * (f.bits / 8);
127
+ const silence = (s) => Buffer.alloc(align * Math.round(f.rate * Math.max(0, s || 0)));
128
+ const data = Buffer.concat([silence(lead), ...wavs.flatMap((w, j) => [w.data, silence(gaps[j])])]);
129
+ const h = Buffer.alloc(44);
130
+ h.write('RIFF', 0, 'ascii'); h.writeUInt32LE(36 + data.length, 4); h.write('WAVE', 8, 'ascii');
131
+ h.write('fmt ', 12, 'ascii'); h.writeUInt32LE(16, 16); h.writeUInt16LE(f.format, 20); h.writeUInt16LE(f.channels, 22);
132
+ h.writeUInt32LE(f.rate, 24); h.writeUInt32LE(f.rate * align, 28); h.writeUInt16LE(align, 32); h.writeUInt16LE(f.bits, 34);
133
+ h.write('data', 36, 'ascii'); h.writeUInt32LE(data.length, 40);
134
+ return Buffer.concat([h, data]);
135
+ }
136
+
137
+ /** Which encoder is on this machine: ffmpeg first, then Core Audio's afconvert. */
138
+ export function findEncoder(run = runBounded) {
139
+ const have = (bin) => {
140
+ try { run(bin, ['-version'], { stdio: 'ignore', timeout: PROBE_MS }); return true; } catch (e) { return e?.code !== 'ENOENT'; }
141
+ };
142
+ return have('ffmpeg') ? 'ffmpeg' : have('afconvert') ? 'afconvert' : null;
143
+ }
144
+
145
+ /**
146
+ * Voice `html`'s notes into `dir`.
147
+ *
148
+ * tts an engine from tools/tts-engines.mjs `createEngine`
149
+ * voice, style what each sentence is asked for with — the header records them
150
+ * format 'wav' | 'm4a' | 'mp3' — the track's (trackFormat), or a fresh one's
151
+ * range { from, to }, 1-based — outside it every entry of `prev` stands
152
+ * prev the track's manifest before this run (readTrack), or null
153
+ * cache tools/tts-cache.mjs `createTtsCache`
154
+ * reuseTextFrom folders whose slide-NN.txt is voiced instead of the notes
155
+ * keepWav keep the lossless intermediates of an encoded track (lipsync)
156
+ *
157
+ * Returns `{ manifest, skipped, cost }`. The manifest is also written after
158
+ * every slide, so an interrupted run resumes where it stopped. A slide whose
159
+ * hash still matches and whose file is on disk is kept, whoever made it.
160
+ */
161
+ export async function synthesizeSlides({
162
+ html, dir, tts, voice, style, format = DEFAULT_FORMAT, range = null, prev = null,
163
+ cache, reuseTextFrom = [], keepWav = false, log = console.log,
164
+ run = runBounded, encoder = undefined,
165
+ }) {
166
+ if (!TRACK_FORMATS.includes(format)) throw new Error(`a track is ${TRACK_FORMATS.join(', ')} — not ${format}`);
167
+ const raw = slideNotes(html);
168
+ // ⟨PAUSE⟩ markers kept (#560): they are baked into the audio, so
169
+ // they are part of the text a slide is hashed over and the script written
170
+ // beside it
171
+ const slides = raw.map((r) => (r ? cleanNotes(r, { marks: true }) : ''));
172
+ const holds = markerPauses(html);
173
+ const span = range ?? { from: 1, to: slides.length };
174
+ if (range && prev) {
175
+ const drift = voiceDrift(prev, { engine: tts.name, model: tts.model ?? null, voice }, { modelIsVoice: !tts.modelIsDefaultVoice });
176
+ if (drift) {
177
+ throw new Error(`${dir} is voiced in ${drift} — voicing slides ${span.from}–${span.to} in another would leave the `
178
+ + 'track in two voices; voice the whole track, or give the other voice its own folder (-o)');
179
+ }
180
+ }
181
+
182
+ const synthExt = extFor(tts.synth.mimeType ?? 'audio/wav');
183
+ // An encoder is needed only to change what the engine spoke into something
184
+ // else, and to stitch beats together — which the concat demuxer does, so
185
+ // stitching needs ffmpeg specifically.
186
+ const enc = encoder === undefined ? findEncoder(run) : encoder;
187
+ if (format !== synthExt && !enc) {
188
+ throw new Error(`no encoder for a ${format} track — install ffmpeg (apt install ffmpeg / brew install ffmpeg)`);
189
+ }
190
+ if (format === 'mp3' && enc !== 'ffmpeg') throw new Error('an mp3 track needs ffmpeg — install it (brew install ffmpeg)');
191
+ // A hold is baked by joining WAVs; an engine that
192
+ // speaks anything else has its clips decoded first, and only ffmpeg decodes.
193
+ if (synthExt !== 'wav' && enc !== 'ffmpeg' && !tts.audioTags
194
+ && slides.some((t, i) => t.includes(PAUSE_MARK) && i + 1 >= span.from && i + 1 <= span.to)) {
195
+ throw new Error(`[pause] in the notes needs ffmpeg with an engine that speaks ${synthExt} — install it (brew install ffmpeg)`);
196
+ }
197
+ const canSegment = enc === 'ffmpeg';
198
+ if (!canSegment && raw.some((r) => notesSegments(r))) {
199
+ log(' note: [click] segments need ffmpeg to concatenate — narrating each slide whole');
200
+ }
201
+ /** `audio` (in `from`, the synthesis format by default) into `dst` in the track's, or a plain write. */
202
+ const encode = (audio, dst, from = synthExt) => {
203
+ if (format === from) { writeFileSync(dst, audio); return; }
204
+ const src = `${dst}.${from}`;
205
+ writeFileSync(src, audio);
206
+ const args = format === 'm4a'
207
+ ? (enc === 'ffmpeg' ? ['-y', '-i', src, '-c:a', 'aac', '-b:a', '128k', dst] : ['-f', 'm4af', '-d', 'aac', src, dst])
208
+ : format === 'mp3' ? ['-y', '-i', src, '-c:a', 'libmp3lame', '-b:a', '128k', dst]
209
+ : ['-y', '-i', src, dst];
210
+ run(enc, args, { stdio: 'ignore', timeout: CODEC_MS, why: 'the encoder is stuck on this file — check it plays, then retry' });
211
+ // keep the lossless intermediate beside it, named as it always was
212
+ if (keepWav && from === 'wav') writeFileSync(dst.replace(/\.\w+$/, '.wav'), audio);
213
+ rmSync(src, { force: true });
214
+ };
215
+
216
+ // `--voice` omitted on ElevenLabs means "the first of your voices", and the
217
+ // deck's picker offers that roster in that order — so the name is resolved
218
+ // HERE, for the key. Left undefined it would hash differently from the
219
+ // identical sentence the bridge just synthesized, and the cross-process
220
+ // reuse the cache exists for would silently never hit.
221
+ let keyVoice = voice;
222
+ if (!keyVoice && tts.listVoices) {
223
+ try { keyVoice = (await tts.listVoices())[0]?.name; } catch { /* keep it undefined */ }
224
+ }
225
+ /** `tts.synth`, but a sentence anyone has already paid for is free. */
226
+ const synth = async (text) => {
227
+ const key = clipKey(tts, { voice: keyVoice, style, text });
228
+ const hit = cache.read(key, synthExt);
229
+ if (hit) return { wav: hit, usage: { chars: 0, cost: 0 }, cached: true };
230
+ const out = await tts.synth(text, { voice, style });
231
+ cache.write(key, out.wav, synthExt);
232
+ return { ...out, cached: false };
233
+ };
234
+ /**
235
+ * A stretch of notes voiced, its ⟨PAUSE⟩ holds (`hold` seconds each) baked
236
+ * in as silence (#560). Without a marker it is exactly `synth`, so a note with none costs
237
+ * and caches as it always has; with one, each run of words between markers
238
+ * is its own clip — no marker ever reaches the engine — and the clips are
239
+ * joined as WAV. `ext` is the format `wav` is in.
240
+ *
241
+ * An engine that cannot act on audio tags (`[whispers]`) is sent the words
242
+ * without them — never the tag read aloud — and a run that was only
243
+ * direction is no clip: its hold joins the one before it. One that CAN
244
+ * (ElevenLabs v3/v4) holds each ⟨PAUSE⟩ itself: it is sent as `[pause]`,
245
+ * in one clip, and nothing is joined.
246
+ */
247
+ const voiceText = async (text, hold) => {
248
+ text = tts.audioTags ? voicedPauses(text) : forEngine(tts, text);
249
+ if (!text.includes(PAUSE_MARK)) return { ...(await synth(text)), ext: synthExt };
250
+ const { lead: bare, runs: all } = speechRuns(text);
251
+ let lead = bare;
252
+ const runs = [];
253
+ for (const r of all) {
254
+ if (r.text.trim()) runs.push({ ...r });
255
+ else if (runs.length) runs[runs.length - 1].pause += r.pause;
256
+ else lead += r.pause;
257
+ }
258
+ const outs = [];
259
+ for (const r of runs) outs.push(await synth(r.text));
260
+ let clips = outs.map((o) => o.wav);
261
+ if (synthExt !== 'wav') {
262
+ clips = clips.map((clip, j) => {
263
+ const src = join(dir, `.pause-${j}.${synthExt}`);
264
+ const dst = join(dir, `.pause-${j}.wav`);
265
+ writeFileSync(src, clip);
266
+ try {
267
+ run('ffmpeg', ['-y', '-i', src, dst], { stdio: 'ignore', timeout: CODEC_MS, why: 'the decoder is stuck on this clip — retry' });
268
+ return readFileSync(dst);
269
+ } finally { rmSync(src, { force: true }); rmSync(dst, { force: true }); }
270
+ });
271
+ }
272
+ const wav = joinWav(clips, runs.map((r) => r.pause * hold), lead * hold);
273
+ if (!wav) throw new Error(`${tts.name} spoke the runs of one note in different sample formats — cannot join them`);
274
+ return {
275
+ wav, ext: 'wav', cached: outs.every((o) => o.cached),
276
+ usage: { cost: outs.reduce((sum, o) => sum + (o.usage?.cost ?? 0), 0) },
277
+ };
278
+ };
279
+ // The header names every input the slide hash is taken over, and the hash
280
+ // is taken FROM it — `manifestHash`, the function `decklight video` checks
281
+ // with (#557). Stamped from the engine instead, a default-voice ElevenLabs
282
+ // track hashed under the resolved voice beside a header with none, and the
283
+ // check could never reproduce it: a re-voiced slide stayed stale forever.
284
+ //
285
+ // A track that already has audio keeps its own terms. Its `voice: null` is
286
+ // the default voice, which is what an unasked-for voice resolves to, and its
287
+ // format (absent: wav) is what its other slides were stamped under —
288
+ // resolving either would turn every slide outside a range stale against a
289
+ // header they were never checked under. A fresh track, or one whose header
290
+ // never named a voice, gets the resolved one; with it, the hash is the clip
291
+ // key shortened, as before.
292
+ const inherits = prev?.slides?.some(Boolean) && prev.engine === tts.name;
293
+ const headerVoice = voice ?? (inherits && prev.voice === null ? null : keyVoice) ?? null;
294
+ const headerFormat = inherits ? prev.format : synthExt === 'wav' ? undefined : synthExt;
295
+ const header = {
296
+ engine: tts.name, model: tts.model ?? null, voice: headerVoice, style,
297
+ ...(headerFormat ? { format: headerFormat } : {}),
298
+ };
299
+ const slideHash = (text) => manifestHash(header, text);
300
+ // What this core stamped before #557 — the clip key, under a header that
301
+ // did not always name its voice or format. Still these words in this voice,
302
+ // so a slide carrying it is kept and re-stamped rather than paid for again.
303
+ const clipHash = (text) => clipKey(tts, { voice: keyVoice, style, text }).slice(0, 16);
304
+ // ONE-TIME MIGRATION. The hash gained `model` and lost the style no engine
305
+ // reads, so a folder recorded before that hashes differently — and would be
306
+ // re-synthesized in full, handing an ElevenLabs user a bill for clips already
307
+ // on disk. A slide matching the OLD formula is accepted once and re-stamped;
308
+ // only a header without `model` can claim it, so it cannot be claimed twice.
309
+ const legacyHash = (text) => createHash('sha256')
310
+ .update(`${header.engine}|${voice}|${style}|${text}`).digest('hex').slice(0, 16);
311
+ const preDatesModel = prev && prev.model === undefined
312
+ && prev.engine === header.engine && prev.voice === voice && prev.style === style;
313
+ // A slide the DECK's recorder voiced was stamped over the file's old reading
314
+ // of the notes, before entities were decoded; it spoke the decoded words all
315
+ // along, so a stamp matching that reading still vouches for them.
316
+ const oldReading = prev?.recorder === 'deck' ? priorSlideTexts(html) : [];
317
+
318
+ // Whatever else the header carried (the recorder's `recorder: 'deck'`) is
319
+ // the track's, and a refresh of it keeps it.
320
+ const extras = Object.fromEntries(Object.entries(prev ?? {}).filter(([k]) => !HEADER_KEYS.includes(k)));
321
+ const manifestOf = (entries) => ({ ...extras, ...header, slides: entries });
322
+ const save = (entries) => writeFileSync(join(dir, 'manifest.json'), JSON.stringify(manifestOf(entries), null, 1));
323
+
324
+ mkdirSync(dir, { recursive: true });
325
+ let skipped = 0;
326
+ let cost = 0;
327
+ const entries = [];
328
+ for (let i = 0; i < slides.length; i++) {
329
+ const n = String(i + 1).padStart(2, '0');
330
+ // Outside the range the track's own entry stands, segments and all: a
331
+ // ranged run is a surgical redo, the promise `decklight narrate --mic --slides`
332
+ // makes, and the video rendered from this folder still finds the rest.
333
+ if (i + 1 < span.from || i + 1 > span.to) { entries.push(prev?.slides?.[i] ?? null); continue; }
334
+ // no words — or nothing but ⟨PAUSE⟩ and audio tags: direction with nothing to direct
335
+ if (!hasWords(slides[i])) { entries.push(null); continue; }
336
+ const txt = join(dir, `slide-${n}.txt`);
337
+ // reused text: a second take (another engine or voice) narrates the SAME
338
+ // words, not a re-roll
339
+ const prior = reuseTextFrom.map((d) => join(d, `slide-${n}.txt`)).find((f) => existsSync(f));
340
+ const text = prior ? canonMarks(readFileSync(prior, 'utf8')).replace(/\s+/g, ' ').trim() : slides[i];
341
+ const file = `slide-${n}.${format}`;
342
+ writeFileSync(txt, writtenMarks(text)); // read back through canonMarks: the hash is of `text`
343
+ const hash = slideHash(text);
344
+ entries.push({ file, hash });
345
+
346
+ // Unchanged: the audio on disk is still these words in this voice. The
347
+ // file checked is the one the ENTRY names — a slide another producer wrote
348
+ // (the deck's recorder) is kept as it is, never re-voiced to rename it.
349
+ // A file in another format is not kept: a track is one format, and a run
350
+ // asked for another (`--format`) is converting it.
351
+ const was = prev?.slides?.[i];
352
+ if (was?.file && extname(was.file) === `.${format}`
353
+ && (was.hash === hash || was.hash === clipHash(text) || (preDatesModel && was.hash === legacyHash(text))
354
+ || (oldReading[i] && was.hash === slideHash(oldReading[i])))
355
+ && existsSync(join(dir, was.file))) {
356
+ entries[i] = { ...was, hash };
357
+ // Carry the segments across only while they are still on disk — the
358
+ // manifest is the one thing that knows they are there.
359
+ if (!was.segments?.every((sg) => existsSync(join(dir, sg.file)))) delete entries[i].segments;
360
+ skipped++;
361
+ log(` slide ${n}: unchanged — kept${entries[i].segments ? ` (${entries[i].segments.length} segments)` : ''}`);
362
+ continue;
363
+ }
364
+
365
+ // A segmented slide is synthesized beat by beat and the slide's file is
366
+ // CONCATENATED from the beats — one synthesis, both shapes; TTS is billed
367
+ // per character. Reused text is one script, so it goes whole.
368
+ const segs = prior || !canSegment ? null : notesSegments(raw[i], { marks: true });
369
+ let slideCost = 0;
370
+ let cachedBeats = 0;
371
+ if (segs) {
372
+ const parts = [];
373
+ for (let k = 0; k < segs.length; k++) {
374
+ const kk = String(k + 1).padStart(2, '0');
375
+ const beat = `slide-${n}-${kk}.${format}`;
376
+ const out = await voiceText(segs[k], holds[i]);
377
+ if (out.cached) cachedBeats++;
378
+ // the beat's own words beside its audio — tools/lipsync.mjs hands this
379
+ // to Rhubarb as the dialog hint for that beat
380
+ writeFileSync(join(dir, `slide-${n}-${kk}.txt`), writtenMarks(segs[k]));
381
+ slideCost += out.usage?.cost ?? 0;
382
+ encode(out.wav, join(dir, beat), out.ext);
383
+ parts.push(beat);
384
+ }
385
+ const list = join(dir, `slide-${n}.concat`);
386
+ writeFileSync(list, `${parts.map((p) => `file '${join(dir, p).replaceAll("'", "'\\''")}'`).join('\n')}\n`);
387
+ run('ffmpeg', ['-y', '-f', 'concat', '-safe', '0', '-i', list, '-c', 'copy', join(dir, file)], { stdio: 'ignore' });
388
+ rmSync(list, { force: true });
389
+ entries[i].segments = parts.map((p) => ({ file: p }));
390
+ } else {
391
+ const out = await voiceText(text, holds[i]);
392
+ if (out.cached) cachedBeats++;
393
+ slideCost = out.usage?.cost ?? 0;
394
+ encode(out.wav, join(dir, file), out.ext);
395
+ }
396
+ cost += slideCost;
397
+ // "cached" is worth a word: on a paid engine it is the difference between
398
+ // a rerun that costs nothing and one that quietly re-bills the deck
399
+ const cacheNote = cachedBeats ? ` · ${segs ? `${cachedBeats}/${segs.length} ` : ''}cached` : '';
400
+ log(` slide ${n}: ${text.length} chars → ${file}`
401
+ + `${segs ? ` (${segs.length} [click] segments)` : ''}${cacheNote}${slideCost ? ` · ~$${slideCost.toFixed(4)}` : ''}`);
402
+ save(entries); // crash-safe: an interrupted run resumes from here
403
+ }
404
+ save(entries);
405
+ return { manifest: manifestOf(entries), skipped, cost };
406
+ }
407
+
408
+ /** The plan line `decklight narrate` prints — the edit server reads its `· N to voice`. */
409
+ export function planLine(name, html, range, ranged) {
410
+ const texts = slideNotes(html).map((r) => (r ? cleanNotes(r) : ''));
411
+ const span = range ?? { from: 1, to: texts.length };
412
+ const toVoice = texts.filter((s, i) => s && i + 1 >= span.from && i + 1 <= span.to).length;
413
+ return `${name}: ${texts.length} slides, ${texts.filter(Boolean).length} with notes`
414
+ + `${!ranged ? '' : span.from === span.to ? ` — voicing slide ${span.from} only` : ` — voicing slides ${span.from}–${span.to} only`}`
415
+ + ` · ${toVoice} to voice`;
416
+ }