decklight 0.5.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 (53) hide show
  1. package/README.md +20 -9
  2. package/SPEC.md +239 -17
  3. package/cli/agents.mjs +97 -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 +475 -0
  10. package/cli/decklight.mjs +95 -25
  11. package/cli/dev.mjs +193 -25
  12. package/cli/edit.mjs +1055 -39
  13. package/cli/git-tree.mjs +87 -0
  14. package/cli/git.mjs +370 -0
  15. package/cli/history.mjs +145 -0
  16. package/cli/init.mjs +199 -7
  17. package/cli/marketplace.mjs +123 -17
  18. package/cli/port-conflict.mjs +228 -22
  19. package/cli/present.mjs +297 -12
  20. package/cli/publish.mjs +15 -40
  21. package/cli/record.mjs +154 -0
  22. package/cli/restore.mjs +120 -4
  23. package/cli/review-remote.mjs +330 -0
  24. package/cli/review-store.mjs +107 -0
  25. package/cli/review-submit.mjs +292 -0
  26. package/cli/review.mjs +361 -0
  27. package/cli/serve.mjs +60 -1
  28. package/cli/skill-content.mjs +12 -1
  29. package/cli/theme.mjs +78 -11
  30. package/cli/units.mjs +2 -2
  31. package/cli/upstream.mjs +256 -0
  32. package/cli/util.mjs +59 -0
  33. package/dist/build-info.json +1 -0
  34. package/dist/decklight.css +534 -3
  35. package/dist/decklight.js +102 -76
  36. package/dist/decklight.js.map +4 -4
  37. package/docs/architecture.svg +7 -0
  38. package/package.json +2 -1
  39. package/tools/args.mjs +20 -0
  40. package/tools/deck-html.mjs +84 -0
  41. package/tools/elevenlabs-tts.mjs +1 -1
  42. package/tools/lipsync-server.mjs +64 -2
  43. package/tools/lipsync.mjs +40 -24
  44. package/tools/local-voice.mjs +170 -16
  45. package/tools/publish-voices.mjs +78 -18
  46. package/tools/recording-impact.mjs +110 -0
  47. package/tools/review-anchor.mjs +180 -0
  48. package/tools/test-impact.mjs +259 -0
  49. package/tools/tts-engines.mjs +211 -12
  50. package/tools/tts-setup.mjs +2 -9
  51. package/tools/video.mjs +56 -12
  52. package/tools/voiceover-server.mjs +262 -11
  53. package/tools/voiceover.mjs +32 -13
@@ -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
+ }
@@ -0,0 +1,157 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Committing on YOUR word, with a snapshot underneath so the word can wait.
6
+ *
7
+ * The cadence used to commit the deck every `--commit-every` seconds. It cost
8
+ * nothing to write and it produced the thing everyone actually saw: a column of
9
+ * `decklight: autosave talk.html`, one every five minutes, in which no commit
10
+ * marks anything and `git log` answers no question. The commits were a backup
11
+ * wearing a history's clothes.
12
+ *
13
+ * So the two jobs are separated, because they were never the same job:
14
+ *
15
+ * the BACKUP is a snapshot, and it is silent. Every tick, the deck's current
16
+ * bytes are written to `refs/decklight/wip` — a real commit object, parented
17
+ * on HEAD, reachable by name and by nothing else. It is not on your branch,
18
+ * it does not move your branch, `git log` never shows it, and a push never
19
+ * carries it. A crash costs you `git show decklight/wip:<deck>`, not an
20
+ * afternoon.
21
+ *
22
+ * the HISTORY is a commit, and it is yours. decklight asks — once per stretch
23
+ * of uncommitted work — and the commit happens when you answer, with a
24
+ * message about what changed.
25
+ *
26
+ * ONE NAG PER EPISODE is the load-bearing rule, and it is the one the push
27
+ * toast (src/core/devmode.js) learned first: "a limit expressed as a count
28
+ * cannot become a limit expressed as every few minutes by accident, which is
29
+ * what happens to interval-based nudges and why people turn them off". The
30
+ * trigger here is time OR size, whichever comes first, but it fires once and
31
+ * then stays quiet until a commit resets the episode. An unanswered nag is an
32
+ * answer.
33
+ */
34
+
35
+ import { execFileSync } from 'node:child_process';
36
+ import { putBlob } from './git-tree.mjs';
37
+
38
+ /** The ref the snapshot lives on — outside every branch, on purpose. */
39
+ export const WIP_REF = 'refs/decklight/wip';
40
+
41
+ /** How long uncommitted work may sit before the nag, and how much may change. */
42
+ export const NAG_AFTER_MS = 10 * 60 * 1000;
43
+
44
+ /**
45
+ * How long any single git call in the watch may take before it is killed.
46
+ *
47
+ * The watch runs on the event loop. An unbounded `execFileSync` there is not a
48
+ * slow snapshot, it is a dead server — so every call this file makes carries a
49
+ * cap, and a git that blows through it costs one tick.
50
+ */
51
+ export const GIT_TIMEOUT_MS = 10_000;
52
+ /** `git`, but it can never hold the server for longer than the cap. */
53
+ const boundedGit = (args, cwd) =>
54
+ execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: GIT_TIMEOUT_MS }).trim();
55
+ export const NAG_AFTER_LINES = 40;
56
+
57
+ /**
58
+ * How much of the deck differs from HEAD, and whether anything does.
59
+ *
60
+ * `--numstat` over the deck alone, because the deck is the only thing decklight
61
+ * commits and the only thing it is entitled to describe. A repository holding
62
+ * somebody's whole project reports its own state through git; this reports the
63
+ * deck's.
64
+ *
65
+ * A deck with no HEAD to compare against (the very first commit has not
66
+ * happened) counts as dirty with unknown size: there is something to commit,
67
+ * and no numstat can say how much.
68
+ */
69
+ export function deckDirty(cwd, deckRel, { run = boundedGit } = {}) {
70
+ let out;
71
+ try { out = run(['diff', '--numstat', 'HEAD', '--', deckRel], cwd); }
72
+ catch { return { dirty: true, lines: 0, firstCommit: true }; }
73
+ const line = (out ?? '').split('\n').find(Boolean);
74
+ if (!line) {
75
+ // Nothing against HEAD — but an untracked deck has no diff either, and it
76
+ // is the most uncommitted a file can be.
77
+ let tracked = true;
78
+ try { run(['ls-files', '--error-unmatch', '--', deckRel], cwd); }
79
+ catch { tracked = false; }
80
+ return tracked ? { dirty: false, lines: 0 } : { dirty: true, lines: 0, untracked: true };
81
+ }
82
+ const [add, del] = line.split('\t');
83
+ return { dirty: true, lines: (Number(add) || 0) + (Number(del) || 0) };
84
+ }
85
+
86
+ /**
87
+ * Write the deck's current bytes to the snapshot ref. Returns the sha, or null.
88
+ *
89
+ * Deck-only, and that is the whole reason this is plumbing rather than
90
+ * `git stash create`: stash snapshots every tracked change in the working
91
+ * tree, and decklight commits one file. Someone editing a deck inside a larger
92
+ * repository must not have their unrelated work swept into decklight's ref.
93
+ *
94
+ * Nothing here touches the index, the working tree, or any branch: a blob, a
95
+ * tree built from HEAD's with one path replaced, a commit parented on HEAD, and
96
+ * a ref update. It is invisible until somebody asks for it by name.
97
+ *
98
+ * NEVER FATAL. This is the safety net, so it fails the way a safety net should
99
+ * — quietly, leaving everything else working. A repository mid-rebase, a
100
+ * detached HEAD, a missing object: the editing session carries on.
101
+ */
102
+ export function snapshotWip(cwd, deckPath, deckRel, { exec = execFileSync, timeout = GIT_TIMEOUT_MS } = {}) {
103
+ // git-tree's helpers take `(args, input)` — `mktree` FEEDS ITS ENTRIES ON
104
+ // STDIN, so an adapter that drops the second argument writes an empty tree
105
+ // and reports success. The snapshot then holds a commit with nothing in it,
106
+ // which is the one failure this whole file exists to prevent.
107
+ //
108
+ // EVERY call is bounded. This runs on a timer, on the server's event loop,
109
+ // and `execFileSync` blocks it for as long as the child takes — so a git that
110
+ // never returns does not cost a snapshot, it costs the whole author server:
111
+ // still listening, answering nothing, until somebody kills it. That is not a
112
+ // hypothetical. `git hash-object -w --stdin` was found wedged for eight hours
113
+ // with the server dead behind it, and because a `file://` deck probes the
114
+ // author port, it silently broke every headless render on the machine too.
115
+ const g = (args, input) => exec('git', args, { cwd, encoding: 'utf8', input, timeout }).trim();
116
+ try {
117
+ const head = g(['rev-parse', 'HEAD']);
118
+ // The PATH form, not `--stdin`. Handing git a 700 KB deck down a pipe is a
119
+ // deadlock waiting for a slow reader; letting it open the file itself has
120
+ // no pipe to deadlock on, and is what wedged above.
121
+ const blob = g(['hash-object', '-w', '--', deckPath]);
122
+ const tree = putBlob(g, `${head}^{tree}`, deckRel.split(/[/\\]/).filter(Boolean), blob);
123
+ const sha = g(['commit-tree', tree, '-p', head, '-m',
124
+ `decklight: wip snapshot of ${deckRel}`]);
125
+ g(['update-ref', WIP_REF, sha]);
126
+ return sha;
127
+ } catch { return null; }
128
+ }
129
+
130
+ /**
131
+ * Should we nag right now?
132
+ *
133
+ * Pure, so the whole rule is testable without a clock or a repository — the
134
+ * planServices idiom. `nagged` is the episode latch: once true, nothing here
135
+ * says yes again until a commit clears it.
136
+ */
137
+ export function planNag({
138
+ dirty = false, lines = 0, sinceMs = 0, nagged = false, dismissed = false,
139
+ afterMs = NAG_AFTER_MS, afterLines = NAG_AFTER_LINES,
140
+ } = {}) {
141
+ if (!dirty || nagged || dismissed) return false;
142
+ return sinceMs >= afterMs || lines >= afterLines;
143
+ }
144
+
145
+ /** What the chip says — the count and the age, so the ask is proportionate. */
146
+ export function nagText({ lines = 0, sinceMs = 0 } = {}) {
147
+ const mins = Math.floor(sinceMs / 60000);
148
+ const age = mins >= 60 ? `${Math.floor(mins / 60)}h` : mins >= 1 ? `${mins}m` : 'just now';
149
+ const size = lines ? `${lines} line${lines === 1 ? '' : 's'}` : 'changes';
150
+ return `${size} uncommitted${mins >= 1 ? ` · ${age}` : ''}`;
151
+ }
152
+
153
+ /** The line author prints when the snapshot is what stands behind the nag. */
154
+ export function wipLine(deckRel) {
155
+ return ` git: committing ${deckRel} when you say so — a silent snapshot rides on`
156
+ + ` ${WIP_REF.replace('refs/', '')} in between (git show decklight/wip:${deckRel})`;
157
+ }