decklight 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +16 -8
  2. package/SPEC.md +166 -10
  3. package/cli/agents.mjs +52 -2
  4. package/cli/banner.mjs +125 -0
  5. package/cli/bundle.mjs +14 -4
  6. package/cli/{rec.mjs → cast.mjs} +25 -8
  7. package/cli/comments.mjs +389 -0
  8. package/cli/commit-flow.mjs +157 -0
  9. package/cli/commit-message.mjs +125 -0
  10. package/cli/decklight.mjs +88 -25
  11. package/cli/dev.mjs +159 -13
  12. package/cli/edit.mjs +927 -39
  13. package/cli/git-tree.mjs +87 -0
  14. package/cli/git.mjs +22 -0
  15. package/cli/init.mjs +37 -5
  16. package/cli/port-conflict.mjs +187 -16
  17. package/cli/publish.mjs +15 -40
  18. package/cli/record.mjs +154 -0
  19. package/cli/review-remote.mjs +330 -0
  20. package/cli/review-store.mjs +107 -0
  21. package/cli/review-submit.mjs +292 -0
  22. package/cli/review.mjs +361 -0
  23. package/cli/serve.mjs +36 -1
  24. package/cli/skill-content.mjs +3 -1
  25. package/cli/units.mjs +2 -2
  26. package/cli/util.mjs +59 -0
  27. package/dist/build-info.json +1 -0
  28. package/dist/decklight.css +244 -1
  29. package/dist/decklight.js +102 -79
  30. package/dist/decklight.js.map +4 -4
  31. package/docs/architecture.svg +7 -0
  32. package/package.json +2 -1
  33. package/tools/args.mjs +20 -0
  34. package/tools/deck-html.mjs +50 -0
  35. package/tools/elevenlabs-tts.mjs +1 -1
  36. package/tools/lipsync-server.mjs +64 -2
  37. package/tools/lipsync.mjs +40 -24
  38. package/tools/local-voice.mjs +170 -16
  39. package/tools/publish-voices.mjs +78 -18
  40. package/tools/recording-impact.mjs +110 -0
  41. package/tools/review-anchor.mjs +180 -0
  42. package/tools/test-impact.mjs +259 -0
  43. package/tools/tts-engines.mjs +26 -4
  44. package/tools/tts-setup.mjs +1 -1
  45. package/tools/video.mjs +15 -3
  46. package/tools/voiceover-server.mjs +167 -7
  47. package/tools/voiceover.mjs +30 -1
package/cli/edit.mjs CHANGED
@@ -46,15 +46,41 @@
46
46
  // `decklight author` asks interactively before passing --git down.
47
47
 
48
48
  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';
49
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, appendFileSync, watch, existsSync } from 'node:fs';
50
+ import { resolve, relative, dirname, sep, basename } from 'node:path';
51
+ import { spawn, execFileSync } from 'node:child_process';
52
+ import { agentCommand, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent, claudeActivity } from './agents.mjs';
53
53
  import { exitWhenOrphaned } from './supervise.mjs';
54
- import { argReader, isMain } from '../tools/args.mjs';
54
+ import { readyLine } from './banner.mjs';
55
+
56
+ /**
57
+ * Say a startup fact.
58
+ *
59
+ * Under author (DECKLIGHT_BANNER) it becomes a row on the one banner author
60
+ * prints, so it cannot land above the URL. Run standalone — `decklight edit` —
61
+ * it prints the line it always printed, which is why every call passes both:
62
+ * the SHORT text a banner row wants, and the full sentence a bare terminal
63
+ * needs because it has no banner to sit under.
64
+ */
65
+ const startup = (key, text, human) => {
66
+ if (process.env.DECKLIGHT_BANNER) console.log(readyLine({ key, text }));
67
+ else console.log(human);
68
+ };
69
+ import { argReader, firstPositional, isMain } from '../tools/args.mjs';
55
70
  import { NOTES_ASIDE, locateSlide, sectionChildRanges } from '../tools/deck-html.mjs';
71
+ // the boot-call locator audit and upgrade share — three commands, one answer
72
+ // about which <script> is the init call
73
+ import { classifyScripts } from './audit.mjs';
74
+ import { reviewPathFor, parseReview, serializeRecord, newId } from './review-store.mjs';
75
+ // The arbiters of what a comment IS, shared with the review server so two
76
+ // writers cannot put two shapes into one union-merged file.
77
+ import { commentProblem, reviewRecord } from './review.mjs';
78
+ import { foldReview } from '../tools/review-anchor.mjs';
79
+ import { recordingImpact, impactWarning, slidesFromFiles } from '../tools/recording-impact.mjs';
80
+ import { indexDeckFile, slideTextOf, knowsCommit } from './comments.mjs';
56
81
  import { deckHistory, decorateHistory, restoreDeck, deckAt, withBaseHref } from './restore.mjs';
57
82
  import { escapeHtml, sseChannel, staticFiles, listenTakingOverIfNeeded, allowEditRequest } from './serve.mjs';
83
+ import { reviewsWaiting, reviewLine, reviewCheckSuppressed, setCommentDone } from './review-remote.mjs';
58
84
  import { configureEngine, loadCredentials, forgetCredentials, redactAnswers, validateSchema, provenance, BRIDGE_ADDR, CONFIGURED, UNREACHABLE, PREREQUISITE } from './wizard.mjs';
59
85
 
60
86
  // The `/edit/*` surface answers loopback only — but "loopback" is the wrong
@@ -144,6 +170,305 @@ export function setSlideElementHtml(html, slide, index, outerHtml) {
144
170
  // The spec's 7 entrance styles (MOTION), plus 'none' — an explicit, instant
145
171
  // build step, distinct from having no data-build attribute at all: one more
146
172
  // advance still reveals the element, it just has no animation.
173
+ /**
174
+ * Skip one JS string literal starting at `i` (which is its quote). Returns the
175
+ * index of the closing quote, or the end of the text if it never closes.
176
+ *
177
+ * The whole reason the walkers below are walkers and not regexes: a config
178
+ * carrying `{ alt: "Acme (Inc)" }` or `{ title: "a } b" }` closes nothing, and
179
+ * a regex counting brackets reads both as structure. `cli/audit.mjs` learned
180
+ * this first (isBootCall); this is the same rule applied to the object.
181
+ */
182
+ function skipString(text, i) {
183
+ const q = text[i];
184
+ for (i++; i < text.length && text[i] !== q; i++) if (text[i] === '\\') i++;
185
+ return i;
186
+ }
187
+
188
+ /**
189
+ * Skip one JS comment starting at `i` (which is its `/`). Returns the index of
190
+ * the comment's last character, or `i` unchanged when this `/` is not a
191
+ * comment at all (division, a lone slash in whatever).
192
+ *
193
+ * The walkers below skip strings and skipped nothing else — so a deck whose
194
+ * boot call carried a commented-out earlier track (`// narration: { files:
195
+ * 'old' }` — exactly what an author leaves behind) had that key
196
+ * FOUND, the splice landed inside the comment, and the UI said ✓ while the
197
+ * deck played nothing. An unbalanced `)` in a comment likewise ended
198
+ * initArgument's span early, and a splice into a truncated span corrupts the
199
+ * file rather than missing it.
200
+ */
201
+ function skipComment(text, i) {
202
+ if (text[i] !== '/') return i;
203
+ if (text[i + 1] === '/') {
204
+ const nl = text.indexOf('\n', i + 2);
205
+ return nl === -1 ? text.length : nl;
206
+ }
207
+ if (text[i + 1] === '*') {
208
+ const end = text.indexOf('*/', i + 2);
209
+ return end === -1 ? text.length : end + 1;
210
+ }
211
+ return i;
212
+ }
213
+
214
+ /**
215
+ * The `Decklight.init(…)` argument in `html`: where it starts and ends.
216
+ *
217
+ * Located through the same classifier `audit` and `upgrade` use, so all three
218
+ * agree on which `<script>` is the boot call rather than each finding its own.
219
+ * Returns null when the deck has no boot call at all.
220
+ */
221
+ export function initArgument(html) {
222
+ const boot = classifyScripts(html).find((b) => b.kind === 'boot');
223
+ if (!boot) return null;
224
+ const inner = html.slice(boot.start, boot.end);
225
+ const m = /Decklight\s*\.\s*init\s*\(/.exec(inner);
226
+ if (!m) return null;
227
+ const open = m.index + m[0].length - 1;
228
+ let depth = 0;
229
+ for (let i = open; i < inner.length; i++) {
230
+ const c = inner[i];
231
+ if (c === '"' || c === "'" || c === '`') { i = skipString(inner, i); continue; }
232
+ if (c === '/') { const j = skipComment(inner, i); if (j !== i) { i = j; continue; } }
233
+ if (c === '(') depth++;
234
+ else if (c === ')' && --depth === 0) {
235
+ return { start: boot.start + open + 1, end: boot.start + i };
236
+ }
237
+ }
238
+ return null;
239
+ }
240
+
241
+ /**
242
+ * Where a TOP-LEVEL key's value sits inside an object literal, or null.
243
+ *
244
+ * Depth-aware and string-aware: a `narration:` nested inside `character: {…}`
245
+ * is not this object's key, and `{ note: "narration: off" }` is not a key at
246
+ * all. Both are things a plausible deck contains.
247
+ */
248
+ function objectKey(obj, key) {
249
+ const re = new RegExp(`^${key}\\s*:`);
250
+ let depth = 0;
251
+ for (let i = 0; i < obj.length; i++) {
252
+ const c = obj[i];
253
+ if (c === '"' || c === "'" || c === '`') { i = skipString(obj, i); continue; }
254
+ if (c === '/') { const j = skipComment(obj, i); if (j !== i) { i = j; continue; } }
255
+ if (c === '{' || c === '[' || c === '(') { depth++; continue; }
256
+ if (c === '}' || c === ']' || c === ')') { depth--; continue; }
257
+ if (depth !== 1) continue;
258
+ // The boundary is checked against the PREVIOUS character, not folded into
259
+ // the regex: `^` matches the start of every slice, so the old
260
+ // `(^|[{,\\s])` form let `mynarration:` match at its own `n`.
261
+ if (i > 0 && !/[{,\s]/.test(obj[i - 1])) continue;
262
+ const m = re.exec(obj.slice(i, i + key.length + 2));
263
+ if (!m) continue;
264
+ // the value runs to the comma or closing brace at THIS depth
265
+ let j = i + m[0].length;
266
+ let d = 0;
267
+ for (; j < obj.length; j++) {
268
+ const v = obj[j];
269
+ if (v === '"' || v === "'" || v === '`') { j = skipString(obj, j); continue; }
270
+ if (v === '/') { const k2 = skipComment(obj, j); if (k2 !== j) { j = k2; continue; } }
271
+ if (v === '{' || v === '[' || v === '(') d++;
272
+ else if (v === '}' || v === ']' || v === ')') { if (d === 0) break; d--; }
273
+ else if (v === ',' && d === 0) break;
274
+ }
275
+ return { from: i, to: j, valueFrom: i + m[0].length };
276
+ }
277
+ return null;
278
+ }
279
+
280
+ /**
281
+ * The span of each top-level element of an array literal, `[` … `]` included
282
+ * in the input. String- and depth-aware for the same reason everything else
283
+ * here is: `[{ label: 'a, b' }]` is one element, not two.
284
+ */
285
+ function arrayEntries(arr) {
286
+ const out = [];
287
+ let depth = 0;
288
+ let start = -1;
289
+ for (let i = 0; i < arr.length; i++) {
290
+ const c = arr[i];
291
+ if (c === '"' || c === "'" || c === '`') { i = skipString(arr, i); continue; }
292
+ if (c === '/') { const j = skipComment(arr, i); if (j !== i) { i = j; continue; } }
293
+ if (c === '{' || c === '[' || c === '(') {
294
+ if (depth === 1 && start === -1) start = i;
295
+ depth++;
296
+ continue;
297
+ }
298
+ if (c === '}' || c === ']' || c === ')') {
299
+ depth--;
300
+ if (depth === 1 && start !== -1) { out.push({ from: start, to: i + 1 }); start = -1; }
301
+ continue;
302
+ }
303
+ if (depth === 1 && start === -1 && !/[\s,]/.test(c)) start = i;
304
+ if (depth === 1 && start !== -1 && c === ',') { out.push({ from: start, to: i }); start = -1; }
305
+ }
306
+ if (start !== -1) out.push({ from: start, to: arr.lastIndexOf(']') });
307
+ return out;
308
+ }
309
+
310
+ /** `{ files: 'voiceover', ext: 'wav', segments: true }`, as a person writes it. */
311
+ export function narrationLiteral(cfg) {
312
+ const parts = [];
313
+ for (const [k, v] of Object.entries(cfg)) {
314
+ if (v === undefined || v === null) continue;
315
+ parts.push(`${k}: ${typeof v === 'string' ? `'${v.replace(/'/g, "\\'")}'` : v}`);
316
+ }
317
+ return `{ ${parts.join(', ')} }`;
318
+ }
319
+
320
+ /**
321
+ * Point the deck's own config at a track that was just recorded.
322
+ *
323
+ * The recorder writes the files and then had to ask you to paste a config line
324
+ * into the deck by hand — the one manual step in a flow that is otherwise a
325
+ * key and an arrow. The author server already owns this file (it writes notes,
326
+ * layouts and element edits), so it can write this too, through the same
327
+ * applyEdit door: Z undoes it, live-reload shows it.
328
+ *
329
+ * Returns the new HTML, or **null when the config is not a literal at the call
330
+ * site** — `const cfg = {…}; Decklight.init(cfg)` has nothing here to edit, and
331
+ * guessing which `cfg` is meant, in which scope, is how an editor corrupts a
332
+ * file. That deck keeps the printed line and is told why.
333
+ */
334
+ /** `{ label: 'Rachel · ElevenLabs', dir: 'voices/rachel', ext: 'wav' }` */
335
+ export function trackLiteral(track) {
336
+ return narrationLiteral(track);
337
+ }
338
+
339
+ /**
340
+ * Add a recorded track to the deck's `narration.files`, or update it in place.
341
+ *
342
+ * ADD, not replace. A deck can carry as many tracks as you have voices — four
343
+ * cloned ones, the system voice, two takes of your own — and `N` is the
344
+ * switcher. Replacing the key (which is what this did when it only knew how to
345
+ * write one) threw the others away the first time somebody recorded a second
346
+ * voice, which is exactly when a multi-track deck exists.
347
+ *
348
+ * A track already listed under the same `dir` is UPDATED rather than added
349
+ * twice: re-recording into a folder should refresh what the deck says about
350
+ * it, not leave the picker showing the same folder twice.
351
+ *
352
+ * The one-string form (`files: 'voiceover'`, with `ext`/`segments` beside it)
353
+ * becomes a one-element list carrying those same keys — the shape
354
+ * `narrationTracks()` already normalises it to internally, so the deck plays
355
+ * identically before and after.
356
+ *
357
+ * Returns the new HTML, or null when there is no literal here to edit.
358
+ */
359
+ /**
360
+ * The local track directories a deck's `narration.files` names, in order.
361
+ *
362
+ * A directory track is a folder of recorded audio; a `manifest`/cloud entry
363
+ * has no local `dir` and is not one. Uses the same init walkers upsert does,
364
+ * so it reads exactly the config the deck actually runs — the `files: 'x'`
365
+ * one-string form counts too. Returns `[]` for a deck with no narration, a
366
+ * config built outside the call, or a manifest-only track.
367
+ */
368
+ export function configuredTrackDirs(html) {
369
+ const arg = initArgument(html);
370
+ if (!arg) return [];
371
+ const raw = html.slice(arg.start, arg.end);
372
+ const open = raw.indexOf('{');
373
+ if (open === -1 || raw.slice(0, open).trim()) return [];
374
+ const obj = raw.slice(open, raw.lastIndexOf('}') + 1);
375
+ const narr = objectKey(obj, 'narration');
376
+ if (!narr) return [];
377
+ const nval = obj.slice(narr.valueFrom, narr.to).trim();
378
+ if (!nval.startsWith('{')) return [];
379
+ const files = objectKey(nval, 'files');
380
+ if (!files) return [];
381
+ const fval = nval.slice(files.valueFrom, files.to).trim();
382
+ const dirs = [];
383
+ if (fval.startsWith('[')) {
384
+ for (const e of arrayEntries(fval)) {
385
+ const entry = fval.slice(e.from, e.to);
386
+ // a `dir` names a folder; a `manifest` entry is cloud and has none
387
+ const m = /\bdir\s*:\s*(['"`])([^'"`]*)\1/.exec(entry);
388
+ if (m && !/\bmanifest\s*:/.test(entry)) dirs.push(m[2]);
389
+ }
390
+ } else {
391
+ // the one-string form: files: 'voiceover'
392
+ const m = /^(['"`])([^'"`]*)\1$/.exec(fval);
393
+ if (m) dirs.push(m[2]);
394
+ }
395
+ return dirs;
396
+ }
397
+
398
+ export function upsertNarrationTrack(html, track) {
399
+ const arg = initArgument(html);
400
+ if (!arg) return null;
401
+ const raw = html.slice(arg.start, arg.end);
402
+ const splice = (from, to, text) => html.slice(0, from) + text + html.slice(to);
403
+ const one = narrationLiteral(track);
404
+
405
+ // no config object at the call site at all
406
+ if (!raw.trim()) return splice(arg.start, arg.end, `{ narration: { files: [${one}] } }`);
407
+ const open = raw.indexOf('{');
408
+ if (open === -1 || raw.slice(0, open).trim()) return null;
409
+ const close = raw.lastIndexOf('}');
410
+ if (close < open) return null;
411
+ const obj = raw.slice(open, close + 1);
412
+ const at = arg.start + open;
413
+
414
+ const narr = objectKey(obj, 'narration');
415
+ if (!narr) {
416
+ const inner = obj.slice(1, -1);
417
+ const body = inner.trim()
418
+ ? `{ narration: { files: [${one}] },${inner.replace(/^\s*\n?/, inner.includes('\n') ? '\n' : ' ')}}`
419
+ : `{ narration: { files: [${one}] } }`;
420
+ return splice(at, arg.start + close + 1, body);
421
+ }
422
+
423
+ const nval = obj.slice(narr.valueFrom, narr.to).trim();
424
+ const nvalAt = at + narr.valueFrom + (obj.slice(narr.valueFrom, narr.to).length - obj.slice(narr.valueFrom, narr.to).trimStart().length);
425
+ if (!nval.startsWith('{')) return null; // narration built elsewhere
426
+
427
+ const files = objectKey(nval, 'files');
428
+ if (!files) {
429
+ const inner = nval.slice(1, -1);
430
+ const body = inner.trim() ? `{ files: [${one}],${inner.replace(/^\s*/, ' ')}}` : `{ files: [${one}] }`;
431
+ return splice(nvalAt, nvalAt + nval.length, body);
432
+ }
433
+
434
+ const fval = nval.slice(files.valueFrom, files.to).trim();
435
+ const fvalStart = nvalAt + nval.indexOf(fval, files.valueFrom);
436
+
437
+ // already a list: update the entry naming this folder, else append
438
+ if (fval.startsWith('[')) {
439
+ const entries = arrayEntries(fval);
440
+ const same = entries.find((e) => {
441
+ const m = /\bdir\s*:\s*(['"`])([^'"`]*)\1/.exec(fval.slice(e.from, e.to));
442
+ return m && m[2] === track.dir;
443
+ });
444
+ if (same) return splice(fvalStart + same.from, fvalStart + same.to, one);
445
+ const closeAt = fval.lastIndexOf(']');
446
+ const body = entries.length ? `,\n ${one}\n ` : one;
447
+ return splice(fvalStart + closeAt, fvalStart + closeAt, body);
448
+ }
449
+
450
+ // the one-string form: carry it across as the first entry, keys and all
451
+ const m = /^(['"`])([^'"`]*)\1$/.exec(fval);
452
+ if (!m) return null;
453
+ const kept = { label: m[2], dir: m[2] };
454
+ for (const k of ['ext', 'segments']) {
455
+ const found = objectKey(nval, k);
456
+ if (!found) continue;
457
+ const v = nval.slice(found.valueFrom, found.to).trim();
458
+ kept[k] = v === 'true' ? true : v === 'false' ? false : v.replace(/^['"`]|['"`]$/g, '');
459
+ }
460
+ const list = kept.dir === track.dir ? [one] : [narrationLiteral(kept), one];
461
+ // the sibling ext/segments moved INTO the entry they described, so they must
462
+ // not stay behind saying it about every track
463
+ const rest = [];
464
+ for (const [k, span] of ['liveUrl', 'character', 'engine', 'voice', 'style']
465
+ .map((k) => [k, objectKey(nval, k)]).filter(([, v]) => v)) {
466
+ rest.push(nval.slice(span.from, span.to).trim().replace(/,$/, ''));
467
+ }
468
+ const body = `{ files: [\n ${list.join(',\n ')}\n ]${rest.length ? `, ${rest.join(', ')}` : ''} }`;
469
+ return splice(nvalAt, nvalAt + nval.length, body);
470
+ }
471
+
147
472
  export const BUILD_EFFECTS = ['fade', 'fade-up', 'fade-down', 'zoom', 'pop', 'draw', 'highlight', 'none'];
148
473
 
149
474
  /**
@@ -198,10 +523,25 @@ export function createHistory(limit = 200) {
198
523
  // re-exported so long-standing importers (init, the tests) keep finding it
199
524
  // where edit grew it.
200
525
  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';
526
+ import {
527
+ describeCommit, describeWorking, messagesLine, rememberPref, storedPref,
528
+ } from './commit-message.mjs';
529
+ import { WIP_REF, deckDirty, nagText, planNag, snapshotWip, wipLine } from './commit-flow.mjs';
202
530
  export { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit };
203
531
 
204
- export async function editMain(args) {
532
+ /** Who the author is, from git's own answer — see cli/review.mjs. */
533
+ function reviewerName(cwd = process.cwd()) {
534
+ const cfg = (key) => {
535
+ try { return execFileSync('git', ['config', key], { cwd, encoding: 'utf8' }).trim(); } catch { return ''; }
536
+ };
537
+ const name = cfg('user.name');
538
+ const email = cfg('user.email');
539
+ return (name && email) ? `${name} <${email}>` : (name || email || '');
540
+ }
541
+
542
+ export async function editMain(args, { onListen = null } = {}) {
543
+ // /edit/review/incoming's answer, briefly remembered (see the route).
544
+ let incomingCache = null;
205
545
  if (args.includes('--help') || args.includes('-h') || !args.filter((a) => !a.startsWith('-')).length) {
206
546
  console.log(`usage: node cli/edit.mjs <deck.html> [--port 8788] [--git | --no-git]
207
547
  [--commit-every <seconds>] [--agent <name>] [--commit-messages]
@@ -210,16 +550,28 @@ export async function editMain(args) {
210
550
  element edit mode (E, then right-click an element), undo/redo (Z/⇧Z), agent asks (A)
211
551
  a taken --port offers to take over that session (on a TTY) or moves on to
212
552
  the next free one
213
- --git auto-commit the deck on a regular basis (creates the repo if needed)
553
+ --git keep the deck in git (creates the repo if needed): a silent
554
+ snapshot on refs/decklight/wip, and K commits when you say so
214
555
  --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]
556
+ --commit-every N cadence in seconds, timer mode only [300]
557
+ --git-mode M agent one commit per agent edit, plus whatever K commits
558
+ timer the old five-minute cadence, bookends included
559
+ off never commit [agent]
218
560
  --agent <name> preferred AI agent for A (default: first one detected)
219
561
  the server binds 127.0.0.1 only; for a phone remote use decklight present`);
220
562
  return;
221
563
  }
222
564
  const { opt } = argReader(args);
565
+
566
+ // DECLARED HERE, not down with the rest of the agent wiring, because
567
+ // `ownCommit` closes over it and editMain CALLS ownCommit synchronously —
568
+ // the opening commit, taken when git has never seen this deck. Left where it
569
+ // reads better, that call ran while this binding was still in its temporal
570
+ // dead zone and `decklight author` died on a ReferenceError before the
571
+ // server ever came up. It needed both halves to show: a deck git does not
572
+ // know, and commit-messages on (only that path reads `agentPref`), which is
573
+ // why adding a SECOND deck to a repo was the way to find it.
574
+ let agentPref = opt('--agent') ?? preferredAgent();
223
575
  const port = Number(opt('--port', 8788));
224
576
  // Refused out loud, not ignored (PRESENT#REMOTE). Someone typing --remote
225
577
  // wants a clicker; silently binding loopback would leave them holding a phone
@@ -231,13 +583,13 @@ export async function editMain(args) {
231
583
  console.error(' A clicker used to cost you an editing server on the LAN: /edit/notes, /edit/layout and');
232
584
  console.error(' /edit/agent were reachable from the same run you were not watching. present has no edit');
233
585
  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`);
586
+ console.error(`\n decklight present ${firstPositional(args, ['--port', '--commit-every', '--agent']) ?? '<deck.html>'} --remote`);
235
587
  process.exitCode = 2;
236
588
  return;
237
589
  }
238
590
  const host = '127.0.0.1';
239
591
  const root = process.cwd();
240
- const deckPath = resolve(root, args.find((a) => !a.startsWith('-')));
592
+ const deckPath = resolve(root, firstPositional(args, ['--port', '--commit-every', '--agent']));
241
593
  if (!existsSync(deckPath)) { console.error(`deck not found: ${deckPath}`); process.exitCode = 1; return; }
242
594
  if (!deckPath.startsWith(root + sep)) { console.error('deck must live under the current directory'); process.exitCode = 1; return; }
243
595
  const deckUrl = '/' + deckPath.slice(root.length + 1).split(sep).join('/');
@@ -262,10 +614,14 @@ export async function editMain(args) {
262
614
  const wantGit = args.includes('--git');
263
615
  const commitEvery = Math.max(5, Number(opt('--commit-every', 300)) || 300);
264
616
  // --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');
617
+ // template. Still never inferred from what happens to be on PATH — but the
618
+ // permission can have been GIVEN already: `init` (and author's own first-run
619
+ // git offer) asks once, when the repository is created, and stores the answer
620
+ // in that repository's git config. The flag on the command line outranks it
621
+ // in both directions, so a stored yes is still one `--no-commit-messages`
622
+ // away from off for a single session.
623
+ const wantMessages = args.includes('--no-commit-messages') ? false
624
+ : args.includes('--commit-messages') || storedPref(process.cwd()) === true;
269
625
 
270
626
  /**
271
627
  * Every commit decklight authors ITSELF goes through here — the cadence, the
@@ -287,6 +643,9 @@ export async function editMain(args) {
287
643
  ? gitAutocommit(deckPath, root)
288
644
  : gitAutocommit(deckPath, root, message);
289
645
  if (!made) return false;
646
+ // Whatever wrote it — the overlay, an agent, a bookend — this stretch of
647
+ // uncommitted work is over, so the nag re-arms for the NEXT one.
648
+ resetEpisode();
290
649
  const sha = lastCommitSha;
291
650
  if (wantMessages && sha) {
292
651
  const template = message ?? `decklight: autosave ${basename(deckPath)}`;
@@ -296,9 +655,58 @@ export async function editMain(args) {
296
655
  }
297
656
  return true;
298
657
  }
299
- // timer (default, unchanged) · agent (one commit per agent edit) · off
658
+ // timer (the old cadence) · agent (one commit per agent edit, the default) · off
300
659
  const gitMode = resolveGitMode(args);
301
660
  let gitOn = false;
661
+
662
+ // ── the commit watch (cli/commit-flow.mjs) ──────────────────────────────
663
+ // How often the snapshot is refreshed and the nag rule re-read. Far shorter
664
+ // than the old commit cadence because nothing here writes history: a tick is
665
+ // one `git diff --numstat` and, when the deck moved, one loose commit object.
666
+ // The NAG is governed by its own rule, not by this interval — see planNag.
667
+ const WATCH_EVERY_MS = 30_000;
668
+ // …but never slower than the cadence the author asked for. `--commit-every`
669
+ // governs `--git-mode timer` outright; in the default mode it is still the
670
+ // knob for "how often should decklight look at my deck", so a tighter number
671
+ // tightens the snapshot too. Without this the interval was a constant nobody
672
+ // could reach, which is also what made it untestable end to end.
673
+ const watchEveryMs = Math.min(commitEvery * 1000, WATCH_EVERY_MS);
674
+ let dirtySince = 0; // when this stretch of uncommitted work began
675
+ let dirtyLines = 0; // how much of the deck differs from HEAD
676
+ let nagged = false; // the episode latch: asked once, then quiet
677
+ let nagDismissed = false;
678
+ let lastWip = null; // the snapshot sha, so the ping can prove it exists
679
+ /** A commit happened: this stretch of uncommitted work is over. */
680
+ const resetEpisode = () => {
681
+ dirtySince = 0; dirtyLines = 0; nagged = false; nagDismissed = false;
682
+ };
683
+ /**
684
+ * Re-read what is uncommitted, right now.
685
+ *
686
+ * Anything ANSWERING A QUESTION calls this rather than reporting the last
687
+ * tick's numbers. The tick is 30s apart, and K is pressed the moment after an
688
+ * edit: a cached "clean" would refuse to commit work that plainly exists,
689
+ * which is the worst possible answer from the button whose whole job is to
690
+ * commit it. The nag latch is deliberately untouched here — measuring is not
691
+ * asking.
692
+ */
693
+ const measureDirty = () => {
694
+ const d = deckDirty(root, deckRel);
695
+ if (!d.dirty) { dirtySince = 0; dirtyLines = 0; return d; }
696
+ if (!dirtySince) dirtySince = Date.now();
697
+ dirtyLines = d.lines;
698
+ return d;
699
+ };
700
+ /** What the deck knows about uncommitted work — ping and SSE both send this. */
701
+ const commitState = () => ({
702
+ dirty: dirtySince > 0,
703
+ lines: dirtyLines,
704
+ sinceMs: dirtySince ? Date.now() - dirtySince : 0,
705
+ nag: nagged && !nagDismissed,
706
+ wip: lastWip,
707
+ canWrite: gitOn && gitMode !== 'off',
708
+ messages: wantMessages,
709
+ });
302
710
  if (!noGit && (wantGit || inGitRepo(root))) {
303
711
  if (!inGitRepo(root)) {
304
712
  try {
@@ -310,26 +718,91 @@ export async function editMain(args) {
310
718
  }
311
719
  if (inGitRepo(root)) {
312
720
  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.
721
+ // An answer given on the command line becomes the repository's answer,
722
+ // once. This is what makes the first-run question (dev.mjs, asked before
723
+ // the repository existed and so with nowhere to write) stick: the next
724
+ // session reads it back instead of asking again. Only when nothing is
725
+ // stored yet — a later `--no-commit-messages` is one session's override,
726
+ // not a silent change to what the repository has been told.
727
+ if (storedPref(root) === null
728
+ && (args.includes('--commit-messages') || args.includes('--no-commit-messages'))) {
729
+ rememberPref(root, wantMessages);
730
+ }
731
+ // The session bookends are the cadence's siblings: generic subjects for
732
+ // moments nobody described, and in the default mode the snapshot covers
733
+ // what they were covering. THE FIRST COMMIT IS NOT ONE OF THEM. A
734
+ // repository decklight just created has no commits at all, and a deck git
735
+ // has never seen is in no commit — in both cases there is no HEAD for the
736
+ // snapshot to parent on and nothing in git to recover, so this commit is
737
+ // how the deck ENTERS history rather than an autosave of it.
738
+ const opening = deckDirty(root, deckRel);
739
+ if (gitMode === 'timer') ownCommit(`decklight: start editing ${basename(deckPath)}`);
740
+ else if (opening.firstCommit || opening.untracked) ownCommit(`decklight: add ${basename(deckPath)}`);
741
+ else { measureDirty(); lastWip = snapshotWip(root, deckPath, deckRel) ?? lastWip; }
742
+ // The cadence no longer WRITES HISTORY. It used to commit every
743
+ // --commit-every seconds, and what that produced was a column of
744
+ // `decklight: autosave talk.html` in which no commit marked anything —
745
+ // a backup wearing a history's clothes. The two jobs are now separate:
746
+ // the tick takes a silent snapshot (refs/decklight/wip, off every branch)
747
+ // so a crash still costs nothing, and asks ONCE per stretch of
748
+ // uncommitted work whether you want to commit it. `--git-mode timer`
749
+ // keeps the old cadence for anyone who wants the wall back.
319
750
  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)`);
751
+ if (agentJob) return; // never mid-run: see shouldCommit
752
+ if (gitMode === 'timer') {
753
+ if (shouldCommit(gitMode, { kind: 'timer' })) ownCommit();
754
+ return;
755
+ }
756
+ commitWatchTick();
757
+ }, gitMode === 'timer' ? commitEvery * 1000 : watchEveryMs).unref();
758
+ startup('git',
759
+ gitMode === 'timer'
760
+ ? `auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`
761
+ : 'commits on your word · snapshot on decklight/wip',
762
+ gitMode === 'timer'
763
+ ? ` git: auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`
764
+ : wipLine(deckRel));
765
+ }
766
+ }
767
+ /**
768
+ * One tick: refresh the snapshot, and decide whether to ask.
769
+ *
770
+ * Order matters. The snapshot is taken FIRST and unconditionally, because it
771
+ * is the safety net and must not depend on any nag rule being right. Only
772
+ * then is the question considered — and `planNag` answers it once per episode,
773
+ * so an ignored nag stays ignored instead of becoming a five-minute alarm.
774
+ */
775
+ function commitWatchTick() {
776
+ const d = measureDirty();
777
+ if (!d.dirty) { resetEpisode(); return; }
778
+ lastWip = snapshotWip(root, deckPath, deckRel) ?? lastWip;
779
+ if (planNag({ dirty: true, lines: dirtyLines, sinceMs: Date.now() - dirtySince, nagged, dismissed: nagDismissed })) {
780
+ nagged = true;
781
+ broadcast('commit', commitState());
782
+ console.log(` git: ${nagText({ lines: dirtyLines, sinceMs: Date.now() - dirtySince })}`
783
+ + ' — K in the deck commits it');
325
784
  }
326
785
  }
786
+
327
787
  const finalCommit = () => {
328
788
  if (!gitOn) return;
329
789
  // Not ownCommit: this runs inside the SIGINT handler and the process exits
330
790
  // immediately after, so there is no later for an amend to arrive in. The
331
791
  // bookend keeps its literal subject, which is true anyway.
332
- gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`);
792
+ if (gitMode === 'timer') {
793
+ gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`);
794
+ } else {
795
+ // Committing work you deliberately did not commit would be the cadence
796
+ // again, wearing an exit for a hat. The snapshot is refreshed instead —
797
+ // one last time, synchronously, so the newest bytes are safe — and the
798
+ // uncommitted work is NAMED on the way out rather than swallowed.
799
+ const d = deckDirty(root, deckRel);
800
+ if (d.dirty) {
801
+ snapshotWip(root, deckPath, deckRel);
802
+ console.log(` git: ${deckRel} has uncommitted changes — they are safe on`
803
+ + ` ${WIP_REF.replace('refs/', '')} (git show decklight/wip:${deckRel})`);
804
+ }
805
+ }
333
806
  // The last moment anyone is looking. Synchronous and fetch-free on purpose:
334
807
  // this runs inside the SIGINT handler, and a network call there would hang
335
808
  // a Ctrl-C — the worst possible place to hang.
@@ -344,11 +817,11 @@ export async function editMain(args) {
344
817
  // ── AI agents — one-shot editing tasks from the player (A) ─────────────
345
818
  // Precedence, like every other saved choice: the flag wins, then what was
346
819
  // remembered (#125), then the first detected agent.
347
- let agentPref = opt('--agent') ?? preferredAgent();
348
820
  const agents = detectAgents();
349
821
  if (agents.length) {
350
822
  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`);
823
+ startup('agents', agents.map(mark).join(', '),
824
+ ` agents: ${agents.map(mark).join(', ')} — “Ask agent” (A) is live`);
352
825
  }
353
826
  // A remembered agent that is not on this machine is said ONCE, at startup,
354
827
  // rather than discovered at the moment someone presses A mid-talk.
@@ -361,7 +834,9 @@ export async function editMain(args) {
361
834
  // git lines because it names the agent, and the roster is only resolved now.
362
835
  if (gitOn && wantMessages) {
363
836
  const who = agents.find((a) => a.name === agentPref) ?? agents[0];
364
- console.log(` ${messagesLine(who?.name ?? null)}`);
837
+ startup('git',
838
+ who?.name ? `${who.name} writes the subjects` : '--commit-messages needs an agent on PATH',
839
+ ` ${messagesLine(who?.name ?? null)}`);
365
840
  }
366
841
 
367
842
  // ── live reload: watch the deck, broadcast SSE (debounced — editors fire
@@ -490,7 +965,15 @@ export async function editMain(args) {
490
965
  };
491
966
 
492
967
  let pending = null;
493
- watch(deckPath, () => {
968
+ // The DIRECTORY, not the file. A path watch follows the inode, and an
969
+ // atomic write — temp file + rename, which is how an agent's editor and
970
+ // most careful tools save — replaces the inode: the watcher then sits deaf
971
+ // on the old one, and every later edit, restore included, reloads nobody.
972
+ // Found in 0.7.0 manual testing as "restore worked but the deck kept
973
+ // showing the old slides". A directory watch names the entry that changed
974
+ // and survives any number of replacements.
975
+ watch(dirname(deckPath), (kind, filename) => {
976
+ if (filename && filename !== basename(deckPath)) return;
494
977
  clearTimeout(pending);
495
978
  pending = setTimeout(() => {
496
979
  clients.raw('data: reload\n\n');
@@ -517,8 +1000,42 @@ export async function editMain(args) {
517
1000
  const child = spawn(cmd.bin, cmd.args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
518
1001
  let tail = '';
519
1002
  const keep = (chunk) => { tail = (tail + chunk).slice(-4000); };
520
- child.stdout.on('data', keep);
521
- child.stderr.on('data', keep);
1003
+ // The clue the chip shows. An agent run used to be a timer and nothing
1004
+ // else — ten minutes of "is it stuck?" with no way to tell. claude's
1005
+ // stream-json narrates every tool call, so those become activity events
1006
+ // on the same SSE channel the start/done events already ride; any other
1007
+ // agent gets its last non-empty stdout line, throttled, which is what a
1008
+ // person watching the terminal would glance at anyway.
1009
+ let resultText = null;
1010
+ let lastSaid = 0;
1011
+ const say = (text) => {
1012
+ if (!text || !agentJob) return;
1013
+ agentJob.activity = text; // /edit/ping carries it across a reload
1014
+ broadcast('agent', { state: 'activity', agent: cmd.name, text });
1015
+ console.log(` agent: ${text}`);
1016
+ };
1017
+ if (cmd.stream === 'claude-json') {
1018
+ let buf = '';
1019
+ child.stdout.on('data', (chunk) => {
1020
+ buf += chunk;
1021
+ for (let nl = buf.indexOf('\n'); nl !== -1; nl = buf.indexOf('\n')) {
1022
+ const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
1023
+ const clue = claudeActivity(line);
1024
+ if (clue?.activity) say(clue.activity);
1025
+ else if (clue?.result != null) resultText = clue.result;
1026
+ }
1027
+ });
1028
+ child.stderr.on('data', keep);
1029
+ } else {
1030
+ child.stdout.on('data', (chunk) => {
1031
+ keep(chunk);
1032
+ const now = Date.now();
1033
+ if (now - lastSaid < 800) return;
1034
+ const line = String(chunk).split('\n').map((l) => l.trim()).filter(Boolean).pop();
1035
+ if (line) { lastSaid = now; say(line.slice(0, 80)); }
1036
+ });
1037
+ child.stderr.on('data', keep);
1038
+ }
522
1039
  const timeout = setTimeout(() => child.kill('SIGTERM'), 10 * 60 * 1000);
523
1040
  child.on('error', (e) => {
524
1041
  clearTimeout(timeout);
@@ -537,12 +1054,35 @@ export async function editMain(args) {
537
1054
  const subject = commitSubject(message ?? prompt, `decklight: ${cmd.name} edited ${basename(deckPath)}`);
538
1055
  if (gitAutocommit(deckPath, root, subject)) console.log(` git: committed "${subject}"`);
539
1056
  }
1057
+ // Did the edit orphan, stale, or reshape a recording? A track is
1058
+ // minutes of somebody's own voice, and a whole-deck rewrite can drop the
1059
+ // config that plays it or the notes it reads with nothing on screen to
1060
+ // say so — this is where before/after both exist, so it is where the
1061
+ // word is said. A warning, never a block: the file is already written,
1062
+ // Z takes it back, and the audio never left the disk.
1063
+ let recordingWarning = null;
1064
+ if (changed) {
1065
+ try {
1066
+ const impact = recordingImpact(before, after, {
1067
+ dirsOf: configuredTrackDirs,
1068
+ recordedSlides: (dir) => {
1069
+ try { return slidesFromFiles(readdirSync(resolve(dirname(deckPath), dir))); }
1070
+ catch { return []; }
1071
+ },
1072
+ });
1073
+ recordingWarning = impactWarning(impact);
1074
+ } catch { recordingWarning = null; } // a warning that throws is worse than none
1075
+ }
540
1076
  agentJob = null;
541
1077
  broadcast('agent', {
542
1078
  state: 'done', agent: cmd.name, ok: code === 0, changed, code,
543
- tail: tail.trim().split('\n').slice(-6).join('\n').slice(-600),
1079
+ // the agent's own words when the stream carried them — raw stream-json
1080
+ // stdout is a wall of JSON nobody should be shown
1081
+ tail: (resultText ?? tail.trim().split('\n').slice(-6).join('\n')).slice(-600),
1082
+ ...(recordingWarning ? { recordingWarning } : {}),
544
1083
  });
545
1084
  console.log(` agent: ${cmd.name} exited (${code}) — deck ${changed ? 'changed' : 'unchanged'}`);
1085
+ if (recordingWarning) console.log(` ${recordingWarning}`);
546
1086
  });
547
1087
  return cmd;
548
1088
  }
@@ -583,7 +1123,37 @@ export async function editMain(args) {
583
1123
  preferredAgent: agentPref ?? null,
584
1124
  agentBusy: agentJob && { agent: agentJob.agent, prompt: agentJob.prompt, startedAt: agentJob.startedAt },
585
1125
  wizards: await configurableEngines(),
1126
+ // What is uncommitted, so a deck that loads mid-session shows the
1127
+ // chip without waiting for the next tick to broadcast one.
1128
+ commit: (gitOn && measureDirty(), commitState()),
1129
+ });
1130
+ }
1131
+ // ── committing on the author's word (SPEC PRESENTING) ─────────────────
1132
+ // What is uncommitted, right now. The overlay opens on this rather than
1133
+ // on whatever the last SSE event said, because K can be pressed at any
1134
+ // moment and a stale count is a lie about what you are agreeing to.
1135
+ if (req.method === 'GET' && url.pathname === '/edit/commit') {
1136
+ if (gitOn) measureDirty(); // the answer must be about NOW, not the last tick
1137
+ return json(200, { ok: true, ...commitState(), deck: deckRel });
1138
+ }
1139
+ // A subject for work that is not committed yet — the overlay's "write one
1140
+ // for me". Gated on the same permission as every other diff that leaves
1141
+ // the machine: no `--commit-messages`, no ask.
1142
+ if (req.method === 'POST' && url.pathname === '/edit/commit/subject') {
1143
+ if (!wantMessages) {
1144
+ return json(403, { ok: false, error: 'commit subjects are not enabled — decklight author --commit-messages' });
1145
+ }
1146
+ const subject = await describeWorking({
1147
+ cwd: root, deckPath, deckRel, agent: agentPref,
1148
+ template: `decklight: autosave ${basename(deckPath)}`,
586
1149
  });
1150
+ return json(200, { ok: true, subject: subject ?? null });
1151
+ }
1152
+ if (req.method === 'POST' && url.pathname === '/edit/commit/dismiss') {
1153
+ // Not the same as committing: the work stays uncommitted and the
1154
+ // snapshot keeps running. It only means "stop asking about THIS one".
1155
+ nagDismissed = true;
1156
+ return json(200, { ok: true, ...commitState() });
587
1157
  }
588
1158
  if (req.method === 'GET' && url.pathname === '/edit/events') {
589
1159
  clients.add(req, res, CORS);
@@ -687,6 +1257,17 @@ export async function editMain(args) {
687
1257
  const kind = url.searchParams.get('kind');
688
1258
  if (!Number.isInteger(slide) || slide < 1 || slide > 9999) return json(400, { ok: false, error: 'bad slide' });
689
1259
  if (kind !== 'wav' && kind !== 'visemes') return json(400, { ok: false, error: 'bad kind' });
1260
+ // `seg` is the per-⟨CLICK⟩ file number — the audio that lets a recording
1261
+ // step the builds (slide-NN-KK.wav) and the viseme timeline cut to
1262
+ // match it (slide-NN-KK.visemes.json). Absent means the whole slide.
1263
+ // Bounded and integral like `slide`, and for the same reason: it is
1264
+ // half of a filename this server builds, and the only defence that
1265
+ // survives someone deciding the name should be more flexible one day.
1266
+ const segRaw = url.searchParams.get('seg');
1267
+ const seg = segRaw == null ? null : Number(segRaw);
1268
+ if (seg !== null && (!Number.isInteger(seg) || seg < 1 || seg > 999)) {
1269
+ return json(400, { ok: false, error: 'bad seg' });
1270
+ }
690
1271
  // The player names the FOLDER (its own `narration.files`, so a recorded
691
1272
  // set lands where that deck already plays from) and nothing else: the
692
1273
  // file name is built here, so no request can choose one. The folder is
@@ -700,7 +1281,9 @@ export async function editMain(args) {
700
1281
  if (!dir || (!dir.startsWith(root + sep) && dir !== root)) {
701
1282
  return json(400, { ok: false, error: 'the recording folder must sit inside the deck\'s own directory' });
702
1283
  }
703
- const name = `slide-${String(slide).padStart(2, '0')}.${kind === 'wav' ? 'wav' : 'visemes.json'}`;
1284
+ const name = `slide-${String(slide).padStart(2, '0')}`
1285
+ + (seg === null ? '' : `-${String(seg).padStart(2, '0')}`)
1286
+ + `.${kind === 'wav' ? 'wav' : 'visemes.json'}`;
704
1287
  const chunks = [];
705
1288
  let size = 0;
706
1289
  for await (const chunk of req) {
@@ -719,6 +1302,277 @@ export async function editMain(args) {
719
1302
  if (req.method === 'POST') {
720
1303
  for await (const chunk of req) { body += chunk; if (body.length > 1e6) throw new Error('too large'); }
721
1304
  }
1305
+ // The commit the author asked for. The subject is THEIRS — typed, or an
1306
+ // agent's sentence they looked at and kept — so it goes through
1307
+ // `commitSubject` like every other message that reaches a command line
1308
+ // (one line, capped, never a leading `-`) and nothing else rewrites it:
1309
+ // `describeCommit`'s amend is for messages decklight authored, and this
1310
+ // one has an author.
1311
+ if (req.method === 'POST' && url.pathname === '/edit/commit') {
1312
+ if (!gitOn) return json(409, { ok: false, error: 'this session is not committing — start author with --git' });
1313
+ let msg = '';
1314
+ try { msg = String(JSON.parse(body || '{}').message ?? '').trim(); } catch { /* below */ }
1315
+ if (!msg) return json(400, { ok: false, error: 'a commit needs a message' });
1316
+ const subject = commitSubject(msg, `decklight: autosave ${basename(deckPath)}`);
1317
+ // gitAutocommit reports false for "nothing to commit", which is not an
1318
+ // error: it is the answer to pressing K twice.
1319
+ const made = gitAutocommit(deckPath, root, subject);
1320
+ if (!made) return json(200, { ok: true, committed: false, ...commitState() });
1321
+ resetEpisode();
1322
+ console.log(` git: committed ${deckRel} — "${subject}"`);
1323
+ return json(200, {
1324
+ ok: true, committed: true, subject, ...history.counts(), ...commitState(),
1325
+ });
1326
+ }
1327
+ // ── review comments (SPEC REVIEW) ─────────────────────────────
1328
+ // The author's side of `decklight review`. The same file, the same
1329
+ // append-only rule: this server may add a line (a resolve, a reply) and
1330
+ // may not rewrite one, because `merge=union` is what keeps two reviewers
1331
+ // from conflicting and an edit in place is what would break it.
1332
+ if (req.method === 'GET' && url.pathname === '/edit/review') {
1333
+ const store = reviewPathFor(deckPath);
1334
+ if (!existsSync(store)) return json(200, { ok: true, records: [], skipped: 0 });
1335
+ const { records, skipped } = parseReview(readFileSync(store, 'utf8'));
1336
+ return json(200, { ok: true, records, skipped });
1337
+ }
1338
+ // What reviews are waiting on the remote — the M overlay's incoming
1339
+ // section. This one is a fetch the author DID ask for: it runs behind
1340
+ // the keypress that just opened the overlay, on demand and nowhere else.
1341
+ // The 60s cache is what keeps a nervous author tapping M from turning
1342
+ // one gesture into a fetch storm; the off switches still win outright.
1343
+ if (req.method === 'GET' && url.pathname === '/edit/review/incoming') {
1344
+ // ci: false — this fetch is ASKED FOR, behind the keypress that
1345
+ // opened the overlay; only the explicit switches silence it.
1346
+ const skipped = reviewCheckSuppressed({ args, ci: false });
1347
+ if (skipped) return json(200, { ok: true, state: 'suppressed', reason: skipped, reviews: [] });
1348
+ if (!incomingCache || Date.now() - incomingCache.at > 60_000) {
1349
+ const r = await reviewsWaiting(deckPath);
1350
+ incomingCache = { at: Date.now(), r };
1351
+ }
1352
+ return json(200, { ok: true, ...incomingCache.r });
1353
+ }
1354
+ // What tracks already sit next to this deck. The runtime cannot see the
1355
+ // filesystem — which is why `segments: true` is opt-in at all — so it
1356
+ // cannot know that `voices/rachel` is taken before proposing it. One
1357
+ // question, asked when a recorder opens.
1358
+ if (req.method === 'GET' && url.pathname === '/edit/tracks') {
1359
+ const root2 = resolve(deckPath, '..');
1360
+ const seen = [];
1361
+ const look = (rel) => {
1362
+ let entries;
1363
+ try { entries = readdirSync(resolve(root2, rel), { withFileTypes: true }); } catch { return; }
1364
+ const wav = entries.filter((e) => e.isFile() && /^slide-\d+(-\d+)?\.(wav|m4a|mp3)$/.test(e.name));
1365
+ if (wav.length) {
1366
+ let engine = null; let voice = null;
1367
+ try {
1368
+ const m = JSON.parse(readFileSync(resolve(root2, rel, 'manifest.json'), 'utf8'));
1369
+ engine = m.engine ?? null; voice = m.voice ?? null;
1370
+ } catch { /* a folder recorded by hand has no manifest, and needs none */ }
1371
+ seen.push({
1372
+ dir: rel.split(sep).join('/'),
1373
+ files: wav.length,
1374
+ // the beats are what let a track pace the builds, so whether it
1375
+ // has them is the one fact worth reporting beside the count
1376
+ segments: wav.some((e) => /^slide-\d+-\d+\./.test(e.name)),
1377
+ ext: (wav[0].name.split('.').pop()),
1378
+ engine,
1379
+ voice,
1380
+ });
1381
+ }
1382
+ return entries;
1383
+ };
1384
+ for (const e of look('.') ?? []) {
1385
+ if (!e.isDirectory() || e.name.startsWith('.') || e.name === 'node_modules') continue;
1386
+ const kids = look(e.name) ?? [];
1387
+ // one more level, because the convention is voices/<voice>
1388
+ for (const k of kids) {
1389
+ if (k.isDirectory() && !k.name.startsWith('.')) look(`${e.name}${sep}${k.name}`);
1390
+ }
1391
+ }
1392
+ return json(200, { ok: true, tracks: seen });
1393
+ }
1394
+ // Point the deck at a track the recorder just wrote. The one manual step
1395
+ // in a flow that is otherwise a key and an arrow — and this server
1396
+ // already owns the file, so it can take that step too.
1397
+ if (req.method === 'GET' && url.pathname === '/edit/review/at') {
1398
+ // The orphan's context: what the slide SAID when the comment was
1399
+ // written — `comments --at`, served, so the overlay can put the dead
1400
+ // slide's prose under the objection that was about it. Read-only, all
1401
+ // local (the commit is already in this clone or the answer is "not
1402
+ // here"), and gated exactly as the CLI gates it.
1403
+ const id = url.searchParams.get('id') ?? '';
1404
+ if (!/^[a-z0-9]{1,12}$/.test(id)) return json(400, { ok: false, error: 'bad comment id' });
1405
+ const store = reviewPathFor(deckPath);
1406
+ if (!existsSync(store)) return json(404, { ok: false, error: 'no comments here' });
1407
+ const c = foldReview(parseReview(readFileSync(store, 'utf8')).records).find((x) => x.id === id);
1408
+ if (!c) return json(404, { ok: false, error: `no comment [${id}]` });
1409
+ if (!c.deck) return json(200, { ok: true, known: false, why: 'written outside a repository — there is no earlier version to show' });
1410
+ if (!gitOn || !knowsCommit(c.deck, root)) {
1411
+ return json(200, { ok: true, known: false, why: `this clone does not have ${c.deck}` });
1412
+ }
1413
+ try {
1414
+ const thenHtml = deckAt(deckPath, c.deck, root);
1415
+ const wasAt = indexDeckFile(thenHtml)[(c.slide ?? 0) - 1] ?? null;
1416
+ return json(200, {
1417
+ ok: true,
1418
+ known: true,
1419
+ deck: c.deck,
1420
+ slide: c.slide ?? null,
1421
+ title: wasAt?.title ?? null,
1422
+ text: slideTextOf(thenHtml, c.slide) || '',
1423
+ });
1424
+ } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1425
+ }
1426
+ if (req.method === 'POST' && url.pathname === '/edit/review/done') {
1427
+ // Mark ONE of a reviewer's comments done, or take the mark off. Their
1428
+ // comments live on their branch, which is not ours to write, so the
1429
+ // mark is kept in this clone's git config — private, never pushed.
1430
+ // Your OWN comments do not come through here at all: they already have
1431
+ // a way to be finished with, the append-only `resolve` record below,
1432
+ // which travels so the reviewer can see you dealt with their point.
1433
+ //
1434
+ // The branch is looked up in what the incoming reader LISTED, so it is
1435
+ // data here and never an argument; the id is shape-checked before it
1436
+ // becomes half of a config key.
1437
+ const { branch, id, done = true } = JSON.parse(body || '{}');
1438
+ const listed = incomingCache?.r?.reviews?.find((v) => v.branch === branch);
1439
+ if (!listed) return json(400, { ok: false, error: 'not a review this deck knows about — press M again to refresh' });
1440
+ if (!listed.records?.some((r) => r.id === id)) {
1441
+ return json(400, { ok: false, error: 'no such comment in that review' });
1442
+ }
1443
+ if (!setCommentDone(root, branch, id, !!done)) {
1444
+ return json(500, { ok: false, error: 'could not write the mark to git config' });
1445
+ }
1446
+ // the list just changed shape — the cache must not keep the old marks
1447
+ incomingCache = null;
1448
+ console.log(` review: ${branch} ${id} ${done ? 'marked done' : 'reopened'}`);
1449
+ return json(200, { ok: true, branch, id, done: !!done });
1450
+ }
1451
+ if (req.method === 'POST' && url.pathname === '/edit/review') {
1452
+ const { op, re, body: text, slide, title, fp } = JSON.parse(body || '{}');
1453
+ // A NEW comment — no `op`, no `re`. The author leaving one on their own
1454
+ // deck (⇧M), which until now only a `decklight review` server could
1455
+ // take: the composer was gated on one answering, so an author had to
1456
+ // start a second server on a second port, in a mode that would not let
1457
+ // them edit the slide they were commenting on.
1458
+ //
1459
+ // Same file, same append-only rule, same record shape — through
1460
+ // `commentProblem` and `reviewRecord`, which review.mjs already exports
1461
+ // and which are the arbiters of what a comment is. Two servers writing
1462
+ // two shapes into one union-merged file is how a store stops parsing.
1463
+ if (op === undefined && re === undefined) {
1464
+ const input = { body: text, slide, title, fp };
1465
+ const bad = commentProblem(input);
1466
+ if (bad) return json(400, { ok: false, error: bad });
1467
+ let deckAt = null;
1468
+ try { deckAt = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(); }
1469
+ catch { deckAt = null; }
1470
+ const rec = reviewRecord(input, {
1471
+ by: reviewerName(), at: new Date().toISOString(), deck: deckAt, id: newId(),
1472
+ });
1473
+ const store_ = reviewPathFor(deckPath);
1474
+ try { appendFileSync(store_, `${serializeRecord(rec)}\n`); }
1475
+ catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1476
+ if (gitOn) {
1477
+ gitAutocommit(store_, root,
1478
+ commitSubject(`review: ${rec.body}`, `review: a comment on ${basename(deckPath)}`));
1479
+ }
1480
+ console.log(` review: comment on slide ${rec.slide} → ${basename(store_)}`);
1481
+ return json(200, { ok: true, id: rec.id });
1482
+ }
1483
+ if (typeof re !== 'string' || !/^[a-z0-9]{1,12}$/.test(re)) {
1484
+ return json(400, { ok: false, error: 'bad comment id' });
1485
+ }
1486
+ if (op === 'anchor') {
1487
+ // moving a comment to the slide the author is looking at — the
1488
+ // reconciliation for a slide that was deleted or rewritten past
1489
+ // what fingerprint + title can find
1490
+ const n = Number(slide);
1491
+ if (!Number.isInteger(n) || n < 1 || n > 9999) return json(400, { ok: false, error: 'an anchor needs a slide' });
1492
+ if (title !== undefined && (typeof title !== 'string' || title.length > 500)) return json(400, { ok: false, error: 'bad title' });
1493
+ if (fp !== undefined && (typeof fp !== 'string' || !/^[0-9a-f]{1,16}$/.test(fp))) return json(400, { ok: false, error: 'bad fingerprint' });
1494
+ } else if (op !== 'resolve' && !(typeof text === 'string' && text.trim() && text.length <= 4000)) {
1495
+ return json(400, { ok: false, error: 'a reply needs something in it' });
1496
+ }
1497
+ const store = reviewPathFor(deckPath);
1498
+ // A reply is a new statement about the deck and carries which version it
1499
+ // was made against, exactly as a comment does. A resolve does not: it is
1500
+ // about the comment, not about the slide.
1501
+ let at = null;
1502
+ try { at = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(); }
1503
+ catch { at = null; }
1504
+ const rec = op === 'anchor'
1505
+ ? {
1506
+ op: 'anchor',
1507
+ re,
1508
+ slide: Number(slide),
1509
+ ...(title !== undefined ? { title } : {}),
1510
+ ...(fp !== undefined ? { fp } : {}),
1511
+ at: new Date().toISOString(),
1512
+ by: reviewerName(),
1513
+ }
1514
+ : op === 'resolve'
1515
+ ? { op: 'resolve', re, at: new Date().toISOString(), by: reviewerName() }
1516
+ : {
1517
+ id: newId(),
1518
+ at: new Date().toISOString(),
1519
+ by: reviewerName(),
1520
+ ...(at ? { deck: at } : {}),
1521
+ re,
1522
+ body: text,
1523
+ };
1524
+ try { appendFileSync(store, `${serializeRecord(rec)}\n`); }
1525
+ catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1526
+ if (gitOn) {
1527
+ gitAutocommit(store, root, op === 'anchor'
1528
+ ? commitSubject(`review: move ${re} to slide ${rec.slide}`, 'review: re-anchor a comment')
1529
+ : op === 'resolve'
1530
+ ? commitSubject(`review: resolve ${re}`, 'review: resolve a comment')
1531
+ : commitSubject(`review: reply to ${re}`, 'review: a reply'));
1532
+ }
1533
+ console.log(` review: ${op === 'anchor' ? `moved ${re} to slide ${rec.slide}`
1534
+ : op === 'resolve' ? `resolved ${re}` : `replied to ${re}`}`);
1535
+ return json(200, { ok: true });
1536
+ }
1537
+ if (req.method === 'POST' && url.pathname === '/edit/narration') {
1538
+ const { files, ext, segments } = JSON.parse(body || '{}');
1539
+ // The same three shapes /edit/record refuses for a folder, refused
1540
+ // again here: this one is written INTO the deck, where a bad value is
1541
+ // not a failed request but a deck that no longer plays.
1542
+ if (typeof files !== 'string' || !files.trim() || files.length > 200
1543
+ || /^[/\\]/.test(files) || /^[a-zA-Z]:/.test(files)
1544
+ || files.split(/[/\\]/).includes('..')) {
1545
+ return json(400, { ok: false, error: 'bad narration folder' });
1546
+ }
1547
+ if (ext !== undefined && !/^[a-z0-9]{1,5}$/.test(String(ext))) {
1548
+ return json(400, { ok: false, error: 'bad ext' });
1549
+ }
1550
+ if (segments !== undefined && typeof segments !== 'boolean') {
1551
+ return json(400, { ok: false, error: 'bad segments' });
1552
+ }
1553
+ const { label } = JSON.parse(body || '{}');
1554
+ if (label !== undefined && (typeof label !== 'string' || label.length > 120)) {
1555
+ return json(400, { ok: false, error: 'bad label' });
1556
+ }
1557
+ // upsert, never replace: a deck carries as many tracks as you have
1558
+ // voices, and writing one must not throw the others away
1559
+ const next = upsertNarrationTrack(readDeck(), {
1560
+ label: label || files.trim(),
1561
+ dir: files.trim(),
1562
+ ...(ext === undefined ? {} : { ext }),
1563
+ ...(segments === undefined ? {} : { segments }),
1564
+ });
1565
+ if (next === null) {
1566
+ // Not a failure of this server — a deck whose config is built
1567
+ // somewhere else. Say which, so the answer is "paste this line",
1568
+ // not "it did not work".
1569
+ return json(409, { ok: false,
1570
+ error: 'this deck builds its config outside the Decklight.init(…) call, so there is no literal here to edit' });
1571
+ }
1572
+ const changed = applyEdit(next);
1573
+ if (changed) console.log(` narration: ${files} in the deck's config`);
1574
+ return json(200, { ok: true, changed, ...history.counts() });
1575
+ }
722
1576
  if (req.method === 'POST' && url.pathname === '/edit/restore') {
723
1577
  if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
724
1578
  const { ref } = JSON.parse(body || '{}');
@@ -949,7 +1803,41 @@ export async function editMain(args) {
949
1803
  });
950
1804
 
951
1805
  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`);
1806
+ // `decklight record` runs this same server in-process and needs to know
1807
+ // WHICH port it ended up on (a taken --port moves to the next free one) and
1808
+ // to print its own banner instead of the authoring one.
1809
+ if (onListen) onListen({ port: actual, deckUrl, server });
1810
+ else if (process.env.DECKLIGHT_BANNER) {
1811
+ // The port is reported rather than assumed: `listenTakingOverIfNeeded` can
1812
+ // land somewhere other than the port author resolved, and the URL on the
1813
+ // banner has to be the one that actually answers.
1814
+ console.log(readyLine({
1815
+ url: `http://127.0.0.1:${actual}${deckUrl}`,
1816
+ keys: 'E edit · L layouts · Z undo · A agent · Ctrl-C stops',
1817
+ }));
1818
+ } 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`);
1819
+
1820
+ // Did somebody review this deck? Asked ONCE, after the last startup line,
1821
+ // detached and never awaited — the update-check shape: nothing about it can
1822
+ // delay the server coming up or hang authoring on a remote that is down. It
1823
+ // is a fetch the author did not type, which is why it is the sanctioned
1824
+ // exception cli/git.mjs names, why it is never on a timer, and why it is
1825
+ // nowhere near the SIGINT path (finalCommit above says what lives there and
1826
+ // why nothing else may).
1827
+ if (!onListen) {
1828
+ const skipped = reviewCheckSuppressed({ args });
1829
+ if (skipped) {
1830
+ startup('reviews', `not checked — ${skipped}`, ` reviews: not checked — ${skipped}`);
1831
+ } else {
1832
+ reviewsWaiting(deckPath)
1833
+ .then((r) => {
1834
+ const line = reviewLine(r, { deck: relative(process.cwd(), deckPath) || basename(deckPath) });
1835
+ if (line) startup('reviews', line.replace(/^reviews:\s*/, ''), ` ${line}`);
1836
+ })
1837
+ .catch(() => {});
1838
+ }
1839
+ }
1840
+ return { port: actual, deckUrl, host, server };
953
1841
  }
954
1842
 
955
1843