decklight 0.9.0 → 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 (48) hide show
  1. package/PLATFORM.md +44 -3
  2. package/README.md +7 -5
  3. package/SPEC.md +100 -31
  4. package/cli/agent-review.mjs +5 -4
  5. package/cli/agents.mjs +11 -5
  6. package/cli/bundle-audio.mjs +10 -3
  7. package/cli/bundle-module.mjs +95 -0
  8. package/cli/bundle.mjs +58 -6
  9. package/cli/cast.mjs +41 -5
  10. package/cli/check-fixes.mjs +186 -0
  11. package/cli/check.mjs +32 -5
  12. package/cli/commit-flow.mjs +7 -3
  13. package/cli/commit-message.mjs +1 -1
  14. package/cli/commit-split.mjs +2 -2
  15. package/cli/deck-refs.mjs +8 -3
  16. package/cli/design-system-refs.mjs +263 -6
  17. package/cli/design-system.mjs +82 -14
  18. package/cli/edit-git.mjs +2 -2
  19. package/cli/edit-handover.mjs +129 -23
  20. package/cli/edit-look.mjs +248 -5
  21. package/cli/edit.mjs +504 -58
  22. package/cli/enhance.mjs +12 -10
  23. package/cli/git.mjs +13 -0
  24. package/cli/init.mjs +8 -3
  25. package/cli/marketplace-autocheck.mjs +200 -0
  26. package/cli/marketplace.mjs +250 -13
  27. package/cli/narrate.mjs +78 -3
  28. package/cli/open.mjs +24 -6
  29. package/cli/pdf.mjs +27 -8
  30. package/cli/pptx-export.mjs +7 -4
  31. package/cli/record.mjs +73 -13
  32. package/cli/remote.mjs +32 -6
  33. package/cli/serve.mjs +2 -2
  34. package/cli/skill-content.mjs +40 -3
  35. package/cli/skills.mjs +247 -3
  36. package/cli/theme-refs.mjs +14 -2
  37. package/cli/units.mjs +75 -7
  38. package/dist/build-info.json +1 -1
  39. package/dist/decklight.css +429 -32
  40. package/dist/decklight.js +169 -123
  41. package/dist/decklight.js.map +4 -4
  42. package/package.json +1 -1
  43. package/tools/design-system-format.mjs +25 -0
  44. package/tools/design-system-migrations.mjs +207 -0
  45. package/tools/exec.mjs +10 -2
  46. package/tools/narration-manifest.mjs +77 -3
  47. package/tools/site-clip.mjs +114 -0
  48. package/tools/video.mjs +69 -6
@@ -194,11 +194,12 @@ const order = (a, b) => a.slide - b.slide || ruleRank(a.rule) - ruleRank(b.rule)
194
194
  * Review the deck in `html`: batches of `REVIEW_BATCH` slides, a few at a
195
195
  * time, each through a read-only ask. Resolves to `{ findings, failed }`,
196
196
  * `failed` being `[{ slides, why }]` for a batch that timed out or answered
197
- * nothing usable. Throws only when there is no agent to ask at all.
197
+ * nothing usable. Throws only when there is no agent to ask at all. `signal`
198
+ * stops it: the asks in flight are killed and no batch after them is asked.
198
199
  */
199
200
  export async function reviewDeck(html, {
200
201
  agent = null, cwd = process.cwd(), env = process.env, timeoutMs = REVIEW_TIMEOUT_MS,
201
- concurrency = ENHANCE_CONCURRENCY, resolveAgent = agentAsk, exec = ask, onBatch = () => {},
202
+ concurrency = ENHANCE_CONCURRENCY, resolveAgent = agentAsk, exec = ask, onBatch = () => {}, signal = null,
202
203
  } = {}) {
203
204
  if (!resolveAgent(agent, 'x', { env })) throw new Error(agentUnavailable(agent, detectAgents({ env })));
204
205
  const slides = reviewSlides(html);
@@ -209,10 +210,10 @@ export async function reviewDeck(html, {
209
210
  const failed = [];
210
211
  let next = 0, done = 0;
211
212
  const worker = async () => {
212
- while (next < batches.length) {
213
+ while (next < batches.length && !signal?.aborted) {
213
214
  const batch = batches[next++];
214
215
  const cmd = resolveAgent(agent, reviewPrompt(batch, outline), { env });
215
- const out = cmd ? await exec(cmd, cwd, timeoutMs) : null;
216
+ const out = cmd ? await exec(cmd, cwd, timeoutMs, signal) : null;
216
217
  const r = out == null ? { why: 'the agent did not answer in time' } : parseReview(out, batch);
217
218
  if (r.findings) findings.push(...r.findings);
218
219
  else failed.push({ slides: batch.map((s) => s.slide), why: r.why });
package/cli/agents.mjs CHANGED
@@ -39,8 +39,12 @@ export const AGENTS = [
39
39
  // check nothing overflows before it is done. Only decklight's own CLI
40
40
  // is allowed; everything else still needs a permission it has no TTY
41
41
  // to ask for, which is the point.
42
- args: (prompt) => ['-p', prompt, '--permission-mode', 'acceptEdits',
42
+ // --add-dir: claude reads only inside the project unless told, and a
43
+ // migration's skill lives in a marketplace checkout under ~/.decklight
44
+ // (#893): each folder a job must read is named, and nothing more.
45
+ args: (prompt, deck, { dirs = [] } = {}) => ['-p', prompt, '--permission-mode', 'acceptEdits',
43
46
  '--allowedTools', 'Bash(npx decklight:*)', 'Bash(decklight:*)',
47
+ ...dirs.flatMap((d) => ['--add-dir', d]),
44
48
  '--output-format', 'stream-json', '--verbose'],
45
49
  stream: 'claude-json',
46
50
  // no --permission-mode: an ASK is read-only by construction, and a
@@ -310,8 +314,10 @@ export function agentUnavailable(name, roster, home = configHome(),
310
314
  /**
311
315
  * The exact spawn for one editing task: `name` picks the agent (or the first
312
316
  * detected one when omitted), `instruction` is the user's ask, `deck` the
313
- * file it should edit. Returns { bin, args, label } or null when the agent
314
- * isn't available.
317
+ * file it should edit, `dirs` folders outside the project it must be able to
318
+ * read (an agent that confines its reads to the project is given them; one
319
+ * whose sandbox already reads anywhere ignores them). Returns { bin, args,
320
+ * label } or null when the agent isn't available.
315
321
  */
316
322
  /**
317
323
  * The same agent, asked a QUESTION rather than told to edit (SPEC `PRESENTING`).
@@ -348,7 +354,7 @@ export function agentAsk(name, prompt, { env = process.env, hasBin = canRun, hom
348
354
  /** 1 → first, 2 → second … for a sentence an agent reads. */
349
355
  const ordinal = (n) => (n === 1 ? 'first' : n === 2 ? 'second' : n === 3 ? 'third' : `${n}th`);
350
356
 
351
- export function agentCommand(name, instruction, deck, { env = process.env, hasBin = canRun, home, spec = spawnSpec, slide = null } = {}) {
357
+ export function agentCommand(name, instruction, deck, { env = process.env, hasBin = canRun, home, spec = spawnSpec, slide = null, dirs = [] } = {}) {
352
358
  const roster = detectAgents({ env, hasBin, home });
353
359
  // Precedence, matching how every other saved choice resolves (PRESENTING):
354
360
  // an explicit name > the remembered preference > the first detected agent.
@@ -385,7 +391,7 @@ export function agentCommand(name, instruction, deck, { env = process.env, hasBi
385
391
  const how = spec(agent.bin, { env }) ?? { bin: agent.bin, prefix: [] };
386
392
  return {
387
393
  bin: how.bin,
388
- args: [...how.prefix, ...agent.args(prompt, deck)],
394
+ args: [...how.prefix, ...agent.args(prompt, deck, { dirs })],
389
395
  label: agent.label,
390
396
  name: agent.name,
391
397
  // which stream dialect stdout speaks, if any — the server's activity
@@ -24,6 +24,7 @@ import os from 'node:os';
24
24
  import path from 'node:path';
25
25
  import { configuredTrackDirs } from './edit.mjs';
26
26
  import { runAsync, CODEC_MS, PROBE_MS } from '../tools/exec.mjs';
27
+ import { renumber, sliceManifest } from './bundle-module.mjs';
27
28
 
28
29
  export const AUDIO_CHOICES = ['original', 'aac', 'opus'];
29
30
 
@@ -56,8 +57,10 @@ export const sizeLabel = (n) => (n < 1048576 ? `${(n / 1024).toFixed(1)} KB` : `
56
57
  * `file` entries. `found` maps the URL the runtime plays to the file;
57
58
  * `folders` reads "voices/ (12), cloud/ (3)"; `remote` counts manifest entries
58
59
  * with a `url` of their own (a bucket's, often signed), which stay there.
60
+ * With `mod` (`bundle --module`, cli/bundle-module.mjs) only that chapter's
61
+ * files are found, each under the slide number it has in the chapter.
59
62
  */
60
- export function narrationAudio(html, deckDir) {
63
+ export function narrationAudio(html, deckDir, mod = null) {
61
64
  const found = new Map();
62
65
  const where = new Map();
63
66
  const add = (key, abs) => {
@@ -70,7 +73,11 @@ export function narrationAudio(html, deckDir) {
70
73
  if (ABSOLUTE.test(d)) continue; // a public bucket's prefix: nothing on this disk
71
74
  const abs = path.resolve(deckDir, d);
72
75
  if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) continue;
73
- for (const f of fs.readdirSync(abs).sort()) if (AUDIO_FILE.test(f)) add(`${d.replace(/\/+$/, '')}/${f}`, path.join(abs, f));
76
+ for (const f of fs.readdirSync(abs).sort()) {
77
+ if (!AUDIO_FILE.test(f)) continue;
78
+ const as = renumber(f, mod);
79
+ if (as) add(`${d.replace(/\/+$/, '')}/${as}`, path.join(abs, f));
80
+ }
74
81
  }
75
82
  let remote = 0;
76
83
  // `manifest: '…'` in a boot call, `"manifest": "…"` in a configuration block
@@ -80,7 +87,7 @@ export function narrationAudio(html, deckDir) {
80
87
  try { data = JSON.parse(fs.readFileSync(abs, 'utf8')); } catch { continue; }
81
88
  const clean = rel.replace(/[?#].*$/, '');
82
89
  const base = clean.slice(0, clean.lastIndexOf('/') + 1); // voicetrack.js manifestBase
83
- const entries = (data?.slides ?? []).flatMap((e) => (e ? [e, ...(e.segments ?? []).filter(Boolean)] : []));
90
+ const entries = (sliceManifest(data, mod)?.slides ?? []).flatMap((e) => (e ? [e, ...(e.segments ?? []).filter(Boolean)] : []));
84
91
  for (const e of entries) {
85
92
  if (e.url) { remote++; continue; }
86
93
  if (typeof e.file !== 'string' || ABSOLUTE.test(e.file)) continue;
@@ -0,0 +1,95 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // One chapter of a deck as a bundle of its own (`bundle --module`, SPEC
5
+ // PRESENTING): the sections from a `data-module` marker up to the next one,
6
+ // and the narration that goes with them.
7
+ //
8
+ // The narration is the part that needs care. A track's files are named by
9
+ // slide number (`slide-07-02.wav`, `slide-07.visemes.json`) and a manifest is
10
+ // indexed by it (`slides[6]`), because the runtime builds those names from the
11
+ // slide it is on, counting from 1. Cut a chapter out and its slides are
12
+ // numbered from 1 again, so every name is moved down by the chapter's offset
13
+ // and anything outside the chapter is left out. Nothing is re-voiced: the
14
+ // clips are the same bytes under the number the bundle will ask for.
15
+
16
+ /** The top-level `<section>`s inside `[contentStart, contentEnd)`, depth-aware. */
17
+ function sectionSpans(html, contentStart, contentEnd) {
18
+ const spans = [];
19
+ const re = /<section\b[^>]*>|<\/section\s*>/gi;
20
+ re.lastIndex = contentStart;
21
+ let depth = 0, open = -1, m;
22
+ while ((m = re.exec(html)) && m.index < contentEnd) {
23
+ if (m[0][1] === '/') {
24
+ if (depth > 0 && --depth === 0) spans.push({ start: open, end: m.index + m[0].length, tag: html.slice(open, html.indexOf('>', open) + 1) });
25
+ } else if (depth++ === 0) open = m.index;
26
+ }
27
+ return spans;
28
+ }
29
+
30
+ const unescapeAttr = (s) => s.replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
31
+
32
+ /**
33
+ * The deck's chapters, in order: `{ n, title, offset, count }`, where `offset`
34
+ * is how many slides come before the chapter and `count` how many it holds.
35
+ * Slides before the first marker belong to no chapter.
36
+ */
37
+ export function deckModules(html, bounds) {
38
+ const spans = sectionSpans(html, bounds.contentStart, bounds.contentEnd);
39
+ const out = [];
40
+ spans.forEach((s, i) => {
41
+ const m = s.tag.match(/\bdata-module\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
42
+ if (!m) return;
43
+ if (out.length) out[out.length - 1].count = i - out[out.length - 1].offset;
44
+ out.push({ n: out.length + 1, title: unescapeAttr(m[1] ?? m[2]).trim(), offset: i, count: spans.length - i });
45
+ });
46
+ return { modules: out, spans };
47
+ }
48
+
49
+ /**
50
+ * The chapter `want` names: its number (1-based) or its title, case and
51
+ * surrounding space ignored. Throws an Error with a sentence that lists the
52
+ * chapters when nothing matches, or says there are none.
53
+ */
54
+ export function pickModule(modules, want) {
55
+ if (!modules.length) {
56
+ throw new Error('--module: this deck has no chapters — a chapter starts at a <section data-module="…">');
57
+ }
58
+ const key = String(want).trim();
59
+ const byNumber = /^\d+$/.test(key) ? modules[Number(key) - 1] : null;
60
+ const hit = byNumber ?? modules.find((m) => m.title.toLowerCase() === key.toLowerCase());
61
+ if (hit) return hit;
62
+ throw new Error(`--module: no chapter "${key}" in this deck — its chapters are:\n`
63
+ + modules.map((m) => ` ${m.n} ${m.title} (${m.count === 1 ? '1 slide' : `${m.count} slides`})`).join('\n'));
64
+ }
65
+
66
+ /** The deck with only `mod`'s sections left inside the container. */
67
+ export function sliceModule(html, bounds, spans, mod) {
68
+ const keep = spans.slice(mod.offset, mod.offset + mod.count);
69
+ const inner = keep.map((s) => html.slice(s.start, s.end)).join('\n\n ');
70
+ return html.slice(0, bounds.contentStart) + '\n\n ' + inner + '\n\n ' + html.slice(bounds.contentEnd);
71
+ }
72
+
73
+ /**
74
+ * A track file's name moved into the chapter: `slide-07-02.wav` with an
75
+ * offset of 4 is `slide-03-02.wav`, and a slide outside the chapter is null.
76
+ * Works on a bare stem (`slide-07`) and on a path (`voices/slide-07.m4a`).
77
+ * With no `mod` the name is returned as it is.
78
+ */
79
+ export function renumber(name, mod) {
80
+ if (!mod) return name;
81
+ const m = name.match(/^(.*?\bslide-)(\d+)((?:-\d+)?(?:\..*)?)$/);
82
+ if (!m) return name;
83
+ const n = Number(m[2]) - mod.offset;
84
+ if (n < 1 || n > mod.count) return null;
85
+ return `${m[1]}${String(n).padStart(Math.max(2, m[2].length), '0')}${m[3]}`;
86
+ }
87
+
88
+ /** A manifest's `slides` cut to the chapter (entry k is slide k + 1). */
89
+ export function sliceManifest(data, mod) {
90
+ if (!mod || !Array.isArray(data?.slides)) return data;
91
+ return { ...data, slides: data.slides.slice(mod.offset, mod.offset + mod.count) };
92
+ }
93
+
94
+ /** "Foundations" → "foundations", for the default file name. */
95
+ export const slug = (s) => s.toLowerCase().normalize('NFKD').replace(/[^\w\s-]/g, '').trim().replace(/[\s_]+/g, '-').replace(/-+/g, '-') || 'module';
package/cli/bundle.mjs CHANGED
@@ -55,6 +55,7 @@ import { escapeHtml } from '../tools/escape.mjs';
55
55
  import { isMain } from '../tools/args.mjs';
56
56
  import { AUDIO_CHOICES, CODECS, estimateAudio, inlineAudio, narrationAudio, sizeLabel } from './bundle-audio.mjs';
57
57
  import { injectBeforeBodyEnd } from '../tools/deck-html.mjs';
58
+ import { deckModules, pickModule, renumber, sliceManifest, sliceModule, slug } from './bundle-module.mjs';
58
59
 
59
60
  const fail = makeFail('bundle');
60
61
 
@@ -204,14 +205,20 @@ function mergeDecks(jobs, baseDir, notices) {
204
205
 
205
206
  // ---------------------------------------------------------------- arguments
206
207
 
207
- /** `client` is the sigstore seam — see publishMain; omitted, the real one is used. */
208
- export async function bundleMain(argv = process.argv.slice(2), { client, estimate = false } = {}) {
208
+ /**
209
+ * `client` is the sigstore seam — see publishMain; omitted, the real one is used.
210
+ * `report`, when given, is filled with `{ out, notices }` once the file is
211
+ * written: where it went and the notes printed after it, for a caller (the edit
212
+ * server's bundle card) that says them somewhere other than this terminal.
213
+ */
214
+ export async function bundleMain(argv = process.argv.slice(2), { client, estimate = false, report = null } = {}) {
209
215
 
210
216
  if (!argv.length || argv.includes('--help') || argv.includes('-h')) {
211
217
  process.stdout.write(`decklight bundle — flatten deck(s) into one self-contained HTML file
212
218
 
213
219
  Usage:
214
220
  decklight bundle <deck.html> [-o out.html] [--audio [original|aac|opus]] [--sign] [--deck] [--themes current|all|…]
221
+ decklight bundle <deck.html> --module <title | n> [-o out.html] [--audio …] [--themes …]
215
222
  decklight bundle <deck.html> --all [-o out.html] [--title "…"] [--themes …]
216
223
  decklight bundle <a.html> <b.html> … [-o out.html] [--title "…"] [--themes …]
217
224
 
@@ -232,6 +239,10 @@ Options:
232
239
  --sign, because the container is the signed artifact. A
233
240
  .decklight renamed to .html still plays in a browser: the
234
241
  deck comes first in the file and the metadata is appended.
242
+ --module <t|n> bundle one chapter of the deck: the slides from its
243
+ <section data-module="…"> up to the next one, named by
244
+ title or by number. The chapter's narration comes with it,
245
+ renumbered to its slides (--audio carries it inside)
235
246
  --title <t> <title> for the multi-module deck
236
247
  --transform <name> run an installed build-time transform (decklight library
237
248
  add transform <name>) on the deck's own source before anything else
@@ -273,6 +284,7 @@ let outPath = null, themesSel = 'current', all = false, mergedTitle = null, sign
273
284
  let allowMissingSystems = false;
274
285
  let allowMissingFonts = false;
275
286
  let audioChoice = null;
287
+ let moduleWant = null;
276
288
  const transformNames = [];
277
289
  for (let i = 0; i < argv.length; i++) {
278
290
  const a = argv[i];
@@ -287,6 +299,10 @@ for (let i = 0; i < argv.length; i++) {
287
299
  // an attestation. Naming the implication beats refusing the obvious command.
288
300
  else if (a === '--deck') { deckFile = true; sign = true; }
289
301
  else if (a === '--title') mergedTitle = argv[++i];
302
+ else if (a === '--module') {
303
+ moduleWant = argv[++i];
304
+ if (moduleWant == null || moduleWant.startsWith('-')) fail('--module takes a chapter: its title, or its number');
305
+ }
290
306
  else if (a === '--allow-missing-design-systems') allowMissingSystems = true;
291
307
  else if (a === '--allow-missing-fonts') allowMissingFonts = true;
292
308
  // `--audio` alone is the files as recorded; a codec after it re-encodes them
@@ -297,6 +313,7 @@ for (let i = 0; i < argv.length; i++) {
297
313
  }
298
314
  if (!inputs.length) fail('no deck given');
299
315
  if (all && inputs.length > 1) fail('--all takes a single deck (it follows that deck’s playlist)');
316
+ if (moduleWant != null && inputs.length > 1) fail('--module takes a single deck (it bundles one chapter of it)');
300
317
 
301
318
  const firstPath = path.resolve(inputs[0]);
302
319
  if (!fs.existsSync(firstPath)) fail(`deck not found: ${firstPath}`);
@@ -309,6 +326,14 @@ if (all) {
309
326
  const src = fs.readFileSync(firstPath, 'utf8');
310
327
  const modules = parsePlaylist(src);
311
328
  if (!modules.length) fail('--all: the deck has no parseable playlist ({ title, href } modules)');
329
+ if (moduleWant != null) {
330
+ // A playlist's module is a file of its own: bundling it is bundling that file.
331
+ const k = /^\d+$/.test(moduleWant.trim()) ? Number(moduleWant) - 1
332
+ : modules.findIndex((m) => m.title.toLowerCase() === moduleWant.trim().toLowerCase());
333
+ fail(modules[k]
334
+ ? `--module with --all: a playlist module is a file of its own — bundle it as one:\n decklight bundle ${path.join(path.relative(process.cwd(), deckDir) || '.', modules[k].href)}`
335
+ : '--module bundles one chapter of a single deck; --all merges a playlist — use one or the other');
336
+ }
312
337
  jobs = modules.map((m) => {
313
338
  const p = path.resolve(deckDir, m.href);
314
339
  if (!fs.existsSync(p)) fail(`playlist module not found: ${m.href} (${p})`);
@@ -323,6 +348,8 @@ if (all) {
323
348
  }
324
349
 
325
350
  let html;
351
+ // `--module`: the chapter being bundled; its narration is renumbered to it
352
+ let chapter = null;
326
353
  if (jobs) {
327
354
  html = mergeDecks(jobs, deckDir, notices);
328
355
  const t = mergedTitle ||
@@ -332,8 +359,20 @@ if (jobs) {
332
359
  path.join(deckDir, path.basename(firstPath, '.html') + '-course.html'));
333
360
  } else {
334
361
  html = fs.readFileSync(firstPath, 'utf8');
362
+ let suffix = '-standalone';
363
+ if (moduleWant != null) {
364
+ const bounds = containerBounds(html);
365
+ if (!bounds) fail(`no .decklight container in ${firstPath}`);
366
+ const { modules, spans } = deckModules(html, bounds);
367
+ try { chapter = pickModule(modules, moduleWant); } catch (e) { fail(e.message); }
368
+ html = sliceModule(html, bounds, spans, chapter);
369
+ html = html.replace(/<title>([^<]*)<\/title>/i, (t, was) =>
370
+ `<title>${was.trim() ? `${was.trim()} · ` : ''}${escapeHtml(chapter.title)}</title>`);
371
+ suffix = `-${slug(chapter.title)}`;
372
+ notices.push(`module ${chapter.n} of ${modules.length}: ${chapter.title} — slides ${chapter.offset + 1}–${chapter.offset + chapter.count} of the deck, 1–${chapter.count} in the bundle`);
373
+ }
335
374
  outPath = path.resolve(outPath ||
336
- path.join(deckDir, path.basename(firstPath, '.html') + '-standalone.html'));
375
+ path.join(deckDir, path.basename(firstPath, '.html') + suffix + '.html'));
337
376
  }
338
377
 
339
378
  // What went into the file and where each piece came from, said once at the end
@@ -695,6 +734,11 @@ html = html.replace(
695
734
  if (vm) {
696
735
  // vm[1] is the whole STEM (`slide-07`, `slide-07-02`) — the same name
697
736
  // the runtime looks the block up by, so the two cannot drift apart.
737
+ if (chapter) {
738
+ // the chapter's own timelines, under the slide number the bundle asks for
739
+ vm[1] = renumber(vm[1], chapter);
740
+ if (!vm[1]) continue;
741
+ }
698
742
  if (seen.has(vm[1])) {
699
743
  notices.push(`character visemes: ${d}/${f} skipped — ${vm[1]} already inlined from another track`);
700
744
  continue;
@@ -704,7 +748,9 @@ html = html.replace(
704
748
  + `${scriptSafe(fs.readFileSync(path.join(abs, f), 'utf8'))}\n</script>`);
705
749
  } else if (/^slide-\d+\.mp4$/.test(f)) mp4s++;
706
750
  }
707
- if (mp4s) {
751
+ if (mp4s && chapter) {
752
+ notices.push(`character video: ${mp4s} slide-NN.mp4 in ${d}/ are numbered for the whole deck and stay external — the chapter's character plays from its visemes`);
753
+ } else if (mp4s) {
708
754
  notices.push(`character video: ${mp4s} slide-NN.mp4 in ${d}/ stay external — ship the folder next to the bundle`);
709
755
  }
710
756
  }
@@ -734,8 +780,13 @@ html = html.replace(
734
780
  notices.push(`narration manifest: ${rel} not found — the bundle will fetch it at runtime`);
735
781
  continue;
736
782
  }
783
+ let text = fs.readFileSync(abs, 'utf8');
784
+ if (chapter) {
785
+ // the manifest is indexed by slide: cut it to the chapter's
786
+ try { text = JSON.stringify(sliceManifest(JSON.parse(text), chapter), null, 1); } catch { /* not JSON: inlined as it is */ }
787
+ }
737
788
  embeds.push(`<script type="application/json" data-decklight-voices="${rel.replace(/"/g, '&quot;')}">\n`
738
- + `${scriptSafe(fs.readFileSync(abs, 'utf8'))}\n</script>`);
789
+ + `${scriptSafe(text)}\n</script>`);
739
790
  n++;
740
791
  }
741
792
  if (n) notices.push(`narration: inlined ${n} voice manifest(s) — the audio stays in its bucket`);
@@ -751,7 +802,7 @@ html = html.replace(
751
802
  // files it left out or took in.
752
803
  let audioEstimate = null;
753
804
  {
754
- const { found, remote, folders } = narrationAudio(html, deckDir);
805
+ const { found, remote, folders } = narrationAudio(html, deckDir, chapter);
755
806
  if (estimate) {
756
807
  if (found.size) audioEstimate = { ...(await estimateAudio(found)), folders };
757
808
  } else if (found.size && audioChoice) {
@@ -910,6 +961,7 @@ if (bundleSig) {
910
961
  }
911
962
  }
912
963
  for (const n of notices) process.stdout.write(`note: ${n}\n`);
964
+ if (report) Object.assign(report, { out: outPath, notices });
913
965
  }
914
966
 
915
967
  if (isMain(import.meta.url)) process.exitCode = await runMain('bundle', bundleMain);
package/cli/cast.mjs CHANGED
@@ -113,6 +113,23 @@ function shellArgs(shellPath) {
113
113
  return [];
114
114
  }
115
115
 
116
+ /**
117
+ * The two lines a step is written as: the command in a brace group, and the
118
+ * sentinel that marks its end. A command stopped with Ctrl-C (an `interact`
119
+ * send of \u0003, the way a server is ended) used to take the sentinel with
120
+ * it: an interactive shell abandons the rest of the line on an interrupt, so
121
+ * the marker never printed and the step timed out. zsh's `always` block runs
122
+ * after an interrupt and bash's INT trap fires on one, both printing the
123
+ * marker with the interrupt's status (130); any other shell keeps the plain
124
+ * form.
125
+ */
126
+ export function stepLine(shellBase, cmd) {
127
+ const mark = (status) => `printf '${GS_OCTAL}DECKLIGHT:%d:${GS_OCTAL}\\n' ${status}`;
128
+ if (shellBase === 'zsh') return `{\n${cmd}\n} always { ${mark('$?')} }\n`;
129
+ if (shellBase === 'bash') return `trap "${mark(130).replace(/"/g, '\\"')}" INT; {\n${cmd}\n}; ${mark('$?')}; trap - INT\n`;
130
+ return `{\n${cmd}\n}; ${mark('$?')}\n`;
131
+ }
132
+
116
133
  function setupLine(shellBase) {
117
134
  const common = `stty -echo; printf '${GS_OCTAL}DECKLIGHT-READY${GS_OCTAL}\\n'`;
118
135
  if (shellBase === 'zsh') return `unsetopt zle prompt_cr prompt_sp banghist 2>/dev/null; PS1=''; PROMPT=''; PS2=''; PROMPT2=''; ${common}\n`;
@@ -165,6 +182,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
165
182
  let onChunk = null; // (data) => void — active step's collector
166
183
  let shellDead = false;
167
184
  let onExitCb = null;
185
+ let finished = false; // every step recorded — the shell is idle at its prompt
168
186
  term.onData(d => { buffer += d; if (onChunk) onChunk(d); });
169
187
  term.onExit(() => { shellDead = true; if (onExitCb) onExitCb(); });
170
188
 
@@ -217,7 +235,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
217
235
  // lines while parsing, so nothing is buffered for the command's stdin —
218
236
  // interact sends are the only input it can see. The lone `}` line also
219
237
  // makes trailing `#` comments in cmd harmless.
220
- term.write(`{\n${step.cmd}\n}; printf '${GS_OCTAL}DECKLIGHT:%d:${GS_OCTAL}\\n' $?\n`);
238
+ term.write(stepLine(path.basename(shellPath), step.cmd));
221
239
 
222
240
  // interact: watch output, answer prompts (expect/send) — runs alongside
223
241
  // the sentinel wait; secrets are sent for real but recorded as ▓▓▓ and
@@ -225,7 +243,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
225
243
  const interacts = Array.isArray(step.interact) ? step.interact : [];
226
244
  const inputs = [];
227
245
  const stepRedactions = [];
228
- let interactState = { done: interacts.length === 0, error: null, pending: null, cancelled: false };
246
+ let interactState = { done: interacts.length === 0, error: null, pending: null, cancelled: false, interrupted: false };
229
247
  if (interacts.length) {
230
248
  (async () => {
231
249
  let searchFrom = 0;
@@ -249,6 +267,7 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
249
267
  display = text;
250
268
  }
251
269
  inputs.push([round3(Number(process.hrtime.bigint() - t0) / 1e9), display]);
270
+ if (text.includes('\x03')) interactState.interrupted = true;
252
271
  term.write(text);
253
272
  interactState.pending = null;
254
273
  }
@@ -310,14 +329,31 @@ export async function recordScript(script, { scriptDir, allowFail = false, log =
310
329
  ...(inClamped.length ? { input: inClamped } : {}),
311
330
  });
312
331
  log(` ✓ ${step.cmd} (exit ${exit}, ${duration.toFixed(2)}s)`);
313
- if (exit !== 0 && !allowFail) {
332
+ // 130 is how a command ends when the script itself pressed Ctrl-C:
333
+ // that is the step working (a server stopped), not failing
334
+ if (exit !== 0 && !(exit === 130 && interactState.interrupted) && !allowFail) {
314
335
  throw new Error(`step ${idx + 1} exited ${exit}: ${step.cmd} (use --allow-fail to record failures as content)`);
315
336
  }
316
337
  }
338
+ finished = true;
317
339
  return steps;
318
340
  } finally {
319
- try { term.write('exit\n'); } catch { /* already dead */ }
320
- await new Promise(res => { if (shellDead) return res(); onExitCb = res; setTimeout(res, 1500); });
341
+ // A run that completed leaves the shell at its prompt, where `exit` ends
342
+ // it in a few milliseconds. A run that bailed mid-step (a timeout, an
343
+ // abort) leaves that command in the foreground, where `exit` would only
344
+ // queue behind it until the cap below gave up — so that shell is hung up
345
+ // on directly, which takes its foreground job with it.
346
+ if (finished) { try { term.write('exit\n'); } catch { /* already dead */ } }
347
+ else { try { term.kill(); } catch { /* already dead */ } }
348
+ // The cap is a fallback, so it must not outlive the exit it guards: a
349
+ // pending timer keeps the event loop alive, and this one held every
350
+ // recording open for its full 1.5s after the shell had already gone —
351
+ // ~1.5s per `rec` on a 100ms recording, and the bulk of test/cast.test.mjs.
352
+ await new Promise(res => {
353
+ if (shellDead) return res();
354
+ const cap = setTimeout(res, 1500);
355
+ onExitCb = () => { clearTimeout(cap); res(); };
356
+ });
321
357
  try { term.kill(); } catch { /* already dead */ }
322
358
  }
323
359
  }
@@ -0,0 +1,186 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * The quick fixes Check deck… offers for what `decklight check` finds (SPEC
6
+ * PRESENTING_EDITING). Pure over the deck's text and the resolved design
7
+ * systems: nothing here writes, spawns or reads the clock. The edit server's
8
+ * `GET /deck/edit/check` runs `quickFixes` over the static findings so every
9
+ * row the panel shows carries what pressing its fix WOULD do, and its
10
+ * `POST /deck/edit/check/fix` applies the transforms below.
11
+ *
12
+ * Two kinds of fix (the issue's distinction, #889). A DETERMINISTIC one is a
13
+ * rename or a setting the server can apply itself, in one write:
14
+ *
15
+ * ds-behind migrate design-system migrate (DESIGN_SYSTEM_MIGRATIONS)
16
+ * theme-off-brand theme the theme the brand's migration renames it to,
17
+ * else the brand's first theme
18
+ * off-role rename a renamed role → its successor, on that slide
19
+ * (batchable: ⇧F does every slide at once)
20
+ * ds-unresolved update marketplace update <marketplace>
21
+ * ds-unknown-system add design-system add <name>@<marketplace>, when a
22
+ * registered marketplace offers one of that name
23
+ *
24
+ * Everything else — clipped and crowded slides, ⟨CLICK⟩s against builds, a
25
+ * literal off the palette, a slot left empty — is a JUDGEMENT fix: the panel
26
+ * hands it to the A agent as an ordinary ask (src/core/deckcheck.js writes
27
+ * that prompt, since the live page has findings of its own), and nothing
28
+ * here claims one.
29
+ */
30
+
31
+ import { deckDesignSystems } from './check.mjs';
32
+ import { configBlock } from './runtime-link.mjs';
33
+ import { deckBehind, designSystemRefs, marketplaceDesignSystems, planMigration } from './design-system-refs.mjs';
34
+ import { configHome, loadRegistry } from './marketplace.mjs';
35
+ import { applyRenames, composeRenames, findRenamed, migrationsOf } from '../tools/design-system-migrations.mjs';
36
+ import { tokenPrefixOf } from '../tools/design-system-format.mjs';
37
+ import { locateSlide, sectionBodies } from '../tools/deck-html.mjs';
38
+
39
+ /** The rules whose fix is deterministic and safe to apply to every slide at once. */
40
+ export const BATCH_RULES = ['off-role'];
41
+
42
+ const readConfig = (html) => { try { return JSON.parse(configBlock(html)?.inner ?? 'null') ?? {}; } catch { return {}; } };
43
+
44
+ /**
45
+ * The role renames every design system the deck uses declares, composed
46
+ * across its migrations: `[{ prefix, roles }]`. ALL its migrations, not
47
+ * only the pending ones: an off-role that still meets a renamed role is a
48
+ * deck recorded at the current version with an old name left in it, which
49
+ * is exactly the case `ds-behind` does not cover (SPEC
50
+ * DESIGN_SYSTEM_MIGRATIONS).
51
+ */
52
+ function roleRenames(systems) {
53
+ const out = [];
54
+ for (const sys of systems.values()) {
55
+ const mm = sys.migrationManifest;
56
+ if (!mm) continue;
57
+ const roles = composeRenames(migrationsOf(mm)).roles;
58
+ if (Object.keys(roles).length) out.push({ prefix: tokenPrefixOf(mm), roles });
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /** The renamed roles slide `n` still uses, as `findRenamed` names them. */
64
+ function renamedRolesOn(html, n, systems) {
65
+ const body = sectionBodies(html)[n - 1];
66
+ if (!body) return [];
67
+ return roleRenames(systems).flatMap(({ prefix, roles }) => findRenamed([body], { roles }, prefix));
68
+ }
69
+
70
+ /**
71
+ * The theme a deck held to its brand should wear instead of the off-brand
72
+ * one its configuration names (SPEC BRAND_PALETTE): the one a design
73
+ * system's migration renames it to, when that is a brand theme, else the
74
+ * brand's first theme, which is what the runtime opens on. Null when the
75
+ * deck is not off its brand or the brand has no themes.
76
+ */
77
+ export function offBrandTarget(html, systems = deckDesignSystems(html)) {
78
+ const config = readConfig(html);
79
+ if (config.brandThemesOnly === false || typeof config.theme !== 'string' || !config.theme) return null;
80
+ const brand = [...systems.values()].flatMap((sys) => sys.themeNames ?? []);
81
+ if (!brand.length || brand.includes(config.theme)) return null;
82
+ for (const sys of systems.values()) {
83
+ const mm = sys.migrationManifest;
84
+ const to = mm ? composeRenames(migrationsOf(mm)).themes[config.theme]?.to : null;
85
+ if (to && brand.includes(to)) return { from: config.theme, to, renamed: true };
86
+ }
87
+ return { from: config.theme, to: brand[0], renamed: false };
88
+ }
89
+
90
+ /**
91
+ * A renamed role moved to its successor on slide `n`, or on every slide
92
+ * (`n` null): `{ html, count, slides }`, the markup otherwise byte for byte.
93
+ * The head and the tail are never touched — a role a stylesheet writes is
94
+ * the migration's, not a slide's.
95
+ */
96
+ export function renameRoles(html, n, systems = deckDesignSystems(html)) {
97
+ const renames = roleRenames(systems);
98
+ const total = sectionBodies(html).length;
99
+ const targets = n ? [n] : Array.from({ length: total }, (_, i) => i + 1);
100
+ let out = html;
101
+ let count = 0;
102
+ const slides = [];
103
+ for (const slide of targets) {
104
+ if (slide < 1 || slide > total) continue;
105
+ const { parts, idx } = locateSlide(out, slide);
106
+ let body = parts[idx];
107
+ let here = 0;
108
+ for (const { prefix, roles } of renames) {
109
+ const r = applyRenames(body, { roles }, prefix);
110
+ body = r.text;
111
+ here += r.count;
112
+ }
113
+ if (!here) continue;
114
+ parts[idx] = body;
115
+ out = parts.join('');
116
+ count += here;
117
+ slides.push(slide);
118
+ }
119
+ return { html: out, count, slides };
120
+ }
121
+
122
+ /** `name@marketplace` → its marketplace, when the reference is spelled so. */
123
+ const marketplaceOf = (ref) => /^[^@\s]+@([\w-]+)$/.exec(String(ref ?? ''))?.[1] ?? null;
124
+
125
+ /**
126
+ * The static findings, each with the deterministic fix the server can apply
127
+ * for it (`fix: { kind, label, … }`) — or none, which the panel says in so
128
+ * many words. `label` is what the fix WILL do, written on the row (*Migrate
129
+ * to acme 3.0.0 · 3 renames*), never a verb alone.
130
+ */
131
+ export function quickFixes(findings, html, dir, { home = configHome(), deck = 'deck.html', systems = null } = {}) {
132
+ const sys = systems ?? (designSystemRefs(html).length ? deckDesignSystems(html) : new Map());
133
+ let behind = null;
134
+ let offered = null;
135
+ const registered = () => { try { return Object.keys(loadRegistry(home).marketplaces ?? {}); } catch { return []; } };
136
+ const fixFor = (f) => {
137
+ switch (f.rule) {
138
+ case 'ds-behind': {
139
+ behind ??= deckBehind(html, dir, home, { deck });
140
+ const b = behind.find((x) => f.message.startsWith(`${x.ref} `)) ?? behind[0];
141
+ if (!b) return null;
142
+ const plan = planMigration(html, dir, b.ref, home);
143
+ if (plan.error || !plan.changed) return null;
144
+ return {
145
+ kind: 'migrate', ref: b.ref,
146
+ label: `Migrate to ${plan.name} ${plan.version}${plan.renamed ? ` · ${plan.renamed} rename${plan.renamed === 1 ? '' : 's'}` : ''}`,
147
+ ...(b.skills.length ? { skills: b.skills } : {}),
148
+ };
149
+ }
150
+ case 'theme-off-brand': {
151
+ const t = offBrandTarget(html, sys);
152
+ return t ? { kind: 'theme', theme: t.to, label: `Switch to ${t.to}${t.renamed ? ` (${t.from} was renamed)` : ', the brand’s first theme'}` } : null;
153
+ }
154
+ case 'off-role': {
155
+ if (!f.slide) return null;
156
+ const found = renamedRolesOn(html, f.slide, sys);
157
+ if (!found.length) return null;
158
+ return {
159
+ kind: 'rename', slide: f.slide, batch: true,
160
+ label: `Rename ${found.length === 1 ? `${found[0].from} → ${found[0].to}` : `${found.length} roles to their successors`} on slide ${f.slide}`,
161
+ };
162
+ }
163
+ case 'ds-unresolved': {
164
+ const ref = /^design system (\S+) cannot be read/.exec(f.message)?.[1];
165
+ const name = marketplaceOf(ref);
166
+ if (!name || !registered().includes(name)) return null;
167
+ return { kind: 'marketplace-update', name, label: `Update the ${name} marketplace` };
168
+ }
169
+ case 'ds-unknown-system': {
170
+ const want = /no design system called "([^"]+)"/.exec(f.message)?.[1];
171
+ if (!want) return null;
172
+ offered ??= marketplaceDesignSystems(home).systems;
173
+ const hit = offered.find((s) => s.name === want && !s.missing);
174
+ return hit ? { kind: 'design-system-add', ref: hit.qualified, label: `Add ${hit.qualified} to the deck` } : null;
175
+ }
176
+ default: return null;
177
+ }
178
+ };
179
+ return findings.map((f) => {
180
+ const fix = fixFor(f);
181
+ return fix ? { ...f, fix } : f;
182
+ });
183
+ }
184
+
185
+ /** `fix: <rule> on slide N`, or `fix: <rule>` for the deck — the commit a quick fix makes. */
186
+ export const fixSubject = (rule, slide = null) => `fix: ${rule}${slide ? ` on slide ${slide}` : ''}`;