decklight 0.6.0 → 0.8.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 (61) hide show
  1. package/README.md +23 -11
  2. package/SPEC.md +187 -23
  3. package/cli/agents.mjs +52 -2
  4. package/cli/associate.mjs +2 -2
  5. package/cli/banner.mjs +125 -0
  6. package/cli/bundle.mjs +15 -5
  7. package/cli/{rec.mjs → cast.mjs} +25 -8
  8. package/cli/comments.mjs +389 -0
  9. package/cli/commit-flow.mjs +157 -0
  10. package/cli/commit-message.mjs +125 -0
  11. package/cli/decklight.mjs +96 -25
  12. package/cli/dev.mjs +159 -13
  13. package/cli/edit.mjs +981 -40
  14. package/cli/git-tree.mjs +87 -0
  15. package/cli/git.mjs +22 -0
  16. package/cli/import.mjs +41 -11
  17. package/cli/init.mjs +37 -5
  18. package/cli/pdf.mjs +59 -14
  19. package/cli/port-conflict.mjs +187 -16
  20. package/cli/pptx-export.mjs +107 -0
  21. package/cli/present.mjs +8 -4
  22. package/cli/publish.mjs +25 -42
  23. package/cli/record.mjs +154 -0
  24. package/cli/review-remote.mjs +330 -0
  25. package/cli/review-store.mjs +107 -0
  26. package/cli/review-submit.mjs +292 -0
  27. package/cli/review.mjs +361 -0
  28. package/cli/serve.mjs +36 -1
  29. package/cli/skill-content.mjs +4 -1
  30. package/cli/units.mjs +2 -2
  31. package/cli/util.mjs +59 -0
  32. package/dist/build-info.json +1 -0
  33. package/dist/decklight.css +254 -1
  34. package/dist/decklight.js +153 -79
  35. package/dist/decklight.js.map +4 -4
  36. package/docs/architecture.svg +10 -3
  37. package/package.json +3 -1
  38. package/tools/args.mjs +20 -0
  39. package/tools/bridge.mjs +25 -2
  40. package/tools/deck-html.mjs +59 -0
  41. package/tools/elevenlabs-tts.mjs +3 -3
  42. package/tools/exec.mjs +54 -0
  43. package/tools/gemini-tts.mjs +4 -4
  44. package/tools/lipsync-server.mjs +70 -2
  45. package/tools/lipsync.mjs +46 -30
  46. package/tools/local-voice.mjs +243 -19
  47. package/tools/pptx-write.mjs +151 -0
  48. package/tools/pptx.mjs +82 -2
  49. package/tools/publish-site-voices.mjs +2 -2
  50. package/tools/publish-targets.mjs +39 -2
  51. package/tools/publish-voices.mjs +80 -20
  52. package/tools/recording-impact.mjs +110 -0
  53. package/tools/review-anchor.mjs +180 -0
  54. package/tools/template-theme.mjs +154 -0
  55. package/tools/test-impact.mjs +266 -0
  56. package/tools/tts-cache.mjs +191 -0
  57. package/tools/tts-engines.mjs +85 -8
  58. package/tools/tts-setup.mjs +4 -3
  59. package/tools/video.mjs +21 -6
  60. package/tools/voiceover-server.mjs +163 -17
  61. package/tools/voiceover.mjs +124 -16
@@ -0,0 +1,154 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * A PowerPoint template's palette and fonts, as a decklight theme.
6
+ *
7
+ * `decklight import` throws the template's LOOK away on purpose — the deck you
8
+ * get is a decklight deck, not a screenshot of the old one — and every
9
+ * imported corporate deck arrived in `midnight`, to be re-themed by hand. The
10
+ * part of the look that is a THEME rather than a layout was in the file all
11
+ * along: ppt/theme/theme1.xml carries the colour scheme (dk1, lt1, dk2, lt2,
12
+ * accent1–6, hlink) and the font scheme (a heading face and a body face). That
13
+ * is most of what a brand team means by "our template".
14
+ *
15
+ * So this reads those two schemes and derives the full SPEC THEMING token set
16
+ * from them. Derives, not copies: a template has twelve colours and a theme
17
+ * needs fifty-six tokens with contrast gates between them, so the rest is
18
+ * chosen from the twelve and then PUSHED until every gate in
19
+ * tools/theme-check.mjs clears — a link colour that reads on the slide
20
+ * background, six diagram fills a label can be read on, a code palette that
21
+ * is legible on the block. The result is validated by the same function
22
+ * `decklight theme check` runs, and if it cannot be made to pass, that is
23
+ * reported rather than shipped.
24
+ */
25
+
26
+ import { parseXml, find, findAll } from './ooxml.mjs';
27
+ import { parseColor, contrast } from './color.mjs';
28
+ import { validateTheme, GATES } from './theme-check.mjs';
29
+
30
+ const SLOTS = ['dk1', 'lt1', 'dk2', 'lt2', 'accent1', 'accent2', 'accent3', 'accent4', 'accent5', 'accent6', 'hlink', 'folHlink'];
31
+
32
+ /** Windows system colours a theme may name instead of a hex value. */
33
+ const SYSTEM = { windowText: '000000', window: 'FFFFFF' };
34
+
35
+ const hex = ([r, g, b]) => '#' + [r, g, b].map((v) => Math.max(0, Math.min(255, Math.round(v))).toString(16).padStart(2, '0')).join('');
36
+ const rgb = (h) => parseColor(h);
37
+ const mix = (a, b, t) => hex(rgb(a).map((v, i) => v + (rgb(b)[i] - v) * t));
38
+
39
+ /**
40
+ * The scheme, or null when the part is not a theme. Each colour slot resolves
41
+ * `a:srgbClr` or `a:sysClr` (with its lastClr, else the system default).
42
+ */
43
+ export function parseTemplateTheme(xml) {
44
+ const doc = parseXml(xml ?? '');
45
+ const scheme = find(doc, 'a:clrScheme');
46
+ if (!scheme) return null;
47
+ const colors = {};
48
+ for (const slot of SLOTS) {
49
+ const node = find(scheme, `a:${slot}`);
50
+ if (!node) continue;
51
+ const srgb = find(node, 'a:srgbClr')?.attrs.val;
52
+ const sys = find(node, 'a:sysClr');
53
+ const val = srgb ?? sys?.attrs.lastClr ?? (sys && SYSTEM[sys.attrs.val]);
54
+ if (val && /^[0-9a-f]{6}$/i.test(val)) colors[slot] = '#' + val.toLowerCase();
55
+ }
56
+ const fonts = find(doc, 'a:fontScheme');
57
+ const face = (which) => find(find(fonts, which) ?? { children: [] }, 'a:latin')?.attrs.typeface ?? null;
58
+ return {
59
+ name: scheme.attrs.name ?? find(doc, 'a:theme')?.attrs.name ?? 'template',
60
+ colors,
61
+ fonts: { heading: fonts ? face('a:majorFont') : null, body: fonts ? face('a:minorFont') : null },
62
+ };
63
+ }
64
+
65
+ /** Nudge `fg` toward black or white — whichever moves it away from `bg` — until the gate clears. */
66
+ function pushUntil(fg, bg, min) {
67
+ const dark = contrast(rgb(bg), [0, 0, 0]) > contrast(rgb(bg), [255, 255, 255]);
68
+ const target = dark ? '#000000' : '#ffffff';
69
+ let out = fg;
70
+ for (let t = 0; t <= 1.0001 && contrast(rgb(out), rgb(bg)) < min; t += 0.05) out = mix(fg, target, t);
71
+ return out;
72
+ }
73
+
74
+ /** A font stack around the template's face, with the same fallbacks the shipped themes use. */
75
+ const stack = (face, mono = false) => (mono
76
+ ? '"SF Mono", SFMono-Regular, ui-monospace, "Cascadia Code", Menlo, Consolas, monospace'
77
+ : `${face ? `"${face.replace(/"/g, '')}", ` : ''}-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif`);
78
+
79
+ /**
80
+ * The full token set, derived from a scheme and pushed through the gates.
81
+ *
82
+ * Light by construction: PowerPoint templates are lt1-on-dk1 far more often
83
+ * than not, and a slide background that is the template's page colour is what
84
+ * "looks like our template" means. Returns { css, name, ok, errors }; `ok` is
85
+ * theme-check's verdict on the CSS this produced.
86
+ */
87
+ export function themeFromTemplate(parsed, { name } = {}) {
88
+ const c = parsed.colors;
89
+ const bg = c.lt1 ?? '#ffffff';
90
+ const fg = c.dk1 ?? '#1a1a1a';
91
+ const accents = [1, 2, 3, 4, 5, 6].map((i) => c[`accent${i}`] ?? mix(fg, bg, 0.3 + i * 0.08));
92
+ const tok = {};
93
+ tok.bg = bg;
94
+ tok['bg-accent'] = mix(bg, c.lt2 ?? accents[0], 0.35);
95
+ tok.fg = pushUntil(fg, bg, 4.5);
96
+ tok.muted = pushUntil(mix(c.dk2 ?? fg, bg, 0.35), bg, 3.0);
97
+ tok['font-body'] = stack(parsed.fonts.body);
98
+ tok['font-heading'] = stack(parsed.fonts.heading ?? parsed.fonts.body);
99
+ tok['font-mono'] = stack(null, true);
100
+ tok['heading-color'] = pushUntil(c.dk2 ?? accents[0], bg, 3.0);
101
+ tok['heading-weight'] = '700';
102
+ tok.link = pushUntil(c.hlink ?? accents[0], bg, 3.0);
103
+ tok.accent = accents[0];
104
+ tok['accent-contrast'] = contrast(rgb(accents[0]), rgb(bg)) >= contrast(rgb(accents[0]), rgb(fg)) ? bg : fg;
105
+ tok['accent-contrast'] = pushUntil(tok['accent-contrast'], accents[0], 4.5);
106
+ tok['block-bg'] = mix(bg, c.lt2 ?? fg, 0.08);
107
+ tok['block-border'] = `1px solid ${mix(bg, fg, 0.18)}`;
108
+ tok['block-radius'] = '10px';
109
+ tok.shadow = '0 10px 32px rgba(0, 0, 0, 0.12)';
110
+ // code: the template's secondary light on the page, ink on it
111
+ tok['code-bg'] = mix(bg, c.lt2 ?? fg, 0.12);
112
+ tok['code-fg'] = pushUntil(fg, tok['code-bg'], 4.5);
113
+ const hl = ['keyword', 'string', 'number', 'function', 'type', 'punct'];
114
+ hl.forEach((h, i) => { tok[`hl-${h}`] = pushUntil(accents[i % 6], tok['code-bg'], 4.5); });
115
+ tok['hl-comment'] = pushUntil(tok.muted, tok['code-bg'], 3.0);
116
+ // diagrams. SPEC CHARTS: the --d-fill panels sit deliberately CLOSE TO THE
117
+ // CANVAS, gated for text on them — so a fill is a pale tint of its accent,
118
+ // not the accent, and the ink on it is the page's ink. Each tint is then
119
+ // pushed toward the page until that ink clears the gate on it.
120
+ const towardBg = (fill, ink, min) => {
121
+ let out = fill;
122
+ for (let t = 0; t <= 1.0001 && contrast(rgb(ink), rgb(out)) < min; t += 0.05) out = mix(fill, bg, t);
123
+ return out;
124
+ };
125
+ tok['d-text'] = tok.fg;
126
+ accents.forEach((a, i) => { tok[`d-fill-${i + 1}`] = towardBg(mix(a, bg, 0.72), tok.fg, 3.0); });
127
+ const fills = [1, 2, 3, 4, 5, 6].map((i) => tok[`d-fill-${i}`]);
128
+ // one muted and one accent ink that read on EVERY fill: push against the hardest one
129
+ const onAllFills = (ink, min) => fills.reduce((out, f) => pushUntil(out, f, min), ink);
130
+ tok['d-muted'] = onAllFills(mix(tok.fg, bg, 0.4), 2.6);
131
+ tok['d-accent'] = onAllFills(accents[0], 2.6);
132
+ tok['d-stroke'] = pushUntil(c.dk2 ?? fg, bg, 3.0);
133
+ // terminal: the template's dark on itself — a terminal on a light theme is still dark
134
+ tok['term-bg'] = c.dk2 ?? mix(fg, '#000000', 0.2);
135
+ tok['term-fg'] = pushUntil(bg, tok['term-bg'], 3.0);
136
+ tok['term-prompt'] = pushUntil(accents[0], tok['term-bg'], 3.0);
137
+ tok['term-cursor'] = tok['term-fg'];
138
+ tok['term-selection'] = mix(tok['term-bg'], tok['term-fg'], 0.3);
139
+ const ansi = { black: mix(tok['term-bg'], tok['term-fg'], 0.45), red: accents[0], green: accents[1], yellow: accents[2], blue: accents[3], magenta: accents[4], cyan: accents[5], white: tok['term-fg'] };
140
+ for (const [k, v] of Object.entries(ansi)) {
141
+ tok[`ansi-${k}`] = pushUntil(v, tok['term-bg'], 3.0);
142
+ tok[`ansi-bright-${k}`] = pushUntil(mix(v, tok['term-fg'], 0.35), tok['term-bg'], 3.0);
143
+ }
144
+ // one last pass over EVERY gate, in case a derived token moved another's background
145
+ for (const [f, b, min] of GATES) {
146
+ if (f.startsWith('d-')) continue; // settled above, against every fill at once
147
+ if (tok[f] && tok[b] && /^#/.test(tok[f]) && /^#/.test(tok[b]) && contrast(rgb(tok[f]), rgb(tok[b])) < min) tok[f] = pushUntil(tok[f], tok[b], min);
148
+ }
149
+ const themeName = name ?? `template-${String(parsed.name).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'template'}`;
150
+ const lines = Object.entries(tok).map(([k, v]) => ` --${k}: ${v};`);
151
+ const css = `/* Decklight theme · ${themeName}\n light · derived from the PowerPoint template's colour and font schemes\n Token contract: SPEC.md THEMING */\n.decklight {\n${lines.join('\n')}\n}\n`;
152
+ const check = validateTheme(css);
153
+ return { css, name: themeName, ok: check.ok, errors: check.errors ?? [] };
154
+ }
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * `npm run test:impact` — which tests does THIS change actually need?
7
+ *
8
+ * The suites are not the same shape, and the honest answer differs per suite.
9
+ * Measured on a laptop (2026-08-27, 85 unit files / 19 harnesses):
10
+ *
11
+ * unit `npm test` ~48s wall — 319s of work, run in parallel by node
12
+ * render `npm run verify` ~200s wall — strictly serial, one browser at a time
13
+ *
14
+ * So this script does NOT try to pick unit tests. 38 of the 85 files finish
15
+ * under 0.3s and node already overlaps them 6.6×; selecting a subset would save
16
+ * seconds and risk missing the one file that mattered. The unit suite is cheap
17
+ * enough to always be right, and being right is what a test picker is for.
18
+ *
19
+ * The render harnesses are the opposite: serial, minutes long, and each one
20
+ * pinned to a subsystem you can name. The five narration groups together are ~100s — a third
21
+ * of the suite — and a change to `cli/pdf.mjs` has no business waiting for it.
22
+ * That is the decision worth automating, so that is the only one made here.
23
+ *
24
+ * THE FALLBACK IS THE WHOLE SUITE. A path this map does not recognise selects
25
+ * everything, loudly, and says why. A test picker that guesses "probably
26
+ * nothing" on an unfamiliar path is worse than no picker: it turns an unrun
27
+ * suite into a green line. Same rule as the ingredients label — unchecked is
28
+ * its own answer and never a pass.
29
+ *
30
+ * This is a DEVELOPER shortcut for the edit-run loop, not a CI gate. CI keeps
31
+ * running everything, because the map is a claim about the code and the map can
32
+ * be wrong; the full suite is what notices.
33
+ */
34
+
35
+ import { execFileSync, spawnSync } from 'node:child_process';
36
+ import path from 'node:path';
37
+ import { fileURLToPath } from 'node:url';
38
+ import { isMain } from './args.mjs';
39
+
40
+ const here = path.dirname(fileURLToPath(import.meta.url));
41
+ const repo = path.resolve(here, '..');
42
+
43
+ /** narration-render's five concerns, as verify runs them (see test/verify.mjs). */
44
+ const NARRATION = ['narration-render:live', 'narration-render:picker', 'narration-render:recorded', 'narration-render:segments', 'narration-render:record'];
45
+
46
+ /** Every harness `verify` knows, in its running order. */
47
+ export const ALL = [
48
+ 'render', 'player-render',
49
+ 'narration-render:live', 'narration-render:picker', 'narration-render:recorded', 'narration-render:segments', 'narration-render:record',
50
+ 'record-render', 'review-render',
51
+ 'character-render', 'engine-render', 'pin-render', 'overflow-render', 'split-render',
52
+ 'strict-render', 'shot-render', 'plugin-render', 'extension-check-render',
53
+ 'deckfile-render', 'pdf-render', 'import-render', 'contrast', 'palette-rules',
54
+ ];
55
+
56
+ /**
57
+ * The two lint harnesses read `themes/` and `tools/`, never the built runtime —
58
+ * so a change to `src/` does not implicate them, and a change to a theme does.
59
+ * Kept as a named set because "every harness except the ones that never open a
60
+ * browser" is the distinction the rules below keep needing.
61
+ */
62
+ const LINT = ['contrast', 'palette-rules'];
63
+ const BROWSER = ALL.filter((h) => !LINT.includes(h));
64
+
65
+ /**
66
+ * changed path → the harnesses that could see it.
67
+ *
68
+ * Ordered, first match wins, so the broad "this is core" rules sit at the top.
69
+ * Every entry carries WHY, because the cost of this file being subtly wrong is
70
+ * a harness that stops running and nobody noticing for a month.
71
+ */
72
+ const RULES = [
73
+ // ── everything the built bundle rests on ────────────────────────────────
74
+ // Each browser harness loads dist/decklight.js, so these reach all of them.
75
+ [/^src\/core\/engine\.js$/, BROWSER, 'the engine every harness boots'],
76
+ [/^src\/core\/overlay\.js$/, BROWSER, 'the overlay contract every dialog registers through'],
77
+ [/^src\/index\.js$/, BROWSER, 'the bundle entry'],
78
+ [/^src\/decklight\.css$/, BROWSER, 'one stylesheet, every rendered deck'],
79
+ [/^build\.mjs$/, ALL, 'the build that produces what the harnesses load'],
80
+ [/^test\/harness\.mjs$/, ALL, 'the shared dump/assert helper'],
81
+ [/^package\.json$/, ALL, 'scripts, deps and packed files'],
82
+
83
+ // ── subsystems, each with a harness that is about it ────────────────────
84
+ [/^src\/core\/narration\.js$/, [...NARRATION, 'record-render', 'character-render'],
85
+ 'narration drives playback, the recorder and the character overlay'],
86
+ [/^src\/core\/character\.js$/, ['character-render', ...NARRATION], 'the talking head'],
87
+ [/^src\/core\/character-art\.js$/, ['character-render'], 'the head it draws'],
88
+ [/^src\/core\/review\.js$/, ['review-render'], 'the review overlay and its anchor resolver'],
89
+ [/^src\/core\/overflow\.js$/, ['overflow-render', 'pin-render'], 'the overflow guardrail and the pinned-title case'],
90
+ [/^src\/core\/annotate\.js$/, ['engine-render', 'render'], 'ink rides the engine scale'],
91
+ [/^src\/core\/themes\.js$/, ['render', 'contrast'], 'theme picking, and the contrast gate behind it'],
92
+ [/^src\/core\/(editmode|history)\.js$/, ['engine-render'], 'the author surfaces the engine harness drives'],
93
+ [/^src\/core\/hud\.js$/, ['engine-render'], 'clock and progress live on the engine'],
94
+ [/^src\/core\/finder\.js$/, ['engine-render', 'review-render'], 'slide titles: the finder names them, review anchors by them'],
95
+ [/^src\/terminal\//, ['player-render'], 'the cast player'],
96
+ [/^src\/code\//, ['render'], 'code blocks render in the smoke deck'],
97
+ [/^src\/core\//, BROWSER, 'an unmapped core module — assume every harness'],
98
+
99
+ // ── the CLI and tools, each spawned by the harness that tests it ────────
100
+ [/^cli\/audit\.mjs$/, ['strict-render'], 'the ingredients label and --strict stripping'],
101
+ [/^cli\/bundle\.mjs$/, ['strict-render', 'render'], 'bundling, and the deck it produces'],
102
+ [/^cli\/plugin\.mjs$/, ['plugin-render'], 'presenter plugins'],
103
+ [/^cli\/import\.mjs$/, ['import-render'], 'deck import'],
104
+ [/^cli\/deckfile\.mjs$/, ['deckfile-render'], 'the .decklight container'],
105
+ [/^cli\/pdf\.mjs$/, ['pdf-render'], 'PDF export'],
106
+ [/^cli\/(present|shot)\.mjs$/, ['shot-render'], 'present, and the screenshot containment it asserts'],
107
+ [/^cli\/(comments|review-anchor|review-store|review-remote|review-submit)\.mjs$/, ['review-render'],
108
+ 'the CLI half of review — the harness cross-checks the browser against it'],
109
+ [/^cli\/(units|marketplace|loader|pin)\.mjs$/, ['pin-render', 'extension-check-render'],
110
+ 'unit pinning and the admission check'],
111
+ [/^tools\/extension-check\.mjs$/, ['extension-check-render'], 'the admission gate itself'],
112
+ [/^tools\/(theme-check|color)\.mjs$/, LINT, 'the theme lints'],
113
+ [/^tools\/chrome\.mjs$/, ALL, 'every harness starts a browser through it'],
114
+ [/^tools\/review-anchor\.mjs$/, ['review-render'], 'the anchor resolver both halves share'],
115
+ [/^tools\/(tts-engines|local-voice|voiceover-server|lipsync)\.mjs$/, [...NARRATION, 'record-render'],
116
+ 'the voice bridge narration talks to'],
117
+ [/^themes\//, ['render', ...LINT], 'a theme, and the gates that read every theme'],
118
+ [/^demo\//, ['render'], 'the smoke deck itself'],
119
+
120
+ // ── things no harness reads ────────────────────────────────────────────
121
+ // Named explicitly rather than left to the fallback, so "nothing" is a
122
+ // decision on the record and not an omission.
123
+ [/^(docs|\.github|\.claude)\//, [], 'not read by any harness'],
124
+ [/^(SPEC|README|CONTRIBUTING|CLAUDE|CHANGELOG)\.md$/, [], 'prose'],
125
+ [/^test\/.*\.test\.mjs$/, [], 'a unit test — the unit suite covers it'],
126
+ ];
127
+
128
+ /** Which harnesses a single path implicates, and why. */
129
+ export function forPath(p) {
130
+ for (const [re, harnesses, why] of RULES) {
131
+ if (re.test(p)) return { harnesses, why };
132
+ }
133
+ // A harness fixture is about its own harness; `foo-render.mjs` / `foo.html`.
134
+ const m = /^test\/([a-z-]+?)(?:-render)?\.(?:mjs|html)$/.exec(p);
135
+ if (m) {
136
+ // `narration.html` is the fixture for all five narration groups
137
+ const hits = ALL.filter((h) => h === m[1] || h === `${m[1]}-render` || h.startsWith(`${m[1]}-render:`));
138
+ if (hits.length) return { harnesses: hits, why: hits.length > 1 ? 'its own harnesses' : 'its own harness' };
139
+ }
140
+ return { harnesses: ALL, why: 'UNMAPPED — falling back to everything' };
141
+ }
142
+
143
+ /** What changed: committed against the base, plus whatever is uncommitted. */
144
+ function changedFiles(base) {
145
+ const git = (...a) => {
146
+ try { return execFileSync('git', a, { cwd: repo, encoding: 'utf8' }); } catch { return ''; }
147
+ };
148
+ // A base that does not resolve makes `git diff` fail, and a swallowed failure
149
+ // here would report "nothing changed" — the one answer that must never be
150
+ // wrong. `origin/main` is missing in more checkouts than you would think: a
151
+ // clone whose remote is named something else, or one fetched shallow.
152
+ try {
153
+ execFileSync('git', ['rev-parse', '--verify', `${base}^{commit}`],
154
+ { cwd: repo, stdio: 'ignore' });
155
+ } catch {
156
+ process.stdout.write(`test:impact: cannot resolve "${base}" — `
157
+ + `pass --since <ref> with a ref this clone has (or fetch it).\n`);
158
+ process.exit(2);
159
+ }
160
+ const out = new Set();
161
+ // `...` is deliberate: the merge base, so a stale branch does not report
162
+ // every file main moved under it as something this change touched.
163
+ for (const l of git('diff', '--name-only', `${base}...HEAD`).split('\n')) if (l.trim()) out.add(l.trim());
164
+ for (const l of git('status', '--porcelain').split('\n')) {
165
+ const f = l.slice(3).trim();
166
+ if (f) out.add(f.includes(' -> ') ? f.split(' -> ')[1] : f);
167
+ }
168
+ return [...out];
169
+ }
170
+
171
+ // ── the command ───────────────────────────────────────────────────────────
172
+ // Guarded so the map above can be imported and asserted (test/test-impact.test.mjs)
173
+ // without this file running a suite as a side effect of being read.
174
+ if (!isMain(import.meta.url)) { /* imported for the map — the CLI below is inert */ } else {
175
+ const args = process.argv.slice(2);
176
+ const run = args.includes('--run');
177
+ const baseArg = args.indexOf('--since');
178
+ const base = baseArg !== -1 ? args[baseArg + 1] : 'origin/main';
179
+ // `i !== baseArg + 1` drops --since's VALUE, and only when --since is present:
180
+ // with no flag `baseArg` is -1 and the guard would silently eat argv[0], which
181
+ // is the first path somebody asked about.
182
+ const paths = args.filter((a, i) => !a.startsWith('--') && !(baseArg !== -1 && i === baseArg + 1));
183
+
184
+ if (args.includes('--help') || args.includes('-h')) {
185
+ process.stdout.write(`decklight test:impact — which tests this change needs
186
+
187
+ npm run test:impact what would run, against origin/main
188
+ npm run test:impact -- --run run it
189
+ npm run test:impact -- --since main compare against another ref
190
+ npm run test:impact -- src/core/review.js ask about explicit paths
191
+
192
+ The unit suite ALWAYS runs: it is ~48s and parallel, so picking a subset saves
193
+ little and can be wrong. Only the render harnesses (~200s, serial) are selected.
194
+ An unrecognised path selects every harness. CI always runs everything.
195
+ `);
196
+ process.exit(0);
197
+ }
198
+
199
+ const files = paths.length ? paths : changedFiles(base);
200
+ if (!files.length) {
201
+ process.stdout.write(`test:impact: nothing changed against ${base} — nothing to run\n`);
202
+ process.exit(0);
203
+ }
204
+
205
+ const picked = new Map(); // harness → the reasons it was picked
206
+ let unmapped = false;
207
+ for (const f of files) {
208
+ const { harnesses, why } = forPath(f);
209
+ if (why.startsWith('UNMAPPED')) unmapped = true;
210
+ for (const h of harnesses) {
211
+ if (!picked.has(h)) picked.set(h, new Set());
212
+ picked.get(h).add(`${f} — ${why}`);
213
+ }
214
+ }
215
+ const selected = ALL.filter((h) => picked.has(h));
216
+
217
+ // Measured on a laptop; a rough shape so the report can say what it saves.
218
+ const COST = {
219
+ 'narration-render:live': 25, 'narration-render:picker': 12, 'narration-render:recorded': 12,
220
+ 'narration-render:segments': 12, 'narration-render:record': 40, 'extension-check-render': 23, 'engine-render': 17, render: 20,
221
+ 'pdf-render': 10, 'split-render': 9, 'review-render': 8, 'pin-render': 7, 'record-render': 7,
222
+ 'strict-render': 6, 'overflow-render': 6, 'plugin-render': 6, 'deckfile-render': 4,
223
+ 'shot-render': 4, 'player-render': 3, 'character-render': 2, 'import-render': 2,
224
+ contrast: 1, 'palette-rules': 1,
225
+ };
226
+ const cost = (list) => list.reduce((n, h) => n + (COST[h] ?? 10), 0);
227
+
228
+ process.stdout.write(`\n─── test:impact ${'─'.repeat(52)}\n`);
229
+ process.stdout.write(`${files.length} changed file${files.length === 1 ? '' : 's'} against ${base}\n\n`);
230
+ for (const f of files.slice(0, 20)) process.stdout.write(` ${f}\n`);
231
+ if (files.length > 20) process.stdout.write(` … and ${files.length - 20} more\n`);
232
+
233
+ process.stdout.write(`\nunit suite ALWAYS — npm test (~48s, parallel)\n`);
234
+ if (!selected.length) {
235
+ process.stdout.write(`render none — nothing changed that a harness reads\n`);
236
+ } else {
237
+ process.stdout.write(`render ${selected.length} of ${ALL.length} harnesses`
238
+ + ` (~${cost(selected)}s of ~${cost(ALL)}s)\n`);
239
+ for (const h of selected) {
240
+ const [first] = [...picked.get(h)];
241
+ process.stdout.write(` ${h.padEnd(24)} ${first}\n`);
242
+ }
243
+ }
244
+ if (unmapped) {
245
+ process.stdout.write(`\n! an unmapped path selected everything. If that path has a harness that\n`
246
+ + ` is really about it, add a rule to tools/test-impact.mjs.\n`);
247
+ }
248
+ if (!run) {
249
+ process.stdout.write(`\n(--run to run it; CI still runs everything)\n`);
250
+ process.exit(0);
251
+ }
252
+
253
+ process.stdout.write(`\n─── npm test ${'─'.repeat(55)}\n`);
254
+ const unit = spawnSync('npm', ['test'], { cwd: repo, stdio: 'inherit', shell: process.platform === 'win32' });
255
+ let bad = unit.status !== 0;
256
+ if (selected.length) {
257
+ const verify = spawnSync('npm', ['run', 'verify'], {
258
+ cwd: repo,
259
+ stdio: 'inherit',
260
+ shell: process.platform === 'win32',
261
+ env: { ...process.env, VERIFY_ONLY: selected.join(',') },
262
+ });
263
+ bad = bad || verify.status !== 0;
264
+ }
265
+ process.exit(bad ? 1 : 0);
266
+ }
@@ -0,0 +1,191 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The synthesis cache on disk — one clip per (engine, model, format, voice,
6
+ * style, text), shared by everything that speaks.
7
+ *
8
+ * It lived inside tools/voiceover-server.mjs and served only the free local
9
+ * engines, on the argument that a cloud engine's output drifts with the
10
+ * server's model and a stale clip is worse than re-billing one preview
11
+ * sentence. That argument was answering the wrong question: it treated the
12
+ * MODEL as invisible, so the only way to avoid serving audio from last
13
+ * quarter's model was to keep no audio at all. Put the model in the key and
14
+ * the drift is not a risk, it is a cache miss — a new model is new bytes under
15
+ * a new name, and yesterday's clip is unreachable rather than wrong.
16
+ *
17
+ * What that buys is the thing the memory cache never could: the live bridge
18
+ * and `decklight voiceover` are SEPARATE PROCESSES, so a deck previewed
19
+ * sentence by sentence in the browser and then batch-recorded paid ElevenLabs
20
+ * twice for identical text. They now meet here, because the key is derived
21
+ * from what was said and how — not from who is asking.
22
+ *
23
+ * The key deliberately does NOT include the deck, the slide number or the
24
+ * output directory. The same sentence in two decks is the same audio, and a
25
+ * second take into a different `-o` should cost nothing.
26
+ *
27
+ * Nothing here throws. A cache that cannot be read is a cache miss and a cache
28
+ * that cannot be written is a cache — read-only media, a full disk and a
29
+ * locked-down $HOME all degrade to "synthesize it again", never to a failed
30
+ * talk.
31
+ */
32
+
33
+ import { createHash } from 'node:crypto';
34
+ import { mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
35
+ import { homedir } from 'node:os';
36
+ import { join } from 'node:path';
37
+
38
+ /**
39
+ * How much audio is allowed to accumulate before the oldest is dropped.
40
+ *
41
+ * A per-sentence cache grows forever, and a silent 10 GB in ~/.cache is not a
42
+ * cache, it is a leak with a euphemism.
43
+ */
44
+ export const CACHE_LIMIT = 400 * 1024 * 1024;
45
+
46
+ /** Where clips live. `$XDG_CACHE_HOME` wins, so a test never touches the real one. */
47
+ export function cacheHome(env = process.env) {
48
+ return join(env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'decklight', 'tts');
49
+ }
50
+
51
+ /**
52
+ * The file extension for what an engine returned.
53
+ *
54
+ * ElevenLabs' `--tts-format mp3` is the only path that is not a WAV, and
55
+ * filing an mp3 under `.wav` would make the cache dir a pile of lies — playable
56
+ * by nothing that trusts the name, prunable only by accident.
57
+ */
58
+ export function extFor(mime) {
59
+ return mime === 'audio/mpeg' ? 'mp3' : 'wav';
60
+ }
61
+
62
+ /** Every extension the cache is allowed to own, for pruning. */
63
+ export const CACHE_EXTS = ['.wav', '.mp3'];
64
+
65
+ /**
66
+ * The name a clip is filed under.
67
+ *
68
+ * Everything that changes the AUDIO is in here and nothing else is. `model` is
69
+ * the addition that lets cloud engines be cached at all; `format` is here
70
+ * because pcm and mp3 of one sentence are different bytes with the same words.
71
+ *
72
+ * NUL joins the fields so they cannot run together — a style ending in a space
73
+ * and a text starting with one must not hash like their neighbours — but
74
+ * written as an ESCAPE, not a raw byte: git calls any file with a NUL in its
75
+ * first 8 KB binary, and this file would silently become undiffable.
76
+ */
77
+ export function cacheKey({ engine, model, format, voice, style, text } = {}) {
78
+ return createHash('sha256')
79
+ .update([engine, model, format, voice, style, text].map((f) => f ?? '').join('\u0000'))
80
+ .digest('hex');
81
+ }
82
+
83
+ /**
84
+ * The key for one sentence on one ENGINE — the form both callers use.
85
+ *
86
+ * `cacheKey` above takes loose fields, which is what makes it testable; this
87
+ * takes the engine object and derives them, which is what makes the live
88
+ * bridge and `decklight voiceover` agree. They used to assemble the fields
89
+ * separately, and separately is how a cache that spans two processes quietly
90
+ * stops hitting: one of them starts sending a field the other does not, every
91
+ * lookup misses, and nothing fails — you just pay twice again.
92
+ *
93
+ * Two rules are worth naming, because both were bugs before they were rules.
94
+ *
95
+ * WHAT `model` MEANS DIFFERS BY ENGINE, and only gemini, chirp and ElevenLabs
96
+ * mean by it what the word says. For say and SAPI it is the voice the process
97
+ * booted with, while the voice that actually speaks arrives per sentence — so
98
+ * a bridge started without `--voice` and a recorder started with one hashed
99
+ * the same sentence, in the same voice, two different ways, and the batch
100
+ * recording missed every clip the browser had just filed. For piper it is the
101
+ * loaded model and the per-sentence voice is ignored entirely, which is the
102
+ * opposite mistake: keying on the request would let two runs under different
103
+ * `--voice` models collide on one key and serve the wrong voice. Each engine
104
+ * declares which it is (`modelIsDefaultVoice`, `voiceIsFixed`) rather than
105
+ * this file guessing from the name.
106
+ *
107
+ * STYLE only counts when the engine can act on it. Only gemini and ElevenLabs
108
+ * v3 read a delivery instruction; the rest are handed one and ignore it. The
109
+ * bridge gets its style from the deck (usually none) and the CLI defaults to a
110
+ * paragraph about a warm senior engineer — so keying on a style neither engine
111
+ * read would make identical audio hash two ways. `stylable` is the engine's
112
+ * own answer to "can this change the sound", and only then does it change the
113
+ * name.
114
+ */
115
+ export function clipKey(engine, { voice, style, text } = {}) {
116
+ // The voice that will SPEAK this sentence, and the model that will speak it
117
+ // — never the same axis twice, and never an axis the engine does not have.
118
+ const voiceId = engine?.voiceIsFixed ? engine?.model
119
+ : engine?.modelIsDefaultVoice ? (voice ?? engine?.model)
120
+ : voice;
121
+ const modelId = (engine?.voiceIsFixed || engine?.modelIsDefaultVoice) ? undefined : engine?.model;
122
+ return cacheKey({
123
+ engine: engine?.name,
124
+ model: modelId,
125
+ format: extFor(engine?.synth?.mimeType ?? 'audio/wav'),
126
+ voice: voiceId,
127
+ style: engine?.stylable ? style : undefined,
128
+ text,
129
+ });
130
+ }
131
+
132
+ /**
133
+ * A cache bound to a directory.
134
+ *
135
+ * `enabled: false` returns the same shape doing nothing, so a caller never
136
+ * grows an `if` around every read and write — `--no-cache` is one construction
137
+ * argument rather than a condition threaded through two files.
138
+ */
139
+ export function createTtsCache({ dir = cacheHome(), limit = CACHE_LIMIT, enabled = true } = {}) {
140
+ const path = (key, ext) => join(dir, `${key}.${ext}`);
141
+
142
+ /** The clip, or null. A miss and an unreadable file are the same answer. */
143
+ function read(key, ext = 'wav') {
144
+ if (!enabled) return null;
145
+ try {
146
+ const bytes = readFileSync(path(key, ext));
147
+ return bytes.length ? bytes : null;
148
+ } catch { return null; }
149
+ }
150
+
151
+ /** File a clip. Empty audio is never cached: it would poison the key forever. */
152
+ function write(key, bytes, ext = 'wav') {
153
+ if (!enabled || !bytes?.length) return false;
154
+ try {
155
+ mkdirSync(dir, { recursive: true });
156
+ writeFileSync(path(key, ext), bytes);
157
+ return true;
158
+ } catch { return false; }
159
+ }
160
+
161
+ /**
162
+ * Drop the oldest clips until the directory fits.
163
+ *
164
+ * Called once at startup rather than on every write: the bound is on what a
165
+ * machine keeps, not on what a single run may add, and stat-ing the whole
166
+ * directory per sentence would cost more than the synthesis it saves.
167
+ *
168
+ * Oldest-first by mtime also retires stale keys for free. Changing the key
169
+ * formula (adding `model`, say) orphans every clip filed under the old one;
170
+ * those are by definition never touched again, so they age to the front of
171
+ * this queue and leave on their own.
172
+ */
173
+ function prune() {
174
+ if (!enabled) return 0;
175
+ try {
176
+ const entries = readdirSync(dir)
177
+ .filter((f) => CACHE_EXTS.some((e) => f.endsWith(e)))
178
+ .map((f) => ({ f, ...statSync(join(dir, f)) }))
179
+ .sort((a, b) => a.mtimeMs - b.mtimeMs);
180
+ let total = entries.reduce((sum, e) => sum + e.size, 0);
181
+ let dropped = 0;
182
+ for (const e of entries) {
183
+ if (total <= limit) break;
184
+ try { unlinkSync(join(dir, e.f)); total -= e.size; dropped++; } catch { break; }
185
+ }
186
+ return dropped;
187
+ } catch { return 0; }
188
+ }
189
+
190
+ return { dir, enabled, read, write, prune };
191
+ }