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/banner.mjs ADDED
@@ -0,0 +1,125 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * One banner for `decklight author`, and the deck's URL is the last thing on it.
6
+ *
7
+ * author runs its servers as child processes and used to let each one print its
8
+ * own startup lines through a pipe that did nothing but prefix them. That gave
9
+ * two problems no amount of rewording fixes:
10
+ *
11
+ * THE ORDER WAS A RACE. `deck` and `voice` are separate processes announcing
12
+ * themselves whenever they happen to be ready, so the URL a person is meant
13
+ * to click landed wherever it landed — often above the bridge's line, which
14
+ * is also a URL, and the wrong one to click.
15
+ *
16
+ * NOBODY OWNED THE WHOLE. Each line was defensible alone and the eight
17
+ * together were a wall, because no single place could see them all and
18
+ * decide what mattered.
19
+ *
20
+ * So author prints the banner and the children stop printing startup lines —
21
+ * they hand author a FACT instead, on the same pipe, behind a sentinel
22
+ * (`readyLine`). Only under author: with no `DECKLIGHT_BANNER` in the
23
+ * environment every child prints exactly what it printed before, which is what
24
+ * `decklight edit` and `decklight tts` run on their own still do.
25
+ *
26
+ * Nothing here does I/O. `renderBanner` takes facts and returns lines, so the
27
+ * layout is a unit test rather than something you check by starting a server.
28
+ */
29
+
30
+ /**
31
+ * The marker a child puts in front of a startup fact.
32
+ *
33
+ * The leading \u0001 is deliberate: it cannot occur in a human-facing line, so
34
+ * ordinary child output can never be mistaken for a fact, and a fact can never
35
+ * leak onto the terminal as something to read.
36
+ */
37
+ export const READY = '\u0001decklight:ready ';
38
+
39
+ /** What a child writes instead of its own startup line. */
40
+ export function readyLine(fact) {
41
+ return READY + JSON.stringify(fact);
42
+ }
43
+
44
+ /** A child's line as a fact, or null if it is ordinary output to pass through. */
45
+ export function parseReady(line) {
46
+ if (typeof line !== 'string' || !line.startsWith(READY)) return null;
47
+ try {
48
+ const fact = JSON.parse(line.slice(READY.length));
49
+ return fact && typeof fact === 'object' && !Array.isArray(fact) ? fact : null;
50
+ } catch { return null; }
51
+ }
52
+
53
+ /**
54
+ * The order rows appear in, whatever order the processes woke up in — which is
55
+ * the entire point of collecting them all before printing any.
56
+ *
57
+ * `reviews` is last because it is the only row that is a THING TO DO rather
58
+ * than a thing that is merely true, so it sits closest to the URL.
59
+ */
60
+ export const ROW_ORDER = ['voice', 'lips', 'skipped', 'git', 'agents', 'reviews'];
61
+
62
+ const ESC = { dim: '\x1b[2m', bold: '\x1b[1m', cyan: '\x1b[36m', under: '\x1b[4m', reset: '\x1b[0m' };
63
+
64
+ /**
65
+ * The banner, as lines. `rows` is `[{ key, text }]` in any order; a key not in
66
+ * ROW_ORDER keeps its arrival position after the known ones, so a service added
67
+ * later still appears without anyone having to remember to edit that list.
68
+ */
69
+ export function renderBanner({ deck, url, keys, rows = [], color = false } = {}) {
70
+ const c = (s, ...codes) => (color ? codes.map((k) => ESC[k]).join('') + s + ESC.reset : s);
71
+ const rank = (k) => { const i = ROW_ORDER.indexOf(k); return i === -1 ? ROW_ORDER.length : i; };
72
+ const shown = rows
73
+ .filter((r) => r && r.key && r.text)
74
+ .map((r, i) => ({ ...r, i }))
75
+ .sort((a, b) => rank(a.key) - rank(b.key) || a.i - b.i);
76
+
77
+ const out = [`decklight author${deck ? ` ${c('·', 'dim')} ${deck}` : ''}`];
78
+ if (shown.length) {
79
+ out.push('');
80
+ const w = Math.max(...shown.map((r) => r.key.length));
81
+ for (const r of shown) out.push(` ${c(r.key.padEnd(w), 'dim')} ${r.text}`);
82
+ }
83
+ // The URL last, and the only coloured thing here, because a person scanning
84
+ // this is looking for exactly one thing and it is this.
85
+ out.push('', ` ${c('▸', 'cyan')} ${c(url, 'bold', 'cyan', 'under')}`);
86
+ if (keys) out.push(` ${c(keys, 'dim')}`);
87
+ return out;
88
+ }
89
+
90
+ /**
91
+ * How long to wait before printing the banner, or null for "not yet".
92
+ *
93
+ * Pure, because the ordering bug it encodes is not one you want to find by
94
+ * starting three servers and squinting. A grace window ALONE is not enough:
95
+ * the voice bridge enumerates the machine's voices before it can say what it
96
+ * is, so it reports hundreds of milliseconds after the deck server does, and
97
+ * any grace short enough to feel instant printed the banner without it — the
98
+ * bridge's row then landed UNDER the url, which is the one thing the banner
99
+ * exists to prevent. So the wait is on NAMES: nobody still owed, then a short
100
+ * grace for the genuinely late (the review check fires detached, after the
101
+ * deck server is already listening), and a cap so one silent child cannot sit
102
+ * on the url forever.
103
+ */
104
+ export function nextFlushDelay({ waiting = 0, elapsed = 0, cap = 5000, grace = 350 } = {}) {
105
+ if (waiting > 0) return null;
106
+ return Math.max(0, Math.min(grace, cap - elapsed));
107
+ }
108
+
109
+ /**
110
+ * How anything WATCHING author's output finds the deck's url.
111
+ *
112
+ * Exported because six harnesses each carried their own copy of the old
113
+ * `decklight author on http://…`, and the day that line changed shape all six
114
+ * timed out for the same reason in six different files. A banner is a thing
115
+ * people read, so its wording will change again; this is the part that is a
116
+ * contract, and it lives next to the code that prints it.
117
+ *
118
+ * Group 1 is the port. Tolerant of the colour codes a terminal gets and a pipe
119
+ * does not, so it matches whichever way author was run — and the escapes and
120
+ * the space INTERLEAVE: the reset that closes the ▸ lands between the arrow
121
+ * and the space before the url. A pattern that expected the whitespace first
122
+ * matched every piped harness and none of the ones driven through a pty,
123
+ * which is a single test and a 45-second timeout rather than a failure.
124
+ */
125
+ export const DECK_URL_RE = /\u25b8(?:\s|\x1b\[[0-9;]*m)*http:\/\/127\.0\.0\.1:(\d+)/;
package/cli/bundle.mjs CHANGED
@@ -446,14 +446,20 @@ html = html.replace(
446
446
  if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) continue;
447
447
  let mp4s = 0;
448
448
  for (const f of fs.readdirSync(abs).sort()) {
449
- const vm = f.match(/^slide-(\d+)\.visemes\.json$/);
449
+ // slide-NN and slide-NN-KK alike: a beat-paced track carries a sidecar
450
+ // per ⟨CLICK⟩ beat, and a bundle that inlined only the slide ones would
451
+ // leave the character animating from amplitude the moment it is opened
452
+ // from file:// — which is the one place a bundle is always opened.
453
+ const vm = f.match(/^(slide-\d+(?:-\d+)?)\.visemes\.json$/);
450
454
  if (vm) {
455
+ // vm[1] is the whole STEM (`slide-07`, `slide-07-02`) — the same name
456
+ // the runtime looks the block up by, so the two cannot drift apart.
451
457
  if (seen.has(vm[1])) {
452
- notices.push(`character visemes: ${d}/${f} skipped — slide ${vm[1]} already inlined from another track`);
458
+ notices.push(`character visemes: ${d}/${f} skipped — ${vm[1]} already inlined from another track`);
453
459
  continue;
454
460
  }
455
461
  seen.add(vm[1]);
456
- embeds.push(`<script type="application/json" data-decklight-visemes="slide-${vm[1]}">\n`
462
+ embeds.push(`<script type="application/json" data-decklight-visemes="${vm[1]}">\n`
457
463
  + `${scriptSafe(fs.readFileSync(path.join(abs, f), 'utf8'))}\n</script>`);
458
464
  } else if (/^slide-\d+\.mp4$/.test(f)) mp4s++;
459
465
  }
@@ -461,7 +467,11 @@ html = html.replace(
461
467
  notices.push(`character video: ${mp4s} slide-NN.mp4 in ${d}/ stay external — ship the folder next to the bundle`);
462
468
  }
463
469
  }
464
- if (seen.size) notices.push(`character visemes: inlined ${seen.size} slide timeline(s)`);
470
+ if (seen.size) {
471
+ const beats = [...seen].filter((k) => /^slide-\d+-\d+$/.test(k)).length;
472
+ notices.push(`character visemes: inlined ${seen.size} timeline(s)`
473
+ + (beats ? ` (${seen.size - beats} slides + ${beats} ⟨CLICK⟩ beats)` : ''));
474
+ }
465
475
  }
466
476
 
467
477
  // --------------------------------------------- narration manifest tracks
@@ -3,11 +3,22 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
 
5
5
  /**
6
- * decklight-rec — record truthful terminal casts for Decklight decks (SPEC RECORDER_CLI/CAST_FORMAT).
6
+ * decklight-cast — record truthful terminal casts for Decklight decks (SPEC RECORDER_CLI/CAST_FORMAT).
7
7
  *
8
- * decklight rec <script.term.yaml> [-o out.cast.json] [--allow-fail] [--quiet]
8
+ * decklight cast <script.term.yaml> [-o out.cast.json] [--allow-fail] [--quiet]
9
9
  * decklight refresh <dir | cast.json…> [--allow-fail]
10
10
  *
11
+ * This briefly shipped as `decklight rec`, a name dropped without an alias or
12
+ * a refusal stub: `rec` reads as an abbreviation of `record`, and `decklight
13
+ * record` now records something else entirely — the author's voice — so the
14
+ * old name would have gone on quietly meaning the opposite of what its reader
15
+ * assumes. Nothing depends on it (decklight has no released users yet), so
16
+ * there is nothing to migrate and no stub worth carrying.
17
+ *
18
+ * `cast` is not a new word here: the file is `.cast.json`, the format is SPEC
19
+ * CAST_FORMAT, `refresh` takes casts and `export` flattens one. Only the
20
+ * command that made them ever said `rec`.
21
+ *
11
22
  * How a step boundary is detected (the sentinel technique):
12
23
  * All commands run in ONE persistent PTY shell session. For each step we
13
24
  * write two lines to the PTY: the command itself, then
@@ -25,7 +36,7 @@ import fs from 'node:fs';
25
36
  import path from 'node:path';
26
37
  import os from 'node:os';
27
38
  import { createRequire } from 'node:module';
28
- import { makeFail, runMain } from './util.mjs';
39
+ import { makeFail, runMain, wrongRecorder } from './util.mjs';
29
40
  import { isMain } from '../tools/args.mjs';
30
41
 
31
42
  const require = createRequire(import.meta.url);
@@ -41,7 +52,7 @@ const READY_MARK = `${GS}DECKLIGHT-READY${GS}`;
41
52
 
42
53
  // ---------------------------------------------------------------- utilities
43
54
 
44
- const fail = makeFail('rec');
55
+ const fail = makeFail('cast');
45
56
 
46
57
  function loadDeps() {
47
58
  let yaml, pty;
@@ -445,10 +456,11 @@ async function refresh(targets, { allowFail }) {
445
456
 
446
457
  // --------------------------------------------------------------------- main
447
458
 
448
- const HELP = `decklight rec — record terminal casts for Decklight decks
459
+ const HELP = `decklight cast — record terminal casts for Decklight decks
460
+ (recording your VOICE narrating a deck is a different command: decklight record)
449
461
 
450
462
  Usage:
451
- decklight rec <script.term.yaml> [-o out.cast.json] [--allow-fail] [--quiet]
463
+ decklight cast <script.term.yaml> [-o out.cast.json] [--allow-fail] [--quiet]
452
464
  decklight refresh <dir | cast.json…> [--allow-fail]
453
465
  decklight export <cast.json> [-o out.cast] # asciicast v2
454
466
 
@@ -489,7 +501,7 @@ Notes:
489
501
  decklight export demo.cast.json && agg demo.cast demo.gif
490
502
  `;
491
503
 
492
- export async function recMain(argv = process.argv.slice(2)) {
504
+ export async function castMain(argv = process.argv.slice(2)) {
493
505
  if (!argv.length || argv.includes('--help') || argv.includes('-h')) { console.log(HELP); return; }
494
506
  const allowFail = argv.includes('--allow-fail');
495
507
  const quiet = argv.includes('--quiet');
@@ -517,6 +529,11 @@ export async function recMain(argv = process.argv.slice(2)) {
517
529
 
518
530
  const { yaml } = loadDeps();
519
531
  const scriptPath = rest[0];
532
+ // Named before the YAML parser gets it: a deck handed to this command used
533
+ // to come back as `script has no steps`, which is true of every HTML file
534
+ // and says nothing about the one thing that went wrong.
535
+ const mixedUp = wrongRecorder('cast', scriptPath);
536
+ if (mixedUp) fail(mixedUp);
520
537
  if (!scriptPath || !fs.existsSync(scriptPath)) fail(`script not found: ${scriptPath}`);
521
538
  const oIdx = rest.indexOf('-o');
522
539
  const outPath = oIdx !== -1 && rest[oIdx + 1]
@@ -539,4 +556,4 @@ export async function recMain(argv = process.argv.slice(2)) {
539
556
 
540
557
  // Import-safe: only run the CLI when executed directly (recordScript and
541
558
  // exportAsciicast are importable for tests/tooling).
542
- if (isMain(import.meta.url)) process.exitCode = await runMain('rec', recMain);
559
+ if (isMain(import.meta.url)) process.exitCode = await runMain('cast', castMain);
@@ -0,0 +1,389 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight comments — what reviewers said about a deck. SPEC REVIEW.
6
+ //
7
+ // decklight comments <deck.html> [--unresolved] [--all] [--import <file>] [--incoming]
8
+ //
9
+ // The author's side of `decklight review`. Reads `<deck>.review.jsonl`, resolves
10
+ // every comment against the deck AS IT IS NOW, and prints it grouped by slide.
11
+ //
12
+ // Resolution is the whole job. A comment records the slide it was written on,
13
+ // that slide's title, and a fingerprint of its text — because a slide has no
14
+ // stable identity, and a comment stored as "slide 12" re-attaches to whatever is
15
+ // twelfth after somebody inserts one. So each comment is reported with HOW it
16
+ // was found, and a comment whose slide is gone is listed rather than dropped:
17
+ // somebody objected to a slide and it is not there any more is often the most
18
+ // interesting line in the file.
19
+
20
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
21
+ import { basename, dirname, relative, resolve } from 'node:path';
22
+
23
+ import { argReader, isMain } from '../tools/args.mjs';
24
+ import { sectionBodies, sectionInner, slideText, slideHeading } from '../tools/deck-html.mjs';
25
+ import { fingerprint, resolveAnchor, VERDICT_NOTE, foldReview } from '../tools/review-anchor.mjs';
26
+ import { reviewPathFor, parseReview, serializeRecord, mergeById } from './review-store.mjs';
27
+ import { reviewsWaiting } from './review-remote.mjs';
28
+ import { findDeck } from './history.mjs';
29
+ import { gitAvailable, inGitRepo, gitAutocommit, oneline, git } from './git.mjs';
30
+ import { deckAt } from './restore.mjs';
31
+
32
+ const HELP = `usage: decklight comments <deck.html> [--unresolved] [--all] [--import <file>] [--incoming]
33
+ what reviewers said, resolved against the deck as it is now
34
+
35
+ --unresolved only the ones nobody has closed off
36
+ --all include resolved ones (default: they are counted, not printed)
37
+ --import FILE merge a reviewer's file into this deck's own, skipping anything
38
+ already there, and commit it — the return path for a reviewer
39
+ who was sent the deck and has no clone
40
+ --incoming ask the remote what reviews are WAITING — the branches
41
+ \`decklight review submit\` pushed that you have not merged
42
+ (--remote NAME to ask a remote other than origin)
43
+ --at ID show what the slide SAID when comment ID was written, beside
44
+ what it says now — the point of recording which commit a
45
+ comment was made against
46
+
47
+ comments live in <deck>.review.jsonl beside the deck; reviewers write them
48
+ with: decklight review <deck.html>
49
+ `;
50
+
51
+ /**
52
+ * The deck as the resolver wants it, read from the FILE.
53
+ *
54
+ * The browser builds the same list from the DOM (src/core/review.js). They agree
55
+ * because `fingerprint` removes whitespace, so the two readers' different ideas
56
+ * about spacing between elements cannot matter.
57
+ */
58
+ export function indexDeckFile(html) {
59
+ return sectionBodies(html).map((body, i) => {
60
+ const inner = sectionInner(body);
61
+ return { slide: i + 1, title: slideHeading(inner, i), fp: fingerprint(slideText(inner)) };
62
+ });
63
+ }
64
+
65
+ /**
66
+ * How far the DECK has moved since a comment was written.
67
+ *
68
+ * The anchor verdict answers a different question — whether the SLIDE is still
69
+ * the slide. Both matter and neither implies the other: a comment can be
70
+ * `exact` (that slide is untouched) against a deck that is forty commits older
71
+ * than the one in front of you, and knowing which version somebody was reading
72
+ * is what lets you go and look.
73
+ *
74
+ * `null` when the question cannot be asked — no repository, or a comment
75
+ * written without one. Never `0`: "nobody knows" and "no commits since" are
76
+ * different answers and only one of them is reassuring.
77
+ */
78
+ export function commitsSince(deckCommit, cwd, run = git) {
79
+ if (!deckCommit) return null;
80
+ try {
81
+ const n = run(['rev-list', '--count', `${deckCommit}..HEAD`], cwd);
82
+ return Number.isFinite(Number(n)) ? Number(n) : null;
83
+ } catch { return null; } // the commit is not in this clone — see reviewedElsewhere
84
+ }
85
+
86
+ /**
87
+ * Is this commit one this repository has ever heard of?
88
+ *
89
+ * A comment can arrive by `--import` from somebody whose clone had commits
90
+ * yours does not, and reporting "0 commits since" for a hash you cannot resolve
91
+ * would be a confident lie.
92
+ */
93
+ export function knowsCommit(deckCommit, cwd, run = git) {
94
+ if (!deckCommit) return false;
95
+ try { run(['cat-file', '-e', `${deckCommit}^{commit}`], cwd); return true; } catch { return false; }
96
+ }
97
+
98
+ /** One slide's text out of a whole deck, by number. */
99
+ export function slideTextOf(html, n) {
100
+ const body = sectionBodies(html)[(n ?? 0) - 1];
101
+ return body === undefined ? '' : slideText(sectionInner(body));
102
+ }
103
+
104
+ /** `2h ago`, `3d ago` — the same shape `git log --format=%ar` gives elsewhere. */
105
+ export function ago(iso, now = Date.now()) {
106
+ const then = Date.parse(iso ?? '');
107
+ if (!Number.isFinite(then)) return '';
108
+ const s = Math.max(0, Math.round((now - then) / 1000));
109
+ if (s < 90) return 'just now';
110
+ const m = Math.round(s / 60);
111
+ if (m < 60) return `${m} minutes ago`;
112
+ const h = Math.round(m / 60);
113
+ if (h < 2) return 'an hour ago';
114
+ if (h < 36) return `${h} hours ago`;
115
+ return `${Math.round(h / 24)} days ago`;
116
+ }
117
+
118
+ /**
119
+ * Comments, resolved and grouped for printing.
120
+ *
121
+ * Orphans go last, deliberately: they are the ones with no slide to sit under,
122
+ * and burying them among the numbered groups is how they get missed.
123
+ */
124
+ export function groupComments(comments, slides) {
125
+ const anchored = comments.map((c) => ({ ...c, anchor: resolveAnchor(c, slides) }));
126
+ const groups = new Map();
127
+ const orphans = [];
128
+ for (const c of anchored) {
129
+ if (c.anchor.verdict === 'orphaned') { orphans.push(c); continue; }
130
+ if (!groups.has(c.anchor.slide)) groups.set(c.anchor.slide, []);
131
+ groups.get(c.anchor.slide).push(c);
132
+ }
133
+ return {
134
+ groups: [...groups.entries()].sort((a, b) => a[0] - b[0])
135
+ .map(([slide, items]) => ({ slide, title: slides[slide - 1]?.title ?? '', items })),
136
+ orphans,
137
+ };
138
+ }
139
+
140
+ /**
141
+ * `--incoming`: the SSH-and-pipes surface for "what reviews are waiting".
142
+ *
143
+ * Exit 0 when the question was ANSWERED — including "none" — and 1 only when
144
+ * it could not be asked. A script watching for reviews needs to tell "nothing
145
+ * waiting" from "the network was down", which is the whole reason
146
+ * `reviewsWaiting` returns states instead of an array.
147
+ */
148
+ async function listIncoming(deckPath, { remote, name, out, err }) {
149
+ const r = await reviewsWaiting(deckPath, { remote });
150
+ if (r.state === 'ok') {
151
+ for (const v of r.reviews) {
152
+ out.write(`${v.branch} ${v.comments} comment${v.comments === 1 ? '' : 's'}`
153
+ + `${v.replies ? ` (+${v.replies} repl${v.replies === 1 ? 'y' : 'ies'})` : ''}`
154
+ + `${v.unreadable ? ` (${v.unreadable} unreadable line${v.unreadable === 1 ? '' : 's'})` : ''}`
155
+ + ` · ${v.who}${v.at ? ` · ${ago(v.at)}` : ''}\n`);
156
+ }
157
+ // The deck is the doorway: M shows these comments and T takes a review
158
+ // in. Plain git still works — merging the branch brings the sidecar
159
+ // through the union merge — for whoever prefers the terminal end to end.
160
+ out.write(`\ntake them in: decklight author ${name} then M in the deck`
161
+ + ` (or: git merge ${remote}/${r.reviews[0].branch})\n`);
162
+ return 0;
163
+ }
164
+ if (r.state === 'none') { out.write(`no reviews waiting on ${remote}\n`); return 0; }
165
+ if (r.state === 'no-repo') { err.write(`decklight comments: ${name} is not in a git repository\n`); return 1; }
166
+ if (r.state === 'untracked') { err.write(`decklight comments: ${name} is not a file this repository tracks\n`); return 1; }
167
+ if (r.state === 'no-remote') { err.write(`decklight comments: no remote "${remote}" here (git remote add ${remote} <url>)\n`); return 1; }
168
+ // could not ask — which is an answer, and never rendered as "none waiting"
169
+ err.write(`decklight comments: could not check ${remote} — ${r.state}`
170
+ + `${r.reason ? ` (${r.reason.split('\n')[0]})` : ''}\n`);
171
+ return 1;
172
+ }
173
+
174
+ export function commentsMain(argv = process.argv.slice(2), { out = process.stdout, err = process.stderr } = {}) {
175
+ const { opt } = argReader(argv);
176
+ if (argv.includes('--help') || argv.includes('-h')) { out.write(HELP); return 0; }
177
+
178
+ const cwd = process.cwd();
179
+ let deckArg = argv.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
180
+ if (!deckArg) {
181
+ const { decks } = findDeck(cwd);
182
+ if (decks.length === 1) [deckArg] = decks;
183
+ else if (!decks.length) {
184
+ err.write('decklight comments: name the deck — no decklight deck found in this directory\n');
185
+ return 1;
186
+ } else {
187
+ err.write(`decklight comments: name the deck — this directory has ${decks.length}`
188
+ + ` (${decks.slice(0, 4).join(', ')}${decks.length > 4 ? ', …' : ''})\n`);
189
+ return 1;
190
+ }
191
+ }
192
+ const deckPath = resolve(cwd, deckArg);
193
+ const name = basename(deckPath);
194
+ if (!existsSync(deckPath)) { err.write(`decklight comments: no such file: ${deckArg}\n`); return 1; }
195
+
196
+ const storePath = reviewPathFor(deckPath);
197
+ const storeName = basename(storePath);
198
+ const deckDir = dirname(deckPath);
199
+ const read = (p) => (existsSync(p) ? readFileSync(p, 'utf8') : '');
200
+
201
+ // ── --incoming: what reviews are waiting on the remote ──────────────────
202
+ // The async door in a sync command: everything else here reads local files,
203
+ // and staying sync is what keeps the tests and the dispatcher simple. This
204
+ // one flag genuinely asks the network, so it alone returns a promise — both
205
+ // production callers await the result either way.
206
+ if (argv.includes('--incoming')) {
207
+ return listIncoming(deckPath, {
208
+ remote: opt('--remote', 'origin'), name: relative(cwd, deckPath) || name, out, err,
209
+ });
210
+ }
211
+
212
+ // ── --import: the no-repo reviewer's return path ────────────────────────
213
+ const importArg = opt('--import');
214
+ if (importArg !== undefined) {
215
+ const from = resolve(cwd, importArg);
216
+ if (!existsSync(from)) { err.write(`decklight comments: no such file: ${importArg}\n`); return 1; }
217
+ const incoming = parseReview(read(from));
218
+ if (!incoming.records.length) {
219
+ err.write(`decklight comments: ${basename(from)} has no comments in it`
220
+ + `${incoming.skipped ? ` (${incoming.skipped} unreadable line(s))` : ''}\n`);
221
+ return 1;
222
+ }
223
+ const mine = parseReview(read(storePath)).records;
224
+ const { records, added } = mergeById(mine, incoming.records);
225
+ if (!added) {
226
+ out.write(`${basename(from)} — nothing new; all ${incoming.records.length} already here\n`);
227
+ return 0;
228
+ }
229
+ writeFileSync(storePath, records.map(serializeRecord).join('\n') + '\n');
230
+ out.write(`${basename(from)} → ${storeName}: ${added} new`
231
+ + `${incoming.records.length - added ? `, ${incoming.records.length - added} already here` : ''}\n`);
232
+ if (gitAvailable(deckDir) && inGitRepo(deckDir)) {
233
+ const ok = gitAutocommit(storePath, deckDir, `review: import ${added} comment(s) on ${name}`);
234
+ out.write(ok ? ' committed\n' : ' not committed — nothing changed on disk\n');
235
+ }
236
+ out.write(` read them with: decklight comments ${relative(cwd, deckPath) || name}\n`);
237
+ return 0;
238
+ }
239
+
240
+ // ── --at: what were they actually looking at ────────────────────────────
241
+ //
242
+ // Every comment records the commit the deck was on when it was written, and
243
+ // this is what that field is FOR. An anchor verdict can say "this slide
244
+ // changed since" without being able to say HOW, and "how" is usually the
245
+ // whole question — a reviewer objecting to a sentence that is no longer
246
+ // there has either been answered already or been misread.
247
+ const atArg = opt('--at');
248
+ if (atArg !== undefined) {
249
+ if (!existsSync(storePath)) { err.write(`decklight comments: ${name} has no comments\n`); return 1; }
250
+ const { records } = parseReview(read(storePath));
251
+ const c = foldReview(records).find((x) => x.id === atArg);
252
+ if (!c) { err.write(`decklight comments: no comment [${atArg}] on ${name}\n`); return 1; }
253
+ if (!c.deck) {
254
+ err.write(`decklight comments: [${atArg}] records no commit`
255
+ + ' — it was written outside a repository, so there is no earlier version to show\n');
256
+ return 1;
257
+ }
258
+ if (!(gitAvailable(deckDir) && inGitRepo(deckDir)) || !knowsCommit(c.deck, deckDir)) {
259
+ err.write(`decklight comments: this clone does not have ${c.deck}`
260
+ + ' — the comment came from somewhere with commits this repository has not seen\n');
261
+ return 1;
262
+ }
263
+ let thenHtml;
264
+ try { thenHtml = deckAt(deckPath, c.deck, deckDir); }
265
+ catch (e) { err.write(`decklight comments: could not read ${name} at ${c.deck}: ${oneline(e)}\n`); return 1; }
266
+
267
+ const thenSlides = indexDeckFile(thenHtml);
268
+ const nowSlides = indexDeckFile(read(deckPath));
269
+ // the slide as it was is found by the comment's own index — at THAT commit
270
+ // the number was still true, which is exactly why it was recorded
271
+ const wasAt = thenSlides[(c.slide ?? 0) - 1];
272
+ const anchor = resolveAnchor(c, nowSlides);
273
+ const nowAt = anchor.slide ? nowSlides[anchor.slide - 1] : null;
274
+
275
+ out.write(`[${c.id}] ${c.by ? c.by.replace(/\s*<[^>]*>$/, '') : 'someone'}`
276
+ + `${c.at ? ` · ${ago(c.at)}` : ''} · against ${c.deck}\n`);
277
+ for (const line of String(c.body ?? '').split('\n')) out.write(` ${line}\n`);
278
+ out.write('\n');
279
+ out.write(` then · slide ${c.slide} · ${wasAt?.title ?? '(gone even then)'}\n`);
280
+ out.write(` ${slideTextOf(thenHtml, c.slide) || '(nothing)'}\n\n`);
281
+ if (!nowAt) {
282
+ out.write(` now · ${VERDICT_NOTE.orphaned}\n`);
283
+ } else {
284
+ out.write(` now · slide ${anchor.slide} · ${nowAt.title}`
285
+ + `${anchor.movedFrom ? ` (moved from ${anchor.movedFrom})` : ''}`
286
+ + `${anchor.verdict === 'exact' ? ' — unchanged' : ''}\n`);
287
+ out.write(` ${slideTextOf(read(deckPath), anchor.slide) || '(nothing)'}\n`);
288
+ }
289
+ return 0;
290
+ }
291
+
292
+ // ── the listing ─────────────────────────────────────────────────────────
293
+ if (!existsSync(storePath)) {
294
+ // Not an error: no comments is the state every deck starts in, and the
295
+ // useful answer is how somebody would leave one.
296
+ out.write(`${name} — no comments yet\n`);
297
+ out.write(` a reviewer leaves them with: decklight review ${relative(cwd, deckPath) || name}\n`);
298
+ return 0;
299
+ }
300
+ const { records, skipped } = parseReview(read(storePath));
301
+ const slides = indexDeckFile(read(deckPath));
302
+ const all = foldReview(records);
303
+ const wantAll = argv.includes('--all');
304
+ const onlyOpen = argv.includes('--unresolved');
305
+ const resolvedCount = all.filter((c) => c.resolved).length;
306
+ const shown = all.filter((c) => (onlyOpen || !wantAll ? !c.resolved : true));
307
+
308
+ if (!all.length) {
309
+ out.write(`${name} — ${storeName} exists but holds no comments\n`);
310
+ return 0;
311
+ }
312
+
313
+ const { groups, orphans } = groupComments(shown, slides);
314
+ const openCount = all.length - resolvedCount;
315
+ out.write(`${name} — ${openCount} open comment${openCount === 1 ? '' : 's'}`
316
+ + `${resolvedCount ? `, ${resolvedCount} resolved` : ''}`
317
+ + ` across ${slides.length} slide${slides.length === 1 ? '' : 's'}\n`);
318
+ if (skipped) out.write(` (${skipped} line(s) in ${storeName} could not be read and were skipped)\n`);
319
+ out.write('\n');
320
+
321
+ const inRepo = gitAvailable(deckDir) && inGitRepo(deckDir);
322
+ /**
323
+ * Which version this was written against, and how far the deck has moved.
324
+ *
325
+ * Silent when there is nothing to say — no commit recorded, or the deck has
326
+ * not moved — because a line that appears on every comment is a line nobody
327
+ * reads by the third one.
328
+ */
329
+ // Memoized by hash: `knowsCommit` and `commitsSince` are a git process
330
+ // each, and a reviewed deck repeats the same few hashes across dozens of
331
+ // comments — without this, listing 50 comments spawned up to 100 gits to
332
+ // learn perhaps three answers.
333
+ const againstCache = new Map();
334
+ const against = (c) => {
335
+ if (!c.deck) return '';
336
+ if (againstCache.has(c.deck)) return againstCache.get(c.deck);
337
+ let line;
338
+ if (!inRepo || !knowsCommit(c.deck, deckDir)) line = ` · against ${c.deck}`;
339
+ else {
340
+ const n = commitsSince(c.deck, deckDir);
341
+ line = n === null ? ` · against ${c.deck}`
342
+ : n === 0 ? ` · against ${c.deck} (still current)`
343
+ : ` · against ${c.deck}, ${n} commit${n === 1 ? '' : 's'} ago`;
344
+ }
345
+ againstCache.set(c.deck, line);
346
+ return line;
347
+ };
348
+
349
+ const printOne = (c, indent = ' ') => {
350
+ const who = c.by ? c.by.replace(/\s*<[^>]*>$/, '') : 'someone';
351
+ out.write(`${indent}${who}${c.at ? ` · ${ago(c.at)}` : ''}${against(c)}`
352
+ + `${c.resolved ? ' ✓ resolved' : ''} [${c.id}]\n`);
353
+ for (const line of String(c.body ?? '').split('\n')) out.write(`${indent} ${line}\n`);
354
+ for (const r of c.replies ?? []) {
355
+ const rw = r.by ? r.by.replace(/\s*<[^>]*>$/, '') : 'someone';
356
+ out.write(`${indent} ↳ ${rw}${r.at ? ` · ${ago(r.at)}` : ''}\n`);
357
+ for (const line of String(r.body ?? '').split('\n')) out.write(`${indent} ${line}\n`);
358
+ }
359
+ out.write('\n');
360
+ };
361
+
362
+ for (const g of groups) {
363
+ // The verdict rides on the GROUP heading when every comment in it agrees,
364
+ // which is the usual case and keeps the noise off the prose.
365
+ const notes = new Set(g.items.map((c) => c.anchor.verdict).filter((v) => VERDICT_NOTE[v]));
366
+ const moved = g.items.find((c) => c.anchor.movedFrom);
367
+ out.write(` slide ${g.slide} · ${g.title}`
368
+ + `${moved ? ` (was slide ${moved.anchor.movedFrom} when this was written)` : ''}\n`);
369
+ for (const v of notes) out.write(` ⚠ ${VERDICT_NOTE[v]}\n`);
370
+ for (const c of g.items) printOne(c);
371
+ }
372
+ if (orphans.length) {
373
+ out.write(` ${orphans.length} comment${orphans.length === 1 ? '' : 's'} on slides that are gone\n`);
374
+ out.write(` ⚠ ${VERDICT_NOTE.orphaned}\n`);
375
+ for (const c of orphans) {
376
+ out.write(` (was slide ${c.slide}${c.title ? ` · ${c.title}` : ''})\n`);
377
+ printOne(c, ' ');
378
+ }
379
+ }
380
+ if (!groups.length && !orphans.length) {
381
+ out.write(` nothing open — all ${all.length} resolved (--all to see them)\n`);
382
+ }
383
+ return 0;
384
+ }
385
+
386
+ if (isMain(import.meta.url)) {
387
+ try { process.exitCode = await commentsMain(); }
388
+ catch (e) { process.stderr.write(`decklight comments: ${oneline(e)}\n`); process.exitCode = 1; }
389
+ }