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,87 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ // Building a git tree without touching the working tree.
5
+ //
6
+ // Lifted out of cli/publish.mjs, which invented this, when `review submit`
7
+ // turned out to need exactly the same thing. It is the mechanism behind every "push something without checking
8
+ // anything out" in decklight: objects land in the repository's database,
9
+ // nothing references them until the push, and neither the working tree, the
10
+ // index nor the checked-out branch ever hears about it.
11
+ //
12
+ // Extracted rather than copied because the one subtle line here — git's tree
13
+ // ordering, which compares a directory as if its name ended in `/` — is exactly
14
+ // the kind of thing two copies diverge on silently. A tree sorted the other way
15
+ // is accepted by `mktree` and then reported by `git fsck`, long after whoever
16
+ // wrote the second copy has moved on.
17
+ //
18
+ // Every function takes the caller's own `git(args, input)` runner, so the cwd,
19
+ // the failure convention and the error wording stay the caller's business.
20
+
21
+ /**
22
+ * One tree's entries: `<mode> <type> <sha>\t<name>` per line.
23
+ *
24
+ * `--full-tree` is load-bearing and not a flourish. Plain `git ls-tree <tree>`
25
+ * is implicitly scoped to the CURRENT PATH PREFIX: run from `talks/` it lists
26
+ * `<tree>:talks` rather than the root. Both callers run git in the deck's own
27
+ * directory, so without this a deck in a subdirectory rebuilds the repository's
28
+ * whole tree from that subdirectory's contents — every sibling above it silently
29
+ * deleted in the pushed commit, and no error anywhere.
30
+ */
31
+ export function lsTree(git, sha) {
32
+ return git(['ls-tree', '--full-tree', sha]).split('\n').filter(Boolean).map((l) => {
33
+ const [meta, name] = l.split('\t');
34
+ const [mode, type, entrySha] = meta.split(/\s+/);
35
+ return { mode, type, sha: entrySha, name };
36
+ });
37
+ }
38
+
39
+ /**
40
+ * Write a tree object from entries.
41
+ *
42
+ * The sort is git's own: byte-wise, with a tree's name compared as `name/`.
43
+ * Get it wrong and `mktree` still accepts the tree — `git fsck` is where you
44
+ * find out, which is much later and somewhere else.
45
+ */
46
+ export function mktree(git, entries) {
47
+ const key = (e) => (e.type === 'tree' ? `${e.name}/` : e.name);
48
+ entries.sort((a, b) => (key(a) < key(b) ? -1 : 1));
49
+ return git(['mktree'], entries.map((e) => `${e.mode} ${e.type} ${e.sha}\t${e.name}\n`).join(''));
50
+ }
51
+
52
+ /**
53
+ * A copy of the tree at `treeish` with `blobSha` placed at `pathParts`,
54
+ * building intermediate trees and **keeping every sibling entry**.
55
+ *
56
+ * `treeish` may be a commit — `ls-tree` resolves it — which is why a caller can
57
+ * hand it the parent commit directly. `null`/`undefined` means "nothing there
58
+ * yet", which is how a missing intermediate directory gets created and how an
59
+ * orphan commit's tree is built.
60
+ */
61
+ export function putBlob(git, treeish, pathParts, blobSha) {
62
+ const entries = treeish ? lsTree(git, treeish) : [];
63
+ const name = pathParts[0];
64
+ const kept = entries.filter((e) => e.name !== name);
65
+ if (pathParts.length === 1) {
66
+ kept.push({ mode: '100644', type: 'blob', sha: blobSha, name });
67
+ } else {
68
+ const sub = entries.find((e) => e.name === name && e.type === 'tree');
69
+ kept.push({ mode: '040000', type: 'tree', sha: putBlob(git, sub?.sha, pathParts.slice(1), blobSha), name });
70
+ }
71
+ return mktree(git, kept);
72
+ }
73
+
74
+ /**
75
+ * The commit a remote ref points at, fetched into FETCH_HEAD — or null when
76
+ * the remote has no such ref.
77
+ *
78
+ * The other half of pushing without a checkout: the PARENT, as the REMOTE has
79
+ * it. `ls-remote` first so a missing ref is an answer rather than a fetch
80
+ * error, then a destination-less fetch, so no local ref is created or moved —
81
+ * FETCH_HEAD is a file, not a ref, and nothing in the repository changes.
82
+ */
83
+ export function remoteHead(git, remote, ref) {
84
+ if (!git(['ls-remote', remote, ref])) return null;
85
+ git(['fetch', '--quiet', remote, ref]);
86
+ return git(['rev-parse', 'FETCH_HEAD']);
87
+ }
package/cli/git.mjs CHANGED
@@ -177,6 +177,28 @@ export function gitAutocommit(deckPath, cwd, message = `decklight: autosave ${ba
177
177
  // LOCAL read of remote-tracking refs and needs no network at all. `behind` is
178
178
  // therefore as fresh as your last fetch, and saying so is better than fetching
179
179
  // behind someone's back.
180
+ //
181
+ // ONE named exception: the review check at `decklight author` startup
182
+ // (cli/review-remote.mjs), which exists precisely because "somebody reviewed
183
+ // your deck" is only useful unasked. It is once, detached, off by three
184
+ // switches that each say why, and nowhere near a SIGINT handler — the shape
185
+ // update-check.mjs established. SPEC REVIEW states the contract; anything
186
+ // else that wants to fetch unasked argues there, not here.
187
+
188
+ /**
189
+ * `owner/repo` from a GitHub remote URL, or null for anything else.
190
+ *
191
+ * THE one parser — `pagesUrl` (cli/publish.mjs) derives the Pages site from it
192
+ * and `review submit` hands it to `gh --repo`. It lived in both files as the
193
+ * same regex for a while, which is exactly how one copy grows a spelling the
194
+ * other refuses.
195
+ */
196
+ export function ownerRepo(remoteUrl) {
197
+ const m = (remoteUrl || '').trim().match(
198
+ /^(?:https?:\/\/(?:[^/@]+@)?|git@|ssh:\/\/git@)github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/i,
199
+ );
200
+ return m ? { owner: m[1], repo: m[2] } : null;
201
+ }
180
202
 
181
203
  /** The env every remote-touching git call runs under. See the note above. */
182
204
  export function noPromptEnv(env = process.env) {
package/cli/init.mjs CHANGED
@@ -48,7 +48,10 @@ import {
48
48
  } from './skill-content.mjs';
49
49
  import { THEMES_DIR, themeCss, runtimeCss, runtimeJs } from './pkg.mjs';
50
50
  import { TARGETS, detectedTargets, installGlobalSkill, display } from './skills.mjs';
51
- import { onPath } from './agents.mjs';
51
+ import { onPath, detectAgents } from './agents.mjs';
52
+ import {
53
+ ASK_MESSAGES, planCommitMessages, rememberPref, storedPref,
54
+ } from './commit-message.mjs';
52
55
  import { escapeHtml } from './edit.mjs';
53
56
  import {
54
57
  classifyRemoteError, createRepo, foreignWarning, git as gitRun, inGitRepo, isIdentityError,
@@ -375,13 +378,26 @@ export function openCommand(platform, url) {
375
378
  * cannot launch (headless, no xdg-open) gets one dim line and a normal exit:
376
379
  * the deck was created, which is the product.
377
380
  */
378
- export async function openDeck(deckPath, { platform = process.platform, spawnFn = spawn, out = process.stdout } = {}) {
379
- const url = pathToFileURL(deckPath).href;
380
- const { cmd, args } = openCommand(platform, url);
381
+ export async function openDeck(deckPath, opts = {}) {
381
382
  const rel = path.relative('.', deckPath) || deckPath;
383
+ // the prefix names the FLAG that asked, which is what a reader of the line
384
+ // needs: --open is opt-in, and its one dim failure line has to say so
385
+ return openUrl(pathToFileURL(deckPath).href, { ...opts, what: rel, prefix: '--open: ' });
386
+ }
387
+
388
+ /**
389
+ * The same launcher, for a URL that is not a file — `decklight record` serves
390
+ * the deck over http://127.0.0.1 precisely because a browser will not open a
391
+ * microphone for a `file://` page.
392
+ */
393
+ export async function openUrl(url, {
394
+ platform = process.platform, spawnFn = spawn, out = process.stdout, what = url, prefix = '',
395
+ } = {}) {
396
+ const { cmd, args } = openCommand(platform, url);
397
+ const rel = what;
382
398
  const dim = (s) => (out.isTTY && !process.env.NO_COLOR ? `${DIM}${s}${RESET}` : s);
383
399
  const skipped = (err) =>
384
- out.write(dim(`--open: could not launch a browser (${cmd}: ${err.code ?? err.message}) — open ${rel} yourself\n`));
400
+ out.write(dim(`${prefix}could not launch a browser (${cmd}: ${err.code ?? err.message}) — open ${rel} yourself\n`));
385
401
  await new Promise((resolve) => {
386
402
  let child;
387
403
  try {
@@ -670,6 +686,22 @@ unless --no-skill is given. The deck file is only touched with --force.
670
686
  // would only offer what is on. The line names the flag that turns it off.
671
687
  note(" commits land one per agent edit, with the agent's own message"
672
688
  + ' (--git-mode timer for a plain cadence)');
689
+ // …and the OTHER half of what those commits say. Asked here, once, because
690
+ // this is the moment the commits it governs start existing — and asked at
691
+ // all, rather than defaulted silently, because the answer sends the deck's
692
+ // diffs to an agent. Default yes; a person still has to let it through.
693
+ const msgs = planCommitMessages({
694
+ args: argv, tty, agents: detectAgents().length, creatingRepo: true,
695
+ stored: storedPref(root),
696
+ });
697
+ if (msgs.action === 'ask' || msgs.action === 'on' || msgs.action === 'off') {
698
+ const on = msgs.action === 'ask' ? await askYes(ASK_MESSAGES, true) : msgs.action === 'on';
699
+ rememberPref(root, on);
700
+ note(on
701
+ ? ' commit subjects are written by an agent, from the diff'
702
+ + ' (git config decklight.commit-messages false turns it off)'
703
+ : ' commit subjects stay generic (--commit-messages turns it on)');
704
+ }
673
705
  }
674
706
  else if (action === 'hint') note(' git: no repository here — pass --git to create one and auto-commit the deck');
675
707
 
@@ -14,6 +14,7 @@
14
14
  // that child's stdin is closed (piped, not a TTY), so it could never ask.
15
15
 
16
16
  import { createConnection, createServer } from 'node:net';
17
+ import { execFileSync } from 'node:child_process';
17
18
 
18
19
  /** Is something listening on `port`? Port 0 ("OS picks one") never conflicts. */
19
20
  export function isPortOpen(port, host = '127.0.0.1', timeout = 400) {
@@ -38,6 +39,55 @@ export async function identifyEditServer(port, host = '127.0.0.1') {
38
39
  }
39
40
  }
40
41
 
42
+ /**
43
+ * The same question for a BRIDGE — the voice and lip-sync servers answer
44
+ * `/ping`, not `/edit/ping`, so an edit-server probe reports them as strangers
45
+ * and the offer to take the port over never appears.
46
+ *
47
+ * Returns the same shape the caller already handles: something with a `name`
48
+ * to put in a sentence.
49
+ */
50
+ export async function identifyBridge(port, host = '127.0.0.1') {
51
+ try {
52
+ const res = await fetch(`http://${host}:${port}/ping`, { signal: AbortSignal.timeout(800) });
53
+ if (!res.ok) return null;
54
+ const d = await res.json();
55
+ if (!d?.ok) return null;
56
+ // tts answers with an engine, lipsync with its own shape; either way the
57
+ // point is that a decklight bridge is there and can be asked to stop.
58
+ return { ...d, bridge: true, name: d.engine ? `the ${d.engine} voice bridge` : 'a decklight bridge' };
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Who holds this port, when it is NOT one of ours.
66
+ *
67
+ * This file's whole premise was "ask it over HTTP, never guess at a PID — no
68
+ * lsof, no platform split", and that is still right for anything decklight can
69
+ * stop cleanly. But it left the commonest real case mute: a stranger's process
70
+ * on the port produced a bare "using a different port", or — for the bridges,
71
+ * which never called any of this — a raw EADDRINUSE stack trace.
72
+ *
73
+ * So a stranger gets NAMED, best effort, and only to put in a question. `lsof`
74
+ * is macOS/Linux; Windows and a missing lsof simply return null and the caller
75
+ * falls back to moving ports, which is what it did before.
76
+ */
77
+ export function identifyStranger(port, { exec = null } = {}) {
78
+ if (process.platform === 'win32') return null;
79
+ try {
80
+ const run = exec ?? ((cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', timeout: 2000 }));
81
+ const out = run('lsof', ['-nP', `-iTCP:${port}`, '-sTCP:LISTEN', '-F', 'pc']);
82
+ // `-F pc` prints `p<pid>` and `c<command>` on their own lines
83
+ const pid = /^p(\d+)$/m.exec(out)?.[1];
84
+ const command = /^c(.+)$/m.exec(out)?.[1];
85
+ return pid ? { pid: Number(pid), command: command ?? 'an unknown process' } : null;
86
+ } catch {
87
+ return null; // no lsof, no permission, nothing listening — all "we cannot say"
88
+ }
89
+ }
90
+
41
91
  /** Ask it to stop — it auto-commits and exits, same as its own Ctrl-C. Resolves once the port is free. */
42
92
  export async function shutdownEditServer(port, host = '127.0.0.1') {
43
93
  try {
@@ -94,35 +144,156 @@ export async function nextFreePort(port, host = '127.0.0.1', tries = 64) {
94
144
  /**
95
145
  * Pure: what to do about a taken port — testable without a socket or a
96
146
  * terminal. Only offers to kill an occupant we can actually identify AND
97
- * only when something can be asked; anything else just moves to a free port.
147
+ * only when something can be asked.
148
+ *
149
+ * A BRIDGE MAY NEVER MOVE, and that is the whole reason `kind` exists. The
150
+ * two servers fail differently because only one of them gets to announce
151
+ * where it landed:
152
+ *
153
+ * the EDIT server hands its address to a human. It prints the URL it
154
+ * actually bound and you open that one, so bumping costs nothing.
155
+ *
156
+ * a BRIDGE hands its address to nobody. The deck does not discover the
157
+ * bridge, it ASSUMES it: `src/core/narration.js` hardcodes
158
+ * `http://127.0.0.1:8787/tts` (and derives /ping, /engines, /voices from
159
+ * it), `src/core/character.js` hardcodes `:8789`, and the only override is
160
+ * a `liveUrl`/`bridgeUrl` written into the deck itself. author passes
161
+ * `--tts-port` to the bridge process and never tells the deck — it could
162
+ * not tell it anyway, since the deck is served verbatim and is as often
163
+ * opened over `file://`. The two sides agree only because both default to
164
+ * the same literal.
165
+ *
166
+ * So a bridge that bumps is a bridge nobody is talking to: the deck keeps
167
+ * knocking on 8787, reaches whatever squats there, and reports no live voice
168
+ * with nothing on screen to explain it. That is strictly worse than the
169
+ * EADDRINUSE crash this replaced — the crash at least said something. A
170
+ * bridge therefore either takes ITS port, or stands aside for the bridge
171
+ * already serving it (`reuse`), or declines to start and says why
172
+ * (`refuse`).
98
173
  */
99
- export function planPortConflict({ tty = false, identified = null } = {}) {
100
- return tty && identified ? 'ask' : 'bump';
174
+ export function planPortConflict({ tty = false, identified = null, stranger = null, kind = 'edit' } = {}) {
175
+ // What happens with no terminal — and what a DECLINED offer falls back to.
176
+ const fallback = kind !== 'bridge' ? 'bump' // an edit server announces itself
177
+ : identified ? 'reuse' // ours, already answering: use it
178
+ : 'refuse'; // a bridge off its port is a lie
179
+ if (!tty) return fallback; // never kill anything unattended
180
+ if (identified) return 'ask'; // ours: offer a CLEAN shutdown
181
+ if (stranger) return 'ask-stranger'; // somebody else's: offer, never assume
182
+ return fallback; // nothing we can name
101
183
  }
102
184
 
103
185
  /**
104
186
  * The port is already bound. Work out who's there and either take it over or
105
- * move on. `ask` is `(prompt) => Promise<string>`; its absence means no TTY
106
- * to ask, so the port just bumps. Returns the port actually free to use.
187
+ * step aside. `ask` is `(prompt) => Promise<string>`; its absence means no
188
+ * TTY to ask on, and nothing is ever killed without one.
189
+ *
190
+ * Returns the port to bind, or **null meaning "do not listen at all"** — a
191
+ * bridge whose port is spoken for, which cannot just move (see
192
+ * planPortConflict). `kind: 'edit'` never returns null, so the two existing
193
+ * callers are unaffected.
107
194
  */
108
- export async function resolvePortConflict(port, { host = '127.0.0.1', ask, log = () => {} } = {}) {
109
- const identified = await identifyEditServer(port, host);
110
- const action = planPortConflict({ tty: Boolean(ask), identified });
195
+ export async function resolvePortConflict(port, {
196
+ host = '127.0.0.1', ask, log = () => {}, kind = 'edit', stranger = identifyStranger,
197
+ identify = null,
198
+ } = {}) {
199
+ // Ours, whichever kind: an edit server answers /edit/ping, a bridge answers
200
+ // /ping. Asking only the first reported every bridge as a stranger.
201
+ //
202
+ // Injectable for the same reason `stranger` is: this REALLY CONNECTS to the
203
+ // port, so a test naming a plausible number is at the mercy of whatever the
204
+ // developer happens to be running. That is not hypothetical — the refusal
205
+ // test named 8787, and passed everywhere except on a machine with a live
206
+ // voice bridge on it, which is every machine this feature is for.
207
+ const whoIsThere = identify ?? ((p, h) => (kind === 'bridge'
208
+ ? identifyBridge(p, h)
209
+ : identifyEditServer(p, h).then((e) => e ?? identifyBridge(p, h))));
210
+ const identified = await whoIsThere(port, host);
211
+ const other = identified ? null : stranger(port);
212
+ const action = planPortConflict({ tty: Boolean(ask), identified, stranger: other, kind });
111
213
 
112
- if (action === 'ask') {
113
- log(` port ${port} is already in use — decklight is editing "${identified.name}" there`);
214
+ // Somebody ELSE's process. decklight cannot ask it to stop the way it asks
215
+ // its own — there is no endpoint to POST to — so the only lever is a signal,
216
+ // and a signal is not something to send on decklight's own judgement: that
217
+ // process may be a dev server with unsaved work in it. Named, offered, and
218
+ // DEFAULTED TO THE HARMLESS ANSWER, so the destructive one is only ever
219
+ // reached by typing it.
220
+ let named = false; // the occupant is worth naming once, not once per branch
221
+ if (action === 'ask-stranger') {
222
+ log(` port ${port} is held by ${other.command} (pid ${other.pid}) — not a decklight server`);
223
+ named = true;
224
+ // The alternative to killing is NOT the same for both kinds, so it must not
225
+ // be worded the same: an edit server moves, a bridge does not get to.
226
+ const or = kind === 'bridge' ? '[c]arry on without this bridge? [k/C]' : 'use a [d]ifferent port? [k/D]';
227
+ const answer = (await ask(` [k]ill pid ${other.pid} and take the port, or ${or} `)).trim().toLowerCase();
228
+ if (answer.startsWith('k')) {
229
+ try {
230
+ process.kill(other.pid, 'SIGTERM');
231
+ for (let i = 0; i < 30 && (await isPortOpen(port, host)); i++) await new Promise((r) => setTimeout(r, 100));
232
+ if (!(await isPortOpen(port, host))) { log(` stopped pid ${other.pid}`); return port; }
233
+ log(' it did not stop in time — using a different port instead');
234
+ } catch (e) {
235
+ log(` could not stop pid ${other.pid} (${e.code ?? e.message}) — using a different port instead`);
236
+ }
237
+ }
238
+ } else if (action === 'ask') {
239
+ log(identified.bridge
240
+ ? ` port ${port} is already in use — ${identified.name} is running there`
241
+ : ` port ${port} is already in use — decklight is editing "${identified.name}" there`);
114
242
  const answer = (await ask(' [k]ill that session and take it over, or use a [d]ifferent port? [k/D] ')).trim().toLowerCase();
115
243
  if (answer.startsWith('k')) {
116
- log(` stopping the session editing "${identified.name}"…`);
117
- if (await shutdownEditServer(port, host)) return port;
244
+ log(` stopping ${identified.bridge ? identified.name : `the session editing "${identified.name}"`}…`);
245
+ // An edit server is asked to stop, because it has a final autocommit to
246
+ // make and losing that would be losing work. A BRIDGE has no such
247
+ // endpoint and nothing to lose — it is a stateless synthesiser — so it
248
+ // gets a signal, using the pid the stranger lookup finds. Without a pid
249
+ // (Windows, no lsof) there is nothing to do but move ports, which is
250
+ // exactly what happens.
251
+ if (!identified.bridge) {
252
+ if (await shutdownEditServer(port, host)) return port;
253
+ } else {
254
+ const who = stranger(port);
255
+ if (who) {
256
+ try {
257
+ process.kill(who.pid, 'SIGTERM');
258
+ for (let i = 0; i < 30 && (await isPortOpen(port, host)); i++) await new Promise((r) => setTimeout(r, 100));
259
+ if (!(await isPortOpen(port, host))) return port;
260
+ } catch { /* fall through to the bump */ }
261
+ }
262
+ }
118
263
  log(" it didn't stop in time — using a different port instead");
119
264
  }
120
- } else {
121
- log(identified
122
- ? ` port ${port} is already in use — decklight is editing "${identified.name}" there; using a different port`
123
- : ` port ${port} is already in use; using a different port`);
124
265
  }
125
266
 
267
+ // Whatever was offered was declined, or there was nobody to ask. How that
268
+ // ends is the caller's kind, not this function's mood.
269
+ const ending = planPortConflict({ tty: false, identified, stranger: other, kind });
270
+
271
+ // Ours, and already doing the job. A second bridge would bind a port the
272
+ // deck never calls, so the useful move is to stand aside and say so: null
273
+ // means "do not listen", and the one on `port` serves the deck as before.
274
+ if (ending === 'reuse') {
275
+ log(` port ${port} already has ${identified.name} on it — using that one rather than starting a second`);
276
+ return null;
277
+ }
278
+
279
+ // Somebody else's, and a bridge cannot work anywhere but here. Say who has
280
+ // it and both ways out, then decline: author reports the bridge as gone and
281
+ // the deck degrades honestly, which beats a live voice that fails silently.
282
+ if (ending === 'refuse') {
283
+ if (!named) {
284
+ log(other
285
+ ? ` port ${port} is held by ${other.command} (pid ${other.pid}) — not a decklight bridge`
286
+ : ` port ${port} is already in use`);
287
+ }
288
+ log(` the deck asks for this bridge on ${port} and nowhere else, so it will not start.`);
289
+ log(` free the port (kill ${other ? other.pid : 'the process holding it'}), or move BOTH sides:`);
290
+ log(` run with --port N and set narration.liveUrl in the deck to match.`);
291
+ return null;
292
+ }
293
+
294
+ log(identified
295
+ ? ` port ${port} is already in use — ${identified.bridge ? identified.name : `decklight is editing "${identified.name}"`} there; using a different port`
296
+ : ` port ${port} is already in use; using a different port`);
126
297
  const next = await nextFreePort(port + 1, host);
127
298
  log(` → using port ${next}`);
128
299
  return next;
package/cli/publish.mjs CHANGED
@@ -33,6 +33,8 @@ import path from 'node:path';
33
33
  import { execFileSync } from 'node:child_process';
34
34
  import { makeFail, runMain } from './util.mjs';
35
35
  import { isMain } from '../tools/args.mjs';
36
+ import { putBlob, remoteHead } from './git-tree.mjs';
37
+ import { ownerRepo } from './git.mjs';
36
38
  import { TARGETS, schemaFor, envVarsFor, envAnswers, deploy } from '../tools/publish-targets.mjs';
37
39
  import { checkAnswers } from './wizard.mjs';
38
40
 
@@ -47,12 +49,10 @@ const fail = makeFail('publish');
47
49
  * …/owner/owner.github.io → https://owner.github.io/
48
50
  */
49
51
  export function pagesUrl(remoteUrl) {
50
- const m = (remoteUrl || '').trim().match(
51
- /^(?:https?:\/\/(?:[^/@]+@)?|git@|ssh:\/\/git@)github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?\/?$/i,
52
- );
53
- if (!m) return null;
54
- const owner = m[1].toLowerCase();
55
- const repo = m[2];
52
+ const at = ownerRepo(remoteUrl);
53
+ if (!at) return null;
54
+ const owner = at.owner.toLowerCase();
55
+ const repo = at.repo;
56
56
  if (repo.toLowerCase() === `${owner}.github.io`) return `https://${owner}.github.io/`;
57
57
  return `https://${owner}.github.io/${repo}/`;
58
58
  }
@@ -255,43 +255,18 @@ if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
255
255
 
256
256
  // A second publish parents on the branch as the REMOTE has it — fetched
257
257
  // fresh, so two machines publishing the same deck append to one history.
258
- let parent = null;
259
- if (git(['ls-remote', remote, `refs/heads/${branch}`])) {
260
- git(['fetch', '--quiet', remote, `refs/heads/${branch}`]);
261
- parent = git(['rev-parse', 'FETCH_HEAD']);
262
- }
258
+ const parent = remoteHead(git, remote, `refs/heads/${branch}`);
263
259
 
264
- const lsTree = (sha) => git(['ls-tree', sha]).split('\n').filter(Boolean).map((l) => {
265
- const [meta, name] = l.split('\t');
266
- const [mode, type, entrySha] = meta.split(/\s+/);
267
- return { mode, type, sha: entrySha, name };
268
- });
269
- const mktree = (entries) => {
270
- // git's tree order: byte-wise, with tree names comparing as "name/"
271
- const key = (e) => (e.type === 'tree' ? `${e.name}/` : e.name);
272
- entries.sort((a, b) => (key(a) < key(b) ? -1 : 1));
273
- return git(['mktree'], entries.map((e) => `${e.mode} ${e.type} ${e.sha}\t${e.name}\n`).join(''));
274
- };
275
- // Return a copy of the tree at `treeish` with the blob placed at pathParts,
276
- // building intermediate trees and keeping every sibling entry.
277
- const putBlob = (treeish, pathParts, blobSha) => {
278
- const entries = treeish ? lsTree(treeish) : [];
279
- const name = pathParts[0];
280
- const kept = entries.filter((e) => e.name !== name);
281
- if (pathParts.length === 1) {
282
- kept.push({ mode: '100644', type: 'blob', sha: blobSha, name });
283
- } else {
284
- const sub = entries.find((e) => e.name === name && e.type === 'tree');
285
- kept.push({ mode: '040000', type: 'tree', sha: putBlob(sub?.sha, pathParts.slice(1), blobSha), name });
286
- }
287
- return mktree(kept);
288
- };
260
+ // The tree builders live in cli/git-tree.mjs now — `review submit` needs the
261
+ // same ones, and neither git's `name/` sort order nor the `--full-tree` scoping
262
+ // bug is a thing to keep two copies of.
263
+ const put = (treeish, parts_, blob) => putBlob(git, treeish, parts_, blob);
289
264
 
290
- let tree = putBlob(parent, ['.nojekyll'], nojekyllBlob);
291
- tree = putBlob(tree, [...parts, 'index.html'], pageBlob);
265
+ let tree = put(parent, ['.nojekyll'], nojekyllBlob);
266
+ tree = put(tree, [...parts, 'index.html'], pageBlob);
292
267
  // Beside the page it covers, under the name a verifier will look for.
293
- if (sigBlob) tree = putBlob(tree, [...parts, 'index.html.sig'], sigBlob);
294
- if (deckBlob) tree = putBlob(tree, [...parts, 'index.decklight'], deckBlob);
268
+ if (sigBlob) tree = put(tree, [...parts, 'index.html.sig'], sigBlob);
269
+ if (deckBlob) tree = put(tree, [...parts, 'index.decklight'], deckBlob);
295
270
 
296
271
  const config = (key) => {
297
272
  try { return execFileSync('git', ['config', key], { cwd, encoding: 'utf8' }).trim(); }
package/cli/record.mjs ADDED
@@ -0,0 +1,154 @@
1
+ #!/usr/bin/env node
2
+ // Copyright 2026 Gilles Philippart
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ // decklight record — capture the deck's narration in YOUR voice.
6
+ //
7
+ // decklight record <deck.html> [--port 8788] [--dir voiceover] [--no-open]
8
+ //
9
+ // WHY THIS IS A COMMAND AND NOT JUST A KEY. The recorder itself lives in the
10
+ // deck (⇧R): it has to, because the notes, the builds and the microphone are
11
+ // all in the browser. But a browser will not open a microphone for a page it
12
+ // loaded from `file://` — getUserMedia needs a secure context, and a local file
13
+ // is not one, no matter how many times you click Allow. `http://127.0.0.1` IS
14
+ // one. So this command's whole job is to put the deck on that origin and open
15
+ // it there with the recorder up.
16
+ //
17
+ // The second half of the job is the writing. A recorded take is only useful
18
+ // next to the deck — that is the one place `narration.files` can name and the
19
+ // one place `decklight bundle` looks — and only a server that owns the deck
20
+ // file may write there. That is the edit server, which this runs, in-process:
21
+ // one command, one Ctrl-C, and the files land in the folder the deck already
22
+ // plays from.
23
+ //
24
+ // Deliberately NOT `decklight author`: recording is not editing. Git is off,
25
+ // no bridge is started, nothing is spent. You are reading your own notes aloud.
26
+
27
+ import { editMain } from './edit.mjs';
28
+ import { openUrl } from './init.mjs';
29
+ import { argReader, firstPositional, isMain } from '../tools/args.mjs';
30
+ import { wrongRecorder } from './util.mjs';
31
+ import { exitWhenOrphaned } from './supervise.mjs';
32
+
33
+ const USAGE = `usage: decklight record <deck.html> [--port 8788] [--dir voiceover] [--slides a-b] [--no-open]
34
+ serves the deck over http://127.0.0.1 and opens it with the voice recorder up
35
+
36
+ the deck reads you its notes one ⟨CLICK⟩ beat at a time; → ends a beat, which
37
+ both closes that file and reveals the next build — so your voice paces the
38
+ deck exactly as it will when you present it
39
+
40
+ --port N port to serve on (taken? moves to the next free one) [8788]
41
+ --dir NAME folder to write into, relative to the deck [the deck's own
42
+ narration.files, else voiceover]
43
+ --slides a-b re-record only this range (1-based, inclusive; "7" for one
44
+ slide). Every other slide's files are left untouched, so a
45
+ fluffed beat costs one slide and not the whole deck
46
+ --no-open don't launch a browser — print the URL and wait
47
+
48
+ writes <dir>/slide-NN.wav (the whole slide) and <dir>/slide-NN-KK.wav (one
49
+ per beat); play them back with:
50
+ narration: { files: '<dir>', ext: 'wav', segments: true }
51
+
52
+ a microphone needs a secure context, which is why this serves the deck rather
53
+ than opening the file — and why ⇧R on a file:// deck says so instead of failing
54
+ `;
55
+
56
+ /**
57
+ * The folder name the recorder should write into, or null to let the deck
58
+ * decide from its own `narration.files`.
59
+ *
60
+ * Refused here rather than at the server, so a typo costs a message instead of
61
+ * a 400 per beat halfway through a take: the same three shapes the server
62
+ * rejects (absolute, drive-lettered, containing `..`), plus the empty string.
63
+ */
64
+ export function dirProblem(name) {
65
+ if (name === undefined || name === null) return null;
66
+ if (!name || !name.trim()) return '--dir needs a folder name';
67
+ if (name.length > 200) return '--dir is too long';
68
+ if (/^[/\\]/.test(name) || /^[a-zA-Z]:/.test(name)) {
69
+ return `--dir must be relative to the deck, not an absolute path (${name})`;
70
+ }
71
+ if (name.split(/[/\\]/).includes('..')) {
72
+ return `--dir must stay inside the deck's own directory (${name})`;
73
+ }
74
+ if (/^[a-z][a-z0-9+.-]*:/i.test(name)) return `--dir is a folder, not a URL (${name})`;
75
+ return null;
76
+ }
77
+
78
+ /**
79
+ * The URL to open: the deck, on the server that is running, with `record` set.
80
+ *
81
+ * `?record` rather than a fragment because the runtime reads `location.search`,
82
+ * and rather than a separate page because the deck IS the teleprompter — you
83
+ * record against the slides your audience will see, at the build they will see
84
+ * them at.
85
+ */
86
+ export function recordUrl(port, deckUrl, dir, slides) {
87
+ const q = ['record',
88
+ ...(dir ? [`dir=${encodeURIComponent(dir)}`] : []),
89
+ ...(slides ? [`slides=${encodeURIComponent(slides)}`] : [])].join('&');
90
+ return `http://127.0.0.1:${port}${deckUrl}?${q}`;
91
+ }
92
+
93
+ /**
94
+ * `7` or `3-9` → itself; anything else → a message.
95
+ *
96
+ * The deck's own slide count is not known here (the browser has it), so this
97
+ * checks the SHAPE and leaves the bounds to the runtime, which simply records
98
+ * the slides that exist in range. A range past the end records nothing and
99
+ * says so on the card, which is a better answer than a CLI refusing to start.
100
+ */
101
+ export function slidesProblem(range) {
102
+ if (range === undefined || range === null) return null;
103
+ const m = /^(\d+)(?:-(\d+))?$/.exec(String(range).trim());
104
+ if (!m) return `--slides must be a-b or a single slide number (got "${range}")`;
105
+ const from = Number(m[1]);
106
+ const to = m[2] ? Number(m[2]) : from;
107
+ if (from < 1) return '--slides is 1-based — there is no slide 0';
108
+ if (to < from) return `--slides ${range} ends before it starts`;
109
+ return null;
110
+ }
111
+
112
+ export async function recordMain(args, { open = openUrl, out = process.stdout, onListen = null } = {}) {
113
+ if (args.includes('--help') || args.includes('-h') || !args.filter((a) => !a.startsWith('-')).length) {
114
+ out.write(USAGE);
115
+ return 0;
116
+ }
117
+ const { opt } = argReader(args);
118
+ const dir = opt('--dir');
119
+ const slides = opt('--slides');
120
+ for (const bad of [dirProblem(dir), slidesProblem(slides)]) {
121
+ if (bad) { process.stderr.write(`decklight record: ${bad}\n`); return 2; }
122
+ }
123
+
124
+ const deck = firstPositional(args, ['--dir', '--slides', '--port']);
125
+ // Before the server, not after: this used to serve the YAML file, print a
126
+ // URL and open a browser on it, with no error anywhere.
127
+ const mixedUp = wrongRecorder('record', deck);
128
+ if (mixedUp) { process.stderr.write(`decklight record: ${mixedUp}\n`); return 2; }
129
+ let started;
130
+ // `--no-git`, always: recording is not editing, and a take that happens to
131
+ // coincide with the autocommit cadence has no business creating a commit.
132
+ await editMain([deck, '--port', String(opt('--port', 8788)), '--no-git'], {
133
+ // the same seam editMain offers, passed through: this server outlives the
134
+ // call (it is the whole point), so a caller that is not a terminal — a
135
+ // test — needs a handle to close it
136
+ onListen: (info) => { started = info; onListen?.(info); },
137
+ });
138
+ // editMain reports its own reason and sets process.exitCode when the deck is
139
+ // missing or outside the served root — say nothing on top of it.
140
+ if (!started) return process.exitCode ?? 1;
141
+
142
+ const url = recordUrl(started.port, started.deckUrl, dir, slides);
143
+ out.write(`decklight record on ${url}\n`);
144
+ out.write(' ⇧R opens the recorder · → ends a beat and reveals the next build · Esc stops\n');
145
+ out.write(` files land in ${dir ?? "the deck's narration folder"}, next to the deck.`
146
+ + `${slides ? ` Only slide${/-/.test(slides) ? 's' : ''} ${slides}.` : ''} Ctrl-C when you are done.\n`);
147
+ if (!args.includes('--no-open')) await open(url, { out, what: url });
148
+ return 0;
149
+ }
150
+
151
+ if (isMain(import.meta.url)) {
152
+ exitWhenOrphaned();
153
+ recordMain(process.argv.slice(2)).then((code) => { if (code) process.exitCode = code; });
154
+ }