decklight 0.9.0 → 0.10.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 (48) hide show
  1. package/PLATFORM.md +44 -3
  2. package/README.md +7 -5
  3. package/SPEC.md +100 -31
  4. package/cli/agent-review.mjs +5 -4
  5. package/cli/agents.mjs +11 -5
  6. package/cli/bundle-audio.mjs +10 -3
  7. package/cli/bundle-module.mjs +95 -0
  8. package/cli/bundle.mjs +58 -6
  9. package/cli/cast.mjs +41 -5
  10. package/cli/check-fixes.mjs +186 -0
  11. package/cli/check.mjs +32 -5
  12. package/cli/commit-flow.mjs +7 -3
  13. package/cli/commit-message.mjs +1 -1
  14. package/cli/commit-split.mjs +2 -2
  15. package/cli/deck-refs.mjs +8 -3
  16. package/cli/design-system-refs.mjs +263 -6
  17. package/cli/design-system.mjs +82 -14
  18. package/cli/edit-git.mjs +2 -2
  19. package/cli/edit-handover.mjs +129 -23
  20. package/cli/edit-look.mjs +248 -5
  21. package/cli/edit.mjs +504 -58
  22. package/cli/enhance.mjs +12 -10
  23. package/cli/git.mjs +13 -0
  24. package/cli/init.mjs +8 -3
  25. package/cli/marketplace-autocheck.mjs +200 -0
  26. package/cli/marketplace.mjs +250 -13
  27. package/cli/narrate.mjs +78 -3
  28. package/cli/open.mjs +24 -6
  29. package/cli/pdf.mjs +27 -8
  30. package/cli/pptx-export.mjs +7 -4
  31. package/cli/record.mjs +73 -13
  32. package/cli/remote.mjs +32 -6
  33. package/cli/serve.mjs +2 -2
  34. package/cli/skill-content.mjs +40 -3
  35. package/cli/skills.mjs +247 -3
  36. package/cli/theme-refs.mjs +14 -2
  37. package/cli/units.mjs +75 -7
  38. package/dist/build-info.json +1 -1
  39. package/dist/decklight.css +429 -32
  40. package/dist/decklight.js +169 -123
  41. package/dist/decklight.js.map +4 -4
  42. package/package.json +1 -1
  43. package/tools/design-system-format.mjs +25 -0
  44. package/tools/design-system-migrations.mjs +207 -0
  45. package/tools/exec.mjs +10 -2
  46. package/tools/narration-manifest.mjs +77 -3
  47. package/tools/site-clip.mjs +114 -0
  48. package/tools/video.mjs +69 -6
package/cli/edit.mjs CHANGED
@@ -24,6 +24,7 @@
24
24
  // POST /deck/edit/slide/layout → { slide, layout } write data-layout to the file
25
25
  // POST /deck/edit/slide/hidden → { slide, hidden } data-hidden on or off (HIDDEN_SLIDES)
26
26
  // POST /deck/edit/export → { kind } write the deck out as a file (the palette's hand-over rows)
27
+ // POST /deck/edit/export/stop → stop that export part-way: its children killed, nothing half-written left
27
28
  // GET /deck/edit/publish/plan → where publishing would put this deck, without putting it there
28
29
  // POST /deck/edit/publish → bundle the deck and push it (the palette's Publish row)
29
30
  // GET /deck/edit/export/estimate → ?kind=bundle&theme= how big that file would be, before it is written
@@ -33,7 +34,8 @@
33
34
  // POST /deck/edit/element/effect → { slide, index, effect } write data-build (null strips it)
34
35
  // POST /deck/edit/undo → step the deck file back through the edit history
35
36
  // POST /deck/edit/redo → step it forward again
36
- // POST /deck/edit/agent → { prompt, agent?, slide? } one-shot AI agent edit
37
+ // POST /deck/edit/agent → { prompt, agent?, slide?, offer?, place? } one-shot AI agent edit, the skill offered first
38
+ // POST /deck/edit/agent/stop → stop the agent job in flight: that edit, an enhancement or a review
37
39
  // POST /deck/edit/enhance → { slides: [n…]|'all', agent?, kind? } audio tags ('tags') or written for the ear ('spoken')
38
40
  // POST /deck/edit/enhance/text → { text, agent?, kind? } → { text } the same, for the notes editor's box (writes nothing)
39
41
  // POST /deck/edit/review → { agent? } the agent reads the deck, read-only, for Check deck…'s agent review (writes nothing)
@@ -100,7 +102,7 @@ import { NOTES_ASIDE, locateSlide, sectionChildRanges, elementChildRanges, split
100
102
  import { canonMarks, writtenMarks, CLICK_MARK } from '../tools/sentences.mjs';
101
103
  import { configBlock, hasEmbeddedRuntime, linkRuntime } from './runtime-link.mjs';
102
104
  import { linkReferences } from './deck-refs.mjs';
103
- import { slideTexts, priorSlideTexts, staleSlides } from '../tools/narration-manifest.mjs';
105
+ import { slideTexts, priorSlideTexts, staleSlides, trackDrift } from '../tools/narration-manifest.mjs';
104
106
  // The routes that rewrite a slide, which took three of editMain's bindings and
105
107
  // nothing else with them. The import back — edit-slides reaches here for the
106
108
  // pure transforms — is a deliberate static cycle and not a dynamic one: this
@@ -114,7 +116,7 @@ import { registerSlideRoutes } from './edit-slides.mjs';
114
116
  // reason: the deck's look (themes, design systems, fonts), and handing the
115
117
  // deck over (export, publish, the inspector's read), and git (the commit
116
118
  // window, the deck's history, restore).
117
- import { registerLookRoutes } from './edit-look.mjs';
119
+ import { registerLookRoutes, runMarketplace, autoCheckInBackground } from './edit-look.mjs';
118
120
  import { registerHandoverRoutes } from './edit-handover.mjs';
119
121
  import { registerGitRoutes } from './edit-git.mjs';
120
122
  // the boot-call locator audit and upgrade share — three commands, one answer
@@ -312,7 +314,7 @@ export function previewError(why) {
312
314
  * - `slides` is the command's own `--slides` spelling; `format`, `quality` and
313
315
  * `subtitles` its `--format`, `--quality` and `--subtitles`.
314
316
  * - The voice is ONE of three: `narration` names a recorded folder (inside the
315
- * deck's directory, holding a manifest — a render that cannot find its audio
317
+ * deck's directory, holding a manifest or whole-slide audio — a render that cannot find its audio
316
318
  * should refuse, not come out silent); `synthesize` asks for the live voice
317
319
  * to be voiced into a folder first; `silent` is silence by name. None of them
318
320
  * is the command's own default: a `voiceover/` beside the deck if there is one.
@@ -358,7 +360,11 @@ export function videoExportProblem({ slides, narration, synthesize, silent, form
358
360
  if (narration == null || narration === '') return null;
359
361
  const bad = folderProblem(narration, deckDir, 'the narration');
360
362
  if (bad) return bad;
361
- if (!existsSync(resolve(deckDir, narration, 'manifest.json'))) {
363
+ // a manifest, or the audio itself: your own voice leaves no manifest, and
364
+ // `decklight video` reads the files (folderNarration)
365
+ let audio = false;
366
+ try { audio = readdirSync(resolve(deckDir, narration)).some((f) => /^slide-\d+\.(wav|m4a|mp3)$/.test(f)); } catch { /* no folder */ }
367
+ if (!audio && !existsSync(resolve(deckDir, narration, 'manifest.json'))) {
362
368
  return `no recorded narration in ${narration}/ — record the deck first (V → Record this deck…)`;
363
369
  }
364
370
  return null;
@@ -1038,6 +1044,8 @@ const WRITE_LABELS = {
1038
1044
  '/deck/edit/font/mark': 'font marked',
1039
1045
  '/deck/edit/design-system/apply': 'design system applied',
1040
1046
  '/deck/edit/design-system/mark': 'design system marked',
1047
+ '/deck/edit/design-system/migrate': 'design system migrated',
1048
+ '/deck/edit/check/fix': 'problem fixed',
1041
1049
  '/deck/edit/enhance': 'script enhanced',
1042
1050
  '/deck/edit/wizard': 'engine set up',
1043
1051
  '/deck/upstream/pull': 'git pull',
@@ -1046,6 +1054,18 @@ export function whatWrote(pathname) {
1046
1054
  return WRITE_LABELS[pathname] ?? `${String(pathname ?? '').replace(/^\/deck\/(edit\/)?/, '').replace(/\//g, ' ') || 'the deck'} written`;
1047
1055
  }
1048
1056
 
1057
+ /**
1058
+ * What the agent panel shows of an agent's report: all of it up to `max`,
1059
+ * and past that its start and its end with what was cut said between them.
1060
+ * A report leads with what it did, so the start is never the part to lose.
1061
+ */
1062
+ export function reportText(text, max = 4000) {
1063
+ const s = String(text ?? '').trim();
1064
+ if (s.length <= max) return s;
1065
+ const end = Math.floor(max / 4);
1066
+ return `${s.slice(0, max - end).trimEnd()}\n…\n${s.slice(-end).trimStart()}`;
1067
+ }
1068
+
1049
1069
  /**
1050
1070
  * The reason a reload carries. A write of the server's own within the last
1051
1071
  * moments is that write; the file changing while an agent runs is the
@@ -1056,13 +1076,22 @@ export function whatWrote(pathname) {
1056
1076
  export const RELOAD_WRITE_WINDOW_MS = 2000;
1057
1077
  export function describeReload({ write = null, agent = null, now = Date.now() } = {}) {
1058
1078
  if (write && now - write.at <= RELOAD_WRITE_WINDOW_MS) return { reload: write.what, from: write.from ?? null };
1059
- if (agent) return { reload: `${agent.agent}'s edit`, from: null };
1079
+ // a job that names its own reason says it (a migration: "migrated to acme 6.0.0")
1080
+ if (agent) return { reload: agent.reload ?? `${agent.agent}'s edit`, from: null };
1060
1081
  return { reload: 'changed on disk — an editor, git, or a tool outside this server', from: null };
1061
1082
  }
1062
1083
 
1084
+ /**
1085
+ * Undo and redo, as snapshots of the deck. An entry is the deck's text, or
1086
+ * `{ deck, files: { <path>: text } }` for one step that also wrote files
1087
+ * beside it (a migration renames in the stylesheets the deck links), so one
1088
+ * Z puts them all back. `current` may be a function of the entry being
1089
+ * taken, for the caller to snapshot exactly the files that entry names.
1090
+ */
1063
1091
  export function createHistory(limit = 200) {
1064
1092
  const past = [];
1065
1093
  const future = [];
1094
+ const now = (current, entry) => (typeof current === 'function' ? current(entry) : current);
1066
1095
  return {
1067
1096
  record(before) {
1068
1097
  past.push(before);
@@ -1071,13 +1100,15 @@ export function createHistory(limit = 200) {
1071
1100
  },
1072
1101
  undo(current) {
1073
1102
  if (!past.length) return null;
1074
- future.push(current);
1075
- return past.pop();
1103
+ const entry = past.pop();
1104
+ future.push(now(current, entry));
1105
+ return entry;
1076
1106
  },
1077
1107
  redo(current) {
1078
1108
  if (!future.length) return null;
1079
- past.push(current);
1080
- return future.pop();
1109
+ const entry = future.pop();
1110
+ past.push(now(current, entry));
1111
+ return entry;
1081
1112
  },
1082
1113
  counts() { return { undo: past.length, redo: future.length }; },
1083
1114
  };
@@ -1087,7 +1118,7 @@ export function createHistory(limit = 200) {
1087
1118
  // The plumbing lives in git.mjs now; imported for editMain's use below and
1088
1119
  // re-exported so long-standing importers (init, the tests) keep finding it
1089
1120
  // where edit grew it.
1090
- import { inGitRepo, gitAvailable, createRepo, STARTER_GITIGNORE, gitAutocommit, lastCommitSha, resolveGitMode, shouldCommit, commitSubject, exitPushLine, oneline, remoteState } from './git.mjs';
1121
+ import { inGitRepo, gitAvailable, createRepo, STARTER_GITIGNORE, gitAutocommit, lastCommitSha, resolveGitMode, shouldCommit, commitSubject, untrackedFiles, exitPushLine, oneline, remoteState } from './git.mjs';
1091
1122
  import {
1092
1123
  describeCommit, messagesLine,
1093
1124
  } from './commit-message.mjs';
@@ -1424,7 +1455,7 @@ export async function editMain(args, { onListen = null, client } = {}) {
1424
1455
  // does: a deck that is only data (#520) gets the runtime referenced on its
1425
1456
  // way out, and the audit above described the bytes WITHOUT it — which is
1426
1457
  // the point. `staticFiles` does this for every other page itself.
1427
- const serveAudited = (text) => linkReferences(linkRuntime(rewrite(text, deckPath)));
1458
+ const serveAudited = (text) => linkReferences(linkRuntime(rewrite(text, deckPath)), { dir: dirname(deckPath), deck: basename(deckPath) });
1428
1459
  // The deck itself, in no-trust mode, is served from MEMORY — container and
1429
1460
  // plain HTML alike — from the bytes the audit read and the signature
1430
1461
  // covered. The label, the signature verdict and `strict` were all decided
@@ -1452,6 +1483,26 @@ export async function editMain(args, { onListen = null, client } = {}) {
1452
1483
 
1453
1484
  const history = createHistory();
1454
1485
  const readDeck = () => readFileSync(deckPath, 'utf8');
1486
+ /** Files beside the deck as they are now, `{ path: text }` — for an undo entry that covers them. */
1487
+ const snapshotFiles = (paths) => Object.fromEntries(paths.flatMap((p) => { try { return [[p, readFileSync(p, 'utf8')]]; } catch { return []; } }));
1488
+ /**
1489
+ * What is beside the deck that no commit holds, relative to its folder: the
1490
+ * untracked files git does not ignore, or with no git the folder's entries.
1491
+ * Read before and after an agent run, so what the run left can be named.
1492
+ */
1493
+ const besideDeck = () => {
1494
+ const dir = dirname(deckPath);
1495
+ if (gitOn) return untrackedFiles(dir);
1496
+ try { return readdirSync(dir, { withFileTypes: true }).map((e) => e.name + (e.isDirectory() ? '/' : '')).sort(); } catch { return null; }
1497
+ };
1498
+ /** HEAD's short sha when it holds `paths` exactly as they are on disk, else null. */
1499
+ const cleanHead = (paths) => {
1500
+ try {
1501
+ const git = (...a) => execFileSync('git', a, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
1502
+ if (git('status', '--porcelain', '--', ...paths)) return null;
1503
+ return git('rev-parse', '--short', 'HEAD') || null;
1504
+ } catch { return null; }
1505
+ };
1455
1506
  /**
1456
1507
  * The one door every mutation goes through: snapshot, then write — so Z
1457
1508
  * always works. Answers whether anything actually changed.
@@ -1493,14 +1544,16 @@ export async function editMain(args, { onListen = null, client } = {}) {
1493
1544
  // Declared before the git block below, which reads it to hold the cadence
1494
1545
  // back while a job is in flight.
1495
1546
  let agentJob = null; // { name, prompt, startedAt } — strictly one at a time
1547
+ let agentStop = null; // stops it (POST /deck/edit/agent/stop) — set while it runs
1496
1548
  // The asks of this session, oldest first, with what came of each — what the
1497
1549
  // docked agent panel shows. An agent's edit reloads every browser, so the
1498
1550
  // log lives HERE, not in the page, and rides /deck/ping across the reload.
1499
1551
  const agentAsks = [];
1500
1552
  const ASKS_KEPT = 20;
1501
1553
  let askSeq = 0;
1502
- let enhancing = null; // a script enhancement in flight: { of, done } — one at a time
1503
- let reviewing = null; // an agent review in flight: { of, done } — one at a time
1554
+ let enhancing = null; // a script enhancement in flight: { of, done, stop } — one at a time
1555
+ let reviewing = null; // an agent review in flight: { of, done, stop } — one at a time
1556
+ let exportJob = null; // an export in flight, { kind, what }: cli/edit-handover.mjs says when
1504
1557
  let lastReview = null; // its last result: { at, agent, findings, failed } — kept for Check deck… to re-ask
1505
1558
 
1506
1559
  // ── git autocommit — the durable record, independent of undo/redo ──────
@@ -1509,7 +1562,7 @@ export async function editMain(args, { onListen = null, client } = {}) {
1509
1562
  const commitEvery = Math.max(5, Number(opt('--commit-every', 300)) || 300);
1510
1563
  // Commit subjects written by an agent, from the deck's diff. Two levels:
1511
1564
  //
1512
- // - ON CLICK, by default: the commit window's "write them for me" asks the
1565
+ // - ON CLICK, by default: the commit window's "write it for me" asks the
1513
1566
  // agent installed on this machine when — and only when — it is pressed,
1514
1567
  // and its tooltip names the agent and says the changes go to it (and may
1515
1568
  // go on to its provider). Nothing leaves without that click.
@@ -1550,10 +1603,11 @@ export async function editMain(args, { onListen = null, client } = {}) {
1550
1603
  * this returns, which is the whole contract of autocommit — the subject is
1551
1604
  * an improvement that arrives late or not at all.
1552
1605
  */
1553
- function ownCommit(message) {
1606
+ function ownCommit(message, also = []) {
1607
+ const paths = { also: [...alsoNow().also, ...also] };
1554
1608
  const made = message === undefined
1555
- ? gitAutocommit(deckPath, root, undefined, alsoNow())
1556
- : gitAutocommit(deckPath, root, message, alsoNow());
1609
+ ? gitAutocommit(deckPath, root, undefined, paths)
1610
+ : gitAutocommit(deckPath, root, message, paths);
1557
1611
  if (!made) return false;
1558
1612
  pendingAttr = null;
1559
1613
  // Whatever wrote it — the overlay, an agent, a bookend — this stretch of
@@ -1647,7 +1701,7 @@ export async function editMain(args, { onListen = null, client } = {}) {
1647
1701
  wip: lastWip,
1648
1702
  canWrite: gitOn && gitMode !== 'off',
1649
1703
  messages: wantMessages,
1650
- // who "write them for me" would ask — null when the session turned subjects
1704
+ // who "write it for me" would ask — null when the session turned subjects
1651
1705
  // off, or no agent is installed; `subjectsOff` says which
1652
1706
  describer: describer(),
1653
1707
  subjectsOff,
@@ -1669,13 +1723,20 @@ export async function editMain(args, { onListen = null, client } = {}) {
1669
1723
  // The session bookends are the cadence's siblings: generic subjects for
1670
1724
  // moments nobody described, and in the default mode the snapshot covers
1671
1725
  // what they were covering. THE FIRST COMMIT IS NOT ONE OF THEM. A
1672
- // repository decklight just created has no commits at all, and a deck git
1673
- // has never seen is in no commit — in both cases there is no HEAD for the
1674
- // snapshot to parent on and nothing in git to recover, so this commit is
1675
- // how the deck ENTERS history rather than an autosave of it.
1726
+ // repository decklight just created has no commits at all: there is no
1727
+ // HEAD for the snapshot to parent on, so this commit is how the deck
1728
+ // ENTERS history rather than an autosave of it.
1729
+ //
1730
+ // A deck git has never seen, in a repository that HAS history, is not
1731
+ // that case. It used to be committed here too, on whatever branch was
1732
+ // checked out, before anyone pressed anything: a scratch deck in a repo
1733
+ // landed on main. Whether a deck is versioned is the author's call, so it
1734
+ // stays untracked until K, and the snapshot (which needs only a HEAD, not
1735
+ // the deck in it) keeps it safe meanwhile; the chip already reads an
1736
+ // untracked deck as uncommitted work and asks once, like any other.
1676
1737
  const opening = deckDirty(root, deckRel);
1677
1738
  if (gitMode === 'timer') ownCommit(`decklight: start editing ${basename(deckPath)}`);
1678
- else if (opening.firstCommit || opening.untracked) ownCommit(`decklight: add ${basename(deckPath)}`);
1739
+ else if (opening.firstCommit) ownCommit(`decklight: add ${basename(deckPath)}`);
1679
1740
  else { measureDirty(); lastWip = snapshotWip(root, deckPath, deckRel) ?? lastWip; }
1680
1741
  // The cadence no longer WRITES HISTORY. It used to commit every
1681
1742
  // --commit-every seconds, and what that produced was a column of
@@ -1696,10 +1757,10 @@ export async function editMain(args, { onListen = null, client } = {}) {
1696
1757
  startup('git',
1697
1758
  gitMode === 'timer'
1698
1759
  ? `auto-commit every ${commitEvery}s`
1699
- : 'snapshots on decklight/wip · commits on K',
1760
+ : `snapshots on decklight/wip · ${opening.untracked ? `${basename(deckPath)} is not in git: K adds it` : 'commits on K'}`,
1700
1761
  gitMode === 'timer'
1701
1762
  ? ` git: auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`
1702
- : wipLine(deckRel),
1763
+ : wipLine(deckRel, { untracked: opening.untracked }),
1703
1764
  'ok');
1704
1765
  }
1705
1766
  }
@@ -1897,6 +1958,10 @@ export async function editMain(args, { onListen = null, client } = {}) {
1897
1958
  // defaulting to the first detected agent every session (#125)
1898
1959
  preferredAgent: agentPref ?? null,
1899
1960
  agentBusy: agentJob && { agent: agentJob.agent, prompt: agentJob.prompt, startedAt: agentJob.startedAt, id: agentJob.id },
1961
+ // the long jobs a page that loads mid-run can still stop
1962
+ exportBusy: exportJob,
1963
+ enhanceBusy: !!enhancing,
1964
+ reviewBusy: !!reviewing,
1900
1965
  agentAsks,
1901
1966
  wizards: await configurableEngines(),
1902
1967
  // What is uncommitted, so a deck that loads mid-session shows the
@@ -2202,12 +2267,50 @@ export async function editMain(args, { onListen = null, client } = {}) {
2202
2267
  }, 150);
2203
2268
  });
2204
2269
 
2205
- function runAgent(prompt, name, message, slide) {
2206
- const cmd = agentCommand(name || agentPref, prompt, deckRel, { slide });
2270
+ /**
2271
+ * An entry in the agent panel for work THIS SERVER did — a migration, a
2272
+ * quick fix — so it shows beside the agents' edits (DESIGN_SYSTEM_MIGRATIONS,
2273
+ * PRESENTING_EDITING): the same shape as an ask, by *decklight*, started
2274
+ * now; `ownDone` closes it with what came of it. Both ride the `agent`
2275
+ * events the panel already listens to.
2276
+ */
2277
+ function ownAsk({ kind, title, prompt, slide = undefined }) {
2278
+ const ask = {
2279
+ id: ++askSeq, agent: 'decklight', label: 'decklight', kind, title, prompt,
2280
+ ...(Number.isInteger(slide) && slide > 0 ? { slide } : {}),
2281
+ startedAt: Date.now(), state: 'running',
2282
+ };
2283
+ agentAsks.push(ask);
2284
+ if (agentAsks.length > ASKS_KEPT) agentAsks.shift();
2285
+ broadcast('agent', { state: 'start', agent: ask.agent, label: ask.label, prompt: ask.prompt, kind: ask.kind, title, slide: ask.slide, startedAt: ask.startedAt, id: ask.id });
2286
+ return ask;
2287
+ }
2288
+ function ownDone(ask, { ok = true, changed = false, tail = '' } = {}) {
2289
+ Object.assign(ask, { state: 'done', finishedAt: Date.now(), ok, changed, code: ok ? 0 : 1, tail });
2290
+ broadcast('agent', { state: 'done', id: ask.id, agent: ask.agent, ok, changed, code: ok ? 0 : 1, tail });
2291
+ }
2292
+
2293
+ /**
2294
+ * Hand an ask to an agent. `files` are files beside the deck the job may
2295
+ * also write (a migration's linked stylesheets): snapshotted with the deck,
2296
+ * so one Z takes them all back, and committed with it. `reload` is the
2297
+ * reason the reload its edit causes carries; `kind` and `title` label the
2298
+ * ask in the panel. `subject` is a commit subject this server built (a
2299
+ * migration's), committed as given like the server's own path commits it:
2300
+ * cut to an agent's 72 characters, its version is what fell off. `before`
2301
+ * builds a closing sentence for the prompt from the commit that holds the
2302
+ * deck as it was, once the outstanding work is committed, for a job whose
2303
+ * checks compare against it (a migration's before and after renders).
2304
+ * `dirs` are folders outside the project the agent must read (a
2305
+ * migration's skill, where it is installed).
2306
+ */
2307
+ function runAgent(prompt, name, message, slide, { files = [], reload = null, kind = null, title = null, subject: given = null, before: beforeSay = null, dirs = [] } = {}) {
2308
+ let cmd = agentCommand(name || agentPref, prompt, deckRel, { slide, dirs });
2207
2309
  if (!cmd) return null;
2208
2310
  const ask = {
2209
2311
  id: ++askSeq, agent: cmd.name, label: cmd.label, prompt,
2210
2312
  ...(Number.isInteger(slide) && slide > 0 ? { slide } : {}),
2313
+ ...(kind ? { kind } : {}), ...(title ? { title } : {}),
2211
2314
  startedAt: Date.now(), state: 'running',
2212
2315
  };
2213
2316
  agentAsks.push(ask);
@@ -2219,11 +2322,22 @@ export async function editMain(args, { onListen = null, client } = {}) {
2219
2322
  // under the agent's message, and a history that misattributes authorship is
2220
2323
  // worse than one that only says "autosave".
2221
2324
  if (gitOn && shouldCommit(gitMode, { kind: 'bookend' })
2222
- && ownCommit(`decklight: save before ${cmd.name} edits ${basename(deckPath)}`)) {
2325
+ && ownCommit(`decklight: save before ${cmd.name} edits ${basename(deckPath)}`, files)) {
2223
2326
  console.log(' git: committed your outstanding changes first');
2224
2327
  }
2328
+ if (beforeSay && gitOn) {
2329
+ const head = cleanHead([deckPath, ...files]);
2330
+ if (head) {
2331
+ prompt = `${prompt} ${beforeSay(head)}`;
2332
+ ask.prompt = prompt;
2333
+ cmd = agentCommand(cmd.name, prompt, deckRel, { slide, dirs }) ?? cmd;
2334
+ }
2335
+ }
2225
2336
  const before = readDeck();
2226
- agentJob = { agent: cmd.name, label: cmd.label, prompt, startedAt: ask.startedAt, id: ask.id, slide: ask.slide };
2337
+ const filesBefore = snapshotFiles(files);
2338
+ // what is already beside the deck, so what the run leaves there can be named
2339
+ const leftBefore = new Set(besideDeck() ?? []);
2340
+ agentJob = { agent: cmd.name, label: cmd.label, prompt, startedAt: ask.startedAt, id: ask.id, slide: ask.slide, ...(reload ? { reload } : {}) };
2227
2341
  broadcast('agent', { state: 'start', ...agentJob });
2228
2342
  console.log(` agent: ${cmd.name} ← "${prompt.slice(0, 80)}"`);
2229
2343
  const child = spawn(cmd.bin, cmd.args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
@@ -2266,23 +2380,39 @@ export async function editMain(args, { onListen = null, client } = {}) {
2266
2380
  child.stderr.on('data', keep);
2267
2381
  }
2268
2382
  const timeout = setTimeout(() => child.kill('SIGTERM'), 10 * 60 * 1000);
2383
+ // Stopped by the author: SIGTERM, which every agent CLI answers by
2384
+ // winding down, then SIGKILL for one that has not a few seconds later.
2385
+ // Whatever it had written by then stays, and Z takes it back like any edit.
2386
+ let stopped = false, hard = null;
2387
+ agentStop = () => {
2388
+ stopped = true;
2389
+ child.kill('SIGTERM');
2390
+ hard = setTimeout(() => child.kill('SIGKILL'), 5000);
2391
+ };
2269
2392
  child.on('error', (e) => {
2270
2393
  clearTimeout(timeout);
2394
+ clearTimeout(hard);
2271
2395
  agentJob = null;
2396
+ agentStop = null;
2272
2397
  finish({ ok: false, changed: false, error: String(e.message || e) });
2273
2398
  broadcast('agent', { state: 'done', id: ask.id, agent: cmd.name, ok: false, changed: false, error: String(e.message || e) });
2274
2399
  });
2275
2400
  child.on('exit', (code) => {
2276
2401
  clearTimeout(timeout);
2402
+ clearTimeout(hard);
2403
+ agentStop = null;
2277
2404
  const after = readDeck();
2278
- const changed = after !== before;
2279
- if (changed) history.record(before); // Z takes the agent's edit back
2405
+ const filesAfter = snapshotFiles(files);
2406
+ const filesChanged = Object.keys(filesBefore).some((p) => filesAfter[p] !== filesBefore[p]);
2407
+ const changed = after !== before || filesChanged;
2408
+ // Z takes the agent's edit back — with the files beside the deck it wrote, in the same step
2409
+ if (changed) history.record(filesChanged ? { deck: before, files: filesBefore } : before);
2280
2410
  // One commit per completed agent edit, carrying the agent's own summary
2281
2411
  // — the boundary and the message both come from the work, not a clock.
2282
2412
  // A failed run or one that changed nothing commits nothing.
2283
2413
  if (gitOn && shouldCommit(gitMode, { kind: 'agent', ok: code === 0, changed })) {
2284
- const subject = commitSubject(message ?? prompt, `decklight: ${cmd.name} edited ${basename(deckPath)}`);
2285
- if (gitAutocommit(deckPath, root, subject, alsoNow())) { pendingAttr = null; console.log(` git: committed "${subject}"`); }
2414
+ const subject = given ?? commitSubject(message ?? prompt, `decklight: ${cmd.name} edited ${basename(deckPath)}`);
2415
+ if (gitAutocommit(deckPath, root, subject, { also: [...alsoNow().also, ...files] })) { pendingAttr = null; console.log(` git: committed "${subject}"`); }
2286
2416
  }
2287
2417
  // Did the edit orphan, stale, or reshape a recording? A track is
2288
2418
  // minutes of somebody's own voice, and a whole-deck rewrite can drop the
@@ -2306,13 +2436,21 @@ export async function editMain(args, { onListen = null, client } = {}) {
2306
2436
  agentJob = null;
2307
2437
  // the agent's own words when the stream carried them — raw stream-json
2308
2438
  // stdout is a wall of JSON nobody should be shown
2309
- const said = (resultText ?? tail.trim().split('\n').slice(-6).join('\n')).slice(-600);
2310
- finish({ ok: code === 0, changed, code, tail: said });
2439
+ // — from its start: a report leads with what it did (a migration's
2440
+ // renames and their counts), and the panel scrolls
2441
+ const said = reportText(resultText ?? tail.trim().split('\n').slice(-6).join('\n'));
2442
+ // Files the run created beside the deck and left there: never in the
2443
+ // commit (it names its paths), and said, so the author can delete them
2444
+ const left = (besideDeck() ?? []).filter((f) => !leftBefore.has(f));
2445
+ if (left.length) console.log(` agent: ${cmd.name} left ${left.join(', ')} beside the deck (not committed)`);
2446
+ finish({ ok: code === 0, changed, code, tail: said, ...(left.length ? { left } : {}), ...(stopped ? { stopped } : {}) });
2311
2447
  broadcast('agent', {
2312
2448
  state: 'done', id: ask.id, agent: cmd.name, ok: code === 0, changed, code, tail: said,
2449
+ ...(left.length ? { left } : {}),
2450
+ ...(stopped ? { stopped } : {}),
2313
2451
  ...(recordingWarning ? { recordingWarning } : {}),
2314
2452
  });
2315
- console.log(` agent: ${cmd.name} exited (${code}) — deck ${changed ? 'changed' : 'unchanged'}`);
2453
+ console.log(` agent: ${cmd.name} ${stopped ? 'stopped' : `exited (${code})`} — deck ${changed ? 'changed' : 'unchanged'}`);
2316
2454
  if (recordingWarning) console.log(` ${recordingWarning}`);
2317
2455
  });
2318
2456
  return cmd;
@@ -2384,9 +2522,13 @@ export async function editMain(args, { onListen = null, client } = {}) {
2384
2522
  function undoRedoRoute({ url, json }) {
2385
2523
  const dir = url.pathname.endsWith('undo') ? 'undo' : 'redo';
2386
2524
  const cur = readDeck();
2387
- const content = history[dir](cur);
2525
+ // an entry that wrote files beside the deck is answered by those files as they are now
2526
+ const content = history[dir]((e) => (typeof e === 'string' ? cur : { deck: cur, files: snapshotFiles(Object.keys(e.files ?? {})) }));
2388
2527
  if (content === null) return json(409, { ok: false, error: `nothing to ${dir}`, ...history.counts() });
2389
- writeDeck(content);
2528
+ if (typeof content !== 'string') {
2529
+ for (const [p, text] of Object.entries(content.files ?? {})) writeFileAtomic(p, text);
2530
+ }
2531
+ writeDeck(typeof content === 'string' ? content : content.deck);
2390
2532
  console.log(` ${dir} → ${JSON.stringify(history.counts())}`);
2391
2533
  return json(200, { ok: true, ...history.counts() });
2392
2534
  }
@@ -2579,8 +2721,13 @@ export async function editMain(args, { onListen = null, client } = {}) {
2579
2721
  let req2;
2580
2722
  try { req2 = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return json(400, { ok: false, error: 'the manifest is not JSON' }); }
2581
2723
  const str = (v, max = 120) => (typeof v === 'string' && v.length <= max && /^[\w .:+()'-]*$/.test(v) ? v : null);
2582
- const header = { engine: str(req2.engine, 40), model: str(req2.model), voice: str(req2.voice), style: typeof req2.style === 'string' && req2.style.length <= 400 ? req2.style : null };
2583
- if (!header.engine) return json(400, { ok: false, error: 'the manifest names no engine' });
2724
+ // `mine`: your own voice (#850), which no engine voiced. Its manifest
2725
+ // carries the beats as you read them, so a moved ⟨CLICK⟩ can be told
2726
+ // from changed words, and the notes hash `decklight video` checks.
2727
+ const mine = req2.mine === true;
2728
+ const header = mine ? { engine: null, model: null, voice: null, style: null }
2729
+ : { engine: str(req2.engine, 40), model: str(req2.model), voice: str(req2.voice), style: typeof req2.style === 'string' && req2.style.length <= 400 ? req2.style : null };
2730
+ if (!mine && !header.engine) return json(400, { ok: false, error: 'the manifest names no engine' });
2584
2731
  const from = Number(req2.range?.[0]), to = Number(req2.range?.[1]);
2585
2732
  if (!Number.isInteger(from) || !Number.isInteger(to) || from < 1 || to < from || to > 9999) return json(400, { ok: false, error: 'bad range' });
2586
2733
  const recorded = {};
@@ -2589,10 +2736,22 @@ export async function editMain(args, { onListen = null, client } = {}) {
2589
2736
  if (!Number.isInteger(n) || n < from || n > to) continue;
2590
2737
  recorded[n] = { segments: Array.isArray(v?.segments) ? v.segments.map(Number) : [] };
2591
2738
  }
2592
- const { recorderManifest, slideTexts } = await import('../tools/narration-manifest.mjs');
2739
+ const { recorderManifest, slideTexts, slideBeats } = await import('../tools/narration-manifest.mjs');
2593
2740
  let prev = null;
2594
2741
  try { prev = JSON.parse(readFileSync(resolve(dir, 'manifest.json'), 'utf8')); } catch { /* first take here */ }
2595
- const manifest = recorderManifest({ prev: Array.isArray(prev?.slides) ? prev : null, header, texts: slideTexts(readDeck()), range: { from, to }, recorded });
2742
+ // A folder of your voice recorded before it had a manifest: its other
2743
+ // slides are on disk, and a manifest naming only this one would hide
2744
+ // them from `decklight video`, which trusts a manifest over the files.
2745
+ // They are kept as found, with no record of what was read: unknown.
2746
+ if (!Array.isArray(prev?.slides) && mine) {
2747
+ const { folderNarration } = await import('../tools/video.mjs');
2748
+ prev = folderNarration(dir);
2749
+ }
2750
+ const deckNow = readDeck();
2751
+ const manifest = recorderManifest({
2752
+ prev: Array.isArray(prev?.slides) ? prev : null, header, texts: slideTexts(deckNow), range: { from, to }, recorded,
2753
+ ...(mine ? { recorder: 'mic', beats: slideBeats(deckNow) } : {}),
2754
+ });
2596
2755
  try {
2597
2756
  mkdirSync(dir, { recursive: true });
2598
2757
  writeFileSync(resolve(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
@@ -2625,13 +2784,19 @@ export async function editMain(args, { onListen = null, client } = {}) {
2625
2784
  try { entries = readdirSync(resolve(root2, rel), { withFileTypes: true }); } catch { return; }
2626
2785
  const wav = entries.filter((e) => e.isFile() && /^slide-\d+(-\d+)?\.(wav|m4a|mp3)$/.test(e.name));
2627
2786
  if (wav.length) {
2628
- let engine = null; let voice = null; let manifest = false; let stale = 0;
2787
+ let engine = null; let voice = null; let manifest = false; let stale = 0; let mine = false;
2788
+ let drift = [];
2629
2789
  try {
2630
2790
  const m = JSON.parse(readFileSync(resolve(root2, rel, 'manifest.json'), 'utf8'));
2631
- engine = m.engine ?? null; voice = m.voice ?? null; manifest = true;
2791
+ engine = m.engine ?? null; voice = m.voice ?? null; manifest = true; mine = m.recorder === 'mic';
2632
2792
  // how many of its slides were voiced from other notes than the deck
2633
2793
  // has now — the export card marks the track with it (#536)
2634
- if (Array.isArray(m.slides)) stale = staleSlides(m, texts, null, prior).stale.length;
2794
+ if (Array.isArray(m.slides)) {
2795
+ stale = staleSlides(m, texts, null, prior).stale.length;
2796
+ // …and which, and how (#850): the V panel and narrate --check
2797
+ // say "the [click] moved" rather than only "different notes"
2798
+ drift = trackDrift(m, deck).drift;
2799
+ }
2635
2800
  } catch { /* a folder recorded by hand has no manifest, and needs none */ }
2636
2801
  seen.push({
2637
2802
  dir: rel.split(sep).join('/'),
@@ -2639,12 +2804,20 @@ export async function editMain(args, { onListen = null, client } = {}) {
2639
2804
  // the beats are what let a track pace the builds, so whether it
2640
2805
  // has them is the one fact worth reporting beside the count
2641
2806
  segments: wav.some((e) => /^slide-\d+-\d+\./.test(e.name)),
2807
+ // …and which slides have a whole-slide file: the recorder's plan
2808
+ // card lists every slide as recorded, missing or out of step
2809
+ slides: wav.map((e) => /^slide-(\d+)\.(wav|m4a|mp3)$/.exec(e.name)).filter(Boolean)
2810
+ .map((m) => Number(m[1])).sort((a, b) => a - b),
2642
2811
  ext: (wav[0].name.split('.').pop()),
2643
2812
  engine,
2644
2813
  voice,
2645
- // only a folder with a manifest is one `decklight video` can render
2646
- // from — your own voice leaves none, and the export must not offer it
2647
2814
  manifest,
2815
+ mine,
2816
+ drift,
2817
+ // what `decklight video` can render from: a manifest, or a
2818
+ // whole-slide file to read off the disk, which is what your own
2819
+ // voice leaves (folderNarration). Beats alone render nothing.
2820
+ renders: manifest || wav.some((e) => /^slide-\d+\./.test(e.name)),
2648
2821
  stale,
2649
2822
  });
2650
2823
  }
@@ -2699,17 +2872,27 @@ export async function editMain(args, { onListen = null, client } = {}) {
2699
2872
  const html = readDeck();
2700
2873
  const of = enhanceable(html, which).length;
2701
2874
  if (!of) return json(422, { ok: false, error: which?.length === 1 ? `slide ${which[0]} has no notes to enhance` : 'no notes to enhance' });
2702
- enhancing = { of, done: 0 };
2875
+ const stop = new AbortController();
2876
+ enhancing = { of, done: 0, stop: () => stop.abort() };
2703
2877
  broadcast('enhance', { state: 'start', of, agent: cmd.name, kind });
2704
2878
  console.log(` enhance: ${of} slide${of === 1 ? '' : 's'}${kind === 'spoken' ? ', written for the ear' : ''} ← ${cmd.name} (read-only)`);
2705
2879
  enhanceDeck(html, which, {
2706
- kind, agent: name, cwd: dirname(deckPath),
2880
+ kind, agent: name, cwd: dirname(deckPath), signal: stop.signal,
2707
2881
  onSlide: (r) => {
2708
2882
  enhancing.done = r.done;
2709
2883
  broadcast('enhance', { state: 'slide', ...r });
2710
2884
  console.log(` enhance: slide ${r.slide} ${r.ok ? (r.changed ? verb : 'unchanged') : `left as it was — ${r.why}`}`);
2711
2885
  },
2712
2886
  }).then(({ answers, results }) => {
2887
+ // Stopped: nothing is written. Half a deck tagged reads as a deck
2888
+ // somebody forgot to finish, and the slides already answered are a
2889
+ // cache hit for nobody — the agent is asked afresh next time.
2890
+ if (stop.signal.aborted) {
2891
+ enhancing = null;
2892
+ broadcast('enhance', { state: 'done', ok: false, stopped: true, kind });
2893
+ console.log(' enhance: stopped — nothing written');
2894
+ return;
2895
+ }
2713
2896
  let stale = [];
2714
2897
  // against the deck as it is NOW: a slide edited while the agent thought keeps the edit
2715
2898
  applyEdit((cur) => { const a = applyEnhanced(cur, answers); stale = a.stale; return a.html; });
@@ -2761,13 +2944,22 @@ export async function editMain(args, { onListen = null, client } = {}) {
2761
2944
  const html = readDeck();
2762
2945
  const of = Math.ceil(reviewSlides(html).length / REVIEW_BATCH);
2763
2946
  if (!of) return json(422, { ok: false, error: 'no slides to review' });
2764
- reviewing = { of, done: 0 };
2947
+ const stop = new AbortController();
2948
+ reviewing = { of, done: 0, stop: () => stop.abort() };
2765
2949
  broadcast('review', { state: 'start', of, agent: cmd.name });
2766
2950
  console.log(` review: ${of} batch${of === 1 ? '' : 'es'} ← ${cmd.name} (read-only)`);
2767
2951
  reviewDeck(html, {
2768
- agent: name, cwd: dirname(deckPath),
2952
+ agent: name, cwd: dirname(deckPath), signal: stop.signal,
2769
2953
  onBatch: (r) => { reviewing.done = r.done; broadcast('review', { state: 'batch', ...r }); },
2770
2954
  }).then(({ findings, failed }) => {
2955
+ // Stopped: the last review's findings stand — part of a deck's review
2956
+ // would read as a deck with nothing to say about the rest.
2957
+ if (stop.signal.aborted) {
2958
+ reviewing = null;
2959
+ broadcast('review', { state: 'done', ok: false, stopped: true });
2960
+ console.log(' review: stopped');
2961
+ return;
2962
+ }
2771
2963
  lastReview = { at: Date.now(), agent: cmd.name, findings, failed };
2772
2964
  reviewing = null;
2773
2965
  broadcast('review', { state: 'done', ok: true, found: findings.length, failed });
@@ -2792,16 +2984,253 @@ export async function editMain(args, { onListen = null, client } = {}) {
2792
2984
  return json(200, { ok: true, reviewed: true, running: !!reviewing, at: lastReview.at, agent: lastReview.agent, findings, failed: lastReview.failed });
2793
2985
  }
2794
2986
 
2795
- function agentRoute({ body, json }) {
2796
- const { prompt, agent, message, slide } = JSON.parse(body);
2987
+ // Stop the agent job in flight, whichever of the three it is: an A edit, a
2988
+ // script enhancement or a review. Answers at once; the job's own `done`
2989
+ // event, with `stopped`, is what says it has gone.
2990
+ function agentStopRoute({ json }) {
2991
+ const stop = agentStop ?? enhancing?.stop ?? reviewing?.stop;
2992
+ if (!stop) return json(409, { ok: false, error: 'no agent is running' });
2993
+ const what = agentStop ? `${agentJob?.agent ?? 'the agent'}'s edit` : enhancing ? 'the enhancement' : 'the review';
2994
+ console.log(` agent: stopping ${what} …`);
2995
+ stop();
2996
+ return json(200, { ok: true, stopping: what });
2997
+ }
2998
+
2999
+ /**
3000
+ * What an agent edit needs installed before it runs: Decklight's own skill,
3001
+ * which every edit's prompt sends the agent to, and `extra`, a migration's
3002
+ * skills. One the agent does not load yet, from the project or its config
3003
+ * home, is offered first, every project recommended. Asked only of a page
3004
+ * that can answer (`offer`); with no `place` the answer is the offer
3005
+ * (`{ choose: 'skill', skills, places }`), with one it is installed, or
3006
+ * with `none` not, and a no to Decklight's skill is remembered for this
3007
+ * project. Answers the offer, `{ error }`, or null to go ahead.
3008
+ */
3009
+ async function skillGate(agentName, { offer = false, place = null, extra = [], marketplace = null } = {}) {
3010
+ if (!offer && !place) return null;
3011
+ if (place !== null && !['global', 'project', 'none'].includes(place)) throw new Error('bad payload');
3012
+ const name = agentCommand(agentName || agentPref, '', deckRel)?.name;
3013
+ if (!name) return null;
3014
+ const S = await import('./skills.mjs');
3015
+ const missing = [
3016
+ ...(S.TARGETS[name] && !S.placedDecklightSkill(name, { dir: root }) && !S.skillOfferDeclined(name, { dir: root })
3017
+ ? [{ skill: 'decklight', ...S.decklightSkillPlaces(name, { dir: root }) }] : []),
3018
+ ...extra.filter((x) => !S.placedSkill(x, { dir: root })).map((x) => ({ skill: x, ...S.skillPlaces(x, { dir: root }) })),
3019
+ ];
3020
+ if (!missing.length) return null;
3021
+ if (!place) return { offer: { ok: true, choose: 'skill', agent: name, skills: missing.map((m) => m.skill), places: missing } };
3022
+ for (const { skill } of missing) {
3023
+ if (place === 'none') { if (skill === 'decklight') S.declineSkillOffer(name, { dir: root }); continue; }
3024
+ const global = place === 'global';
3025
+ try {
3026
+ const lines = skill === 'decklight'
3027
+ ? S.installDecklightSkill(name, { global, dir: root })
3028
+ : (await S.placeSkill(skill, { global, dir: root, ref: marketplace ? `${skill}@${marketplace}` : skill })).lines;
3029
+ for (const line of lines) console.log(` skill: ${line}`);
3030
+ } catch (e) { return { error: `could not install the ${skill} skill: ${e.message}` }; }
3031
+ }
3032
+ return null;
3033
+ }
3034
+
3035
+ async function agentRoute({ body, json }) {
3036
+ const { prompt, agent, message, slide, offer, place = null } = JSON.parse(body);
2797
3037
  if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('bad payload');
2798
3038
  if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is already running` });
2799
3039
  if (reviewing) return json(409, { ok: false, error: 'the agent is reviewing the deck — wait for it to finish' });
3040
+ const gate = await skillGate(agent, { offer, place });
3041
+ if (gate?.offer) return json(200, gate.offer);
3042
+ if (gate?.error) return json(409, { ok: false, error: gate.error });
2800
3043
  const cmd = runAgent(prompt.trim(), agent, message, slide);
2801
3044
  if (!cmd) return json(400, { ok: false, error: agentUnavailable(agent ?? agentPref, agents) });
2802
3045
  return json(200, { ok: true, agent: cmd.name, label: cmd.label });
2803
3046
  }
2804
3047
 
3048
+ /**
3049
+ * `POST /deck/edit/design-system/migrate` `{ ref, agent?, offer?, place? }` (SPEC
3050
+ * DESIGN_SYSTEM_MIGRATIONS): Migrate, from the behind toast or the
3051
+ * marketplace update's what's new. A job the author watches in the agent
3052
+ * panel, not a silent rewrite. When the pending migrations name a skill
3053
+ * and an agent is installed, it is an ask like any other: the agent runs
3054
+ * `design-system migrate` for the declared renames, then the skill's
3055
+ * checks and judgement calls, and its report is what the panel shows.
3056
+ * Otherwise this server runs the migration itself and records it in the
3057
+ * same panel: the renames by kind, the count, the version, and the skill
3058
+ * named for what a rename cannot decide. Either way it is one undo step
3059
+ * over the deck and the stylesheets it links, committed on its own like
3060
+ * an agent edit, and the reload says what it was. A skill the agent does
3061
+ * not load yet is asked about first (`skillGate`): the answer is
3062
+ * `{ choose: 'skill', places }`, and the page posts again with `place`:
3063
+ * `global` (every project), `project`, or `none` (this run reads it where
3064
+ * it is).
3065
+ */
3066
+ async function designSystemMigrateRoute({ body, json }) {
3067
+ const { ref, agent, offer, place = null } = JSON.parse(body || '{}');
3068
+ if (typeof ref !== 'string' || !ref.trim()) throw new Error('bad payload');
3069
+ if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is already running` });
3070
+ if (reviewing) return json(409, { ok: false, error: 'the agent is reviewing the deck — wait for it to finish' });
3071
+ const { planMigration, migrationLines, linkedStylesheets, skillFile } = await import('./design-system-refs.mjs');
3072
+ // read once: the plan, the undo entry and the stylesheets are all of these bytes
3073
+ const before = readDeck();
3074
+ const plan = planMigration(before, dirname(deckPath), ref.trim());
3075
+ if (plan.error) return json(409, { ok: false, error: plan.error });
3076
+ if (!plan.changed) return json(200, { ok: true, nothing: true, said: `already on ${plan.ref} ${plan.version} — nothing to migrate` });
3077
+ const deckName = basename(deckPath);
3078
+ const reload = `migrated to ${plan.name} ${plan.version}`;
3079
+ const title = `migrate to ${plan.name} ${plan.version}`;
3080
+ const subject = `decklight: migrate ${deckName} to ${plan.name} ${plan.version}`;
3081
+ // every stylesheet it links from its folder, not only those the renames
3082
+ // touch: the skill's judgement calls may reach the others
3083
+ const sheets = linkedStylesheets(before, dirname(deckPath)).map((x) => x.path).filter((p) => p.startsWith(root + sep));
3084
+ const skills = plan.status.skills;
3085
+ if (skills.length && agentCommand(agent || agentPref, '', deckRel)) {
3086
+ // its skills and Decklight's, offered first when the agent has not
3087
+ // got them: installed on the author's word, never for one run behind
3088
+ // their back, which is what left a stray .claude/ (#893)
3089
+ const gate = await skillGate(agent, { offer, place, extra: skills, marketplace: plan.marketplace });
3090
+ if (gate?.offer) return json(200, gate.offer);
3091
+ if (gate?.error) return json(409, { ok: false, error: gate.error });
3092
+ const { placedSkill } = await import('./skills.mjs');
3093
+ // The skill where the agent loads it, else (the author said not now)
3094
+ // where it already is on this machine, the library's copy or the
3095
+ // marketplace's checkout. Only that last folder is handed to the agent
3096
+ // (`--add-dir`): one that reads only inside the project was refused the
3097
+ // file the prompt named, and one installed for it needs no extra reach.
3098
+ const placed = skills.map((s) => placedSkill(s, { dir: root })?.file ?? null);
3099
+ const found = skills.map((s, i) => placed[i] ?? skillFile(s, plan.marketplace));
3100
+ const where = skills.map((s, i) => (found[i]
3101
+ ? `read ${found[i]}`
3102
+ : `it is not on this machine (decklight library add skill ${s} --global puts it in your home, never in this project)`));
3103
+ const dirs = [...new Set(found.filter((f, i) => f && !placed[i]).map((f) => dirname(f)))];
3104
+ const prompt = `Migrate this deck from ${plan.name} ${plan.recorded ?? '(no version recorded)'} to ${plan.version} with the ${skills.join(' and ')} skill`
3105
+ + ` (${where.join('; ')}). First run \`decklight design-system migrate ${plan.ref} ${deckRel}\``
3106
+ + ' for the renames the design system declares; then do what the skill says a rename cannot: its checks (renders before and after),'
3107
+ + ' and its judgement calls (a name removed with no successor). Report the renames with their counts, each judgement call you made,'
3108
+ + ' and anything you left alone. Only the deck and its stylesheets change: leave no file you created (a copy, a render) in the project.';
3109
+ const cmd = runAgent(prompt, agent, subject, null, {
3110
+ files: sheets, reload, kind: 'migrate', title, subject, dirs,
3111
+ // the skill renders "before" first, but the prompt has the renames run
3112
+ // first: name the commit that holds the deck as it was
3113
+ before: (sha) => `The deck as it was before this migration is commit ${sha}: \`git show ${sha}:./${deckRel.split(sep).join('/')}\`.`,
3114
+ });
3115
+ if (cmd) return json(200, { ok: true, by: 'agent', agent: cmd.name, label: cmd.label });
3116
+ }
3117
+
3118
+ // No agent to run the skill, or no skill to run: this server applies the
3119
+ // renames itself, and the panel records it as an entry like an ask.
3120
+ const ask = ownAsk({ kind: 'migrate', title, prompt: `decklight design-system migrate ${plan.ref} ${deckRel}` });
3121
+ if (gitOn && shouldCommit(gitMode, { kind: 'bookend' })
3122
+ && ownCommit(`decklight: save before migrating ${deckName}`, sheets)) {
3123
+ console.log(' git: committed your outstanding changes first');
3124
+ }
3125
+ const filesBefore = snapshotFiles(plan.sheets.map((x) => x.path));
3126
+ history.record(plan.sheets.length ? { deck: before, files: filesBefore } : before);
3127
+ for (const x of plan.sheets) writeFileAtomic(x.path, x.text);
3128
+ writeDeck(plan.html);
3129
+ noteWrite(reload, lastWrite?.from ?? null);
3130
+ if (gitOn && shouldCommit(gitMode, { kind: 'agent', ok: true, changed: true })
3131
+ && gitAutocommit(deckPath, root, subject, { also: [...alsoNow().also, ...sheets] })) {
3132
+ pendingAttr = null;
3133
+ console.log(` git: committed "${subject}"`);
3134
+ }
3135
+ const { placedSkill } = await import('./skills.mjs');
3136
+ const tail = migrationLines(plan, deckRel, { placed: (s) => placedSkill(s, { dir: root }) }).join('\n');
3137
+ ownDone(ask, { changed: true, tail });
3138
+ console.log(` design system: ${reload} — ${plan.renamed} rename${plan.renamed === 1 ? '' : 's'}`);
3139
+ return json(200, { ok: true, by: 'server', renamed: plan.renamed, version: plan.version, ask });
3140
+ }
3141
+
3142
+ /**
3143
+ * `POST /deck/edit/check/fix` `{ rule, slide?, all?, ref?, agent? }`: the
3144
+ * quick fix Check deck… offers for one of `decklight check`'s findings
3145
+ * (PRESENTING_EDITING, cli/check-fixes.mjs), applied by this server and
3146
+ * recorded in the agent panel as an entry by *decklight*, beside the
3147
+ * agents' edits. One undo entry and one commit (`fix: <rule> on slide N`,
3148
+ * or `fix: <rule>` for the deck); `all` applies a batchable rule to every
3149
+ * slide as one of each. `ds-behind` is Migrate (above), which keeps its
3150
+ * own words. The judgement fixes never come here: the page hands those to
3151
+ * the A agent as an ordinary ask.
3152
+ */
3153
+ async function checkFixRoute({ body, json }) {
3154
+ const { rule, slide, all, ref, agent } = JSON.parse(body || '{}');
3155
+ if (typeof rule !== 'string' || !/^[a-z][a-z-]*$/.test(rule)) throw new Error('bad payload');
3156
+ if (slide != null && !(Number.isInteger(slide) && slide > 0)) throw new Error('bad payload');
3157
+ if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is already running` });
3158
+ if (rule === 'ds-behind') {
3159
+ if (typeof ref !== 'string' || !ref.trim()) return json(400, { ok: false, error: 'which design system? — its reference' });
3160
+ return designSystemMigrateRoute({ body: JSON.stringify({ ref, agent }), json });
3161
+ }
3162
+ const { BATCH_RULES, fixSubject, offBrandTarget, renameRoles } = await import('./check-fixes.mjs');
3163
+ const { setDeckTheme } = await import('./runtime-link.mjs');
3164
+ const where = all && BATCH_RULES.includes(rule) ? null : slide ?? null;
3165
+ const subject = fixSubject(rule, where);
3166
+ const before = readDeck();
3167
+ /** The deck rewritten in one step, committed as the fix, and said in the panel. */
3168
+ const land = (next, { said, tail, prompt }) => {
3169
+ const ask = ownAsk({ kind: 'fix', title: subject, prompt, slide: where ?? undefined });
3170
+ if (gitOn && shouldCommit(gitMode, { kind: 'bookend' }) && ownCommit(`decklight: save before fixing ${rule}`)) {
3171
+ console.log(' git: committed your outstanding changes first');
3172
+ }
3173
+ const changed = applyEdit(next, before);
3174
+ if (changed && gitOn && shouldCommit(gitMode, { kind: 'agent', ok: true, changed: true })
3175
+ && gitAutocommit(deckPath, root, subject, alsoNow())) {
3176
+ pendingAttr = null;
3177
+ console.log(` git: committed "${subject}"`);
3178
+ }
3179
+ ownDone(ask, { changed, tail: changed ? tail : 'nothing to change — already fixed' });
3180
+ console.log(` check: ${subject} — ${changed ? said : 'nothing to change'}`);
3181
+ return json(200, { ok: true, changed, said: changed ? said : 'nothing to change — already fixed', ask, ...history.counts() });
3182
+ };
3183
+ switch (rule) {
3184
+ case 'theme-off-brand': {
3185
+ const t = offBrandTarget(before);
3186
+ if (!t) return json(409, { ok: false, error: 'the deck is not off its brand — nothing to fix' });
3187
+ const next = setDeckTheme(before, t.to);
3188
+ if (next === null) return json(409, { ok: false, error: `this deck does not carry a theme the server can set to ${t.to}` });
3189
+ return land(next, {
3190
+ said: `theme ${t.from} → ${t.to}`, prompt: `set "theme": "${t.to}"`,
3191
+ tail: `${deckRel}: "theme": "${t.from}" → "${t.to}"${t.renamed ? ` (${t.from} was renamed)` : ' (the brand\'s first theme)'}`,
3192
+ });
3193
+ }
3194
+ case 'off-role': {
3195
+ if (!where && !all) return json(400, { ok: false, error: 'which slide? — or all: true for every slide' });
3196
+ const r = renameRoles(before, where);
3197
+ if (!r.count) return json(409, { ok: false, error: `no renamed role on ${where ? `slide ${where}` : 'any slide'} — nothing to fix` });
3198
+ const said = `${r.count} role${r.count === 1 ? '' : 's'} renamed on slide${r.slides.length === 1 ? '' : 's'} ${r.slides.join(', ')}`;
3199
+ return land(r.html, { said, prompt: where ? `rename the renamed roles on slide ${where}` : 'rename the renamed roles on every slide', tail: `${deckRel}: ${said}` });
3200
+ }
3201
+ case 'ds-unresolved': {
3202
+ const name = typeof ref === 'string' ? ref.trim() : '';
3203
+ if (!/^\w[\w-]*$/.test(name)) return json(400, { ok: false, error: 'which marketplace? — its registered name' });
3204
+ const ask = ownAsk({ kind: 'fix', title: subject, prompt: `decklight marketplace update ${name}` });
3205
+ const out = await runMarketplace(['update', name]);
3206
+ ownDone(ask, { ok: out.ok, changed: false, tail: out.ok ? out.said : `failed — ${out.error}` });
3207
+ if (!out.ok) return json(409, { ok: false, error: out.error, ask });
3208
+ console.log(` check: ${subject} — updated ${name}`);
3209
+ // nothing in the deck changed: the page reloads to link what resolves now
3210
+ return json(200, { ok: true, changed: false, reload: true, said: out.said, ask });
3211
+ }
3212
+ case 'ds-unknown-system': {
3213
+ if (typeof ref !== 'string' || !ref.trim()) return json(400, { ok: false, error: 'which design system? — name@marketplace' });
3214
+ const ask = ownAsk({ kind: 'fix', title: subject, prompt: `decklight design-system add ${ref.trim()} ${deckRel}` });
3215
+ let answer = null;
3216
+ await routes.get('POST /deck/edit/design-system/mark')({
3217
+ body: JSON.stringify({ ref: ref.trim(), used: true }),
3218
+ json: (code, payload) => { answer = { code, payload }; },
3219
+ });
3220
+ const ok = answer?.code === 200 && answer.payload?.ok;
3221
+ if (ok && gitOn && shouldCommit(gitMode, { kind: 'agent', ok: true, changed: true }) && gitAutocommit(deckPath, root, subject, alsoNow())) {
3222
+ pendingAttr = null;
3223
+ console.log(` git: committed "${subject}"`);
3224
+ }
3225
+ ownDone(ask, { ok: !!ok, changed: !!ok && !!answer.payload.changed, tail: ok ? `${deckRel}: now uses ${ref.trim()}` : `failed — ${answer?.payload?.error ?? 'no answer'}` });
3226
+ if (!ok) return json(answer?.code ?? 500, { ok: false, error: answer?.payload?.error ?? 'could not add the design system', ask });
3227
+ return json(200, { ok: true, changed: !!answer.payload.changed, said: `added ${ref.trim()}`, ask, ...history.counts() });
3228
+ }
3229
+ default:
3230
+ return json(400, { ok: false, error: `${rule} has no quick fix the server applies — ask the agent` });
3231
+ }
3232
+ }
3233
+
2805
3234
  // ── the route table ──────────────────────────────────────────────────────
2806
3235
  // Every `/deck/edit/*` surface, keyed `METHOD /path`. This was forty-four
2807
3236
  // `if (req.method === … && url.pathname === …)` arms in one eleven-hundred
@@ -2834,6 +3263,9 @@ export async function editMain(args, { onListen = null, client } = {}) {
2834
3263
  'GET /deck/edit/narration/tracks': tracksRoute,
2835
3264
 
2836
3265
  'POST /deck/edit/agent': agentRoute,
3266
+ 'POST /deck/edit/design-system/migrate': designSystemMigrateRoute,
3267
+ 'POST /deck/edit/check/fix': checkFixRoute,
3268
+ 'POST /deck/edit/agent/stop': agentStopRoute,
2837
3269
  'POST /deck/edit/agent/prefer': agentPreferRoute,
2838
3270
  'POST /deck/edit/enhance': enhanceRoute,
2839
3271
  'POST /deck/edit/enhance/text': enhanceTextRoute,
@@ -2861,7 +3293,7 @@ export async function editMain(args, { onListen = null, client } = {}) {
2861
3293
  // want the deck's text and the two ways of writing it, the undo stack, the
2862
3294
  // event channel, and the quiet-write latch, and nothing else of editMain's.
2863
3295
  registerLookRoutes(routes, {
2864
- readDeck, applyEdit, writeDeck, history, broadcast,
3296
+ readDeck, applyEdit, writeDeck, history, broadcast, deckPath,
2865
3297
  // a quiet pick or mark updates the page that asked: no reload for it
2866
3298
  quiet: (html) => { quietWrite = html; },
2867
3299
  });
@@ -2873,6 +3305,7 @@ export async function editMain(args, { onListen = null, client } = {}) {
2873
3305
  registerHandoverRoutes(routes, {
2874
3306
  readDeck, deckPath, root, broadcast,
2875
3307
  gitOn: () => gitOn,
3308
+ onExport: (job) => { exportJob = job; },
2876
3309
  });
2877
3310
 
2878
3311
  // And git (cli/edit-git.mjs): the commit window and the deck's history. The
@@ -2959,6 +3392,9 @@ export async function editMain(args, { onListen = null, client } = {}) {
2959
3392
  || pathname === '/deck/tts' || pathname.startsWith('/deck/tts/') || pathname.startsWith('/deck/lipsync/')
2960
3393
  || pathname === '/deck/review/incoming' || pathname === '/deck/review/at';
2961
3394
 
3395
+ // What a locked deck still answers: the lock, and the stops.
3396
+ const UNLOCKED_POSTS = new Set(['/deck/edit/lock', '/deck/edit/export/stop', '/deck/edit/agent/stop']);
3397
+
2962
3398
  // Two static servers for one root, chosen per request by the mode. Write
2963
3399
  // mode serves the cwd with the deck at "/" and an author's exotic asset as
2964
3400
  // octet-stream. No-trust mode refuses every extension the MIME table does
@@ -3031,9 +3467,10 @@ export async function editMain(args, { onListen = null, client } = {}) {
3031
3467
  if (noTrust && WRITE_FAMILY(url.pathname)) {
3032
3468
  return json(403, { ok: false, noTrust: true, error: 'this deck is open without trust — nothing here changes it' });
3033
3469
  }
3034
- // locked: no edit route writes, whatever it was aimed at — the one
3035
- // POST that still answers is the lock itself, so it can be lifted
3036
- if (locked && req.method === 'POST' && url.pathname.startsWith('/deck/edit/') && url.pathname !== '/deck/edit/lock') {
3470
+ // locked: no edit route writes, whatever it was aimed at — the POSTs
3471
+ // that still answer are the lock itself, so it can be lifted, and the
3472
+ // stops, which write nothing and end a job started before the lock
3473
+ if (locked && req.method === 'POST' && url.pathname.startsWith('/deck/edit/') && !UNLOCKED_POSTS.has(url.pathname)) {
3037
3474
  return json(423, { ok: false, locked: true, error: 'the deck is locked — unlock it from the palette or the lock chip' });
3038
3475
  }
3039
3476
  const key = `${req.method} ${url.pathname}`;
@@ -3168,6 +3605,15 @@ export async function editMain(args, { onListen = null, client } = {}) {
3168
3605
  })
3169
3606
  .catch(() => {});
3170
3607
  }
3608
+ // Are the marketplaces behind their sources? Only when the author turned
3609
+ // the auto-check on (SPEC MARKETPLACES_SCREEN), at most once in its
3610
+ // window, and the same detached shape: the deck is told when the answer
3611
+ // lands and offers it; a source that does not answer is said on the
3612
+ // screen, never here.
3613
+ autoCheckInBackground({ broadcast }).then((rec) => {
3614
+ const behind = rec?.marketplaces.filter((r) => r.state === 'behind') ?? [];
3615
+ if (behind.length) startup('marketplaces', `${behind.map((r) => r.name).join(', ')} out of date`, ` marketplaces: ${behind.map((r) => r.name).join(', ')} out of date — / → Marketplaces… updates ${behind.length === 1 ? 'it' : 'them'}`);
3616
+ });
3171
3617
  }
3172
3618
  return { port: actual, deckUrl, host, server };
3173
3619
  }