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
@@ -0,0 +1,292 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // `decklight review submit` — send the comments back. SPEC REVIEW.
6
+ //
7
+ // A review that never leaves the reviewer's laptop is a review that did not
8
+ // happen. `decklight review` commits comments locally and then nothing happens:
9
+ // the reviewer presses Ctrl-C and walks away with commits nobody will ever see.
10
+ //
11
+ // WHAT THIS PUSHES, AND WHAT IT DOES NOT.
12
+ //
13
+ // Not the reviewer's branch. `review` commits each comment onto whatever branch
14
+ // they happen to be on, so pushing that would drag every unrelated local commit
15
+ // into somebody else's pull request. Instead this builds a commit the way
16
+ // cli/publish.mjs does — one blob, one tree parented on what the REMOTE has,
17
+ // one commit-tree, one push by object name:
18
+ //
19
+ // hash-object -w --stdin the sidecar's current bytes
20
+ // ls-remote / fetch / rev-parse FETCH_HEAD the parent, as the remote has it
21
+ // putBlob(parent, <path>, blob) every sibling preserved
22
+ // commit-tree <tree> -p <parent>
23
+ // push <sha>:refs/heads/review/<user>-<date>
24
+ //
25
+ // So the pull request's diff is exactly one file, and the working tree, the
26
+ // index and the checked-out branch are never touched — there is no `add`, no
27
+ // `checkout`, no `branch` and no `update-ref` anywhere in the path. That is
28
+ // asserted in test/review-submit.test.mjs with the same `write-tree` snapshot
29
+ // test/publish.test.mjs uses.
30
+ //
31
+ // ON PUSHING AT ALL. SPEC REVIEW said comments were "never pushed", and this
32
+ // changes that sentence deliberately rather than quietly. The invariant that
33
+ // carries the safety is not "no push exists" but "the SERVER never pushes":
34
+ // what a browser is pointed at holds no such capability. This is a subcommand
35
+ // somebody typed, which is the argument `publish` already makes.
36
+
37
+ import { execFileSync } from 'node:child_process';
38
+ import { existsSync, readFileSync } from 'node:fs';
39
+ import { basename, dirname, resolve } from 'node:path';
40
+
41
+ import { makeFail } from './util.mjs';
42
+ import { noPromptEnv, oneline, ownerRepo } from './git.mjs';
43
+ import { refProblem } from './marketplace.mjs';
44
+ import { putBlob, remoteHead } from './git-tree.mjs';
45
+ import { reviewPathFor, parseReview } from './review-store.mjs';
46
+ import { foldReview } from '../tools/review-anchor.mjs';
47
+ import { reviewerIdentity } from './review.mjs';
48
+ import { ghReady } from './init.mjs';
49
+
50
+ const fail = makeFail('review submit');
51
+
52
+ /**
53
+ * A branch-safe rendering of who is speaking.
54
+ *
55
+ * The email's local part first — it is nearly always `[a-z0-9._-]` already and
56
+ * it is the half that identifies a person rather than describing them. The
57
+ * display name is the fallback and needs the most work: "Ana Ruiz" has a space,
58
+ * which git refuses in a ref.
59
+ *
60
+ * Lossy on purpose, and the loss is covered: the FULL identity rides in the
61
+ * commit's `Signed-off-by`, so the branch name never has to be the only record
62
+ * of who wrote a review.
63
+ */
64
+ export function slugUser(identity) {
65
+ const s = String(identity ?? '');
66
+ const email = /<([^>]*)>/.exec(s)?.[1] ?? (s.includes('@') ? s : '');
67
+ const from = email ? email.split('@')[0] : s;
68
+ const slug = from.toLowerCase().normalize('NFKD')
69
+ .replace(/[^a-z0-9._-]+/g, '-')
70
+ .replace(/^[-._]+|[-._]+$/g, '')
71
+ .replace(/-{2,}/g, '-')
72
+ .slice(0, 32);
73
+ // Never empty: a machine with no git identity still gets to submit, and
74
+ // "reviewer" is a true statement about whoever that is.
75
+ return slug || 'reviewer';
76
+ }
77
+
78
+ /**
79
+ * `review/<user>-<YYYY-MM-DD>`.
80
+ *
81
+ * The date is an ISO 8601 calendar date and NOT a full timestamp, because git
82
+ * refuses a `:` in a ref name and an ISO time is full of them. One branch per
83
+ * reviewer per day is also the more useful shape: a second submit the same day
84
+ * lands on the same branch, so a morning's reviewing is one branch and one pull
85
+ * request rather than one per time you pressed the button.
86
+ */
87
+ export function branchName(identity, when = new Date()) {
88
+ const day = when.toISOString().slice(0, 10);
89
+ return `review/${slugUser(identity)}-${day}`;
90
+ }
91
+
92
+ // The GitHub-remote parser moved to cli/git.mjs — `pagesUrl` shares it now.
93
+ // Re-exported so this module keeps answering for the thing `--pr` needs.
94
+ export { ownerRepo } from './git.mjs';
95
+
96
+ /**
97
+ * The compare URL a reviewer can hand somebody when there is no `gh`.
98
+ *
99
+ * `base` is the branch the review is of; without it GitHub compares against
100
+ * the repository default, which for a review of branchA is a page full of
101
+ * branchA's own commits with the comments buried at the bottom.
102
+ */
103
+ export function compareUrl(remoteUrl, branch, base = null) {
104
+ const at = ownerRepo(remoteUrl);
105
+ if (!at) return null;
106
+ // per SEGMENT: the branch's own `/` is part of the path GitHub expects,
107
+ // and encoding it to %2F gives a compare page for a branch nobody has
108
+ const seg = (b) => b.split('/').map(encodeURIComponent).join('/');
109
+ const range = base ? `${seg(base)}...${seg(branch)}` : seg(branch);
110
+ return `https://github.com/${at.owner}/${at.repo}/compare/${range}?expand=1`;
111
+ }
112
+
113
+ /**
114
+ * Push the deck's review sidecar to a branch of its own.
115
+ *
116
+ * `exec` and `now` are injected so the whole thing is testable against a bare
117
+ * repository without a clock.
118
+ */
119
+ export function submitReview(deckPath, {
120
+ remote = 'origin', pr = false, dryRun = false, out = process.stdout,
121
+ exec = execFileSync, now = () => new Date(), gh = ghReady,
122
+ } = {}) {
123
+ const cwd = dirname(resolve(deckPath));
124
+ const name = basename(deckPath);
125
+ // The deck's own directory, like publish: the repository being reviewed is
126
+ // the deck's, wherever the command was typed.
127
+ const git = (args, input) => {
128
+ try {
129
+ return exec('git', args, { cwd, encoding: 'utf8', input, env: noPromptEnv() }).trim();
130
+ } catch (e) {
131
+ fail(`git ${args[0]} failed: ${(e.stderr || e.message || '').toString().trim()}`);
132
+ }
133
+ };
134
+
135
+ if (!existsSync(deckPath)) fail(`no such deck: ${deckPath}`);
136
+ const storePath = reviewPathFor(resolve(deckPath));
137
+ if (!existsSync(storePath)) {
138
+ fail(`no comments to submit — ${basename(storePath)} does not exist yet`
139
+ + `\n leave some first: decklight review ${name}`);
140
+ }
141
+ const bytes = readFileSync(storePath, 'utf8');
142
+ const { records } = parseReview(bytes);
143
+ if (!records.length) fail(`${basename(storePath)} has no comments in it`);
144
+
145
+ try { exec('git', ['rev-parse', '--git-dir'], { cwd, stdio: 'ignore' }); }
146
+ catch { fail(`${cwd} is not inside a git repository — there is nowhere to push to`); }
147
+ let remoteUrl;
148
+ try { remoteUrl = exec('git', ['remote', 'get-url', remote], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
149
+ catch { fail(`no remote "${remote}" in this repository (git remote add ${remote} <url>)`); }
150
+
151
+ const who = reviewerIdentity(cwd, exec);
152
+ const branch = branchName(who, now());
153
+ // The house rule: refuse a bad ref rather than repair it. `refProblem` is an
154
+ // allowlist that already covers every character git forbids plus a leading
155
+ // `-`, which would be read as an option rather than a ref.
156
+ const bad = refProblem(branch);
157
+ if (bad) fail(`the branch name ${JSON.stringify(branch)} ${bad}`);
158
+
159
+ // The parent, as the REMOTE has it. The review branch if it is already there
160
+ // (a second submit today appends to this morning's), else the branch this
161
+ // deck sits on, so the diff is the comments and nothing else.
162
+ const head = (ref) => remoteHead(git, remote, ref);
163
+ let parent = head(`refs/heads/${branch}`);
164
+ const resubmit = Boolean(parent);
165
+ // The branch the review is OF — reviewing a deck on branchA means the pull
166
+ // request must target branchA, or its diff shows branchA's own commits
167
+ // against the default branch with the comments buried underneath. Resolved
168
+ // even on a resubmit, when the parent is the review branch itself: the base
169
+ // is still what --pr and the compare URL diff against.
170
+ let base = null;
171
+ {
172
+ // whatever this checkout tracks, as the remote has it
173
+ let upstreamRef = null;
174
+ try {
175
+ const up = exec('git', ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'],
176
+ // stderr captured, not inherited: "no upstream" is an ANSWER here, and
177
+ // execFileSync would otherwise print git's fatal: line mid-success
178
+ { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
179
+ if (up) upstreamRef = `refs/heads/${up.split('/').slice(1).join('/')}`;
180
+ } catch { upstreamRef = null; }
181
+ if (upstreamRef) {
182
+ const at = head(upstreamRef);
183
+ if (at) {
184
+ base = upstreamRef.slice('refs/heads/'.length);
185
+ if (!parent) parent = at;
186
+ }
187
+ }
188
+ }
189
+ if (!base) {
190
+ // No upstream — a detached HEAD (a reviewer on a tag), or a local branch
191
+ // never pushed. The remote's own default branch is the right base then:
192
+ // it is what a pull request would diff against anyway.
193
+ try {
194
+ const sym = exec('git', ['ls-remote', '--symref', remote, 'HEAD'],
195
+ { cwd, encoding: 'utf8', env: noPromptEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
196
+ const m = /^ref:\s+(refs\/heads\/\S+)\s+HEAD/m.exec(sym);
197
+ if (m) {
198
+ const at = head(m[1]);
199
+ if (at) {
200
+ base = m[1].slice('refs/heads/'.length);
201
+ if (!parent) parent = at;
202
+ }
203
+ }
204
+ } catch { /* refusal below says what came back empty */ }
205
+ }
206
+ // NEVER AN ORPHAN. publish's orphan path is correct for gh-pages — a branch
207
+ // whose whole history is the site. Here an orphan would be a commit whose
208
+ // tree holds ONLY the sidecar, and a pull request from it reads as "delete
209
+ // every file in the repository": a diff that proposes catastrophe, printed
210
+ // under a success message. If no parent can be resolved, the true state is
211
+ // "I cannot see what to base this on", and that is a refusal, not a guess.
212
+ if (!parent) {
213
+ fail(`could not find a commit on ${remote} to base the review on`
214
+ + `\n the review branch, this checkout's upstream, and ${remote}'s default branch all came back empty`
215
+ + `\n push the deck's branch first, or pass --remote if the deck lives on another remote`);
216
+ }
217
+
218
+ const blob = git(['hash-object', '-w', '--stdin'], bytes);
219
+ // `--show-prefix` (where cwd sits under the root), NOT `relative(--show-toplevel, …)`.
220
+ // On macOS the toplevel comes back as /private/var/… while the deck path is
221
+ // /var/… — the same directory through a symlink — and `relative` of those two
222
+ // is a string of `../..` that escapes the repository. That does not throw: it
223
+ // builds a tree with the sidecar at an absurd name and the real directories
224
+ // flattened out of it, which is a silently corrupt push.
225
+ const prefix = git(['rev-parse', '--show-prefix']);
226
+ const inRepo = [...prefix.split('/').filter(Boolean), basename(storePath)];
227
+ const tree = putBlob(git, parent, inRepo, blob);
228
+
229
+ // The same fold `decklight comments` renders with — a raw line count would
230
+ // double-count union-merge duplicates and call a resolved comment a comment.
231
+ const n = foldReview(records).filter((c) => !c.resolved).length;
232
+ // A sidecar can hold nothing but resolves and replies — still worth pushing
233
+ // (the union merge wants them), but never announced as "0 comments".
234
+ const what = n ? `${n} comment${n === 1 ? '' : 's'}` : 'updates';
235
+ let message = `review: ${what} on ${name}`;
236
+ if (who) message += `\n\nSigned-off-by: ${who}`;
237
+ const env = who
238
+ ? { ...process.env, ...noPromptEnv() }
239
+ : {
240
+ ...process.env,
241
+ ...noPromptEnv(),
242
+ GIT_AUTHOR_NAME: 'decklight', GIT_AUTHOR_EMAIL: 'decklight@localhost',
243
+ GIT_COMMITTER_NAME: 'decklight', GIT_COMMITTER_EMAIL: 'decklight@localhost',
244
+ };
245
+ let commit;
246
+ try {
247
+ commit = exec('git', ['commit-tree', tree, '-p', parent, '-m', message],
248
+ { cwd, encoding: 'utf8', env }).trim();
249
+ } catch (e) { fail(`git commit-tree failed: ${oneline(e)}`); }
250
+
251
+ if (dryRun) {
252
+ out.write(`would push ${commit.slice(0, 7)} → ${remote} ${branch}`
253
+ + ` (${what}${resubmit ? ', onto the branch already there' : ''})\n`);
254
+ out.write(' --dry-run: nothing was pushed, and no ref was written\n');
255
+ return { branch, base, commit, pushed: false, comments: n, resubmit };
256
+ }
257
+
258
+ git(['push', '--quiet', remote, `${commit}:refs/heads/${branch}`]);
259
+ out.write(`pushed ${what} on ${name} → ${remote} ${branch}\n`);
260
+
261
+ let prUrl = null;
262
+ if (pr) {
263
+ const at = ownerRepo(remoteUrl);
264
+ if (!at) out.write(` --pr: ${remote} is not a GitHub remote — the branch is pushed\n`);
265
+ else if (!gh(exec)) out.write(' --pr: needs gh installed and signed in (gh auth login) — the branch is pushed\n');
266
+ else {
267
+ try {
268
+ prUrl = exec('gh', ['pr', 'create',
269
+ '--repo', `${at.owner}/${at.repo}`,
270
+ '--head', branch,
271
+ // The branch the review is of — NOT the repo default. A review of a
272
+ // deck on branchA against main would diff all of branchA plus the
273
+ // comments, which is a pull request about the wrong thing.
274
+ ...(base ? ['--base', base] : []),
275
+ '--title', `Review: ${what} on ${name}`,
276
+ '--body', `Left with \`decklight review ${name}\`.\n\n`
277
+ + `Read them with:\n\n decklight comments ${name}\n`,
278
+ ], { cwd, encoding: 'utf8', env: noPromptEnv(), timeout: 60_000 }).trim();
279
+ out.write(` ${prUrl}\n`);
280
+ } catch (e) {
281
+ // A note, never an exit: the comments are pushed, which is the product.
282
+ out.write(` --pr: gh could not open it — ${oneline(e)}\n`);
283
+ }
284
+ }
285
+ }
286
+ if (!prUrl) {
287
+ const url = compareUrl(remoteUrl, branch, base);
288
+ if (url) out.write(` open a pull request: ${url}\n`);
289
+ else out.write(` tell the author: git fetch ${remote} ${branch}\n`);
290
+ }
291
+ return { branch, base, commit, pushed: true, comments: n, resubmit, pr: prUrl };
292
+ }
package/cli/review.mjs ADDED
@@ -0,0 +1,361 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight review — leave comments on somebody's deck. SPEC REVIEW.
6
+ //
7
+ // decklight review <deck.html> [--port 8790] [--no-open] [--no-git]
8
+ //
9
+ // WHY THIS IS ITS OWN COMMAND, AND ITS OWN SERVER.
10
+ //
11
+ // SPEC PRESENTING refuses, three separate times, to let a server that is not
12
+ // the authoring server acquire a write capability: "a server that can move a
13
+ // deck that did not ask is an editing server with the writes left out, and that
14
+ // capability is not created here", and "a shared path with a boolean in it is
15
+ // how a presenting server quietly acquires an editing capability later".
16
+ //
17
+ // So reviewing is not a flag on `present` (which writes nothing, by
18
+ // construction — it registers no /edit/* route to have refused) and not a flag
19
+ // on `author` (which would hand a reviewer the power to rewrite the deck they
20
+ // were asked to read). It is a third command with a third route namespace, and
21
+ // the capability it adds is stated by what it registers rather than by what it
22
+ // checks:
23
+ //
24
+ // GET /review/ping who am I looking at
25
+ // GET /review/comments what has been said
26
+ // POST /review/comments say one thing
27
+ //
28
+ // There is no /edit/*, and the deck file is opened for READING only. The one
29
+ // path this process will ever write is `<deck>.review.jsonl`. That is not a
30
+ // promise in a comment — test/review-server.test.mjs asserts every /edit/* route
31
+ // 405s and that the deck is byte-identical afterwards.
32
+ //
33
+ // Git is the backend but never the transport for the SERVER: with a repository,
34
+ // each comment is committed (the sidecar alone, staged by itself); with none,
35
+ // the file is just a file, which is the thing you send back. This server never
36
+ // pushes — pushing is `review submit` (cli/review-submit.mjs), a one-shot the
37
+ // reviewer types (or confirms in the overlay), and POST /review/submit below is
38
+ // that same code behind the same explicit gesture.
39
+
40
+ import { createServer } from 'node:http';
41
+ import { existsSync, readFileSync, appendFileSync } from 'node:fs';
42
+ import { basename, dirname, resolve, relative } from 'node:path';
43
+ import { execFileSync } from 'node:child_process';
44
+
45
+ import { argReader, firstPositional, isMain } from '../tools/args.mjs';
46
+ import { staticFiles, allowEditRequest, listenTakingOverIfNeeded } from './serve.mjs';
47
+ import { inGitRepo, gitAutocommit, gitAvailable, commitSubject, oneline } from './git.mjs';
48
+ import { reviewPathFor, parseReview, serializeRecord, newId } from './review-store.mjs';
49
+ import { openUrl } from './init.mjs';
50
+ import { exitWhenOrphaned } from './supervise.mjs';
51
+
52
+ const USAGE = `usage: decklight review <deck.html> [--port 8790] [--no-open] [--no-git]
53
+ open somebody's deck and leave comments on it, anchored to slides
54
+
55
+ ⇧M in the deck leaves a comment (M reads them all, or / → "Leave a comment…"); the
56
+ comment is attached to the slide you are looking at, and remembers enough
57
+ about it to find that slide again after the deck has moved on
58
+
59
+ --port N port to serve on (taken? moves to the next free one) [8790]
60
+ --no-open don't launch a browser — print the URL and wait
61
+ --no-git write the file and never commit it (each comment still records
62
+ WHICH COMMIT the deck was on — that is provenance, not bookkeeping)
63
+
64
+ comments land in <deck>.review.jsonl beside the deck: one line each,
65
+ append-only, so two reviewers never conflict and a push reads as a diff.
66
+ In a repository each one is committed; without one it is a file to send back
67
+ (the author reads it with: decklight comments <deck.html> --import <file>)
68
+
69
+ this server writes that file and nothing else — it has no /edit/* routes and
70
+ never opens the deck for writing
71
+
72
+ when you are done, send them: decklight review submit <deck.html>
73
+ `;
74
+
75
+ /**
76
+ * Who is speaking, from git's own answer — the only identity decklight has.
77
+ *
78
+ * `publish.mjs` reads it exactly this way, degrading to '' rather than failing,
79
+ * and a comment with no name is still a comment worth keeping: an unsigned
80
+ * remark from a machine with no git identity beats refusing to take it.
81
+ */
82
+ export function reviewerIdentity(cwd, exec = execFileSync) {
83
+ const cfg = (key) => {
84
+ try { return exec('git', ['config', key], { cwd, encoding: 'utf8' }).trim(); } catch { return ''; }
85
+ };
86
+ const name = cfg('user.name');
87
+ const email = cfg('user.email');
88
+ if (name && email) return `${name} <${email}>`;
89
+ return name || email || '';
90
+ }
91
+
92
+ /**
93
+ * The record a posted comment becomes.
94
+ *
95
+ * Pure, so the shape is testable without a server: the browser sends what it
96
+ * knows about the slide (its number, title and fingerprint) and the server adds
97
+ * what only it knows (who, when, and which commit of the deck was on screen).
98
+ *
99
+ * `body` is the reviewer's own prose and is stored verbatim — it is data here,
100
+ * never an argument to anything. The one place it could reach a command line is
101
+ * a commit subject, and that goes through `commitSubject`.
102
+ */
103
+ export function reviewRecord(input, { by, at, deck, id }) {
104
+ const rec = { id, at, ...(by ? { by } : {}), ...(deck ? { deck } : {}) };
105
+ if (input.re) rec.re = String(input.re);
106
+ else {
107
+ rec.slide = Number(input.slide);
108
+ if (input.title) rec.title = String(input.title).slice(0, 200);
109
+ if (input.fp) rec.fp = String(input.fp).slice(0, 32);
110
+ }
111
+ rec.body = String(input.body);
112
+ return rec;
113
+ }
114
+
115
+ /** What a posted comment must carry to be worth storing, or the reason it is not. */
116
+ export function commentProblem(input) {
117
+ if (!input || typeof input !== 'object') return 'not a comment';
118
+ const body = typeof input.body === 'string' ? input.body.trim() : '';
119
+ if (!body) return 'a comment needs something in it';
120
+ if (body.length > 4000) return 'that comment is longer than 4000 characters';
121
+ if (input.re !== undefined && (typeof input.re !== 'string' || !/^[a-z0-9]{1,12}$/.test(input.re))) {
122
+ return 'bad reply target';
123
+ }
124
+ if (input.re === undefined) {
125
+ const n = Number(input.slide);
126
+ if (!Number.isInteger(n) || n < 1 || n > 9999) return 'a comment belongs to a slide';
127
+ }
128
+ return null;
129
+ }
130
+
131
+ const SUBMIT_USAGE = `usage: decklight review submit <deck.html> [--pr] [--remote origin] [--dry-run]
132
+ push the comments you left to a branch of their own, for the author to read
133
+
134
+ the branch is review/<you>-<today>, and a second submit the same day lands on
135
+ the branch already there — a morning of reviewing is one branch, one PR
136
+
137
+ --pr also open a pull request (needs gh, signed in)
138
+ --remote NAME which remote to push to [origin]
139
+ --dry-run build the commit and stop before pushing anything
140
+
141
+ this pushes ONE FILE: the comments. Your branch, your working tree and your
142
+ index are never touched, and none of your own commits come along.
143
+ `;
144
+
145
+ /**
146
+ * `decklight review submit <deck>`.
147
+ *
148
+ * Thin on purpose — everything that could be got wrong lives in
149
+ * cli/review-submit.mjs, where it is testable without a process.
150
+ */
151
+ async function submitSubcommand(args, { out = process.stdout } = {}) {
152
+ const { opt } = argReader(args);
153
+ // The deck is the positional that LOOKS like a deck — `--remote upstream
154
+ // talk.html` must not read "upstream" as the deck. comments.mjs's rule.
155
+ const deckArg = args.find((a) => !a.startsWith('-') && /\.html?$/i.test(a));
156
+ if (!deckArg || args.includes('--help') || args.includes('-h')) {
157
+ out.write(SUBMIT_USAGE);
158
+ return deckArg ? 0 : 1;
159
+ }
160
+ const { submitReview } = await import('./review-submit.mjs');
161
+ try {
162
+ submitReview(resolve(process.cwd(), deckArg), {
163
+ remote: opt('--remote', 'origin'),
164
+ pr: args.includes('--pr'),
165
+ dryRun: args.includes('--dry-run'),
166
+ out,
167
+ });
168
+ return 0;
169
+ } catch (e) {
170
+ // CommandError already carries the command name and a way forward.
171
+ process.stderr.write(`${e?.message ?? e}\n`);
172
+ return 1;
173
+ }
174
+ }
175
+
176
+ export async function reviewMain(args, { open = openUrl, out = process.stdout, onListen = null } = {}) {
177
+ // `review submit <deck>` is a one-shot: it pushes what is already written and
178
+ // exits. It is dispatched here rather than as a command of its own because it
179
+ // is the second half of `review` — the same store, the same reviewer, and a
180
+ // person who typed one will look for the other in the same place.
181
+ if (args[0] === 'submit') return submitSubcommand(args.slice(1), { out });
182
+
183
+ if (args.includes('--help') || args.includes('-h') || !args.filter((a) => !a.startsWith('-')).length) {
184
+ out.write(USAGE);
185
+ return 0;
186
+ }
187
+ const { opt } = argReader(args);
188
+ const deckArg = firstPositional(args, ['--port']);
189
+ const root = process.cwd();
190
+ const deckPath = resolve(root, deckArg);
191
+ if (!existsSync(deckPath)) { process.stderr.write(`decklight review: no such deck: ${deckArg}\n`); return 1; }
192
+ if (!deckPath.startsWith(root + '/') && dirname(deckPath) !== root) {
193
+ process.stderr.write('decklight review: the deck must live under the current directory\n');
194
+ return 1;
195
+ }
196
+
197
+ const deckDir = dirname(deckPath);
198
+ const name = basename(deckPath);
199
+ const storePath = reviewPathFor(deckPath);
200
+ const storeName = basename(storePath);
201
+
202
+ // Git is the backend, not a requirement: a reviewer who was sent a file has
203
+ // no repository and must still be able to say something.
204
+ const noGit = args.includes('--no-git');
205
+ const inRepo = gitAvailable(deckDir) && inGitRepo(deckDir);
206
+ const gitOn = !noGit && inRepo;
207
+ // Whether THIS session pushed. Read by the Ctrl-C line below: a reviewer who
208
+ // wrote comments and never submitted should hear so on the way out.
209
+ let submitted = false;
210
+ const by = inRepo ? reviewerIdentity(deckDir) : '';
211
+ /**
212
+ * WHICH VERSION OF THE DECK this comment is about.
213
+ *
214
+ * Gated on being in a repository, NOT on `--no-git`. Those are two different
215
+ * questions: `--no-git` says "do not commit for me", and this says "which
216
+ * bytes was the reviewer looking at" — provenance, not bookkeeping. Suppressing
217
+ * it with the commit is how a comment loses the one fact that lets anybody
218
+ * check what the slide said at the time.
219
+ *
220
+ * `--short`, because it is read by people and lives in a line somebody scans.
221
+ */
222
+ const deckHead = () => {
223
+ if (!inRepo) return null;
224
+ try { return execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: deckDir, encoding: 'utf8' }).trim(); }
225
+ catch { return null; }
226
+ };
227
+
228
+ const files = staticFiles(deckDir, { knownTypesOnly: true });
229
+ const json = (res, code, body) => {
230
+ res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' });
231
+ res.end(JSON.stringify(body));
232
+ };
233
+
234
+ const server = createServer(async (req, res) => {
235
+ // The same origin gate the edit server uses, for the same reason: binding
236
+ // loopback is the wrong boundary when the dangerous caller is another tab
237
+ // in the reviewer's own browser.
238
+ if (!allowEditRequest(req)) { res.writeHead(403); res.end('this server answers this machine only'); return; }
239
+ const url = new URL(req.url, 'http://127.0.0.1');
240
+
241
+ if (req.method === 'GET' && url.pathname === '/review/ping') {
242
+ return json(res, 200, { ok: true, name, review: true, git: gitOn, by: by || null, store: storeName });
243
+ }
244
+
245
+ if (req.method === 'GET' && url.pathname === '/review/comments') {
246
+ const text = existsSync(storePath) ? readFileSync(storePath, 'utf8') : '';
247
+ const { records, skipped } = parseReview(text);
248
+ // `skipped` travels rather than being swallowed: a reader showing fewer
249
+ // comments than the file holds should be able to say so.
250
+ return json(res, 200, { ok: true, records, skipped });
251
+ }
252
+
253
+ if (req.method === 'POST' && url.pathname === '/review/comments') {
254
+ let body = '';
255
+ try {
256
+ for await (const chunk of req) { body += chunk; if (body.length > 1e5) throw new Error('too large'); }
257
+ } catch { return json(res, 413, { ok: false, error: 'that comment is too large' }); }
258
+ let input;
259
+ try { input = JSON.parse(body || '{}'); } catch { return json(res, 400, { ok: false, error: 'bad payload' }); }
260
+ const bad = commentProblem(input);
261
+ if (bad) return json(res, 400, { ok: false, error: bad });
262
+
263
+ const rec = reviewRecord(input, {
264
+ by, at: new Date().toISOString(), deck: deckHead(), id: newId(),
265
+ });
266
+ try {
267
+ // Append, never rewrite — that is what makes `merge=union` work and a
268
+ // second reviewer harmless.
269
+ appendFileSync(storePath, `${serializeRecord(rec)}\n`);
270
+ } catch (e) { return json(res, 500, { ok: false, error: oneline(e) }); }
271
+
272
+ let committed = false;
273
+ if (gitOn) {
274
+ // The reviewer's own prose reaching a command line, so it goes through
275
+ // the sanitizer every other untrusted subject does: one line, capped,
276
+ // never leading `-`.
277
+ const subject = commitSubject(`review: ${rec.body}`, `review: a comment on ${name}`);
278
+ committed = gitAutocommit(storePath, deckDir, subject);
279
+ }
280
+ out.write(` comment on slide ${rec.slide ?? '—'} → ${storeName}${committed ? ' (committed)' : ''}\n`);
281
+ return json(res, 200, { ok: true, id: rec.id, committed });
282
+ }
283
+
284
+ if (req.method === 'POST' && url.pathname === '/review/submit') {
285
+ // The browser NEVER runs git: it asks, and this server — the only thing
286
+ // in the room holding a capability — does the pushing, with the same
287
+ // code the typed `review submit` runs. Dynamically imported like the
288
+ // subcommand, so review-submit's static import of reviewerIdentity from
289
+ // this file never becomes a cycle.
290
+ try {
291
+ const { submitReview } = await import('./review-submit.mjs');
292
+ const lines = [];
293
+ const r = submitReview(deckPath, { out: { write: (t) => lines.push(t) } });
294
+ out.write(lines.join('')); // the terminal is a log of what happened
295
+ submitted = true;
296
+ return json(res, 200, { ok: true, branch: r.branch, comments: r.comments, resubmit: r.resubmit });
297
+ } catch (e) {
298
+ // A refusal (no remote, nothing to send) arrives with its way forward
299
+ // in the message — the browser toasts it verbatim.
300
+ return json(res, 500, { ok: false, error: String(e?.message ?? e) });
301
+ }
302
+ }
303
+
304
+ if (files(req, res, url)) return;
305
+ // Everything else — including every /edit/* path — lands here. There is no
306
+ // route to have refused, which is the point.
307
+ res.writeHead(405);
308
+ res.end();
309
+ });
310
+
311
+ const actual = await listenTakingOverIfNeeded(server, Number(opt('--port', 8790)), '127.0.0.1');
312
+ const deckUrl = `/${relative(deckDir, deckPath)}`;
313
+ const url = `http://127.0.0.1:${actual}${deckUrl}?review`;
314
+ if (onListen) onListen({ port: actual, deckUrl, server });
315
+
316
+ out.write(`decklight review on ${url}\n`);
317
+ out.write(' M opens the composer · the comment attaches to the slide you are on · Esc closes\n');
318
+ const existing = existsSync(storePath) ? parseReview(readFileSync(storePath, 'utf8')).records.length : 0;
319
+ out.write(` comments go to ${storeName}`
320
+ + `${existing ? ` (${existing} already there)` : ''}`
321
+ // --no-git inside a clone means "don't auto-commit", not "there is no
322
+ // repository" — saying the wrong one steers the reviewer away from
323
+ // `review submit`, which works fine there.
324
+ + `${gitOn ? ', committed as you go'
325
+ : inRepo ? ', not committed (--no-git)'
326
+ : ', not committed — this is not a git repository'}\n`);
327
+ if (!gitOn && !noGit) {
328
+ out.write(` send ${storeName} back when you are done; the author reads it with:\n`);
329
+ out.write(` decklight comments ${name} --import ${storeName}\n`);
330
+ }
331
+ // Where the comments go next. Said at startup rather than only on Ctrl-C: a
332
+ // reviewer who closes the terminal never sees an exit line, and a review that
333
+ // stays on their laptop is a review that did not happen.
334
+ // `deckArg`, not basename: this line exists to be PASTED, and for a deck in
335
+ // a subdirectory `review submit deck.html` resolves against cwd and fails.
336
+ // The path the reviewer just typed is, by construction, one that works here.
337
+ out.write(` when you are done, send them: decklight review submit ${deckArg}`
338
+ + `${inRepo ? '' : ` (no repository here — send ${storeName} back instead)`}\n`);
339
+ out.write(' Ctrl-C when you are done.\n');
340
+ if (!args.includes('--no-open')) await open(url, { out, what: url });
341
+
342
+ // The exit line. Local prints only — cli/edit.mjs:604's rule: a SIGINT
343
+ // handler that touched the network would hang the very keystroke that asks
344
+ // to leave.
345
+ process.on('SIGINT', () => {
346
+ if (!submitted && inRepo && existsSync(storePath)) {
347
+ const { records } = parseReview(readFileSync(storePath, 'utf8'));
348
+ const open_ = records.filter((r) => !r.op && !r.re).length;
349
+ if (open_) {
350
+ out.write(`\n${open_} comment${open_ === 1 ? '' : 's'} not submitted — send them with: decklight review submit ${deckArg}\n`);
351
+ }
352
+ }
353
+ process.exit(0);
354
+ });
355
+ return 0;
356
+ }
357
+
358
+ if (isMain(import.meta.url)) {
359
+ exitWhenOrphaned();
360
+ reviewMain(process.argv.slice(2)).then((code) => { if (code) process.exitCode = code; });
361
+ }