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
package/cli/edit.mjs CHANGED
@@ -20,7 +20,9 @@
20
20
  // GET /edit/ping → { ok, deck, undo, redo, git, agents, agentBusy, wizards }
21
21
  // GET /edit/events → SSE; `reload` on deck change, `agent` job status
22
22
  // POST /edit/notes → { slide, text } rewrite that slide's notes
23
+ // POST /edit/timings → { timings: [{ slide, seconds }] } rehearsed times onto the sections
23
24
  // POST /edit/layout → { slide, layout } write data-layout to the file
25
+ // POST /edit/hidden → { slide, hidden } data-hidden on or off (HIDDEN_SLIDES)
24
26
  // GET /edit/element/source → ?slide=&index= an element's outerHTML, fresh from the file
25
27
  // POST /edit/element/remove → { slide, index } delete that element
26
28
  // POST /edit/element/content → { slide, index, html } replace its outerHTML
@@ -46,15 +48,41 @@
46
48
  // `decklight author` asks interactively before passing --git down.
47
49
 
48
50
  import { createServer } from 'node:http';
49
- import { readFileSync, writeFileSync, mkdirSync, watch, existsSync } from 'node:fs';
50
- import { resolve, sep, basename } from 'node:path';
51
- import { spawn } from 'node:child_process';
52
- import { agentCommand, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent } from './agents.mjs';
51
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, appendFileSync, watch, existsSync } from 'node:fs';
52
+ import { resolve, relative, dirname, sep, basename } from 'node:path';
53
+ import { spawn, execFileSync } from 'node:child_process';
54
+ import { agentCommand, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent, claudeActivity } from './agents.mjs';
53
55
  import { exitWhenOrphaned } from './supervise.mjs';
54
- import { argReader, isMain } from '../tools/args.mjs';
56
+ import { readyLine } from './banner.mjs';
57
+
58
+ /**
59
+ * Say a startup fact.
60
+ *
61
+ * Under author (DECKLIGHT_BANNER) it becomes a row on the one banner author
62
+ * prints, so it cannot land above the URL. Run standalone — `decklight edit` —
63
+ * it prints the line it always printed, which is why every call passes both:
64
+ * the SHORT text a banner row wants, and the full sentence a bare terminal
65
+ * needs because it has no banner to sit under.
66
+ */
67
+ const startup = (key, text, human) => {
68
+ if (process.env.DECKLIGHT_BANNER) console.log(readyLine({ key, text }));
69
+ else console.log(human);
70
+ };
71
+ import { argReader, firstPositional, isMain } from '../tools/args.mjs';
55
72
  import { NOTES_ASIDE, locateSlide, sectionChildRanges } from '../tools/deck-html.mjs';
73
+ // the boot-call locator audit and upgrade share — three commands, one answer
74
+ // about which <script> is the init call
75
+ import { classifyScripts } from './audit.mjs';
76
+ import { reviewPathFor, parseReview, serializeRecord, newId } from './review-store.mjs';
77
+ // The arbiters of what a comment IS, shared with the review server so two
78
+ // writers cannot put two shapes into one union-merged file.
79
+ import { commentProblem, reviewRecord } from './review.mjs';
80
+ import { foldReview } from '../tools/review-anchor.mjs';
81
+ import { recordingImpact, impactWarning, slidesFromFiles } from '../tools/recording-impact.mjs';
82
+ import { indexDeckFile, slideTextOf, knowsCommit } from './comments.mjs';
56
83
  import { deckHistory, decorateHistory, restoreDeck, deckAt, withBaseHref } from './restore.mjs';
57
84
  import { escapeHtml, sseChannel, staticFiles, listenTakingOverIfNeeded, allowEditRequest } from './serve.mjs';
85
+ import { reviewsWaiting, reviewLine, reviewCheckSuppressed, setCommentDone } from './review-remote.mjs';
58
86
  import { configureEngine, loadCredentials, forgetCredentials, redactAnswers, validateSchema, provenance, BRIDGE_ADDR, CONFIGURED, UNREACHABLE, PREREQUISITE } from './wizard.mjs';
59
87
 
60
88
  // The `/edit/*` surface answers loopback only — but "loopback" is the wrong
@@ -117,6 +145,40 @@ export function setSlideLayout(html, slide, name) {
117
145
  return parts.join('');
118
146
  }
119
147
 
148
+ /**
149
+ * Write a rehearsed time onto a slide: `data-timing="42"` (seconds, whole).
150
+ * `null` or 0 removes it. The attribute is the deck's memory of a rehearsal
151
+ * (PRESENTING REHEARSAL_TIMINGS) and travels with the file, so the next
152
+ * speaker view can show planned against actual.
153
+ */
154
+ export function setSlideTiming(html, slide, seconds) {
155
+ const { parts, idx } = locateSlide(html, slide);
156
+ const seg = parts[idx];
157
+ const gt = seg.indexOf('>');
158
+ if (gt < 0) throw new Error(`slide ${slide}: malformed <section> tag`);
159
+ let head = seg.slice(0, gt).replace(/\s+data-timing=("[^"]*"|'[^']*')/, '');
160
+ const n = Math.round(Number(seconds));
161
+ if (Number.isFinite(n) && n > 0) head += ` data-timing="${n}"`;
162
+ parts[idx] = head + seg.slice(gt);
163
+ return parts.join('');
164
+ }
165
+
166
+ /**
167
+ * Hide a slide from the talk, or show it again: `data-hidden` on the section
168
+ * (DECK_ANATOMY HIDDEN_SLIDES). The slide keeps its number and its place in
169
+ * the file — only the audience loses it. Same door as layout and timings.
170
+ */
171
+ export function setSlideHidden(html, slide, hidden) {
172
+ const { parts, idx } = locateSlide(html, slide);
173
+ const seg = parts[idx];
174
+ const gt = seg.indexOf('>');
175
+ if (gt < 0) throw new Error(`slide ${slide}: malformed <section> tag`);
176
+ let head = seg.slice(0, gt).replace(/\s+data-hidden(?:=("[^"]*"|'[^']*'))?(?=[\s>\/]|$)/, '');
177
+ if (hidden) head += ' data-hidden';
178
+ parts[idx] = head + seg.slice(gt);
179
+ return parts.join('');
180
+ }
181
+
120
182
  /** Look up element `index` (raw child position) on slide `slide`, or throw. */
121
183
  function locateElement(html, slide, index) {
122
184
  const { parts, idx } = locateSlide(html, slide);
@@ -144,6 +206,305 @@ export function setSlideElementHtml(html, slide, index, outerHtml) {
144
206
  // The spec's 7 entrance styles (MOTION), plus 'none' — an explicit, instant
145
207
  // build step, distinct from having no data-build attribute at all: one more
146
208
  // advance still reveals the element, it just has no animation.
209
+ /**
210
+ * Skip one JS string literal starting at `i` (which is its quote). Returns the
211
+ * index of the closing quote, or the end of the text if it never closes.
212
+ *
213
+ * The whole reason the walkers below are walkers and not regexes: a config
214
+ * carrying `{ alt: "Acme (Inc)" }` or `{ title: "a } b" }` closes nothing, and
215
+ * a regex counting brackets reads both as structure. `cli/audit.mjs` learned
216
+ * this first (isBootCall); this is the same rule applied to the object.
217
+ */
218
+ function skipString(text, i) {
219
+ const q = text[i];
220
+ for (i++; i < text.length && text[i] !== q; i++) if (text[i] === '\\') i++;
221
+ return i;
222
+ }
223
+
224
+ /**
225
+ * Skip one JS comment starting at `i` (which is its `/`). Returns the index of
226
+ * the comment's last character, or `i` unchanged when this `/` is not a
227
+ * comment at all (division, a lone slash in whatever).
228
+ *
229
+ * The walkers below skip strings and skipped nothing else — so a deck whose
230
+ * boot call carried a commented-out earlier track (`// narration: { files:
231
+ * 'old' }` — exactly what an author leaves behind) had that key
232
+ * FOUND, the splice landed inside the comment, and the UI said ✓ while the
233
+ * deck played nothing. An unbalanced `)` in a comment likewise ended
234
+ * initArgument's span early, and a splice into a truncated span corrupts the
235
+ * file rather than missing it.
236
+ */
237
+ function skipComment(text, i) {
238
+ if (text[i] !== '/') return i;
239
+ if (text[i + 1] === '/') {
240
+ const nl = text.indexOf('\n', i + 2);
241
+ return nl === -1 ? text.length : nl;
242
+ }
243
+ if (text[i + 1] === '*') {
244
+ const end = text.indexOf('*/', i + 2);
245
+ return end === -1 ? text.length : end + 1;
246
+ }
247
+ return i;
248
+ }
249
+
250
+ /**
251
+ * The `Decklight.init(…)` argument in `html`: where it starts and ends.
252
+ *
253
+ * Located through the same classifier `audit` and `upgrade` use, so all three
254
+ * agree on which `<script>` is the boot call rather than each finding its own.
255
+ * Returns null when the deck has no boot call at all.
256
+ */
257
+ export function initArgument(html) {
258
+ const boot = classifyScripts(html).find((b) => b.kind === 'boot');
259
+ if (!boot) return null;
260
+ const inner = html.slice(boot.start, boot.end);
261
+ const m = /Decklight\s*\.\s*init\s*\(/.exec(inner);
262
+ if (!m) return null;
263
+ const open = m.index + m[0].length - 1;
264
+ let depth = 0;
265
+ for (let i = open; i < inner.length; i++) {
266
+ const c = inner[i];
267
+ if (c === '"' || c === "'" || c === '`') { i = skipString(inner, i); continue; }
268
+ if (c === '/') { const j = skipComment(inner, i); if (j !== i) { i = j; continue; } }
269
+ if (c === '(') depth++;
270
+ else if (c === ')' && --depth === 0) {
271
+ return { start: boot.start + open + 1, end: boot.start + i };
272
+ }
273
+ }
274
+ return null;
275
+ }
276
+
277
+ /**
278
+ * Where a TOP-LEVEL key's value sits inside an object literal, or null.
279
+ *
280
+ * Depth-aware and string-aware: a `narration:` nested inside `character: {…}`
281
+ * is not this object's key, and `{ note: "narration: off" }` is not a key at
282
+ * all. Both are things a plausible deck contains.
283
+ */
284
+ function objectKey(obj, key) {
285
+ const re = new RegExp(`^${key}\\s*:`);
286
+ let depth = 0;
287
+ for (let i = 0; i < obj.length; i++) {
288
+ const c = obj[i];
289
+ if (c === '"' || c === "'" || c === '`') { i = skipString(obj, i); continue; }
290
+ if (c === '/') { const j = skipComment(obj, i); if (j !== i) { i = j; continue; } }
291
+ if (c === '{' || c === '[' || c === '(') { depth++; continue; }
292
+ if (c === '}' || c === ']' || c === ')') { depth--; continue; }
293
+ if (depth !== 1) continue;
294
+ // The boundary is checked against the PREVIOUS character, not folded into
295
+ // the regex: `^` matches the start of every slice, so the old
296
+ // `(^|[{,\\s])` form let `mynarration:` match at its own `n`.
297
+ if (i > 0 && !/[{,\s]/.test(obj[i - 1])) continue;
298
+ const m = re.exec(obj.slice(i, i + key.length + 2));
299
+ if (!m) continue;
300
+ // the value runs to the comma or closing brace at THIS depth
301
+ let j = i + m[0].length;
302
+ let d = 0;
303
+ for (; j < obj.length; j++) {
304
+ const v = obj[j];
305
+ if (v === '"' || v === "'" || v === '`') { j = skipString(obj, j); continue; }
306
+ if (v === '/') { const k2 = skipComment(obj, j); if (k2 !== j) { j = k2; continue; } }
307
+ if (v === '{' || v === '[' || v === '(') d++;
308
+ else if (v === '}' || v === ']' || v === ')') { if (d === 0) break; d--; }
309
+ else if (v === ',' && d === 0) break;
310
+ }
311
+ return { from: i, to: j, valueFrom: i + m[0].length };
312
+ }
313
+ return null;
314
+ }
315
+
316
+ /**
317
+ * The span of each top-level element of an array literal, `[` … `]` included
318
+ * in the input. String- and depth-aware for the same reason everything else
319
+ * here is: `[{ label: 'a, b' }]` is one element, not two.
320
+ */
321
+ function arrayEntries(arr) {
322
+ const out = [];
323
+ let depth = 0;
324
+ let start = -1;
325
+ for (let i = 0; i < arr.length; i++) {
326
+ const c = arr[i];
327
+ if (c === '"' || c === "'" || c === '`') { i = skipString(arr, i); continue; }
328
+ if (c === '/') { const j = skipComment(arr, i); if (j !== i) { i = j; continue; } }
329
+ if (c === '{' || c === '[' || c === '(') {
330
+ if (depth === 1 && start === -1) start = i;
331
+ depth++;
332
+ continue;
333
+ }
334
+ if (c === '}' || c === ']' || c === ')') {
335
+ depth--;
336
+ if (depth === 1 && start !== -1) { out.push({ from: start, to: i + 1 }); start = -1; }
337
+ continue;
338
+ }
339
+ if (depth === 1 && start === -1 && !/[\s,]/.test(c)) start = i;
340
+ if (depth === 1 && start !== -1 && c === ',') { out.push({ from: start, to: i }); start = -1; }
341
+ }
342
+ if (start !== -1) out.push({ from: start, to: arr.lastIndexOf(']') });
343
+ return out;
344
+ }
345
+
346
+ /** `{ files: 'voiceover', ext: 'wav', segments: true }`, as a person writes it. */
347
+ export function narrationLiteral(cfg) {
348
+ const parts = [];
349
+ for (const [k, v] of Object.entries(cfg)) {
350
+ if (v === undefined || v === null) continue;
351
+ parts.push(`${k}: ${typeof v === 'string' ? `'${v.replace(/'/g, "\\'")}'` : v}`);
352
+ }
353
+ return `{ ${parts.join(', ')} }`;
354
+ }
355
+
356
+ /**
357
+ * Point the deck's own config at a track that was just recorded.
358
+ *
359
+ * The recorder writes the files and then had to ask you to paste a config line
360
+ * into the deck by hand — the one manual step in a flow that is otherwise a
361
+ * key and an arrow. The author server already owns this file (it writes notes,
362
+ * layouts and element edits), so it can write this too, through the same
363
+ * applyEdit door: Z undoes it, live-reload shows it.
364
+ *
365
+ * Returns the new HTML, or **null when the config is not a literal at the call
366
+ * site** — `const cfg = {…}; Decklight.init(cfg)` has nothing here to edit, and
367
+ * guessing which `cfg` is meant, in which scope, is how an editor corrupts a
368
+ * file. That deck keeps the printed line and is told why.
369
+ */
370
+ /** `{ label: 'Rachel · ElevenLabs', dir: 'voices/rachel', ext: 'wav' }` */
371
+ export function trackLiteral(track) {
372
+ return narrationLiteral(track);
373
+ }
374
+
375
+ /**
376
+ * Add a recorded track to the deck's `narration.files`, or update it in place.
377
+ *
378
+ * ADD, not replace. A deck can carry as many tracks as you have voices — four
379
+ * cloned ones, the system voice, two takes of your own — and `N` is the
380
+ * switcher. Replacing the key (which is what this did when it only knew how to
381
+ * write one) threw the others away the first time somebody recorded a second
382
+ * voice, which is exactly when a multi-track deck exists.
383
+ *
384
+ * A track already listed under the same `dir` is UPDATED rather than added
385
+ * twice: re-recording into a folder should refresh what the deck says about
386
+ * it, not leave the picker showing the same folder twice.
387
+ *
388
+ * The one-string form (`files: 'voiceover'`, with `ext`/`segments` beside it)
389
+ * becomes a one-element list carrying those same keys — the shape
390
+ * `narrationTracks()` already normalises it to internally, so the deck plays
391
+ * identically before and after.
392
+ *
393
+ * Returns the new HTML, or null when there is no literal here to edit.
394
+ */
395
+ /**
396
+ * The local track directories a deck's `narration.files` names, in order.
397
+ *
398
+ * A directory track is a folder of recorded audio; a `manifest`/cloud entry
399
+ * has no local `dir` and is not one. Uses the same init walkers upsert does,
400
+ * so it reads exactly the config the deck actually runs — the `files: 'x'`
401
+ * one-string form counts too. Returns `[]` for a deck with no narration, a
402
+ * config built outside the call, or a manifest-only track.
403
+ */
404
+ export function configuredTrackDirs(html) {
405
+ const arg = initArgument(html);
406
+ if (!arg) return [];
407
+ const raw = html.slice(arg.start, arg.end);
408
+ const open = raw.indexOf('{');
409
+ if (open === -1 || raw.slice(0, open).trim()) return [];
410
+ const obj = raw.slice(open, raw.lastIndexOf('}') + 1);
411
+ const narr = objectKey(obj, 'narration');
412
+ if (!narr) return [];
413
+ const nval = obj.slice(narr.valueFrom, narr.to).trim();
414
+ if (!nval.startsWith('{')) return [];
415
+ const files = objectKey(nval, 'files');
416
+ if (!files) return [];
417
+ const fval = nval.slice(files.valueFrom, files.to).trim();
418
+ const dirs = [];
419
+ if (fval.startsWith('[')) {
420
+ for (const e of arrayEntries(fval)) {
421
+ const entry = fval.slice(e.from, e.to);
422
+ // a `dir` names a folder; a `manifest` entry is cloud and has none
423
+ const m = /\bdir\s*:\s*(['"`])([^'"`]*)\1/.exec(entry);
424
+ if (m && !/\bmanifest\s*:/.test(entry)) dirs.push(m[2]);
425
+ }
426
+ } else {
427
+ // the one-string form: files: 'voiceover'
428
+ const m = /^(['"`])([^'"`]*)\1$/.exec(fval);
429
+ if (m) dirs.push(m[2]);
430
+ }
431
+ return dirs;
432
+ }
433
+
434
+ export function upsertNarrationTrack(html, track) {
435
+ const arg = initArgument(html);
436
+ if (!arg) return null;
437
+ const raw = html.slice(arg.start, arg.end);
438
+ const splice = (from, to, text) => html.slice(0, from) + text + html.slice(to);
439
+ const one = narrationLiteral(track);
440
+
441
+ // no config object at the call site at all
442
+ if (!raw.trim()) return splice(arg.start, arg.end, `{ narration: { files: [${one}] } }`);
443
+ const open = raw.indexOf('{');
444
+ if (open === -1 || raw.slice(0, open).trim()) return null;
445
+ const close = raw.lastIndexOf('}');
446
+ if (close < open) return null;
447
+ const obj = raw.slice(open, close + 1);
448
+ const at = arg.start + open;
449
+
450
+ const narr = objectKey(obj, 'narration');
451
+ if (!narr) {
452
+ const inner = obj.slice(1, -1);
453
+ const body = inner.trim()
454
+ ? `{ narration: { files: [${one}] },${inner.replace(/^\s*\n?/, inner.includes('\n') ? '\n' : ' ')}}`
455
+ : `{ narration: { files: [${one}] } }`;
456
+ return splice(at, arg.start + close + 1, body);
457
+ }
458
+
459
+ const nval = obj.slice(narr.valueFrom, narr.to).trim();
460
+ const nvalAt = at + narr.valueFrom + (obj.slice(narr.valueFrom, narr.to).length - obj.slice(narr.valueFrom, narr.to).trimStart().length);
461
+ if (!nval.startsWith('{')) return null; // narration built elsewhere
462
+
463
+ const files = objectKey(nval, 'files');
464
+ if (!files) {
465
+ const inner = nval.slice(1, -1);
466
+ const body = inner.trim() ? `{ files: [${one}],${inner.replace(/^\s*/, ' ')}}` : `{ files: [${one}] }`;
467
+ return splice(nvalAt, nvalAt + nval.length, body);
468
+ }
469
+
470
+ const fval = nval.slice(files.valueFrom, files.to).trim();
471
+ const fvalStart = nvalAt + nval.indexOf(fval, files.valueFrom);
472
+
473
+ // already a list: update the entry naming this folder, else append
474
+ if (fval.startsWith('[')) {
475
+ const entries = arrayEntries(fval);
476
+ const same = entries.find((e) => {
477
+ const m = /\bdir\s*:\s*(['"`])([^'"`]*)\1/.exec(fval.slice(e.from, e.to));
478
+ return m && m[2] === track.dir;
479
+ });
480
+ if (same) return splice(fvalStart + same.from, fvalStart + same.to, one);
481
+ const closeAt = fval.lastIndexOf(']');
482
+ const body = entries.length ? `,\n ${one}\n ` : one;
483
+ return splice(fvalStart + closeAt, fvalStart + closeAt, body);
484
+ }
485
+
486
+ // the one-string form: carry it across as the first entry, keys and all
487
+ const m = /^(['"`])([^'"`]*)\1$/.exec(fval);
488
+ if (!m) return null;
489
+ const kept = { label: m[2], dir: m[2] };
490
+ for (const k of ['ext', 'segments']) {
491
+ const found = objectKey(nval, k);
492
+ if (!found) continue;
493
+ const v = nval.slice(found.valueFrom, found.to).trim();
494
+ kept[k] = v === 'true' ? true : v === 'false' ? false : v.replace(/^['"`]|['"`]$/g, '');
495
+ }
496
+ const list = kept.dir === track.dir ? [one] : [narrationLiteral(kept), one];
497
+ // the sibling ext/segments moved INTO the entry they described, so they must
498
+ // not stay behind saying it about every track
499
+ const rest = [];
500
+ for (const [k, span] of ['liveUrl', 'character', 'engine', 'voice', 'style']
501
+ .map((k) => [k, objectKey(nval, k)]).filter(([, v]) => v)) {
502
+ rest.push(nval.slice(span.from, span.to).trim().replace(/,$/, ''));
503
+ }
504
+ const body = `{ files: [\n ${list.join(',\n ')}\n ]${rest.length ? `, ${rest.join(', ')}` : ''} }`;
505
+ return splice(nvalAt, nvalAt + nval.length, body);
506
+ }
507
+
147
508
  export const BUILD_EFFECTS = ['fade', 'fade-up', 'fade-down', 'zoom', 'pop', 'draw', 'highlight', 'none'];
148
509
 
149
510
  /**
@@ -198,10 +559,25 @@ export function createHistory(limit = 200) {
198
559
  // re-exported so long-standing importers (init, the tests) keep finding it
199
560
  // where edit grew it.
200
561
  import { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit, lastCommitSha, resolveGitMode, shouldCommit, commitSubject, exitPushLine, oneline, remoteLine, remoteState, unpushed } from './git.mjs';
201
- import { describeCommit, messagesLine } from './commit-message.mjs';
562
+ import {
563
+ describeCommit, describeWorking, messagesLine, rememberPref, storedPref,
564
+ } from './commit-message.mjs';
565
+ import { WIP_REF, deckDirty, nagText, planNag, snapshotWip, wipLine } from './commit-flow.mjs';
202
566
  export { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit };
203
567
 
204
- export async function editMain(args) {
568
+ /** Who the author is, from git's own answer — see cli/review.mjs. */
569
+ function reviewerName(cwd = process.cwd()) {
570
+ const cfg = (key) => {
571
+ try { return execFileSync('git', ['config', key], { cwd, encoding: 'utf8' }).trim(); } catch { return ''; }
572
+ };
573
+ const name = cfg('user.name');
574
+ const email = cfg('user.email');
575
+ return (name && email) ? `${name} <${email}>` : (name || email || '');
576
+ }
577
+
578
+ export async function editMain(args, { onListen = null } = {}) {
579
+ // /edit/review/incoming's answer, briefly remembered (see the route).
580
+ let incomingCache = null;
205
581
  if (args.includes('--help') || args.includes('-h') || !args.filter((a) => !a.startsWith('-')).length) {
206
582
  console.log(`usage: node cli/edit.mjs <deck.html> [--port 8788] [--git | --no-git]
207
583
  [--commit-every <seconds>] [--agent <name>] [--commit-messages]
@@ -210,16 +586,28 @@ export async function editMain(args) {
210
586
  element edit mode (E, then right-click an element), undo/redo (Z/⇧Z), agent asks (A)
211
587
  a taken --port offers to take over that session (on a TTY) or moves on to
212
588
  the next free one
213
- --git auto-commit the deck on a regular basis (creates the repo if needed)
589
+ --git keep the deck in git (creates the repo if needed): a silent
590
+ snapshot on refs/decklight/wip, and K commits when you say so
214
591
  --no-git never touch git (default outside a repository)
215
- --commit-every N autocommit cadence in seconds (timer mode) [300]
216
- --git-mode M when to commit: timer (a cadence), agent (one commit per
217
- agent edit, with the agent's own message), off [timer]
592
+ --commit-every N cadence in seconds, timer mode only [300]
593
+ --git-mode M agent one commit per agent edit, plus whatever K commits
594
+ timer the old five-minute cadence, bookends included
595
+ off never commit [agent]
218
596
  --agent <name> preferred AI agent for A (default: first one detected)
219
597
  the server binds 127.0.0.1 only; for a phone remote use decklight present`);
220
598
  return;
221
599
  }
222
600
  const { opt } = argReader(args);
601
+
602
+ // DECLARED HERE, not down with the rest of the agent wiring, because
603
+ // `ownCommit` closes over it and editMain CALLS ownCommit synchronously —
604
+ // the opening commit, taken when git has never seen this deck. Left where it
605
+ // reads better, that call ran while this binding was still in its temporal
606
+ // dead zone and `decklight author` died on a ReferenceError before the
607
+ // server ever came up. It needed both halves to show: a deck git does not
608
+ // know, and commit-messages on (only that path reads `agentPref`), which is
609
+ // why adding a SECOND deck to a repo was the way to find it.
610
+ let agentPref = opt('--agent') ?? preferredAgent();
223
611
  const port = Number(opt('--port', 8788));
224
612
  // Refused out loud, not ignored (PRESENT#REMOTE). Someone typing --remote
225
613
  // wants a clicker; silently binding loopback would leave them holding a phone
@@ -231,13 +619,13 @@ export async function editMain(args) {
231
619
  console.error(' A clicker used to cost you an editing server on the LAN: /edit/notes, /edit/layout and');
232
620
  console.error(' /edit/agent were reachable from the same run you were not watching. present has no edit');
233
621
  console.error(' surface to widen, so that is where it lives.');
234
- console.error(`\n decklight present ${args.find((a) => !a.startsWith('-')) ?? '<deck.html>'} --remote`);
622
+ console.error(`\n decklight present ${firstPositional(args, ['--port', '--commit-every', '--agent']) ?? '<deck.html>'} --remote`);
235
623
  process.exitCode = 2;
236
624
  return;
237
625
  }
238
626
  const host = '127.0.0.1';
239
627
  const root = process.cwd();
240
- const deckPath = resolve(root, args.find((a) => !a.startsWith('-')));
628
+ const deckPath = resolve(root, firstPositional(args, ['--port', '--commit-every', '--agent']));
241
629
  if (!existsSync(deckPath)) { console.error(`deck not found: ${deckPath}`); process.exitCode = 1; return; }
242
630
  if (!deckPath.startsWith(root + sep)) { console.error('deck must live under the current directory'); process.exitCode = 1; return; }
243
631
  const deckUrl = '/' + deckPath.slice(root.length + 1).split(sep).join('/');
@@ -262,10 +650,14 @@ export async function editMain(args) {
262
650
  const wantGit = args.includes('--git');
263
651
  const commitEvery = Math.max(5, Number(opt('--commit-every', 300)) || 300);
264
652
  // --commit-messages: an agent writes the subject decklight would otherwise
265
- // template. Opt-in, because it sends the deck's diffs to whichever agent CLI
266
- // is installed and most of them are cloud-backed — a permission decklight
267
- // does not infer from what happens to be on PATH.
268
- const wantMessages = args.includes('--commit-messages');
653
+ // template. Still never inferred from what happens to be on PATH — but the
654
+ // permission can have been GIVEN already: `init` (and author's own first-run
655
+ // git offer) asks once, when the repository is created, and stores the answer
656
+ // in that repository's git config. The flag on the command line outranks it
657
+ // in both directions, so a stored yes is still one `--no-commit-messages`
658
+ // away from off for a single session.
659
+ const wantMessages = args.includes('--no-commit-messages') ? false
660
+ : args.includes('--commit-messages') || storedPref(process.cwd()) === true;
269
661
 
270
662
  /**
271
663
  * Every commit decklight authors ITSELF goes through here — the cadence, the
@@ -287,6 +679,9 @@ export async function editMain(args) {
287
679
  ? gitAutocommit(deckPath, root)
288
680
  : gitAutocommit(deckPath, root, message);
289
681
  if (!made) return false;
682
+ // Whatever wrote it — the overlay, an agent, a bookend — this stretch of
683
+ // uncommitted work is over, so the nag re-arms for the NEXT one.
684
+ resetEpisode();
290
685
  const sha = lastCommitSha;
291
686
  if (wantMessages && sha) {
292
687
  const template = message ?? `decklight: autosave ${basename(deckPath)}`;
@@ -296,9 +691,58 @@ export async function editMain(args) {
296
691
  }
297
692
  return true;
298
693
  }
299
- // timer (default, unchanged) · agent (one commit per agent edit) · off
694
+ // timer (the old cadence) · agent (one commit per agent edit, the default) · off
300
695
  const gitMode = resolveGitMode(args);
301
696
  let gitOn = false;
697
+
698
+ // ── the commit watch (cli/commit-flow.mjs) ──────────────────────────────
699
+ // How often the snapshot is refreshed and the nag rule re-read. Far shorter
700
+ // than the old commit cadence because nothing here writes history: a tick is
701
+ // one `git diff --numstat` and, when the deck moved, one loose commit object.
702
+ // The NAG is governed by its own rule, not by this interval — see planNag.
703
+ const WATCH_EVERY_MS = 30_000;
704
+ // …but never slower than the cadence the author asked for. `--commit-every`
705
+ // governs `--git-mode timer` outright; in the default mode it is still the
706
+ // knob for "how often should decklight look at my deck", so a tighter number
707
+ // tightens the snapshot too. Without this the interval was a constant nobody
708
+ // could reach, which is also what made it untestable end to end.
709
+ const watchEveryMs = Math.min(commitEvery * 1000, WATCH_EVERY_MS);
710
+ let dirtySince = 0; // when this stretch of uncommitted work began
711
+ let dirtyLines = 0; // how much of the deck differs from HEAD
712
+ let nagged = false; // the episode latch: asked once, then quiet
713
+ let nagDismissed = false;
714
+ let lastWip = null; // the snapshot sha, so the ping can prove it exists
715
+ /** A commit happened: this stretch of uncommitted work is over. */
716
+ const resetEpisode = () => {
717
+ dirtySince = 0; dirtyLines = 0; nagged = false; nagDismissed = false;
718
+ };
719
+ /**
720
+ * Re-read what is uncommitted, right now.
721
+ *
722
+ * Anything ANSWERING A QUESTION calls this rather than reporting the last
723
+ * tick's numbers. The tick is 30s apart, and K is pressed the moment after an
724
+ * edit: a cached "clean" would refuse to commit work that plainly exists,
725
+ * which is the worst possible answer from the button whose whole job is to
726
+ * commit it. The nag latch is deliberately untouched here — measuring is not
727
+ * asking.
728
+ */
729
+ const measureDirty = () => {
730
+ const d = deckDirty(root, deckRel);
731
+ if (!d.dirty) { dirtySince = 0; dirtyLines = 0; return d; }
732
+ if (!dirtySince) dirtySince = Date.now();
733
+ dirtyLines = d.lines;
734
+ return d;
735
+ };
736
+ /** What the deck knows about uncommitted work — ping and SSE both send this. */
737
+ const commitState = () => ({
738
+ dirty: dirtySince > 0,
739
+ lines: dirtyLines,
740
+ sinceMs: dirtySince ? Date.now() - dirtySince : 0,
741
+ nag: nagged && !nagDismissed,
742
+ wip: lastWip,
743
+ canWrite: gitOn && gitMode !== 'off',
744
+ messages: wantMessages,
745
+ });
302
746
  if (!noGit && (wantGit || inGitRepo(root))) {
303
747
  if (!inGitRepo(root)) {
304
748
  try {
@@ -310,26 +754,91 @@ export async function editMain(args) {
310
754
  }
311
755
  if (inGitRepo(root)) {
312
756
  gitOn = true;
313
- ownCommit(`decklight: start editing ${basename(deckPath)}`);
314
- // The cadence is the backstop, and it runs in agent mode too: an agent
315
- // job only ever sees edits IT made, so hand edits — and any agent driven
316
- // from outside the A flow — would otherwise reach git only via the
317
- // Ctrl-C bookend, which a crash skips. It is held back while a job is in
318
- // flight so nothing commits a half-finished agent run.
757
+ // An answer given on the command line becomes the repository's answer,
758
+ // once. This is what makes the first-run question (dev.mjs, asked before
759
+ // the repository existed and so with nowhere to write) stick: the next
760
+ // session reads it back instead of asking again. Only when nothing is
761
+ // stored yet — a later `--no-commit-messages` is one session's override,
762
+ // not a silent change to what the repository has been told.
763
+ if (storedPref(root) === null
764
+ && (args.includes('--commit-messages') || args.includes('--no-commit-messages'))) {
765
+ rememberPref(root, wantMessages);
766
+ }
767
+ // The session bookends are the cadence's siblings: generic subjects for
768
+ // moments nobody described, and in the default mode the snapshot covers
769
+ // what they were covering. THE FIRST COMMIT IS NOT ONE OF THEM. A
770
+ // repository decklight just created has no commits at all, and a deck git
771
+ // has never seen is in no commit — in both cases there is no HEAD for the
772
+ // snapshot to parent on and nothing in git to recover, so this commit is
773
+ // how the deck ENTERS history rather than an autosave of it.
774
+ const opening = deckDirty(root, deckRel);
775
+ if (gitMode === 'timer') ownCommit(`decklight: start editing ${basename(deckPath)}`);
776
+ else if (opening.firstCommit || opening.untracked) ownCommit(`decklight: add ${basename(deckPath)}`);
777
+ else { measureDirty(); lastWip = snapshotWip(root, deckPath, deckRel) ?? lastWip; }
778
+ // The cadence no longer WRITES HISTORY. It used to commit every
779
+ // --commit-every seconds, and what that produced was a column of
780
+ // `decklight: autosave talk.html` in which no commit marked anything —
781
+ // a backup wearing a history's clothes. The two jobs are now separate:
782
+ // the tick takes a silent snapshot (refs/decklight/wip, off every branch)
783
+ // so a crash still costs nothing, and asks ONCE per stretch of
784
+ // uncommitted work whether you want to commit it. `--git-mode timer`
785
+ // keeps the old cadence for anyone who wants the wall back.
319
786
  setInterval(() => {
320
- if (shouldCommit(gitMode, { kind: 'timer', agentBusy: !!agentJob })) ownCommit();
321
- }, commitEvery * 1000).unref();
322
- console.log(gitMode === 'agent'
323
- ? ` git: committing ${deckRel} once per agent edit with the agent's own message, every ${commitEvery}s otherwise (and on Ctrl-C)`
324
- : ` git: auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`);
787
+ if (agentJob) return; // never mid-run: see shouldCommit
788
+ if (gitMode === 'timer') {
789
+ if (shouldCommit(gitMode, { kind: 'timer' })) ownCommit();
790
+ return;
791
+ }
792
+ commitWatchTick();
793
+ }, gitMode === 'timer' ? commitEvery * 1000 : watchEveryMs).unref();
794
+ startup('git',
795
+ gitMode === 'timer'
796
+ ? `auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`
797
+ : 'commits on your word · snapshot on decklight/wip',
798
+ gitMode === 'timer'
799
+ ? ` git: auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`
800
+ : wipLine(deckRel));
325
801
  }
326
802
  }
803
+ /**
804
+ * One tick: refresh the snapshot, and decide whether to ask.
805
+ *
806
+ * Order matters. The snapshot is taken FIRST and unconditionally, because it
807
+ * is the safety net and must not depend on any nag rule being right. Only
808
+ * then is the question considered — and `planNag` answers it once per episode,
809
+ * so an ignored nag stays ignored instead of becoming a five-minute alarm.
810
+ */
811
+ function commitWatchTick() {
812
+ const d = measureDirty();
813
+ if (!d.dirty) { resetEpisode(); return; }
814
+ lastWip = snapshotWip(root, deckPath, deckRel) ?? lastWip;
815
+ if (planNag({ dirty: true, lines: dirtyLines, sinceMs: Date.now() - dirtySince, nagged, dismissed: nagDismissed })) {
816
+ nagged = true;
817
+ broadcast('commit', commitState());
818
+ console.log(` git: ${nagText({ lines: dirtyLines, sinceMs: Date.now() - dirtySince })}`
819
+ + ' — K in the deck commits it');
820
+ }
821
+ }
822
+
327
823
  const finalCommit = () => {
328
824
  if (!gitOn) return;
329
825
  // Not ownCommit: this runs inside the SIGINT handler and the process exits
330
826
  // immediately after, so there is no later for an amend to arrive in. The
331
827
  // bookend keeps its literal subject, which is true anyway.
332
- gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`);
828
+ if (gitMode === 'timer') {
829
+ gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`);
830
+ } else {
831
+ // Committing work you deliberately did not commit would be the cadence
832
+ // again, wearing an exit for a hat. The snapshot is refreshed instead —
833
+ // one last time, synchronously, so the newest bytes are safe — and the
834
+ // uncommitted work is NAMED on the way out rather than swallowed.
835
+ const d = deckDirty(root, deckRel);
836
+ if (d.dirty) {
837
+ snapshotWip(root, deckPath, deckRel);
838
+ console.log(` git: ${deckRel} has uncommitted changes — they are safe on`
839
+ + ` ${WIP_REF.replace('refs/', '')} (git show decklight/wip:${deckRel})`);
840
+ }
841
+ }
333
842
  // The last moment anyone is looking. Synchronous and fetch-free on purpose:
334
843
  // this runs inside the SIGINT handler, and a network call there would hang
335
844
  // a Ctrl-C — the worst possible place to hang.
@@ -344,11 +853,11 @@ export async function editMain(args) {
344
853
  // ── AI agents — one-shot editing tasks from the player (A) ─────────────
345
854
  // Precedence, like every other saved choice: the flag wins, then what was
346
855
  // remembered (#125), then the first detected agent.
347
- let agentPref = opt('--agent') ?? preferredAgent();
348
856
  const agents = detectAgents();
349
857
  if (agents.length) {
350
858
  const mark = (a) => a.name + (a.name === agentPref ? ' (preferred)' : '') + (a.installed ? ' (installed)' : '');
351
- console.log(` agents: ${agents.map(mark).join(', ')} — “Ask agent” (A) is live`);
859
+ startup('agents', agents.map(mark).join(', '),
860
+ ` agents: ${agents.map(mark).join(', ')} — “Ask agent” (A) is live`);
352
861
  }
353
862
  // A remembered agent that is not on this machine is said ONCE, at startup,
354
863
  // rather than discovered at the moment someone presses A mid-talk.
@@ -361,7 +870,9 @@ export async function editMain(args) {
361
870
  // git lines because it names the agent, and the roster is only resolved now.
362
871
  if (gitOn && wantMessages) {
363
872
  const who = agents.find((a) => a.name === agentPref) ?? agents[0];
364
- console.log(` ${messagesLine(who?.name ?? null)}`);
873
+ startup('git',
874
+ who?.name ? `${who.name} writes the subjects` : '--commit-messages needs an agent on PATH',
875
+ ` ${messagesLine(who?.name ?? null)}`);
365
876
  }
366
877
 
367
878
  // ── live reload: watch the deck, broadcast SSE (debounced — editors fire
@@ -490,7 +1001,15 @@ export async function editMain(args) {
490
1001
  };
491
1002
 
492
1003
  let pending = null;
493
- watch(deckPath, () => {
1004
+ // The DIRECTORY, not the file. A path watch follows the inode, and an
1005
+ // atomic write — temp file + rename, which is how an agent's editor and
1006
+ // most careful tools save — replaces the inode: the watcher then sits deaf
1007
+ // on the old one, and every later edit, restore included, reloads nobody.
1008
+ // Found in 0.7.0 manual testing as "restore worked but the deck kept
1009
+ // showing the old slides". A directory watch names the entry that changed
1010
+ // and survives any number of replacements.
1011
+ watch(dirname(deckPath), (kind, filename) => {
1012
+ if (filename && filename !== basename(deckPath)) return;
494
1013
  clearTimeout(pending);
495
1014
  pending = setTimeout(() => {
496
1015
  clients.raw('data: reload\n\n');
@@ -517,8 +1036,42 @@ export async function editMain(args) {
517
1036
  const child = spawn(cmd.bin, cmd.args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
518
1037
  let tail = '';
519
1038
  const keep = (chunk) => { tail = (tail + chunk).slice(-4000); };
520
- child.stdout.on('data', keep);
521
- child.stderr.on('data', keep);
1039
+ // The clue the chip shows. An agent run used to be a timer and nothing
1040
+ // else — ten minutes of "is it stuck?" with no way to tell. claude's
1041
+ // stream-json narrates every tool call, so those become activity events
1042
+ // on the same SSE channel the start/done events already ride; any other
1043
+ // agent gets its last non-empty stdout line, throttled, which is what a
1044
+ // person watching the terminal would glance at anyway.
1045
+ let resultText = null;
1046
+ let lastSaid = 0;
1047
+ const say = (text) => {
1048
+ if (!text || !agentJob) return;
1049
+ agentJob.activity = text; // /edit/ping carries it across a reload
1050
+ broadcast('agent', { state: 'activity', agent: cmd.name, text });
1051
+ console.log(` agent: ${text}`);
1052
+ };
1053
+ if (cmd.stream === 'claude-json') {
1054
+ let buf = '';
1055
+ child.stdout.on('data', (chunk) => {
1056
+ buf += chunk;
1057
+ for (let nl = buf.indexOf('\n'); nl !== -1; nl = buf.indexOf('\n')) {
1058
+ const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
1059
+ const clue = claudeActivity(line);
1060
+ if (clue?.activity) say(clue.activity);
1061
+ else if (clue?.result != null) resultText = clue.result;
1062
+ }
1063
+ });
1064
+ child.stderr.on('data', keep);
1065
+ } else {
1066
+ child.stdout.on('data', (chunk) => {
1067
+ keep(chunk);
1068
+ const now = Date.now();
1069
+ if (now - lastSaid < 800) return;
1070
+ const line = String(chunk).split('\n').map((l) => l.trim()).filter(Boolean).pop();
1071
+ if (line) { lastSaid = now; say(line.slice(0, 80)); }
1072
+ });
1073
+ child.stderr.on('data', keep);
1074
+ }
522
1075
  const timeout = setTimeout(() => child.kill('SIGTERM'), 10 * 60 * 1000);
523
1076
  child.on('error', (e) => {
524
1077
  clearTimeout(timeout);
@@ -537,12 +1090,35 @@ export async function editMain(args) {
537
1090
  const subject = commitSubject(message ?? prompt, `decklight: ${cmd.name} edited ${basename(deckPath)}`);
538
1091
  if (gitAutocommit(deckPath, root, subject)) console.log(` git: committed "${subject}"`);
539
1092
  }
1093
+ // Did the edit orphan, stale, or reshape a recording? A track is
1094
+ // minutes of somebody's own voice, and a whole-deck rewrite can drop the
1095
+ // config that plays it or the notes it reads with nothing on screen to
1096
+ // say so — this is where before/after both exist, so it is where the
1097
+ // word is said. A warning, never a block: the file is already written,
1098
+ // Z takes it back, and the audio never left the disk.
1099
+ let recordingWarning = null;
1100
+ if (changed) {
1101
+ try {
1102
+ const impact = recordingImpact(before, after, {
1103
+ dirsOf: configuredTrackDirs,
1104
+ recordedSlides: (dir) => {
1105
+ try { return slidesFromFiles(readdirSync(resolve(dirname(deckPath), dir))); }
1106
+ catch { return []; }
1107
+ },
1108
+ });
1109
+ recordingWarning = impactWarning(impact);
1110
+ } catch { recordingWarning = null; } // a warning that throws is worse than none
1111
+ }
540
1112
  agentJob = null;
541
1113
  broadcast('agent', {
542
1114
  state: 'done', agent: cmd.name, ok: code === 0, changed, code,
543
- tail: tail.trim().split('\n').slice(-6).join('\n').slice(-600),
1115
+ // the agent's own words when the stream carried them — raw stream-json
1116
+ // stdout is a wall of JSON nobody should be shown
1117
+ tail: (resultText ?? tail.trim().split('\n').slice(-6).join('\n')).slice(-600),
1118
+ ...(recordingWarning ? { recordingWarning } : {}),
544
1119
  });
545
1120
  console.log(` agent: ${cmd.name} exited (${code}) — deck ${changed ? 'changed' : 'unchanged'}`);
1121
+ if (recordingWarning) console.log(` ${recordingWarning}`);
546
1122
  });
547
1123
  return cmd;
548
1124
  }
@@ -583,7 +1159,37 @@ export async function editMain(args) {
583
1159
  preferredAgent: agentPref ?? null,
584
1160
  agentBusy: agentJob && { agent: agentJob.agent, prompt: agentJob.prompt, startedAt: agentJob.startedAt },
585
1161
  wizards: await configurableEngines(),
1162
+ // What is uncommitted, so a deck that loads mid-session shows the
1163
+ // chip without waiting for the next tick to broadcast one.
1164
+ commit: (gitOn && measureDirty(), commitState()),
1165
+ });
1166
+ }
1167
+ // ── committing on the author's word (SPEC PRESENTING) ─────────────────
1168
+ // What is uncommitted, right now. The overlay opens on this rather than
1169
+ // on whatever the last SSE event said, because K can be pressed at any
1170
+ // moment and a stale count is a lie about what you are agreeing to.
1171
+ if (req.method === 'GET' && url.pathname === '/edit/commit') {
1172
+ if (gitOn) measureDirty(); // the answer must be about NOW, not the last tick
1173
+ return json(200, { ok: true, ...commitState(), deck: deckRel });
1174
+ }
1175
+ // A subject for work that is not committed yet — the overlay's "write one
1176
+ // for me". Gated on the same permission as every other diff that leaves
1177
+ // the machine: no `--commit-messages`, no ask.
1178
+ if (req.method === 'POST' && url.pathname === '/edit/commit/subject') {
1179
+ if (!wantMessages) {
1180
+ return json(403, { ok: false, error: 'commit subjects are not enabled — decklight author --commit-messages' });
1181
+ }
1182
+ const subject = await describeWorking({
1183
+ cwd: root, deckPath, deckRel, agent: agentPref,
1184
+ template: `decklight: autosave ${basename(deckPath)}`,
586
1185
  });
1186
+ return json(200, { ok: true, subject: subject ?? null });
1187
+ }
1188
+ if (req.method === 'POST' && url.pathname === '/edit/commit/dismiss') {
1189
+ // Not the same as committing: the work stays uncommitted and the
1190
+ // snapshot keeps running. It only means "stop asking about THIS one".
1191
+ nagDismissed = true;
1192
+ return json(200, { ok: true, ...commitState() });
587
1193
  }
588
1194
  if (req.method === 'GET' && url.pathname === '/edit/events') {
589
1195
  clients.add(req, res, CORS);
@@ -670,7 +1276,7 @@ export async function editMain(args) {
670
1276
  console.log(` ${dir} → ${JSON.stringify(history.counts())}`);
671
1277
  return json(200, { ok: true, ...history.counts() });
672
1278
  }
673
- // ── ⇧V offline recordings (PRESENTING) ───────────────────────────────
1279
+ // ── the recorder's offline recordings — V → Record this deck… (PRESENTING) ───────────────────────────────
674
1280
  // The player used to hand every stitched slide to the browser's DOWNLOAD
675
1281
  // path, which is why a deck's voice arrived as thirty slide-NN.wav in
676
1282
  // whatever folder the OS calls Downloads — never the deck's, and on
@@ -687,6 +1293,17 @@ export async function editMain(args) {
687
1293
  const kind = url.searchParams.get('kind');
688
1294
  if (!Number.isInteger(slide) || slide < 1 || slide > 9999) return json(400, { ok: false, error: 'bad slide' });
689
1295
  if (kind !== 'wav' && kind !== 'visemes') return json(400, { ok: false, error: 'bad kind' });
1296
+ // `seg` is the per-⟨CLICK⟩ file number — the audio that lets a recording
1297
+ // step the builds (slide-NN-KK.wav) and the viseme timeline cut to
1298
+ // match it (slide-NN-KK.visemes.json). Absent means the whole slide.
1299
+ // Bounded and integral like `slide`, and for the same reason: it is
1300
+ // half of a filename this server builds, and the only defence that
1301
+ // survives someone deciding the name should be more flexible one day.
1302
+ const segRaw = url.searchParams.get('seg');
1303
+ const seg = segRaw == null ? null : Number(segRaw);
1304
+ if (seg !== null && (!Number.isInteger(seg) || seg < 1 || seg > 999)) {
1305
+ return json(400, { ok: false, error: 'bad seg' });
1306
+ }
690
1307
  // The player names the FOLDER (its own `narration.files`, so a recorded
691
1308
  // set lands where that deck already plays from) and nothing else: the
692
1309
  // file name is built here, so no request can choose one. The folder is
@@ -700,7 +1317,9 @@ export async function editMain(args) {
700
1317
  if (!dir || (!dir.startsWith(root + sep) && dir !== root)) {
701
1318
  return json(400, { ok: false, error: 'the recording folder must sit inside the deck\'s own directory' });
702
1319
  }
703
- const name = `slide-${String(slide).padStart(2, '0')}.${kind === 'wav' ? 'wav' : 'visemes.json'}`;
1320
+ const name = `slide-${String(slide).padStart(2, '0')}`
1321
+ + (seg === null ? '' : `-${String(seg).padStart(2, '0')}`)
1322
+ + `.${kind === 'wav' ? 'wav' : 'visemes.json'}`;
704
1323
  const chunks = [];
705
1324
  let size = 0;
706
1325
  for await (const chunk of req) {
@@ -719,6 +1338,277 @@ export async function editMain(args) {
719
1338
  if (req.method === 'POST') {
720
1339
  for await (const chunk of req) { body += chunk; if (body.length > 1e6) throw new Error('too large'); }
721
1340
  }
1341
+ // The commit the author asked for. The subject is THEIRS — typed, or an
1342
+ // agent's sentence they looked at and kept — so it goes through
1343
+ // `commitSubject` like every other message that reaches a command line
1344
+ // (one line, capped, never a leading `-`) and nothing else rewrites it:
1345
+ // `describeCommit`'s amend is for messages decklight authored, and this
1346
+ // one has an author.
1347
+ if (req.method === 'POST' && url.pathname === '/edit/commit') {
1348
+ if (!gitOn) return json(409, { ok: false, error: 'this session is not committing — start author with --git' });
1349
+ let msg = '';
1350
+ try { msg = String(JSON.parse(body || '{}').message ?? '').trim(); } catch { /* below */ }
1351
+ if (!msg) return json(400, { ok: false, error: 'a commit needs a message' });
1352
+ const subject = commitSubject(msg, `decklight: autosave ${basename(deckPath)}`);
1353
+ // gitAutocommit reports false for "nothing to commit", which is not an
1354
+ // error: it is the answer to pressing K twice.
1355
+ const made = gitAutocommit(deckPath, root, subject);
1356
+ if (!made) return json(200, { ok: true, committed: false, ...commitState() });
1357
+ resetEpisode();
1358
+ console.log(` git: committed ${deckRel} — "${subject}"`);
1359
+ return json(200, {
1360
+ ok: true, committed: true, subject, ...history.counts(), ...commitState(),
1361
+ });
1362
+ }
1363
+ // ── review comments (SPEC REVIEW) ─────────────────────────────
1364
+ // The author's side of `decklight review`. The same file, the same
1365
+ // append-only rule: this server may add a line (a resolve, a reply) and
1366
+ // may not rewrite one, because `merge=union` is what keeps two reviewers
1367
+ // from conflicting and an edit in place is what would break it.
1368
+ if (req.method === 'GET' && url.pathname === '/edit/review') {
1369
+ const store = reviewPathFor(deckPath);
1370
+ if (!existsSync(store)) return json(200, { ok: true, records: [], skipped: 0 });
1371
+ const { records, skipped } = parseReview(readFileSync(store, 'utf8'));
1372
+ return json(200, { ok: true, records, skipped });
1373
+ }
1374
+ // What reviews are waiting on the remote — the M overlay's incoming
1375
+ // section. This one is a fetch the author DID ask for: it runs behind
1376
+ // the keypress that just opened the overlay, on demand and nowhere else.
1377
+ // The 60s cache is what keeps a nervous author tapping M from turning
1378
+ // one gesture into a fetch storm; the off switches still win outright.
1379
+ if (req.method === 'GET' && url.pathname === '/edit/review/incoming') {
1380
+ // ci: false — this fetch is ASKED FOR, behind the keypress that
1381
+ // opened the overlay; only the explicit switches silence it.
1382
+ const skipped = reviewCheckSuppressed({ args, ci: false });
1383
+ if (skipped) return json(200, { ok: true, state: 'suppressed', reason: skipped, reviews: [] });
1384
+ if (!incomingCache || Date.now() - incomingCache.at > 60_000) {
1385
+ const r = await reviewsWaiting(deckPath);
1386
+ incomingCache = { at: Date.now(), r };
1387
+ }
1388
+ return json(200, { ok: true, ...incomingCache.r });
1389
+ }
1390
+ // What tracks already sit next to this deck. The runtime cannot see the
1391
+ // filesystem — which is why `segments: true` is opt-in at all — so it
1392
+ // cannot know that `voices/rachel` is taken before proposing it. One
1393
+ // question, asked when a recorder opens.
1394
+ if (req.method === 'GET' && url.pathname === '/edit/tracks') {
1395
+ const root2 = resolve(deckPath, '..');
1396
+ const seen = [];
1397
+ const look = (rel) => {
1398
+ let entries;
1399
+ try { entries = readdirSync(resolve(root2, rel), { withFileTypes: true }); } catch { return; }
1400
+ const wav = entries.filter((e) => e.isFile() && /^slide-\d+(-\d+)?\.(wav|m4a|mp3)$/.test(e.name));
1401
+ if (wav.length) {
1402
+ let engine = null; let voice = null;
1403
+ try {
1404
+ const m = JSON.parse(readFileSync(resolve(root2, rel, 'manifest.json'), 'utf8'));
1405
+ engine = m.engine ?? null; voice = m.voice ?? null;
1406
+ } catch { /* a folder recorded by hand has no manifest, and needs none */ }
1407
+ seen.push({
1408
+ dir: rel.split(sep).join('/'),
1409
+ files: wav.length,
1410
+ // the beats are what let a track pace the builds, so whether it
1411
+ // has them is the one fact worth reporting beside the count
1412
+ segments: wav.some((e) => /^slide-\d+-\d+\./.test(e.name)),
1413
+ ext: (wav[0].name.split('.').pop()),
1414
+ engine,
1415
+ voice,
1416
+ });
1417
+ }
1418
+ return entries;
1419
+ };
1420
+ for (const e of look('.') ?? []) {
1421
+ if (!e.isDirectory() || e.name.startsWith('.') || e.name === 'node_modules') continue;
1422
+ const kids = look(e.name) ?? [];
1423
+ // one more level, because the convention is voices/<voice>
1424
+ for (const k of kids) {
1425
+ if (k.isDirectory() && !k.name.startsWith('.')) look(`${e.name}${sep}${k.name}`);
1426
+ }
1427
+ }
1428
+ return json(200, { ok: true, tracks: seen });
1429
+ }
1430
+ // Point the deck at a track the recorder just wrote. The one manual step
1431
+ // in a flow that is otherwise a key and an arrow — and this server
1432
+ // already owns the file, so it can take that step too.
1433
+ if (req.method === 'GET' && url.pathname === '/edit/review/at') {
1434
+ // The orphan's context: what the slide SAID when the comment was
1435
+ // written — `comments --at`, served, so the overlay can put the dead
1436
+ // slide's prose under the objection that was about it. Read-only, all
1437
+ // local (the commit is already in this clone or the answer is "not
1438
+ // here"), and gated exactly as the CLI gates it.
1439
+ const id = url.searchParams.get('id') ?? '';
1440
+ if (!/^[a-z0-9]{1,12}$/.test(id)) return json(400, { ok: false, error: 'bad comment id' });
1441
+ const store = reviewPathFor(deckPath);
1442
+ if (!existsSync(store)) return json(404, { ok: false, error: 'no comments here' });
1443
+ const c = foldReview(parseReview(readFileSync(store, 'utf8')).records).find((x) => x.id === id);
1444
+ if (!c) return json(404, { ok: false, error: `no comment [${id}]` });
1445
+ if (!c.deck) return json(200, { ok: true, known: false, why: 'written outside a repository — there is no earlier version to show' });
1446
+ if (!gitOn || !knowsCommit(c.deck, root)) {
1447
+ return json(200, { ok: true, known: false, why: `this clone does not have ${c.deck}` });
1448
+ }
1449
+ try {
1450
+ const thenHtml = deckAt(deckPath, c.deck, root);
1451
+ const wasAt = indexDeckFile(thenHtml)[(c.slide ?? 0) - 1] ?? null;
1452
+ return json(200, {
1453
+ ok: true,
1454
+ known: true,
1455
+ deck: c.deck,
1456
+ slide: c.slide ?? null,
1457
+ title: wasAt?.title ?? null,
1458
+ text: slideTextOf(thenHtml, c.slide) || '',
1459
+ });
1460
+ } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1461
+ }
1462
+ if (req.method === 'POST' && url.pathname === '/edit/review/done') {
1463
+ // Mark ONE of a reviewer's comments done, or take the mark off. Their
1464
+ // comments live on their branch, which is not ours to write, so the
1465
+ // mark is kept in this clone's git config — private, never pushed.
1466
+ // Your OWN comments do not come through here at all: they already have
1467
+ // a way to be finished with, the append-only `resolve` record below,
1468
+ // which travels so the reviewer can see you dealt with their point.
1469
+ //
1470
+ // The branch is looked up in what the incoming reader LISTED, so it is
1471
+ // data here and never an argument; the id is shape-checked before it
1472
+ // becomes half of a config key.
1473
+ const { branch, id, done = true } = JSON.parse(body || '{}');
1474
+ const listed = incomingCache?.r?.reviews?.find((v) => v.branch === branch);
1475
+ if (!listed) return json(400, { ok: false, error: 'not a review this deck knows about — press M again to refresh' });
1476
+ if (!listed.records?.some((r) => r.id === id)) {
1477
+ return json(400, { ok: false, error: 'no such comment in that review' });
1478
+ }
1479
+ if (!setCommentDone(root, branch, id, !!done)) {
1480
+ return json(500, { ok: false, error: 'could not write the mark to git config' });
1481
+ }
1482
+ // the list just changed shape — the cache must not keep the old marks
1483
+ incomingCache = null;
1484
+ console.log(` review: ${branch} ${id} ${done ? 'marked done' : 'reopened'}`);
1485
+ return json(200, { ok: true, branch, id, done: !!done });
1486
+ }
1487
+ if (req.method === 'POST' && url.pathname === '/edit/review') {
1488
+ const { op, re, body: text, slide, title, fp } = JSON.parse(body || '{}');
1489
+ // A NEW comment — no `op`, no `re`. The author leaving one on their own
1490
+ // deck (⇧M), which until now only a `decklight review` server could
1491
+ // take: the composer was gated on one answering, so an author had to
1492
+ // start a second server on a second port, in a mode that would not let
1493
+ // them edit the slide they were commenting on.
1494
+ //
1495
+ // Same file, same append-only rule, same record shape — through
1496
+ // `commentProblem` and `reviewRecord`, which review.mjs already exports
1497
+ // and which are the arbiters of what a comment is. Two servers writing
1498
+ // two shapes into one union-merged file is how a store stops parsing.
1499
+ if (op === undefined && re === undefined) {
1500
+ const input = { body: text, slide, title, fp };
1501
+ const bad = commentProblem(input);
1502
+ if (bad) return json(400, { ok: false, error: bad });
1503
+ let deckAt = null;
1504
+ try { deckAt = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(); }
1505
+ catch { deckAt = null; }
1506
+ const rec = reviewRecord(input, {
1507
+ by: reviewerName(), at: new Date().toISOString(), deck: deckAt, id: newId(),
1508
+ });
1509
+ const store_ = reviewPathFor(deckPath);
1510
+ try { appendFileSync(store_, `${serializeRecord(rec)}\n`); }
1511
+ catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1512
+ if (gitOn) {
1513
+ gitAutocommit(store_, root,
1514
+ commitSubject(`review: ${rec.body}`, `review: a comment on ${basename(deckPath)}`));
1515
+ }
1516
+ console.log(` review: comment on slide ${rec.slide} → ${basename(store_)}`);
1517
+ return json(200, { ok: true, id: rec.id });
1518
+ }
1519
+ if (typeof re !== 'string' || !/^[a-z0-9]{1,12}$/.test(re)) {
1520
+ return json(400, { ok: false, error: 'bad comment id' });
1521
+ }
1522
+ if (op === 'anchor') {
1523
+ // moving a comment to the slide the author is looking at — the
1524
+ // reconciliation for a slide that was deleted or rewritten past
1525
+ // what fingerprint + title can find
1526
+ const n = Number(slide);
1527
+ if (!Number.isInteger(n) || n < 1 || n > 9999) return json(400, { ok: false, error: 'an anchor needs a slide' });
1528
+ if (title !== undefined && (typeof title !== 'string' || title.length > 500)) return json(400, { ok: false, error: 'bad title' });
1529
+ if (fp !== undefined && (typeof fp !== 'string' || !/^[0-9a-f]{1,16}$/.test(fp))) return json(400, { ok: false, error: 'bad fingerprint' });
1530
+ } else if (op !== 'resolve' && !(typeof text === 'string' && text.trim() && text.length <= 4000)) {
1531
+ return json(400, { ok: false, error: 'a reply needs something in it' });
1532
+ }
1533
+ const store = reviewPathFor(deckPath);
1534
+ // A reply is a new statement about the deck and carries which version it
1535
+ // was made against, exactly as a comment does. A resolve does not: it is
1536
+ // about the comment, not about the slide.
1537
+ let at = null;
1538
+ try { at = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(); }
1539
+ catch { at = null; }
1540
+ const rec = op === 'anchor'
1541
+ ? {
1542
+ op: 'anchor',
1543
+ re,
1544
+ slide: Number(slide),
1545
+ ...(title !== undefined ? { title } : {}),
1546
+ ...(fp !== undefined ? { fp } : {}),
1547
+ at: new Date().toISOString(),
1548
+ by: reviewerName(),
1549
+ }
1550
+ : op === 'resolve'
1551
+ ? { op: 'resolve', re, at: new Date().toISOString(), by: reviewerName() }
1552
+ : {
1553
+ id: newId(),
1554
+ at: new Date().toISOString(),
1555
+ by: reviewerName(),
1556
+ ...(at ? { deck: at } : {}),
1557
+ re,
1558
+ body: text,
1559
+ };
1560
+ try { appendFileSync(store, `${serializeRecord(rec)}\n`); }
1561
+ catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1562
+ if (gitOn) {
1563
+ gitAutocommit(store, root, op === 'anchor'
1564
+ ? commitSubject(`review: move ${re} to slide ${rec.slide}`, 'review: re-anchor a comment')
1565
+ : op === 'resolve'
1566
+ ? commitSubject(`review: resolve ${re}`, 'review: resolve a comment')
1567
+ : commitSubject(`review: reply to ${re}`, 'review: a reply'));
1568
+ }
1569
+ console.log(` review: ${op === 'anchor' ? `moved ${re} to slide ${rec.slide}`
1570
+ : op === 'resolve' ? `resolved ${re}` : `replied to ${re}`}`);
1571
+ return json(200, { ok: true });
1572
+ }
1573
+ if (req.method === 'POST' && url.pathname === '/edit/narration') {
1574
+ const { files, ext, segments } = JSON.parse(body || '{}');
1575
+ // The same three shapes /edit/record refuses for a folder, refused
1576
+ // again here: this one is written INTO the deck, where a bad value is
1577
+ // not a failed request but a deck that no longer plays.
1578
+ if (typeof files !== 'string' || !files.trim() || files.length > 200
1579
+ || /^[/\\]/.test(files) || /^[a-zA-Z]:/.test(files)
1580
+ || files.split(/[/\\]/).includes('..')) {
1581
+ return json(400, { ok: false, error: 'bad narration folder' });
1582
+ }
1583
+ if (ext !== undefined && !/^[a-z0-9]{1,5}$/.test(String(ext))) {
1584
+ return json(400, { ok: false, error: 'bad ext' });
1585
+ }
1586
+ if (segments !== undefined && typeof segments !== 'boolean') {
1587
+ return json(400, { ok: false, error: 'bad segments' });
1588
+ }
1589
+ const { label } = JSON.parse(body || '{}');
1590
+ if (label !== undefined && (typeof label !== 'string' || label.length > 120)) {
1591
+ return json(400, { ok: false, error: 'bad label' });
1592
+ }
1593
+ // upsert, never replace: a deck carries as many tracks as you have
1594
+ // voices, and writing one must not throw the others away
1595
+ const next = upsertNarrationTrack(readDeck(), {
1596
+ label: label || files.trim(),
1597
+ dir: files.trim(),
1598
+ ...(ext === undefined ? {} : { ext }),
1599
+ ...(segments === undefined ? {} : { segments }),
1600
+ });
1601
+ if (next === null) {
1602
+ // Not a failure of this server — a deck whose config is built
1603
+ // somewhere else. Say which, so the answer is "paste this line",
1604
+ // not "it did not work".
1605
+ return json(409, { ok: false,
1606
+ error: 'this deck builds its config outside the Decklight.init(…) call, so there is no literal here to edit' });
1607
+ }
1608
+ const changed = applyEdit(next);
1609
+ if (changed) console.log(` narration: ${files} in the deck's config`);
1610
+ return json(200, { ok: true, changed, ...history.counts() });
1611
+ }
722
1612
  if (req.method === 'POST' && url.pathname === '/edit/restore') {
723
1613
  if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
724
1614
  const { ref } = JSON.parse(body || '{}');
@@ -879,6 +1769,16 @@ export async function editMain(args) {
879
1769
  console.log(` notes saved: slide ${slide} (${text.length} chars)`);
880
1770
  return json(200, { ok: true, ...history.counts() });
881
1771
  }
1772
+ if (req.method === 'POST' && url.pathname === '/edit/timings') {
1773
+ // every slide's rehearsed time in ONE edit — one undo entry, one commit
1774
+ const { timings } = JSON.parse(body);
1775
+ if (!Array.isArray(timings) || !timings.every((t) => Number.isInteger(t?.slide) && t.slide >= 1 && Number.isFinite(t?.seconds))) throw new Error('bad payload');
1776
+ let next = readDeck();
1777
+ for (const t of timings) next = setSlideTiming(next, t.slide, t.seconds);
1778
+ const changed = applyEdit(next);
1779
+ if (changed) console.log(` rehearsal timings saved: ${timings.length} slides`);
1780
+ return json(200, { ok: true, changed, ...history.counts() });
1781
+ }
882
1782
  if (req.method === 'POST' && url.pathname === '/edit/layout') {
883
1783
  const { slide, layout } = JSON.parse(body);
884
1784
  if (!Number.isInteger(slide) || slide < 1 || typeof layout !== 'string') throw new Error('bad payload');
@@ -886,6 +1786,13 @@ export async function editMain(args) {
886
1786
  if (changed) console.log(` layout saved: slide ${slide} → ${layout}`);
887
1787
  return json(200, { ok: true, changed, ...history.counts() });
888
1788
  }
1789
+ if (req.method === 'POST' && url.pathname === '/edit/hidden') {
1790
+ const { slide, hidden } = JSON.parse(body);
1791
+ if (!Number.isInteger(slide) || slide < 1 || typeof hidden !== 'boolean') throw new Error('bad payload');
1792
+ const changed = applyEdit(setSlideHidden(readDeck(), slide, hidden));
1793
+ if (changed) console.log(` slide ${slide} ${hidden ? 'hidden' : 'shown again'}`);
1794
+ return json(200, { ok: true, changed, ...history.counts() });
1795
+ }
889
1796
  // ── element edit mode (E, right-click a slide element) — #112 ─────
890
1797
  // Same door as layout/notes: a pure (html, slide, index, …) → html
891
1798
  // transform, through applyEdit, onto the ONE undo/redo stack.
@@ -949,7 +1856,41 @@ export async function editMain(args) {
949
1856
  });
950
1857
 
951
1858
  const actual = await listenTakingOverIfNeeded(server, port, host);
952
- console.log(`decklight author on http://127.0.0.1:${actual}${deckUrl} — E element edit mode, L layouts, Z undo, A agent. Ctrl-C stops`);
1859
+ // `decklight record` runs this same server in-process and needs to know
1860
+ // WHICH port it ended up on (a taken --port moves to the next free one) and
1861
+ // to print its own banner instead of the authoring one.
1862
+ if (onListen) onListen({ port: actual, deckUrl, server });
1863
+ else if (process.env.DECKLIGHT_BANNER) {
1864
+ // The port is reported rather than assumed: `listenTakingOverIfNeeded` can
1865
+ // land somewhere other than the port author resolved, and the URL on the
1866
+ // banner has to be the one that actually answers.
1867
+ console.log(readyLine({
1868
+ url: `http://127.0.0.1:${actual}${deckUrl}`,
1869
+ keys: 'E edit · L layouts · Z undo · A agent · Ctrl-C stops',
1870
+ }));
1871
+ } else console.log(`decklight author on http://127.0.0.1:${actual}${deckUrl} — E element edit mode, L layouts, Z undo, A agent. Ctrl-C stops`);
1872
+
1873
+ // Did somebody review this deck? Asked ONCE, after the last startup line,
1874
+ // detached and never awaited — the update-check shape: nothing about it can
1875
+ // delay the server coming up or hang authoring on a remote that is down. It
1876
+ // is a fetch the author did not type, which is why it is the sanctioned
1877
+ // exception cli/git.mjs names, why it is never on a timer, and why it is
1878
+ // nowhere near the SIGINT path (finalCommit above says what lives there and
1879
+ // why nothing else may).
1880
+ if (!onListen) {
1881
+ const skipped = reviewCheckSuppressed({ args });
1882
+ if (skipped) {
1883
+ startup('reviews', `not checked — ${skipped}`, ` reviews: not checked — ${skipped}`);
1884
+ } else {
1885
+ reviewsWaiting(deckPath)
1886
+ .then((r) => {
1887
+ const line = reviewLine(r, { deck: relative(process.cwd(), deckPath) || basename(deckPath) });
1888
+ if (line) startup('reviews', line.replace(/^reviews:\s*/, ''), ` ${line}`);
1889
+ })
1890
+ .catch(() => {});
1891
+ }
1892
+ }
1893
+ return { port: actual, deckUrl, host, server };
953
1894
  }
954
1895
 
955
1896