decklight 0.4.0 → 0.6.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.
package/cli/agents.mjs CHANGED
@@ -22,7 +22,7 @@
22
22
  // small, closed vocabulary, and a template expresses all of them.
23
23
 
24
24
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
25
- import { delimiter, dirname, join } from 'node:path';
25
+ import path, { dirname, join } from 'node:path';
26
26
  import { configHome } from './marketplace.mjs';
27
27
  import { listUnits } from './units.mjs';
28
28
 
@@ -32,48 +32,61 @@ export const AGENTS = [
32
32
  // -p is print (headless) mode; acceptEdits lets it write the deck file
33
33
  // without an interactive approval it has no TTY to ask on.
34
34
  args: (prompt) => ['-p', prompt, '--permission-mode', 'acceptEdits'],
35
+ // no --permission-mode: an ASK is read-only by construction, and a
36
+ // commit-message call has no business being able to edit the deck.
37
+ ask: (prompt) => ['-p', prompt],
35
38
  },
36
39
  {
37
40
  name: 'codex', label: 'Codex CLI', bin: 'codex',
38
41
  // exec is the non-interactive subcommand; --full-auto keeps it inside
39
42
  // the workspace sandbox while allowing file writes.
40
43
  args: (prompt) => ['exec', '--full-auto', prompt],
44
+ ask: (prompt) => ['exec', '--sandbox', 'read-only', prompt],
41
45
  },
42
46
  {
43
47
  name: 'bob', label: 'IBM Bob', bin: 'bob',
44
48
  // -p is Bob Shell's non-interactive prompt mode; --accept-license keeps
45
49
  // it from hanging on the license prompt when there is no TTY.
46
50
  args: (prompt) => ['-p', prompt, '--accept-license'],
51
+ ask: (prompt) => ['-p', prompt, '--accept-license'],
47
52
  },
48
53
  {
49
54
  name: 'gemini', label: 'Gemini CLI', bin: 'gemini',
50
55
  args: (prompt) => ['--yolo', '-p', prompt],
56
+ ask: (prompt) => ['-p', prompt],
51
57
  },
52
58
  {
53
59
  name: 'copilot', label: 'GitHub Copilot CLI', bin: 'copilot',
54
60
  args: (prompt) => ['-p', prompt, '--allow-all-tools'],
61
+ ask: (prompt) => ['-p', prompt],
55
62
  },
56
63
  {
57
64
  name: 'opencode', label: 'OpenCode', bin: 'opencode',
58
65
  args: (prompt) => ['run', prompt],
66
+ ask: (prompt) => ['run', prompt],
59
67
  },
60
68
  {
61
69
  name: 'goose', label: 'Goose', bin: 'goose',
62
70
  args: (prompt) => ['run', '-t', prompt],
71
+ ask: (prompt) => ['run', '-t', prompt],
63
72
  },
64
73
  {
65
74
  name: 'aider', label: 'Aider', bin: 'aider',
66
75
  // aider wants the file on the command line; --no-auto-commits because
67
76
  // dev's own autocommit (and the undo stack) owns history here.
68
77
  args: (prompt, deck) => ['--yes-always', '--no-auto-commits', '--message', prompt, deck],
78
+ // no deck on the command line either: aider edits what it is given
79
+ ask: (prompt) => ['--yes-always', '--no-auto-commits', '--message', prompt],
69
80
  },
70
81
  {
71
82
  name: 'cursor', label: 'Cursor CLI', bin: 'cursor-agent',
72
83
  args: (prompt) => ['-p', prompt, '--force'],
84
+ ask: (prompt) => ['-p', prompt],
73
85
  },
74
86
  {
75
87
  name: 'qwen', label: 'Qwen Code', bin: 'qwen',
76
88
  args: (prompt) => ['--yolo', '-p', prompt],
89
+ ask: (prompt) => ['-p', prompt],
77
90
  },
78
91
  ];
79
92
 
@@ -117,20 +130,108 @@ export function installedAgents(home = configHome()) {
117
130
  return out;
118
131
  }
119
132
 
120
- /** Is `bin` runnable — an explicit path that exists, or a name on $PATH? */
121
- export function onPath(bin, env = process.env) {
122
- if (!bin) return false;
133
+ /**
134
+ * Where `bin` resolves — the file $PATH would find, or null.
135
+ *
136
+ * The Windows extension list is the one Windows itself searches, in its order,
137
+ * and the empty string is in it because a unit descriptor may name a file that
138
+ * genuinely has no extension. WHICH one matched is the thing this returns and
139
+ * `onPath` throws away, and it is exactly what `spawnSpec` below needs.
140
+ */
141
+ export function whichBin(bin, env = process.env, platform = process.platform, exists = existsSync) {
142
+ if (!bin) return null;
123
143
  // An explicit path, spelled either way — a Windows one carries backslashes,
124
144
  // and treating it as a bare name would send it looking down $PATH instead.
125
- if (bin.includes('/') || bin.includes('\\')) return existsSync(bin);
126
- const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
127
- for (const dir of (env.PATH || '').split(delimiter)) {
145
+ if (bin.includes('/') || bin.includes('\\')) return exists(bin) ? bin : null;
146
+ // PATH, whatever the case of the variable: Windows spells it `Path`, and a
147
+ // child env built by hand may carry either.
148
+ const list = env.PATH ?? env.Path ?? env.path ?? '';
149
+ // The path grammar of the platform being DESCRIBED, not the one running —
150
+ // test/soak-platform.mjs learned this the hard way. The host's `join` and
151
+ // `delimiter` would split a Windows PATH on `:` (cutting `C:` off the drive)
152
+ // and answer in the wrong separator, from a function whose whole contract is
153
+ // to be pure over its `platform` argument.
154
+ const p = platform === 'win32' ? path.win32 : path.posix;
155
+ const exts = platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
156
+ for (const dir of list.split(p.delimiter)) {
128
157
  if (!dir) continue;
129
- for (const ext of exts) if (existsSync(join(dir, bin + ext))) return true;
158
+ for (const ext of exts) {
159
+ const file = p.join(dir, bin + ext);
160
+ if (exists(file)) return file;
161
+ }
162
+ }
163
+ return null;
164
+ }
165
+
166
+ /** Is `bin` on this machine at all? Detection, not runnability — see `canRun`. */
167
+ export function onPath(bin, env = process.env) {
168
+ return whichBin(bin, env) !== null;
169
+ }
170
+
171
+ /**
172
+ * The JS file a `.cmd`/`.bat` shim runs, or null if it does not run one.
173
+ *
174
+ * npm installs every JS CLI on Windows as a generated batch shim whose last
175
+ * line hands a script to node; `npx`, `pnpm` and this repo's own test stubs
176
+ * write the same shape with different spelling. So rather than pattern-match
177
+ * one vendor's template, this takes every JS-looking token in the file, expands
178
+ * whichever "the directory I am in" spelling it uses (`%~dp0`, `%dp0%`,
179
+ * `$basedir`), and returns the first that is really there. A batch file that
180
+ * names no such script is not a shim, and gets null.
181
+ */
182
+ export function shimTarget(text, dir, { exists = existsSync, platform = process.platform } = {}) {
183
+ const p = platform === 'win32' ? path.win32 : path.posix;
184
+ for (const m of String(text).matchAll(/(?:"([^"\r\n]+?\.[cm]?js)"|(\S+?\.[cm]?js))(?=["\s]|$)/gi)) {
185
+ const token = (m[1] ?? m[2])
186
+ .replaceAll(/%~dp0\\?|%dp0%\\?|\$basedir\//gi, `${dir}${p.sep}`)
187
+ .replaceAll('"', '');
188
+ const file = p.resolve(dir, token);
189
+ // The existence check is what makes the loose match safe: npm's own
190
+ // template mentions `.JS` in a PATHEXT edit several lines above the one
191
+ // that matters, and no such file is ever on disk.
192
+ if (exists(file)) return file;
130
193
  }
131
- return false;
194
+ return null;
132
195
  }
133
196
 
197
+ /**
198
+ * How to spawn `bin` AS ARGV — `{ bin, prefix }` — or null when this machine
199
+ * cannot run it that way.
200
+ *
201
+ * The whole point is that `shell` is never part of the answer. Since
202
+ * CVE-2024-27980 Node refuses to spawn a `.cmd` or `.bat` without `shell:
203
+ * true`, and turning that on would stop the arguments being arguments: they
204
+ * become one command line for `cmd.exe` to re-split, and one of them is the
205
+ * user's PROMPT — untrusted text that may hold `"`, `&`, `|`, `^` or `%VAR%`.
206
+ * `cmd.exe` quoting cannot make that safe (percent expansion happens before
207
+ * any escaping the caller can do), so decklight does not try: it resolves the
208
+ * shim to the script it would have run and spawns node on it directly. argv
209
+ * stays argv, on both platforms, and a prompt is never anything but one
210
+ * argument.
211
+ *
212
+ * A `.cmd` that is a real batch program rather than a shim resolves to null —
213
+ * DETECTED BUT NOT RUNNABLE is the state #307 is about, and reporting it as
214
+ * available is what made it a bug rather than a gap.
215
+ */
216
+ export function spawnSpec(bin, {
217
+ env = process.env, platform = process.platform, node = process.execPath,
218
+ read = (f) => readFileSync(f, 'utf8'), exists = existsSync,
219
+ } = {}) {
220
+ const found = whichBin(bin, env, platform, exists);
221
+ if (!found) return null;
222
+ // POSIX is untouched: the name goes to spawn exactly as it always did, so
223
+ // $PATH resolution, shebangs and argv all behave as before.
224
+ if (platform !== 'win32') return { bin, prefix: [] };
225
+ const p = path.win32;
226
+ if (!/\.(cmd|bat)$/i.test(found)) return { bin: found, prefix: [] };
227
+ let target = null;
228
+ try { target = shimTarget(read(found), p.dirname(found), { exists, platform }); } catch { /* unreadable */ }
229
+ return target ? { bin: node, prefix: [target] } : null;
230
+ }
231
+
232
+ /** Can an agent whose command is `bin` actually be run here? */
233
+ export const canRun = (bin, env = process.env) => spawnSpec(bin, { env }) !== null;
234
+
134
235
  /**
135
236
  * Every agent this machine can actually run, in preference order.
136
237
  *
@@ -139,7 +240,7 @@ export function onPath(bin, env = process.env) {
139
240
  * silently replacing how `claude` is invoked is not something a catalog
140
241
  * should be able to do to a machine.
141
242
  */
142
- export function detectAgents({ env = process.env, hasBin = onPath, home } = {}) {
243
+ export function detectAgents({ env = process.env, hasBin = canRun, home } = {}) {
143
244
  const builtIn = AGENTS.filter((a) => hasBin(a.bin, env));
144
245
  const known = new Set(AGENTS.map((a) => a.name));
145
246
  const extra = installedAgents(home).filter((a) => !known.has(a.name) && hasBin(a.bin, env));
@@ -174,15 +275,25 @@ export function setPreferredAgent(name, home = configHome()) {
174
275
  * is not a substitutable detail, and one that quietly changed under a
175
276
  * remembered preference would be the worst version of this feature.
176
277
  */
177
- export function agentUnavailable(name, roster, home = configHome()) {
278
+ export function agentUnavailable(name, roster, home = configHome(),
279
+ { env = process.env, spec = spawnSpec, platform = process.platform, exists = existsSync } = {}) {
178
280
  const have = roster.length
179
281
  ? `available here: ${roster.map((a) => a.name).join(', ')}`
180
282
  : 'no agent CLI is detected on this machine';
181
283
  if (!name) return `${have} — install one (claude, codex, bob, …), or: decklight agent add <name>`;
182
- const known = AGENTS.some((a) => a.name === name) || installedAgents(home).some((a) => a.name === name);
183
- return known
184
- ? `"${name}" is known but its command is not on PATH — install it, or pick another (${have})`
185
- : `no agent named "${name}" — ${have}; a marketplace can teach decklight a new one: decklight agent add ${name}`;
284
+ const entry = AGENTS.find((a) => a.name === name) ?? installedAgents(home).find((a) => a.name === name);
285
+ if (!entry) return `no agent named "${name}" — ${have}; a marketplace can teach decklight a new one: decklight agent add ${name}`;
286
+ // Found but not runnable is its own answer, and it names the reason rather
287
+ // than the symptom: telling someone their agent "is not on PATH" while
288
+ // `where claude` prints a path is how #307 stayed invisible.
289
+ const where = whichBin(entry.bin, env, platform, exists);
290
+ if (where && !spec(entry.bin, { env, platform, exists })) {
291
+ return `"${name}" is installed at ${where}, but decklight cannot run it as a program: `
292
+ + 'that file is a batch shim and the script it runs cannot be found. '
293
+ + 'decklight will not hand your prompt to cmd.exe instead — reinstall the agent, '
294
+ + `or point one at its real entry point: decklight agent add ${name}`;
295
+ }
296
+ return `"${name}" is known but its command is not on PATH — install it, or pick another (${have})`;
186
297
  }
187
298
 
188
299
  /**
@@ -191,7 +302,39 @@ export function agentUnavailable(name, roster, home = configHome()) {
191
302
  * file it should edit. Returns { bin, args, label } or null when the agent
192
303
  * isn't available.
193
304
  */
194
- export function agentCommand(name, instruction, deck, { env = process.env, hasBin = onPath, home } = {}) {
305
+ /**
306
+ * The same agent, asked a QUESTION rather than told to edit (SPEC `PRESENTING`).
307
+ *
308
+ * Two things differ from `agentCommand` and both matter. There is no
309
+ * deck-editing preamble — the prompt is passed through verbatim, because the
310
+ * caller is asking about a diff, not about a file. And the argv comes from the
311
+ * agent's `ask` template, which drops every write permission the edit path
312
+ * turns on: `claude` loses `--permission-mode acceptEdits`, `codex` gains
313
+ * `--sandbox read-only`, `aider` is handed no deck at all. An agent invoked to
314
+ * write a commit message has no business being able to change what it is
315
+ * describing.
316
+ *
317
+ * Falls back to the edit argv for an INSTALLED agent (SPEC `AGENT_UNITS`),
318
+ * whose unit declares one template and cannot be asked for a second — noted
319
+ * rather than hidden, since it is the one path here that stays writable.
320
+ */
321
+ export function agentAsk(name, prompt, { env = process.env, hasBin = canRun, home, spec = spawnSpec } = {}) {
322
+ const roster = detectAgents({ env, hasBin, home });
323
+ const wanted = name ?? preferredAgent(home);
324
+ const agent = wanted ? roster.find((a) => a.name === wanted) : roster[0];
325
+ if (!agent) return null;
326
+ const how = spec(agent.bin, { env }) ?? { bin: agent.bin, prefix: [] };
327
+ const build = agent.ask ?? agent.args;
328
+ return {
329
+ bin: how.bin,
330
+ args: [...how.prefix, ...build(prompt)],
331
+ label: agent.label,
332
+ name: agent.name,
333
+ readOnly: !!agent.ask,
334
+ };
335
+ }
336
+
337
+ export function agentCommand(name, instruction, deck, { env = process.env, hasBin = canRun, home, spec = spawnSpec } = {}) {
195
338
  const roster = detectAgents({ env, hasBin, home });
196
339
  // Precedence, matching how every other saved choice resolves (PRESENTING):
197
340
  // an explicit name > the remembered preference > the first detected agent.
@@ -204,5 +347,15 @@ export function agentCommand(name, instruction, deck, { env = process.env, hasBi
204
347
  const prompt = `Edit the Decklight deck file "${deck}" — a single-file HTML presentation ` +
205
348
  '(one top-level <section> per slide; see SPEC.md or the decklight skill if present). ' +
206
349
  `Apply this change, editing the file in place: ${instruction}`;
207
- return { bin: agent.bin, args: agent.args(prompt, deck), label: agent.label, name: agent.name };
350
+ // The spawn spec, not the bare name: on Windows an npm-installed agent is a
351
+ // batch shim, and `prefix` is the script node has to be handed for the
352
+ // arguments below to stay arguments (#307). On POSIX it is empty and this is
353
+ // the same command it always was.
354
+ const how = spec(agent.bin, { env }) ?? { bin: agent.bin, prefix: [] };
355
+ return {
356
+ bin: how.bin,
357
+ args: [...how.prefix, ...agent.args(prompt, deck)],
358
+ label: agent.label,
359
+ name: agent.name,
360
+ };
208
361
  }
@@ -0,0 +1,350 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * `--commit-messages` — an agent writes the subject decklight would otherwise
6
+ * template (SPEC `PRESENTING`).
7
+ *
8
+ * The wall of `decklight: autosave deck.html` is the problem. It is what the
9
+ * cadence has to say when nobody told it what changed, and after an afternoon
10
+ * the H overlay is a column of the same sentence with no way to see what
11
+ * happened when. An agent reading the diff can say `tighten the four-variables
12
+ * build to one line per idea` instead.
13
+ *
14
+ * THE COMMIT LANDS FIRST, ALWAYS. Autocommit exists so a crash cannot cost you
15
+ * an afternoon, and nothing here is allowed to weaken that: decklight commits
16
+ * with its own template exactly as before, and the agent's subject arrives
17
+ * afterwards as an amend. So a slow agent, a wedged agent, a missing agent, an
18
+ * agent that answers a paragraph of prose — every one of those costs a
19
+ * generically-worded commit, never a lost one.
20
+ *
21
+ * That ordering is also why the amend is safe. It rewrites one message, on the
22
+ * tip commit, seconds old, that nothing has been built on: the guard refuses
23
+ * the moment HEAD has moved or the commit has reached a remote.
24
+ *
25
+ * OPT-IN, and the reason is not cost. A diff of your deck goes to whichever
26
+ * agent CLI is installed, and most of them are cloud-backed. decklight does not
27
+ * infer that permission from what happens to be on PATH — the same rule
28
+ * `lipsync --veo` follows for the one part of it that leaves the machine.
29
+ */
30
+
31
+ import { execFile } from 'node:child_process';
32
+ import { basename, relative } from 'node:path';
33
+ import { agentAsk } from './agents.mjs';
34
+ import { commitSubject, git } from './git.mjs';
35
+
36
+ /** How much diff the agent is shown. */
37
+ export const MAX_DIFF = 24 * 1024;
38
+
39
+ /** How long it may take before the commit keeps the message it already has. */
40
+ export const ASK_TIMEOUT_MS = 45_000;
41
+
42
+ /**
43
+ * The change a commit made to the deck, trimmed to something worth sending.
44
+ *
45
+ * `--unified=1` and a byte cap, because the unit here is a single-file HTML
46
+ * deck: swapping a theme rewrites a 70 KB `<style>` block, and a bundled deck
47
+ * carries its whole runtime inline. An unbounded diff would be most of a
48
+ * megabyte of machine-generated CSS with the author's two edited sentences
49
+ * somewhere inside it — slower, more expensive, and harder to summarise than
50
+ * the same diff cut off.
51
+ *
52
+ * Truncation is SAID rather than hidden: an agent that knows it is seeing part
53
+ * of a change writes a subject about the part it saw, instead of a confident
54
+ * one about a change it never read.
55
+ */
56
+ export function changeDiff(cwd, sha, deckRel, { max = MAX_DIFF, run = git } = {}) {
57
+ const out = run(['show', '--format=', '--unified=1', sha, '--', deckRel], cwd) ?? '';
58
+ if (out.length <= max) return { diff: out, truncated: false };
59
+ return { diff: out.slice(0, max), truncated: true };
60
+ }
61
+
62
+ /** How many slide headings the prompt lists before it says "and N more". */
63
+ export const MAX_SLIDES_NAMED = 6;
64
+
65
+ /**
66
+ * The NEW-file line ranges a diff touches. Pure.
67
+ *
68
+ * Only the `+` side: the question is what the deck says now, and a heading
69
+ * looked up in the version that no longer exists would name the slide a line
70
+ * used to be on.
71
+ */
72
+ export function parseHunks(diff) {
73
+ const out = [];
74
+ for (const m of String(diff ?? '').matchAll(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/gm)) {
75
+ const start = Number(m[1]);
76
+ const count = m[2] === undefined ? 1 : Number(m[2]);
77
+ if (Number.isFinite(start) && Number.isFinite(count)) out.push({ start, count });
78
+ }
79
+ return out;
80
+ }
81
+
82
+ /**
83
+ * The deck's slides as `{ index, heading, from, to }`, by line. Pure.
84
+ *
85
+ * A depth counter rather than a regex over the whole document, because a slide
86
+ * may contain a nested `<section>` and only the top-level ones are slides —
87
+ * the same rule the runtime applies when it counts them.
88
+ */
89
+ export function deckOutline(html) {
90
+ const lines = String(html ?? '').split('\n');
91
+ const slides = [];
92
+ let depth = 0;
93
+ let open = null;
94
+ lines.forEach((line, i) => {
95
+ const opens = (line.match(/<section\b/gi) ?? []).length;
96
+ const closes = (line.match(/<\/section\s*>/gi) ?? []).length;
97
+ for (let k = 0; k < opens; k++) {
98
+ if (depth === 0) open = { index: slides.length + 1, heading: null, from: i + 1, to: i + 1 };
99
+ depth += 1;
100
+ }
101
+ if (open && !open.heading) {
102
+ const h = /<h[12][^>]*>([\s\S]*?)<\/h[12]>/i.exec(line);
103
+ if (h) open.heading = h[1].replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim() || null;
104
+ }
105
+ for (let k = 0; k < closes; k++) {
106
+ depth = Math.max(0, depth - 1);
107
+ if (depth === 0 && open) { open.to = i + 1; slides.push(open); open = null; }
108
+ }
109
+ });
110
+ if (open) { open.to = lines.length; slides.push(open); }
111
+ return slides;
112
+ }
113
+
114
+ /**
115
+ * Which slides a diff touched, in order. Pure.
116
+ *
117
+ * This is the context the agent could not otherwise have. `--unified=1` shows
118
+ * it the changed line and one line either side, and git's own hunk header is
119
+ * worse than nothing on a deck — the function-context heuristic picks the last
120
+ * thing that looked like a definition, which in a single-file deck is a CSS
121
+ * selector from the inlined stylesheet thousands of lines above. A real run
122
+ * offered `mtable.tml-small mtd {` for an edit to a slide's table, and the
123
+ * agent, with nothing better, invented a framing the deck never had.
124
+ *
125
+ * An empty result is itself an answer, and a useful one: the change is in the
126
+ * theme, the runtime or the metadata rather than in anything the audience
127
+ * sees, and a subject about "the slides" would be fiction.
128
+ */
129
+ export function changedSlides(html, diff) {
130
+ const slides = deckOutline(html);
131
+ if (!slides.length) return [];
132
+ const hit = new Set();
133
+ for (const { start, count } of parseHunks(diff)) {
134
+ const last = start + Math.max(count, 1) - 1;
135
+ for (const s of slides) if (s.from <= last && s.to >= start) hit.add(s.index);
136
+ }
137
+ return slides.filter((s) => hit.has(s.index));
138
+ }
139
+
140
+ /** `<title>` — what the deck calls itself. */
141
+ export function deckTitle(html) {
142
+ const m = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(String(html ?? ''));
143
+ return m ? m[1].replace(/\s+/g, ' ').trim() || null : null;
144
+ }
145
+
146
+ /**
147
+ * The deck as it stood at `sha`, for the two questions above. Best effort:
148
+ * without it the prompt simply carries less context, which is where this
149
+ * feature started.
150
+ */
151
+ export function deckAtCommit(cwd, sha, deckRel, { run = git } = {}) {
152
+ try { return run(['show', `${sha}:./${deckRel}`], cwd) ?? ''; } catch { return ''; }
153
+ }
154
+
155
+ /**
156
+ * What the agent is asked. Pure, so the wording is reviewable without an agent.
157
+ *
158
+ * Every constraint here exists because of how the answer is used: it goes
159
+ * straight into `git commit --amend -m`, so it has to be ONE line, short
160
+ * enough to survive `commitSubject`'s 72-character cap unmangled, and free of
161
+ * the conversational framing every CLI adds by default. Asking for the bare
162
+ * line is worth more than parsing one out afterwards.
163
+ */
164
+ export function messagePrompt({ deck, diff, truncated, template, title = null, slides = [] }) {
165
+ // WHERE the change is, before WHAT it is. Without this the agent sees the
166
+ // changed line and one line either side of it — enough to say a row was
167
+ // added to a table, not enough to know which talk the table is in, and an
168
+ // agent with a gap will fill it. It did: a row added to a brewing deck's
169
+ // troubleshooting table came back as "the espresso troubleshooting table",
170
+ // a word that appears nowhere in the deck.
171
+ const named = slides.slice(0, MAX_SLIDES_NAMED)
172
+ .map((s) => ` slide ${s.index}${s.heading ? ` — "${s.heading}"` : ' (no heading)'}`);
173
+ const more = slides.length - named.length;
174
+ const where = slides.length
175
+ ? ['The change is on:', ...named, ...(more > 0 ? [` …and ${more} more`] : [])]
176
+ // Not a shrug: a change outside every <section> is the theme, the runtime
177
+ // or the metadata, and a subject about "the slides" would be fiction.
178
+ : ['This change touches NO slide — it is in the theme, the inlined runtime,',
179
+ 'or the deck\'s metadata. Say that, rather than describing slide content.'];
180
+ return [
181
+ `Write the git commit subject for this change to "${deck}", a Decklight deck`,
182
+ '(a single-file HTML presentation; one top-level <section> per slide).',
183
+ '',
184
+ ...(title ? [`The deck is titled "${title}".`] : []),
185
+ ...where,
186
+ '',
187
+ 'Rules:',
188
+ '- ONE line. No body, no preamble, no quotes, no markdown, no trailing period.',
189
+ '- At most 72 characters.',
190
+ '- Say what changed and why it matters to the talk, not which lines moved.',
191
+ ' "cut the pour-over slide down to one claim" — not "edit deck.html".',
192
+ '- Describe the slides, not the HTML: a reader of this log is looking for a',
193
+ ' moment in the deck, not a diff.',
194
+ '- Name a slide by its own words, never by its number: "the troubleshooting',
195
+ ' table" beats "slide 4", which stops being true the moment one is inserted.',
196
+ '- Reply with the subject line and nothing else.',
197
+ '',
198
+ truncated
199
+ ? 'The diff below is TRUNCATED — describe only what you can see in it.'
200
+ : 'The diff:',
201
+ '',
202
+ diff,
203
+ '',
204
+ `If the diff says nothing useful, reply with exactly: ${template}`,
205
+ ].join('\n');
206
+ }
207
+
208
+ /**
209
+ * The subject inside whatever the CLI printed.
210
+ *
211
+ * Agents are chatty and inconsistently so: some answer the bare line, some wrap
212
+ * it in a code fence, some open with "Here's the commit message:". The rule is
213
+ * the LAST non-empty line that is not obviously framing — last, because the
214
+ * preamble comes first and the answer comes last, and because a CLI's own
215
+ * trailing banner is stripped by the same filters that catch the preamble.
216
+ *
217
+ * Deliberately not clever. Anything this does not recognise falls through to
218
+ * the caller's fallback, which is the templated subject the commit already has
219
+ * — a wrong-but-confident subject is worse than a generic one.
220
+ */
221
+ export function subjectFrom(raw) {
222
+ const lines = String(raw ?? '')
223
+ .split('\n')
224
+ .map((l) => l.replace(/^\s*[-*>]\s+/, '').trim())
225
+ .filter(Boolean)
226
+ // fences, banners, and the "here is your answer" line every CLI has
227
+ .filter((l) => !/^```/.test(l))
228
+ .filter((l) => !/^(here'?s?|sure|okay|certainly|the commit|commit message)\b/i.test(l))
229
+ .filter((l) => !/^\[?(info|warn|error|debug)\]?[: ]/i.test(l));
230
+ const last = lines[lines.length - 1];
231
+ if (!last) return null;
232
+ // strip surrounding quotes/backticks an agent added around the line itself
233
+ const bare = last.replace(/^["'`]+|["'`]+$/g, '').replace(/\.$/, '').trim();
234
+ return bare || null;
235
+ }
236
+
237
+ /**
238
+ * Is `sha` still the tip, and still only here?
239
+ *
240
+ * The two conditions that make amending a message a formatting change rather
241
+ * than a rewrite of history. If a commit landed in between — the agent flow's
242
+ * own commit, a restore, a second cadence tick — the message we were about to
243
+ * fix belongs to a commit that is no longer the one we are on, and rewriting
244
+ * anything below the tip is not something this feature is allowed to do.
245
+ */
246
+ export function amendable(cwd, sha, { run = git } = {}) {
247
+ try {
248
+ if (run(['rev-parse', 'HEAD'], cwd) !== sha) return false;
249
+ // `--remotes` needs no upstream, and answers for a repo with no remote at
250
+ // all — where nothing is pushed and every commit is fair game.
251
+ return (run(['branch', '--remotes', '--contains', sha], cwd) ?? '') === '';
252
+ } catch { return false; }
253
+ }
254
+
255
+ /** Replace the tip's subject, leaving its tree, author and date alone. */
256
+ export function amendSubject(cwd, sha, subject, { run = git } = {}) {
257
+ if (!amendable(cwd, sha, { run })) return false;
258
+ try {
259
+ run(['commit', '--amend', '--only', '--no-edit', '-m', subject], cwd);
260
+ return true;
261
+ } catch { return false; }
262
+ }
263
+
264
+ /** Run the agent and resolve its stdout, or null. Never rejects. */
265
+ function ask(cmd, cwd, timeoutMs) {
266
+ return new Promise((resolve) => {
267
+ let done = false;
268
+ const finish = (v) => { if (!done) { done = true; resolve(v); } };
269
+ let child;
270
+ try {
271
+ child = execFile(cmd.bin, cmd.args, {
272
+ cwd,
273
+ timeout: timeoutMs,
274
+ maxBuffer: 4 * 1024 * 1024,
275
+ // The agent is being asked a question about a diff it is given in the
276
+ // prompt; it needs no input and a CLI that waits on one would otherwise
277
+ // hang until the timeout.
278
+ stdio: ['ignore', 'pipe', 'pipe'],
279
+ }, (err, stdout) => finish(err && !stdout ? null : String(stdout ?? '')));
280
+ } catch { return finish(null); }
281
+ child.on('error', () => finish(null));
282
+ });
283
+ }
284
+
285
+ /**
286
+ * Give commit `sha` a subject an agent wrote. Resolves to the new subject, or
287
+ * null when anything at all did not work out.
288
+ *
289
+ * Asynchronous and unawaited by design — see the note at the top of the file.
290
+ * The caller has already committed.
291
+ */
292
+ export async function describeCommit({
293
+ cwd, sha, deckPath, template, agent = null,
294
+ env = process.env, timeoutMs = ASK_TIMEOUT_MS, run = git, exec = ask,
295
+ // Injected alongside `exec`, and it has to be: a caller that supplies the
296
+ // RUNNER is not asking whether this machine happens to have an agent CLI on
297
+ // PATH. Leaving this one un-injectable made the tests pass here and fail on
298
+ // CI — for the honest reason that CI installs no agent, so the resolver said
299
+ // no before the fake runner was ever reached.
300
+ resolve = agentAsk,
301
+ } = {}) {
302
+ const deck = basename(deckPath);
303
+ const cmd = resolve(agent, 'x', { env });
304
+ if (!cmd) return null;
305
+ // Checked BEFORE the agent is spawned as well as after: a commit that has
306
+ // already been superseded is one whose message nobody will ever see, and
307
+ // paying an agent to describe it would be the feature's own busywork.
308
+ if (!amendable(cwd, sha, { run })) return null;
309
+
310
+ const rel = relative(cwd, deckPath) || deck;
311
+ let diff;
312
+ try { diff = changeDiff(cwd, sha, rel, { run }); }
313
+ catch { return null; }
314
+ if (!diff.diff.trim()) return null;
315
+
316
+ // The deck AT the commit, not on disk: the working tree may have moved on
317
+ // while the agent was being asked, and a heading read from it would name a
318
+ // slide the commit does not contain.
319
+ const html = deckAtCommit(cwd, sha, rel, { run });
320
+ const prompt = messagePrompt({
321
+ deck, template, ...diff,
322
+ title: deckTitle(html),
323
+ slides: changedSlides(html, diff.diff),
324
+ });
325
+ const spawned = resolve(agent, prompt, { env });
326
+ if (!spawned) return null;
327
+ // Caught, not propagated. This is called unawaited from the commit path, so
328
+ // a rejection here would be an unhandled one — and the whole contract is that
329
+ // a misbehaving agent costs a generic subject, never anything louder.
330
+ let out;
331
+ try { out = await exec(spawned, cwd, timeoutMs); }
332
+ catch { return null; }
333
+ if (out == null) return null;
334
+
335
+ const found = subjectFrom(out);
336
+ if (!found) return null;
337
+ const subject = commitSubject(found, template);
338
+ // The agent echoing the template back (the prompt's own escape hatch) is a
339
+ // successful answer meaning "nothing worth saying" — and amending a message
340
+ // to itself is a rewrite for no reason.
341
+ if (subject === template) return null;
342
+ return amendSubject(cwd, sha, subject, { run }) ? subject : null;
343
+ }
344
+
345
+ /** The startup line: what is on, who does it, and what leaves the machine. */
346
+ export function messagesLine(agentName) {
347
+ return agentName
348
+ ? `git: ${agentName} writes the commit subjects — the deck's diffs are sent to it`
349
+ : 'git: --commit-messages needs an agent on PATH — subjects stay generic';
350
+ }