decklight 0.8.1 → 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 (138) hide show
  1. package/PLATFORM.md +707 -0
  2. package/README.md +226 -150
  3. package/SPEC.md +803 -888
  4. package/cli/agent-review.mjs +246 -0
  5. package/cli/agents.mjs +35 -9
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +190 -0
  10. package/cli/bundle-module.mjs +95 -0
  11. package/cli/bundle.mjs +439 -35
  12. package/cli/cast.mjs +48 -12
  13. package/cli/check-fixes.mjs +186 -0
  14. package/cli/check.mjs +988 -0
  15. package/cli/clone-deck.mjs +179 -0
  16. package/cli/commands.mjs +345 -0
  17. package/cli/comments.mjs +64 -18
  18. package/cli/commit-flow.mjs +51 -22
  19. package/cli/commit-message.mjs +51 -74
  20. package/cli/commit-split.mjs +601 -0
  21. package/cli/deck-refs.mjs +64 -0
  22. package/cli/deck-routes.mjs +67 -0
  23. package/cli/deckfile.mjs +3 -5
  24. package/cli/decklight.mjs +68 -289
  25. package/cli/design-system-deps.mjs +209 -0
  26. package/cli/design-system-edit.mjs +194 -0
  27. package/cli/design-system-refs.mjs +666 -0
  28. package/cli/design-system.mjs +497 -0
  29. package/cli/doctor.mjs +115 -0
  30. package/cli/edit-git.mjs +353 -0
  31. package/cli/edit-handover.mjs +551 -0
  32. package/cli/edit-look.mjs +631 -0
  33. package/cli/edit-slides.mjs +683 -0
  34. package/cli/edit.mjs +2585 -855
  35. package/cli/enhance.mjs +485 -0
  36. package/cli/extension.mjs +10 -10
  37. package/cli/font-refs.mjs +273 -0
  38. package/cli/font.mjs +246 -0
  39. package/cli/git-tree.mjs +1 -1
  40. package/cli/git.mjs +78 -11
  41. package/cli/import.mjs +56 -10
  42. package/cli/init.mjs +407 -236
  43. package/cli/library.mjs +127 -0
  44. package/cli/loader.mjs +3 -1
  45. package/cli/marketplace-autocheck.mjs +200 -0
  46. package/cli/marketplace.mjs +460 -29
  47. package/cli/narrate.mjs +251 -0
  48. package/cli/open-browser.mjs +63 -0
  49. package/cli/open.mjs +961 -0
  50. package/cli/pdf.mjs +64 -17
  51. package/cli/pkg.mjs +44 -2
  52. package/cli/plugin.mjs +43 -41
  53. package/cli/port-conflict.mjs +53 -23
  54. package/cli/pptx-export.mjs +63 -27
  55. package/cli/publish.mjs +8 -4
  56. package/cli/qr.mjs +1 -1
  57. package/cli/record.mjs +85 -23
  58. package/cli/remote.mjs +43 -17
  59. package/cli/restore.mjs +11 -4
  60. package/cli/review-ref.mjs +125 -0
  61. package/cli/review-remote.mjs +92 -48
  62. package/cli/review-routes.mjs +254 -0
  63. package/cli/review-store.mjs +47 -7
  64. package/cli/review-submit.mjs +47 -57
  65. package/cli/runtime-link.mjs +560 -0
  66. package/cli/serve.mjs +236 -45
  67. package/cli/setup.mjs +112 -0
  68. package/cli/sign.mjs +1 -1
  69. package/cli/skill-content.mjs +229 -35
  70. package/cli/skills.mjs +353 -26
  71. package/cli/start.mjs +110 -0
  72. package/cli/supervise.mjs +6 -6
  73. package/cli/theme-refs.mjs +527 -0
  74. package/cli/theme.mjs +181 -137
  75. package/cli/trust.mjs +83 -0
  76. package/cli/units.mjs +112 -47
  77. package/cli/update-check.mjs +1 -5
  78. package/cli/upgrade.mjs +194 -28
  79. package/cli/upstream.mjs +4 -3
  80. package/cli/util.mjs +4 -4
  81. package/cli/wizard.mjs +6 -6
  82. package/dist/build-info.json +1 -1
  83. package/dist/decklight.css +1533 -59
  84. package/dist/decklight.js +258 -115
  85. package/dist/decklight.js.map +4 -4
  86. package/docs/GLOSSARY.md +141 -0
  87. package/docs/architecture.svg +17 -17
  88. package/package.json +4 -2
  89. package/themes/README.md +9 -8
  90. package/themes/reveal-solarized.css +10 -0
  91. package/tools/args.mjs +20 -0
  92. package/tools/atomic-write.mjs +48 -0
  93. package/tools/brand-palette.mjs +717 -0
  94. package/tools/bridge.mjs +1 -1
  95. package/tools/build-groups.mjs +42 -0
  96. package/tools/color.mjs +48 -0
  97. package/tools/deck-html.mjs +396 -11
  98. package/tools/design-system-format.mjs +778 -0
  99. package/tools/design-system-migrations.mjs +207 -0
  100. package/tools/elevenlabs-tts.mjs +110 -17
  101. package/tools/exec.mjs +11 -3
  102. package/tools/extension-check.mjs +31 -7
  103. package/tools/font-format.mjs +190 -0
  104. package/tools/font-stacks.mjs +24 -0
  105. package/tools/gemini-tts.mjs +3 -0
  106. package/tools/lipsync-config.mjs +103 -0
  107. package/tools/lipsync-engines.mjs +205 -2
  108. package/tools/lipsync-server.mjs +264 -41
  109. package/tools/lipsync.mjs +37 -18
  110. package/tools/local-voice.mjs +32 -42
  111. package/tools/narration-manifest.mjs +270 -0
  112. package/tools/narration-synth.mjs +416 -0
  113. package/tools/pptx.mjs +776 -19
  114. package/tools/publish-targets.mjs +1 -1
  115. package/tools/publish-voices.mjs +3 -3
  116. package/tools/recording-impact.mjs +7 -3
  117. package/tools/render-theme.mjs +33 -0
  118. package/tools/review-anchor.mjs +28 -12
  119. package/tools/semver.mjs +40 -0
  120. package/tools/sentences.mjs +180 -0
  121. package/tools/shot.mjs +14 -7
  122. package/tools/site-clip.mjs +114 -0
  123. package/tools/site-voices.mjs +232 -0
  124. package/tools/template-theme.mjs +1 -1
  125. package/tools/test-impact.mjs +17 -10
  126. package/tools/theme-check.mjs +30 -3
  127. package/tools/tts-cache.mjs +4 -3
  128. package/tools/tts-engines.mjs +38 -20
  129. package/tools/tts-setup.mjs +7 -7
  130. package/tools/video-options.mjs +34 -0
  131. package/tools/video.mjs +530 -54
  132. package/tools/voiceover-server.mjs +185 -104
  133. package/tools/voiceover.mjs +119 -261
  134. package/tools/zip.mjs +1 -1
  135. package/cli/dev.mjs +0 -623
  136. package/cli/present.mjs +0 -853
  137. package/cli/review.mjs +0 -361
  138. package/tools/publish-site-voices.mjs +0 -75
package/cli/edit.mjs CHANGED
@@ -2,35 +2,45 @@
2
2
  // Copyright 2026 Gilles Philippart
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
 
5
- // The live-editing deck server behind `decklight author` (SPEC PRESENTING
6
- // author mode). Not a command of its own anymore — the dispatcher refuses
7
- // `edit` out loud — author spawns this module directly:
5
+ // The live-editing deck server behind `decklight <deck>` (SPEC PRESENTING
6
+ // write mode). Not a command of its own anymore — the dispatcher refuses
7
+ // `edit` out loud — `open` spawns this module directly:
8
8
  //
9
9
  // node cli/edit.mjs <deck.html> [--port 8788] [--git | --no-git]
10
10
  // [--commit-every <seconds>] [--agent <name>] [--commit-messages]
11
11
  //
12
12
  // It binds 127.0.0.1 and nothing else. The phone remote used to be here behind
13
13
  // `--remote`, which meant a clicker cost you an editing server on the LAN;
14
- // `decklight present --remote` hosts it now, with no edit surface to widen
15
- // (PRESENT#REMOTE). Both flags are refused out loud rather than ignored.
14
+ // `decklight <deck.html> --no-trust --remote` hosts it now, with no edit surface to widen
15
+ // (NO_TRUST#REMOTE). Both flags are refused out loud rather than ignored.
16
16
  //
17
17
  // Serves the current working directory over localhost (so decks that
18
18
  // reference ../dist and ../themes just work), watches the deck file, and:
19
19
  //
20
- // GET /edit/ping → { ok, deck, undo, redo, git, agents, agentBusy, wizards }
21
- // GET /edit/events → SSE; `reload` on deck change, `agent` job status
22
- // POST /edit/notes → { slide, text } rewrite that slide's notes
23
- // POST /edit/timings → { timings: [{ slide, seconds }] } rehearsed times onto the sections
24
- // POST /edit/layout → { slide, layout } write data-layout to the file
25
- // POST /edit/hidden → { slide, hidden } data-hidden on or off (HIDDEN_SLIDES)
26
- // GET /edit/element/source → ?slide=&index= an element's outerHTML, fresh from the file
27
- // POST /edit/element/remove → { slide, index } delete that element
28
- // POST /edit/element/content → { slide, index, html } replace its outerHTML
29
- // POST /edit/element/effect → { slide, index, effect } write data-build (null strips it)
30
- // POST /edit/undo → step the deck file back through the edit history
31
- // POST /edit/redo → step it forward again
32
- // POST /edit/agent → { prompt, agent? } one-shot AI agent edit
33
- // POST /edit/shutdown → final autocommit, then exit — same as Ctrl-C, so a
20
+ // GET /deck/ping → { ok, deck, undo, redo, git, agents, agentBusy, wizards }
21
+ // GET /deck/events → SSE; `reload` on deck change, `agent` job status
22
+ // POST /deck/edit/slide/notes → { slide, text } rewrite that slide's notes
23
+ // POST /deck/edit/timings → { timings: [{ slide, seconds }] } rehearsed times onto the sections
24
+ // POST /deck/edit/slide/layout → { slide, layout } write data-layout to the file
25
+ // POST /deck/edit/slide/hidden → { slide, hidden } data-hidden on or off (HIDDEN_SLIDES)
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
28
+ // GET /deck/edit/publish/plan → where publishing would put this deck, without putting it there
29
+ // POST /deck/edit/publish → bundle the deck and push it (the palette's Publish row)
30
+ // GET /deck/edit/export/estimate → ?kind=bundle&theme= how big that file would be, before it is written
31
+ // GET /deck/edit/element/source → ?slide=&index= an element's outerHTML, fresh from the file
32
+ // POST /deck/edit/element/remove → { slide, index } delete that element
33
+ // POST /deck/edit/element/content → { slide, index, html } replace its outerHTML
34
+ // POST /deck/edit/element/effect → { slide, index, effect } write data-build (null strips it)
35
+ // POST /deck/edit/undo → step the deck file back through the edit history
36
+ // POST /deck/edit/redo → step it forward again
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
39
+ // POST /deck/edit/enhance → { slides: [n…]|'all', agent?, kind? } audio tags ('tags') or written for the ear ('spoken')
40
+ // POST /deck/edit/enhance/text → { text, agent?, kind? } → { text } the same, for the notes editor's box (writes nothing)
41
+ // POST /deck/edit/review → { agent? } the agent reads the deck, read-only, for Check deck…'s agent review (writes nothing)
42
+ // GET /deck/edit/review → the last review's findings that still hold, each with the prompt that fixes it
43
+ // POST /deck/edit/shutdown → final autocommit, then exit — same as Ctrl-C, so a
34
44
  // port conflict can take over an old session cleanly
35
45
  //
36
46
  // Every mutation goes through ONE undo history — snapshots of the whole
@@ -41,51 +51,104 @@
41
51
  // agent's edit back exactly like the player's own.
42
52
  //
43
53
  // Git: with --git (or when the deck already sits in a repository and
44
- // --no-git wasn't passed) the server auto-commits the deck on a regular
45
- // basis — every --commit-every seconds when it actually changed, plus a
46
- // final commit on Ctrl-C. --git also creates the repository when none
54
+ // --no-git wasn't passed) the server snapshots the deck silently on
55
+ // refs/decklight/wip and commits it when you say so (K) — an agent's own
56
+ // edit commits itself; --git-mode timer keeps the old commit-every-N-seconds
57
+ // cadence with a final commit on Ctrl-C. --git also creates the repository when none
47
58
  // exists — seeded with a starter .gitignore (createRepo, below).
48
- // `decklight author` asks interactively before passing --git down.
59
+ // `decklight <deck>` asks interactively before passing --git down.
49
60
 
50
- import { createServer } from 'node:http';
61
+ import { createServer, request as httpRequest } from 'node:http';
51
62
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, appendFileSync, watch, existsSync } from 'node:fs';
63
+ // Every write of the DECK goes through this rather than writeFileSync: the
64
+ // edit server rewrites the whole file on every small edit, and a truncate
65
+ // that is interrupted leaves a prefix of a talk where the talk was.
66
+ import { writeFileAtomic } from '../tools/atomic-write.mjs';
52
67
  import { resolve, relative, dirname, sep, basename } from 'node:path';
68
+ import { VIDEO_FORMATS, VIDEO_QUALITIES, VIDEO_SUBTITLES, valuesOf } from '../tools/video-options.mjs';
53
69
  import { spawn, execFileSync } from 'node:child_process';
54
- import { agentCommand, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent, claudeActivity } from './agents.mjs';
70
+ import { AsyncLocalStorage } from 'node:async_hooks';
71
+ import { agentAsk, agentCommand, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent, claudeActivity } from './agents.mjs';
55
72
  import { exitWhenOrphaned } from './supervise.mjs';
56
73
  import { readyLine } from './banner.mjs';
57
74
 
58
75
  /**
59
76
  * Say a startup fact.
60
77
  *
61
- * Under author (DECKLIGHT_BANNER) it becomes a row on the one banner author
78
+ * Under `open` (DECKLIGHT_BANNER) it becomes a row on the one banner author
62
79
  * prints, so it cannot land above the URL. Run standalone — `decklight edit` —
63
80
  * it prints the line it always printed, which is why every call passes both:
64
81
  * the SHORT text a banner row wants, and the full sentence a bare terminal
65
- * needs because it has no banner to sit under.
82
+ * needs because it has no banner to sit under. `mark` is the banner's: 'ok'
83
+ * for something installed and on (a green tick), 'warn' for something to fix.
66
84
  */
67
- const startup = (key, text, human) => {
68
- if (process.env.DECKLIGHT_BANNER) console.log(readyLine({ key, text }));
85
+ const startup = (key, text, human, mark) => {
86
+ if (process.env.DECKLIGHT_BANNER) console.log(readyLine({ key, text, ...(mark ? { mark } : {}) }));
69
87
  else console.log(human);
70
88
  };
71
- import { argReader, firstPositional, isMain } from '../tools/args.mjs';
72
- import { NOTES_ASIDE, locateSlide, sectionChildRanges } from '../tools/deck-html.mjs';
89
+ import { argReader, firstPositional, isMain, parsePort, badPort } from '../tools/args.mjs';
90
+ import { runMain } from './util.mjs';
91
+ import { PKG, AGENTS_MARKER, skillVersionOf } from './skill-content.mjs';
92
+ import { selfCommand } from './pkg.mjs';
93
+ import { slidesSinceHead } from './commit-split.mjs';
94
+ import { semverCompare } from '../tools/semver.mjs';
95
+
96
+ // The flags that take a value, so the deck can be found past them. `--git-mode`
97
+ // was missing, so `edit.mjs --git-mode agent deck.html` refused a deck called
98
+ // "agent". (`decklight <deck>` builds this argv itself and was never affected.)
99
+ const VALUE_FLAGS = ['--port', '--commit-every', '--agent', '--git-mode', '--tts-port', '--lipsync-port',
100
+ '--host', '--root', '--branch', '--into', '--upstream-every'];
101
+ import { NOTES_ASIDE, locateSlide, sectionChildRanges, elementChildRanges, splitOpenTag } from '../tools/deck-html.mjs';
102
+ import { canonMarks, writtenMarks, CLICK_MARK } from '../tools/sentences.mjs';
103
+ import { configBlock, hasEmbeddedRuntime, linkRuntime } from './runtime-link.mjs';
104
+ import { linkReferences } from './deck-refs.mjs';
105
+ import { slideTexts, priorSlideTexts, staleSlides, trackDrift } from '../tools/narration-manifest.mjs';
106
+ // The routes that rewrite a slide, which took three of editMain's bindings and
107
+ // nothing else with them. The import back — edit-slides reaches here for the
108
+ // pure transforms — is a deliberate static cycle and not a dynamic one: this
109
+ // module ends in a top-level `await` (the isMain boot below), so a
110
+ // `await import('./edit-slides.mjs')` from inside editMain would wait on an
111
+ // evaluation that is waiting on IT, and the server would never come up.
112
+ // A static cycle has no such moment: both bodies are function declarations,
113
+ // hoisted before either runs, and nothing is read until a request arrives.
114
+ import { registerSlideRoutes } from './edit-slides.mjs';
115
+ // The route groups split out after it, imported the same way and for the same
116
+ // reason: the deck's look (themes, design systems, fonts), and handing the
117
+ // deck over (export, publish, the inspector's read), and git (the commit
118
+ // window, the deck's history, restore).
119
+ import { registerLookRoutes, runMarketplace, autoCheckInBackground } from './edit-look.mjs';
120
+ import { registerHandoverRoutes } from './edit-handover.mjs';
121
+ import { registerGitRoutes } from './edit-git.mjs';
73
122
  // the boot-call locator audit and upgrade share — three commands, one answer
74
123
  // about which <script> is the init call
75
- import { classifyScripts } from './audit.mjs';
124
+ import { classifyScripts, auditDeck, formatLabel, stripUnaccounted } from './audit.mjs';
125
+ // The no-trust mode's own ingredients (PRESENTING): the signature beside a
126
+ // deck, the .decklight container, the presenter's chrome, the upstream of a
127
+ // clone, and the phone remote. None of them writes.
128
+ import { randomBytes } from 'node:crypto';
129
+ import { verifyFile, verifyBytes, formatSignature, isVerified, UNSIGNED, TAMPERED, VERIFIED } from './sign.mjs';
130
+ import { isContainer, readContainer, formatManifest } from './deckfile.mjs';
131
+ import { loadLibrary, injectChrome } from './plugin.mjs';
132
+ import {
133
+ SAFE_CONFIG, canPull, checkUpstream, resolveInterval, resolveUpstream, runGit, upstreamSuppressed,
134
+ } from './upstream.mjs';
135
+ import { createRemoteRelay } from './remote.mjs';
136
+ import { corsHeaders, readBody } from '../tools/bridge.mjs';
76
137
  import { reviewPathFor, parseReview, serializeRecord, newId } from './review-store.mjs';
77
- // The arbiters of what a comment IS, shared with the review server so two
138
+ import { createReviewRoutes } from './review-routes.mjs';
139
+ import { createDeckRoutes } from './deck-routes.mjs';
140
+ // The arbiters of what a comment IS, shared with the no-trust mode so two
78
141
  // writers cannot put two shapes into one union-merged file.
79
- import { commentProblem, reviewRecord } from './review.mjs';
142
+ import { commentProblem, reviewRecord } from './review-routes.mjs';
80
143
  import { foldReview } from '../tools/review-anchor.mjs';
81
144
  import { recordingImpact, impactWarning, slidesFromFiles } from '../tools/recording-impact.mjs';
82
145
  import { indexDeckFile, slideTextOf, knowsCommit } from './comments.mjs';
83
- import { deckHistory, decorateHistory, restoreDeck, deckAt, withBaseHref } from './restore.mjs';
84
- import { escapeHtml, sseChannel, staticFiles, listenTakingOverIfNeeded, allowEditRequest } from './serve.mjs';
85
- import { reviewsWaiting, reviewLine, reviewCheckSuppressed, setCommentDone } from './review-remote.mjs';
146
+ import { deckAt } from './restore.mjs';
147
+ import { escapeHtml, staticFiles, listenTakingOverIfNeeded, allowEditRequest, allowRemote, lanAddress, isOwnOrigin, CSP } from './serve.mjs';
148
+ import { reviewsWaiting, reviewLine, reviewCheckSuppressed } from './review-remote.mjs';
86
149
  import { configureEngine, loadCredentials, forgetCredentials, redactAnswers, validateSchema, provenance, BRIDGE_ADDR, CONFIGURED, UNREACHABLE, PREREQUISITE } from './wizard.mjs';
87
150
 
88
- // The `/edit/*` surface answers loopback only — but "loopback" is the wrong
151
+ // The `/deck/edit/*` surface answers loopback only — but "loopback" is the wrong
89
152
  // boundary for the threat (#222). The dangerous caller is not off-machine: it
90
153
  // is the user's own browser, where any open tab can `fetch()` this port. Binding
91
154
  // 127.0.0.1 does nothing about that, and a wildcard `access-control-allow-origin`
@@ -102,18 +165,26 @@ const corsHeadersFor = (origin) => ({
102
165
  });
103
166
 
104
167
  // ── remote access & static serving: extracted to serve.mjs / remote.mjs ────
105
- // (PRESENT_SERVER in MARKETPLACE.md: `decklight present` reuses the same core
106
- // with the /edit/* routes ABSENT, not merely refused.) Re-exported here so
168
+ // (NO_TRUST in MARKETPLACE.md: `decklight <deck> --no-trust` reuses the same core
169
+ // with the /deck/edit/* routes ABSENT, not merely refused.) Re-exported here so
107
170
  // existing importers — the tests, init.mjs — and SPEC citations keep working.
108
171
  export { isLoopback, lanAddress, escapeHtml } from './serve.mjs';
109
172
 
110
- /** ⟨CLICK⟩-separated plain text → the aside's inner HTML (one <p> per segment). */
173
+ /**
174
+ * Click-separated plain text → the aside's inner HTML: one <p> per paragraph
175
+ * — a blank line apart, as the author wrote them; saving never merges them —
176
+ * and a `<p>[click]</p>` between beats. Every marker spelling is read
177
+ * (`[click]`, `<click>`, `⟨CLICK⟩`…) and each is written back the one way
178
+ * decklight writes them, in square brackets.
179
+ */
111
180
  export function notesTextToAside(text) {
112
- const segs = text.split(/\s*⟨CLICK⟩\s*/).map((s) => s.replace(/\s+/g, ' ').trim());
113
181
  const ps = [];
114
- segs.forEach((seg, i) => {
115
- if (i > 0) ps.push('<p>⟨CLICK⟩</p>');
116
- if (seg) ps.push(`<p>${escapeHtml(seg)}</p>`);
182
+ canonMarks(text).split(CLICK_MARK).forEach((seg, i) => {
183
+ if (i > 0) ps.push('<p>[click]</p>');
184
+ for (const para of writtenMarks(seg).split(/\n[ \t]*\n/)) {
185
+ const p = para.replace(/\s+/g, ' ').trim();
186
+ if (p) ps.push(`<p>${escapeHtml(p)}</p>`);
187
+ }
117
188
  });
118
189
  return ps.join('\n ');
119
190
  }
@@ -124,12 +195,191 @@ export function setSlideNotes(html, slide, asideInner) {
124
195
  const aside = `<aside class="notes">\n ${asideInner}\n </aside>`;
125
196
  const seg = parts[idx];
126
197
  parts[idx] = NOTES_ASIDE.test(seg)
127
- ? seg.replace(NOTES_ASIDE, aside)
128
- : seg.replace(/<\/section>/, ` ${aside}\n </section>`);
198
+ // FUNCTION replacers: the notes are the author's text, and a string
199
+ // replacement would read `$1`, `$&`, `` $` `` and `$'` in it as patterns —
200
+ // "$1M" spliced the slide's whole old notes in where it was typed (#646)
201
+ ? seg.replace(NOTES_ASIDE, () => aside)
202
+ : seg.replace(/<\/section>/, () => ` ${aside}\n </section>`);
203
+ return parts.join('');
204
+ }
205
+
206
+ /**
207
+ * A slide's sources as the aside's inner HTML (`SLIDE_SOURCES`), or `null`
208
+ * when there is nothing left to write.
209
+ *
210
+ * Link hrefs are restricted to the schemes a reference can honestly be:
211
+ * `javascript:` and `data:` are executable, and this aside travels — a slide
212
+ * taken from a marketplace template carries its sources into your deck, so an
213
+ * editor that will write an executable link is an editor that will eventually
214
+ * write somebody else's.
215
+ */
216
+ export function sourcesToAside({ facts = [], links = [] } = {}, dropped = []) {
217
+ const clean = (u) => (/^(https?:|mailto:|#|\/|\.{0,2}\/)/i.test(String(u).trim()) ? String(u).trim() : null);
218
+ const pairs = facts.filter(([k, v]) => String(k).trim() && String(v).trim());
219
+ const refs = links.filter((l) => {
220
+ if (!String(l?.title ?? '').trim()) return false;
221
+ if (clean(l?.href)) return true;
222
+ // a link that will not be written is a link the author has to hear about:
223
+ // an empty row is just an empty row, a rejected scheme is a decision
224
+ if (String(l?.href ?? '').trim()) dropped.push(String(l.href).trim());
225
+ return false;
226
+ });
227
+ if (!pairs.length && !refs.length) return null;
228
+ const dl = pairs.length
229
+ ? `<dl>${pairs.map(([k, v]) => `<dt>${escapeHtml(k.trim())}</dt><dd>${escapeHtml(v.trim())}</dd>`).join('')}</dl>`
230
+ : '';
231
+ const ul = refs.length
232
+ ? ['<ul>', ...refs.map((l) => ` <li><a href="${escapeHtml(clean(l.href))}">${escapeHtml(String(l.title).trim())}</a>`
233
+ + `${String(l.note ?? '').trim() ? ` — ${escapeHtml(String(l.note).trim())}` : ''}</li>`), ' </ul>'].join('\n')
234
+ : '';
235
+ return [dl, ul].filter(Boolean).join('\n ');
236
+ }
237
+
238
+ /** Replace, insert, or remove slide N's `<aside class="sources">`. */
239
+ export function setSlideSources(html, slide, asideInner) {
240
+ const { parts, idx } = locateSlide(html, slide);
241
+ const seg = parts[idx];
242
+ const existing = /\n?\s*<aside class="sources">[\s\S]*?<\/aside>/;
243
+ if (!asideInner) {
244
+ parts[idx] = seg.replace(existing, '');
245
+ return parts.join('');
246
+ }
247
+ const aside = `<aside class="sources">\n ${asideInner}\n </aside>`;
248
+ parts[idx] = existing.test(seg)
249
+ ? seg.replace(existing, () => `\n ${aside}`) // the author's text: never a replacement pattern (#646)
250
+ : seg.replace(/<\/section>/, () => ` ${aside}\n </section>`);
129
251
  return parts.join('');
130
252
  }
131
253
 
132
254
  // the same ring the player cycles — the file is the source of truth now
255
+ /**
256
+ * Is this deck already one file — nothing left for the bundler to flatten?
257
+ *
258
+ * `decklight bundle` asks exactly this and refuses when the answer is yes, so
259
+ * the publish route asks it FIRST and passes `--no-bundle` rather than handing
260
+ * a presenter a refusal about a flag. An init-scaffolded deck is this case,
261
+ * which makes it the common one rather than the corner.
262
+ */
263
+ export const alreadyOneFile = (html) =>
264
+ !/<link\b[^>]*rel=["']stylesheet["'][^>]*href=["'][^"']*themes\/[\w-]+\.css["']/i.test(html)
265
+ && /<style\b[^>]*\bdata-theme\b/i.test(html)
266
+ // an imported deck with a derived theme embeds that theme and nothing else
267
+ // (#520): the runtime is still to be bundled in
268
+ && hasEmbeddedRuntime(html);
269
+
270
+ /**
271
+ * The files the palette's hand-over rows can ask for (PRESENTING). Each is one
272
+ * of decklight's own commands, named the way the deck names it to the presenter
273
+ * — `what` IS the wording in the toast, so the row, the terminal line and the
274
+ * message log all say the same words.
275
+ */
276
+ export const EXPORT_KINDS = {
277
+ pptx: { what: 'PowerPoint', variant: null },
278
+ pdf: { what: 'PDF', variant: '' },
279
+ 'pdf-notes': { what: 'PDF with notes', variant: 'notes' },
280
+ 'pdf-handout': { what: 'PDF handout', variant: 'handout' },
281
+ video: { what: 'video', variant: null },
282
+ // the self-contained file `decklight bundle` writes — every marked theme in
283
+ // it, opening on the theme on screen
284
+ bundle: { what: 'one file', variant: null },
285
+ };
286
+
287
+ /**
288
+ * The preview frame's failure, as a page rather than as a bare line of text.
289
+ *
290
+ * This frame is 700px of dark chrome inside the history dialog, and a
291
+ * plain-text body rendered in it reads as a black rectangle — which is how
292
+ * #508 looked to everyone who hit it. Styled here, in the server's own words,
293
+ * so the panel needs no failure branch of its own: whatever went wrong is
294
+ * legible in the place somebody is already looking.
295
+ */
296
+ export function previewError(why) {
297
+ return `<!doctype html><meta charset="utf-8"><title>preview unavailable</title>
298
+ <style>
299
+ :root { color-scheme: dark light; }
300
+ body { margin: 0; display: grid; place-items: center; min-height: 100vh;
301
+ background: #16181d; color: #e8eaee; font: 14px/1.6 system-ui, sans-serif; }
302
+ .box { max-width: 34em; padding: 24px; text-align: center; }
303
+ h1 { margin: 0 0 6px; font-size: 15px; font-weight: 600; }
304
+ p { margin: 0; opacity: .7; }
305
+ </style>
306
+ <div class="box"><h1>this version could not be previewed</h1><p>${escapeHtml(why)}</p></div>
307
+ `;
308
+ }
309
+
310
+ /**
311
+ * What is wrong with a video export request, or null. Every field comes from a
312
+ * page, so every one is checked before anything runs.
313
+ *
314
+ * - `slides` is the command's own `--slides` spelling; `format`, `quality` and
315
+ * `subtitles` its `--format`, `--quality` and `--subtitles`.
316
+ * - The voice is ONE of three: `narration` names a recorded folder (inside the
317
+ * deck's directory, holding a manifest or whole-slide audio — a render that cannot find its audio
318
+ * should refuse, not come out silent); `synthesize` asks for the live voice
319
+ * to be voiced into a folder first; `silent` is silence by name. None of them
320
+ * is the command's own default: a `voiceover/` beside the deck if there is one.
321
+ * - A synthesized voice never lands on a take somebody recorded. A folder that
322
+ * already holds audio is refreshed only when its manifest says it was this
323
+ * engine and this voice; anything else — a manifest for another voice, or
324
+ * audio with no manifest at all, which is what your own voice leaves — refuses.
325
+ */
326
+ export function videoExportProblem({ slides, narration, synthesize, silent, format, quality, subtitles, allowStale } = {}, deckDir) {
327
+ if (allowStale != null && typeof allowStale !== 'boolean') return 'allowStale is yes or no';
328
+ // the card's rows and the command's flags read one list (src/core/video-options.js)
329
+ for (const [field, value, list] of [['format', format, VIDEO_FORMATS], ['quality', quality, VIDEO_QUALITIES], ['subtitles', subtitles, VIDEO_SUBTITLES]]) {
330
+ if (value != null && !valuesOf(list).includes(value)) return `${field} must be ${valuesOf(list).join(', ')}`;
331
+ }
332
+ if (slides != null && slides !== '' && !(typeof slides === 'string' && /^\d+(?:-\d+)?$/.test(slides))) {
333
+ return 'slides must be a-b or a single slide number';
334
+ }
335
+ const given = [narration, synthesize, silent].filter((v) => v != null && v !== '' && v !== false);
336
+ if (given.length > 1) return 'one voice at a time — a recorded track, a synthesized one, or silence';
337
+ if (synthesize != null) {
338
+ if (typeof synthesize !== 'object') return 'synthesize names an engine, a voice and a folder';
339
+ const { engine, model, voice, style, dir } = synthesize;
340
+ if (typeof engine !== 'string' || !/^[a-z][a-z0-9-]{0,40}$/.test(engine)) return 'name the engine to synthesize with';
341
+ for (const [field, value, max] of [['model', model, 200], ['voice', voice, 200], ['style', style, 2000]]) {
342
+ if (value != null && (typeof value !== 'string' || value.length > max || /\p{Cc}/u.test(value))) {
343
+ return `the ${field} is not one this server will pass on`;
344
+ }
345
+ }
346
+ const bad = folderProblem(dir, deckDir, 'the synthesized voice');
347
+ if (bad) return bad;
348
+ const at = resolve(deckDir, dir);
349
+ let audio = [];
350
+ try { audio = readdirSync(at).filter((f) => /^slide-\d+(-\d+)?\.(wav|m4a|mp3)$/.test(f)); } catch { /* a new folder */ }
351
+ if (audio.length) {
352
+ let m = null;
353
+ try { m = JSON.parse(readFileSync(resolve(at, 'manifest.json'), 'utf8')); } catch { /* recorded by hand */ }
354
+ if (!m || m.engine !== engine || (m.voice ?? null) !== (voice ?? null)) {
355
+ return `${dir}/ already holds ${m?.voice ? `${m.voice}'s recording` : 'a recording'} — synthesizing into it would replace it`;
356
+ }
357
+ }
358
+ return null;
359
+ }
360
+ if (narration == null || narration === '') return null;
361
+ const bad = folderProblem(narration, deckDir, 'the narration');
362
+ if (bad) return bad;
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'))) {
368
+ return `no recorded narration in ${narration}/ — record the deck first (V → Record this deck…)`;
369
+ }
370
+ return null;
371
+ }
372
+
373
+ /** A folder named by a page: relative, inside the deck's own directory. */
374
+ function folderProblem(dir, deckDir, what) {
375
+ if (typeof dir !== 'string' || !dir || dir.length > 200 || /^[a-z][a-z0-9+.-]*:/i.test(dir)) {
376
+ return `${what} is a folder beside the deck, not a URL`;
377
+ }
378
+ const at = resolve(deckDir, dir);
379
+ if (!at.startsWith(resolve(deckDir) + sep)) return `${what} folder must be inside the deck's folder (${dir})`;
380
+ return null;
381
+ }
382
+
133
383
  export const LAYOUTS = ['auto', 'centered', 'pinned', 'top', 'split', 'split-flip'];
134
384
 
135
385
  /** Set (or, for 'auto', remove) slide N's data-layout attribute in the deck html. */
@@ -180,7 +430,7 @@ export function setSlideHidden(html, slide, hidden) {
180
430
  }
181
431
 
182
432
  /** Look up element `index` (raw child position) on slide `slide`, or throw. */
183
- function locateElement(html, slide, index) {
433
+ export function locateElement(html, slide, index) {
184
434
  const { parts, idx } = locateSlide(html, slide);
185
435
  const seg = parts[idx];
186
436
  const ranges = sectionChildRanges(seg);
@@ -196,6 +446,206 @@ export function removeSlideElement(html, slide, index) {
196
446
  return parts.join('');
197
447
  }
198
448
 
449
+ /**
450
+ * Remove ONE element inside slide N's element `index` (PRESENTING, a shape
451
+ * selected inside a diagram): the node at `path`, addressed and checked the
452
+ * way setElementStyles addresses one. `[]` is refused, since that is the
453
+ * whole element and removeSlideElement's job. A node alone on its line takes
454
+ * the line with it, so the file is left without a blank one.
455
+ */
456
+ export function removeNestedElement(html, slide, index, { path, tag }) {
457
+ if (!Array.isArray(path) || !path.length || path.length > 16 || path.some((n) => !Number.isInteger(n) || n < 0)) throw new Error('bad path');
458
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
459
+ const el = seg.slice(r.start, r.end);
460
+ let start = 0; let end = el.length;
461
+ for (const n of path) {
462
+ const kid = elementChildRanges(el.slice(start, end))[n];
463
+ if (!kid) throw stale(`slide ${slide} #${index}: the file has no element at ${path.join('.')} — reload and try again`);
464
+ end = start + kid.end; start += kid.start;
465
+ }
466
+ const found = /^<([a-zA-Z][\w:-]*)/.exec(el.slice(start, end))?.[1]?.toLowerCase();
467
+ if (tag && found !== String(tag).toLowerCase()) throw stale(`slide ${slide} #${index}: the page found <${tag}> at ${path.join('.')}, the file has <${found}> — reload and try again`);
468
+ const lineStart = el.lastIndexOf('\n', start - 1) + 1;
469
+ const nl = el.indexOf('\n', end);
470
+ const lineEnd = nl < 0 ? el.length : nl;
471
+ if (/^[ \t]*$/.test(el.slice(lineStart, start)) && /^[ \t]*$/.test(el.slice(end, lineEnd)) && nl >= 0) { start = lineStart; end = nl + 1; }
472
+ parts[idx] = seg.slice(0, r.start) + el.slice(0, start) + el.slice(end) + seg.slice(r.end);
473
+ return parts.join('');
474
+ }
475
+
476
+ /**
477
+ * The colours a page may ask this server to write (PRESENTING, element edit
478
+ * mode): a theme token by reference — `var(--d-fill-3)`, so the deck stays
479
+ * theme-aware — a design system's token with ONE hex fallback,
480
+ * `var(--acme-blue, #0056f9)` (SPEC DESIGN_SYSTEMS: the colour survives the
481
+ * design system going missing), or a literal hex colour. Nothing else — no
482
+ * nested var(), no other characters: the value lands inside a style
483
+ * attribute, and a style attribute is markup.
484
+ */
485
+ const STYLE_VALUE = /^(?:var\(--[a-z][a-z0-9-]{0,40}(?:,\s?#[0-9a-f]{3,8})?\)|#[0-9a-f]{3,8})$/i;
486
+ const STYLE_PROPS = new Set(['fill', 'color', 'background-color', 'stroke', 'border-color']);
487
+ // a stroke's width (#717): a number in px, unitless on a shape the way SVG
488
+ // reads it, `px` on a box the way CSS does — never anything that is not one
489
+ const WIDTH_PROPS = new Set(['stroke-width', 'border-width']);
490
+ const WIDTH_VALUE = /^(?:\d{1,2}(?:\.\d{1,2})?)(?:px)?$/;
491
+ // the colour card's Type side: the size in px (deck units: the stage is
492
+ // scaled, not the text), a weight in hundreds, one of the theme's three font
493
+ // roles by reference (never a family name, so the type follows `T` and a
494
+ // deck's marked fonts), and where a line sits. Each a closed shape.
495
+ const TYPE_VALUES = {
496
+ 'font-size': /^(?:[1-9]\d{0,2}(?:\.\d)?)px$/,
497
+ 'font-weight': /^[1-9]00$/,
498
+ 'font-family': /^var\(--font-(?:heading|body|mono)\)$/,
499
+ 'font-style': /^(?:normal|italic)$/,
500
+ 'text-anchor': /^(?:start|middle|end)$/,
501
+ 'text-align': /^(?:left|center|right)$/,
502
+ };
503
+ const kindOf = (prop) => (STYLE_PROPS.has(prop) ? 'colour' : WIDTH_PROPS.has(prop) ? 'width' : Object.hasOwn(TYPE_VALUES, prop) ? prop.replace('-', ' ') : null);
504
+ const valueShape = (prop) => (STYLE_PROPS.has(prop) ? STYLE_VALUE : WIDTH_PROPS.has(prop) ? WIDTH_VALUE : TYPE_VALUES[prop]);
505
+
506
+ /** The page and the file disagree about what is where: a 409, not a bad request. */
507
+ const stale = (message) => Object.assign(new Error(message), { code: 'STALE' });
508
+
509
+ /** `style` text with `prop` set to `value` (null: taken off) — its old declaration replaced, the rest kept in order. */
510
+ export function withStyleProp(style, prop, value) {
511
+ const kept = String(style ?? '').split(';').map((d) => d.trim()).filter(Boolean)
512
+ .filter((d) => d.slice(0, d.indexOf(':')).trim().toLowerCase() !== prop);
513
+ return (value === null ? kept : [...kept, `${prop}: ${value}`]).join('; ');
514
+ }
515
+
516
+ /**
517
+ * Set style properties on elements INSIDE slide N's element `index` — a shape
518
+ * in a diagram and the text on it, in one edit (so `Z` takes both back).
519
+ *
520
+ * Each edit is `{ path, tag, prop, value }`: `path` is the element's
521
+ * child-index path below the slide's top-level element (`[]` is that element
522
+ * itself), counted over the FILE's elements, and `tag` is what the page found
523
+ * there — the live DOM is not the file (the engine adds nodes of its own), so
524
+ * a path that lands on a different tag is refused rather than recoloured.
525
+ * Only the open tag's `style` attribute is touched, textually: every other
526
+ * attribute — `viewBox` and its capitals included — survives byte for byte.
527
+ * A `value` of null takes the declaration back off, and a `style` left empty
528
+ * goes with it. A slot token picked on a nested box still takes its panel's
529
+ * tone (SVG_DIAGRAMS): the pick names the colour family, the engine keeps it
530
+ * legible where it sits — `data-nest="off"` in the markup is the opt-out.
531
+ */
532
+ export function setElementStyles(html, slide, index, edits) {
533
+ if (!Array.isArray(edits) || !edits.length || edits.length > 40) throw new Error('bad edits');
534
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
535
+ let el = seg.slice(r.start, r.end);
536
+ // each edit re-walks from the top: the one before it changed the offsets
537
+ for (const e of edits) {
538
+ if (!Array.isArray(e?.path) || e.path.length > 16 || e.path.some((n) => !Number.isInteger(n) || n < 0)) throw new Error('bad path');
539
+ const kind = kindOf(e.prop);
540
+ if (!kind) throw new Error(`not a property this server writes: ${String(e.prop).slice(0, 40)}`);
541
+ if (e.value !== null && (typeof e.value !== 'string' || !valueShape(e.prop).test(e.value))) throw new Error(`not a ${kind} this server writes: ${String(e.value).slice(0, 40)}`);
542
+ let start = 0; let end = el.length;
543
+ for (const n of e.path) {
544
+ const kids = elementChildRanges(el.slice(start, end));
545
+ const kid = kids[n];
546
+ if (!kid) throw stale(`slide ${slide} #${index}: the file has no element at ${e.path.join('.')} — the engine drew this one, or the deck changed; reload and try again`);
547
+ end = start + kid.end; start += kid.start;
548
+ }
549
+ const node = el.slice(start, end);
550
+ const tag = /^<([a-zA-Z][\w:-]*)/.exec(node)?.[1]?.toLowerCase();
551
+ if (e.tag && tag !== String(e.tag).toLowerCase()) {
552
+ throw stale(`slide ${slide} #${index}: the page found <${e.tag}> at ${e.path.join('.') || 'the element'}, the file has <${tag}> — reload and try again`);
553
+ }
554
+ const { attrs, close, rest } = splitOpenTag(node);
555
+ const styleM = /\sstyle\s*=\s*("([^"]*)"|'([^']*)')/i.exec(attrs);
556
+ const style = withStyleProp(styleM ? (styleM[2] ?? styleM[3]) : '', e.prop, e.value).replace(/"/g, "'");
557
+ const attr = style ? ` style="${style}"` : '';
558
+ const head = styleM ? attrs.replace(styleM[0], () => attr) : attrs + attr;
559
+ el = el.slice(0, start) + head + close + rest + el.slice(end);
560
+ }
561
+ parts[idx] = seg.slice(0, r.start) + el + seg.slice(r.end);
562
+ return parts.join('');
563
+ }
564
+
565
+ /**
566
+ * Set or remove ONE attribute on an element below slide N's child `index`,
567
+ * addressed the way setElementStyles addresses one (`path` below the
568
+ * element, `tag` as the page saw it). What this server writes this way is a
569
+ * closed set — `data-concept` (SVG_DIAGRAMS, #718) — with a value that is a
570
+ * name and nothing else; null takes the attribute off.
571
+ */
572
+ const ATTR_NAMES = new Set(['data-concept']);
573
+ const ATTR_VALUE = /^[a-z][a-z0-9-]{0,40}$/i;
574
+ export function setElementAttr(html, slide, index, { path, tag, name, value }) {
575
+ if (!Array.isArray(path) || path.length > 16 || path.some((n) => !Number.isInteger(n) || n < 0)) throw new Error('bad path');
576
+ if (!ATTR_NAMES.has(name)) throw new Error(`not an attribute this server writes: ${name}`);
577
+ if (value !== null && (typeof value !== 'string' || !ATTR_VALUE.test(value))) throw new Error(`not a name: ${String(value).slice(0, 40)}`);
578
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
579
+ let el = seg.slice(r.start, r.end);
580
+ let start = 0; let end = el.length;
581
+ for (const n of path) {
582
+ const kid = elementChildRanges(el.slice(start, end))[n];
583
+ if (!kid) throw stale(`slide ${slide} #${index}: the file has no element at ${path.join('.')} — reload and try again`);
584
+ end = start + kid.end; start += kid.start;
585
+ }
586
+ const node = el.slice(start, end);
587
+ const found = /^<([a-zA-Z][\w:-]*)/.exec(node)?.[1]?.toLowerCase();
588
+ if (tag && found !== String(tag).toLowerCase()) throw stale(`slide ${slide} #${index}: the page found <${tag}> at ${path.join('.') || 'the element'}, the file has <${found}> — reload and try again`);
589
+ const { attrs, close, rest } = splitOpenTag(node);
590
+ const re = new RegExp(`\\s${name}(?:\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s>]+))?`, 'i');
591
+ const head = value === null ? attrs.replace(re, '') : (re.test(attrs) ? attrs.replace(re, () => ` ${name}="${value}"`) : `${attrs} ${name}="${value}"`);
592
+ el = el.slice(0, start) + head + close + rest + el.slice(end);
593
+ parts[idx] = seg.slice(0, r.start) + el + seg.slice(r.end);
594
+ return parts.join('');
595
+ }
596
+
597
+ /** The text a run of markup reads as: the entities a label is likely to carry, decoded. */
598
+ const decodeText = (s) => String(s).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (m, e) => {
599
+ const k = e.toLowerCase();
600
+ if (k[0] === '#') return String.fromCodePoint(k[1] === 'x' ? parseInt(k.slice(2), 16) : parseInt(k.slice(1), 10));
601
+ return { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }[k];
602
+ });
603
+ const sameWords = (a, b) => String(a).replace(/\s+/g, ' ').trim() === String(b).replace(/\s+/g, ' ').trim();
604
+
605
+ /**
606
+ * Replace the words of ONE diagram label (SVG_DIAGRAMS): the `<text>` or
607
+ * `<tspan>` at `path` below slide N's element `index`, addressed the way
608
+ * setElementStyles addresses a shape. Only what is between its tags changes,
609
+ * and only when that is words: a `<text>` holding `<tspan>` lines is refused,
610
+ * since each line is its own label. `was` is what the page showed there, and
611
+ * a file that says something else is stale (a 409), not overwritten. The
612
+ * whitespace the file has around the words is kept, and `<`, `>` and `&` are
613
+ * escaped on the way in, so the markup around the label survives byte for
614
+ * byte. One line, because SVG text does not wrap.
615
+ */
616
+ const LABEL_TAGS = new Set(['text', 'tspan']);
617
+ export function setElementText(html, slide, index, { path, tag, was, text }) {
618
+ if (!Array.isArray(path) || path.length > 16 || path.some((n) => !Number.isInteger(n) || n < 0)) throw new Error('bad path');
619
+ if (typeof text !== 'string' || text.length > 400 || /[\u0000-\u001f\u007f]/.test(text)) throw new Error('a label is one line of at most 400 characters');
620
+ if (typeof was !== 'string') throw new Error('bad payload');
621
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
622
+ let el = seg.slice(r.start, r.end);
623
+ let start = 0; let end = el.length;
624
+ for (const n of path) {
625
+ const kid = elementChildRanges(el.slice(start, end))[n];
626
+ if (!kid) throw stale(`slide ${slide} #${index}: the file has no element at ${path.join('.')} — reload and try again`);
627
+ end = start + kid.end; start += kid.start;
628
+ }
629
+ const node = el.slice(start, end);
630
+ const found = /^<([a-zA-Z][\w:-]*)/.exec(node)?.[1]?.toLowerCase();
631
+ if (tag && found !== String(tag).toLowerCase()) throw stale(`slide ${slide} #${index}: the page found <${tag}> at ${path.join('.') || 'the element'}, the file has <${found}> — reload and try again`);
632
+ if (!LABEL_TAGS.has(found)) throw new Error(`not a diagram label: <${found}>`);
633
+ const { attrs, close, rest } = splitOpenTag(node);
634
+ const closeAt = rest.toLowerCase().lastIndexOf(`</${found}`);
635
+ if (close.endsWith('/>') || closeAt < 0) throw new Error(`<${found}> has no words to edit`);
636
+ const inner = rest.slice(0, closeAt);
637
+ if (/<(?!!--)/.test(inner)) throw new Error(`this <${found}> holds other elements — edit one line at a time`);
638
+ if (!sameWords(decodeText(inner.replace(/<!--[\s\S]*?-->/g, '')), was)) {
639
+ throw stale(`slide ${slide} #${index}: the file's label is not the one the page showed — reload and try again`);
640
+ }
641
+ const escaped = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
642
+ const lead = /^\s*/.exec(inner)[0]; const trail = /\s*$/.exec(inner)[0];
643
+ const words = inner.trim() ? lead + escaped + trail : escaped;
644
+ el = el.slice(0, start) + attrs + close + words + rest.slice(closeAt) + el.slice(end);
645
+ parts[idx] = seg.slice(0, r.start) + el + seg.slice(r.end);
646
+ return parts.join('');
647
+ }
648
+
199
649
  /** Replace slide N's element at raw child index `index` with `outerHtml` verbatim. */
200
650
  export function setSlideElementHtml(html, slide, index, outerHtml) {
201
651
  const { parts, idx, seg, r } = locateElement(html, slide, index);
@@ -358,7 +808,7 @@ export function narrationLiteral(cfg) {
358
808
  *
359
809
  * The recorder writes the files and then had to ask you to paste a config line
360
810
  * into the deck by hand — the one manual step in a flow that is otherwise a
361
- * key and an arrow. The author server already owns this file (it writes notes,
811
+ * key and an arrow. The edit server already owns this file (it writes notes,
362
812
  * layouts and element edits), so it can write this too, through the same
363
813
  * applyEdit door: Z undoes it, live-reload shows it.
364
814
  *
@@ -367,11 +817,6 @@ export function narrationLiteral(cfg) {
367
817
  * guessing which `cfg` is meant, in which scope, is how an editor corrupts a
368
818
  * file. That deck keeps the printed line and is told why.
369
819
  */
370
- /** `{ label: 'Rachel · ElevenLabs', dir: 'voices/rachel', ext: 'wav' }` */
371
- export function trackLiteral(track) {
372
- return narrationLiteral(track);
373
- }
374
-
375
820
  /**
376
821
  * Add a recorded track to the deck's `narration.files`, or update it in place.
377
822
  *
@@ -402,6 +847,14 @@ export function trackLiteral(track) {
402
847
  * config built outside the call, or a manifest-only track.
403
848
  */
404
849
  export function configuredTrackDirs(html) {
850
+ // A deck as data (#520): the configuration is JSON, and reads as such.
851
+ const block = configBlock(html);
852
+ if (block) {
853
+ const files = block.config?.narration?.files;
854
+ if (typeof files === 'string') return [files];
855
+ if (!Array.isArray(files)) return [];
856
+ return files.flatMap((e) => (typeof e === 'string' ? [e] : e && typeof e === 'object' && e.dir && !e.manifest ? [e.dir] : []));
857
+ }
405
858
  const arg = initArgument(html);
406
859
  if (!arg) return [];
407
860
  const raw = html.slice(arg.start, arg.end);
@@ -432,6 +885,31 @@ export function configuredTrackDirs(html) {
432
885
  }
433
886
 
434
887
  export function upsertNarrationTrack(html, track) {
888
+ // A deck as data (#520): the block is parsed, changed and written back as
889
+ // JSON — its own formatting goes, its every key survives. Null when the
890
+ // block is not JSON: an editor that guesses at broken data corrupts it.
891
+ const block = configBlock(html);
892
+ if (block) {
893
+ if (!block.config) return null;
894
+ const cfg = block.config;
895
+ if (cfg.narration !== undefined && (typeof cfg.narration !== 'object' || cfg.narration === null || Array.isArray(cfg.narration))) return null;
896
+ const narr = cfg.narration ?? (cfg.narration = {});
897
+ const entry = Object.fromEntries(Object.entries(track).filter(([, v]) => v !== undefined && v !== null));
898
+ let list;
899
+ if (Array.isArray(narr.files)) list = narr.files;
900
+ else if (typeof narr.files === 'string') {
901
+ // the one-string form becomes the first entry, ext/segments moving into it
902
+ const kept = { label: narr.files, dir: narr.files };
903
+ for (const k of ['ext', 'segments']) if (narr[k] !== undefined) { kept[k] = narr[k]; delete narr[k]; }
904
+ list = kept.dir === track.dir ? [] : [kept];
905
+ } else list = [];
906
+ const same = list.findIndex((e) => (typeof e === 'string' ? e : e?.dir) === track.dir);
907
+ if (same >= 0) list[same] = entry; else list.push(entry);
908
+ narr.files = list;
909
+ const indent = /(?:^|\n)([ \t]*)[^\n]*$/.exec(html.slice(0, block.start))?.[1] ?? '';
910
+ const json = JSON.stringify(cfg, null, 2).split('\n').map((l) => indent + l).join('\n');
911
+ return `${html.slice(0, block.innerStart)}\n${json}\n${indent}${html.slice(block.innerEnd)}`;
912
+ }
435
913
  const arg = initArgument(html);
436
914
  if (!arg) return null;
437
915
  const raw = html.slice(arg.start, arg.end);
@@ -531,9 +1009,89 @@ export function setSlideElementBuild(html, slide, index, effect) {
531
1009
  * land on the opposite stack, so nothing is silently lost) and return what
532
1010
  * to write, or null when the stack is empty.
533
1011
  */
1012
+ /**
1013
+ * What a write route did, in the words the page's debug log shows beside a
1014
+ * reload (PRESENTING, debug log). The reload message names it, so a page that
1015
+ * comes back can say WHY it went — "notes saved · this tab" rather than a
1016
+ * bare reload, which is the one thing a log wiped by the reload cannot say.
1017
+ */
1018
+ const WRITE_LABELS = {
1019
+ '/deck/edit/slide/notes': 'notes saved',
1020
+ '/deck/edit/slide/sources': 'sources saved',
1021
+ '/deck/edit/timings': 'rehearsal timings saved',
1022
+ '/deck/edit/slide/layout': 'layout picked',
1023
+ '/deck/edit/slide/template': 'template switched',
1024
+ '/deck/edit/slide/hidden': 'slide hidden or shown',
1025
+ '/deck/edit/slide': 'slides rearranged',
1026
+ '/deck/edit/narration': 'narration track saved',
1027
+ '/deck/edit/narration/record': 'narration recorded',
1028
+ '/deck/edit/element/remove': 'element removed',
1029
+ '/deck/edit/element/content': 'element content saved',
1030
+ '/deck/edit/element/effect': 'build effect set',
1031
+ '/deck/edit/element/style': 'colours saved',
1032
+ '/deck/edit/element/concept': 'concept set',
1033
+ '/deck/edit/element/text': 'text saved',
1034
+ '/deck/edit/element/image': 'image placed',
1035
+ '/deck/edit/concepts': 'concept colours saved',
1036
+ '/deck/edit/asset': 'asset added',
1037
+ '/deck/edit/undo': 'undo (Z)',
1038
+ '/deck/edit/redo': 'redo (⇧Z)',
1039
+ '/deck/edit/restore': 'restored from git',
1040
+ '/deck/edit/theme': 'theme picked',
1041
+ '/deck/edit/brand-themes': 'brand themes set',
1042
+ '/deck/edit/theme/add': 'theme added',
1043
+ '/deck/edit/theme/mark': 'theme marked',
1044
+ '/deck/edit/font/mark': 'font marked',
1045
+ '/deck/edit/design-system/apply': 'design system applied',
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',
1049
+ '/deck/edit/enhance': 'script enhanced',
1050
+ '/deck/edit/wizard': 'engine set up',
1051
+ '/deck/upstream/pull': 'git pull',
1052
+ };
1053
+ export function whatWrote(pathname) {
1054
+ return WRITE_LABELS[pathname] ?? `${String(pathname ?? '').replace(/^\/deck\/(edit\/)?/, '').replace(/\//g, ' ') || 'the deck'} written`;
1055
+ }
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
+
1069
+ /**
1070
+ * The reason a reload carries. A write of the server's own within the last
1071
+ * moments is that write; the file changing while an agent runs is the
1072
+ * agent's; anything else changed on disk by a hand this server never saw —
1073
+ * an editor, git, a tool. The page shows it as the first line after the
1074
+ * reload, with "this tab" or "another tab" when the write said which page.
1075
+ */
1076
+ export const RELOAD_WRITE_WINDOW_MS = 2000;
1077
+ export function describeReload({ write = null, agent = null, now = Date.now() } = {}) {
1078
+ if (write && now - write.at <= RELOAD_WRITE_WINDOW_MS) return { reload: write.what, from: write.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 };
1081
+ return { reload: 'changed on disk — an editor, git, or a tool outside this server', from: null };
1082
+ }
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
+ */
534
1091
  export function createHistory(limit = 200) {
535
1092
  const past = [];
536
1093
  const future = [];
1094
+ const now = (current, entry) => (typeof current === 'function' ? current(entry) : current);
537
1095
  return {
538
1096
  record(before) {
539
1097
  past.push(before);
@@ -542,13 +1100,15 @@ export function createHistory(limit = 200) {
542
1100
  },
543
1101
  undo(current) {
544
1102
  if (!past.length) return null;
545
- future.push(current);
546
- return past.pop();
1103
+ const entry = past.pop();
1104
+ future.push(now(current, entry));
1105
+ return entry;
547
1106
  },
548
1107
  redo(current) {
549
1108
  if (!future.length) return null;
550
- past.push(current);
551
- return future.pop();
1109
+ const entry = future.pop();
1110
+ past.push(now(current, entry));
1111
+ return entry;
552
1112
  },
553
1113
  counts() { return { undo: past.length, redo: future.length }; },
554
1114
  };
@@ -558,14 +1118,14 @@ export function createHistory(limit = 200) {
558
1118
  // The plumbing lives in git.mjs now; imported for editMain's use below and
559
1119
  // re-exported so long-standing importers (init, the tests) keep finding it
560
1120
  // where edit grew it.
561
- import { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit, lastCommitSha, resolveGitMode, shouldCommit, commitSubject, exitPushLine, oneline, remoteLine, remoteState, unpushed } from './git.mjs';
1121
+ import { inGitRepo, gitAvailable, createRepo, STARTER_GITIGNORE, gitAutocommit, lastCommitSha, resolveGitMode, shouldCommit, commitSubject, untrackedFiles, exitPushLine, oneline, remoteState } from './git.mjs';
562
1122
  import {
563
- describeCommit, describeWorking, messagesLine, rememberPref, storedPref,
1123
+ describeCommit, messagesLine,
564
1124
  } from './commit-message.mjs';
565
1125
  import { WIP_REF, deckDirty, nagText, planNag, snapshotWip, wipLine } from './commit-flow.mjs';
566
1126
  export { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit };
567
1127
 
568
- /** Who the author is, from git's own answer — see cli/review.mjs. */
1128
+ /** Who the author is, from git's own answer — see cli/review-routes.mjs. */
569
1129
  function reviewerName(cwd = process.cwd()) {
570
1130
  const cfg = (key) => {
571
1131
  try { return execFileSync('git', ['config', key], { cwd, encoding: 'utf8' }).trim(); } catch { return ''; }
@@ -575,17 +1135,145 @@ function reviewerName(cwd = process.cwd()) {
575
1135
  return (name && email) ? `${name} <${email}>` : (name || email || '');
576
1136
  }
577
1137
 
578
- export async function editMain(args, { onListen = null } = {}) {
579
- // /edit/review/incoming's answer, briefly remembered (see the route).
1138
+
1139
+ /** `decklight <deck> --no-trust --help`: the no-trust mode's own flags. */
1140
+ const READ_ONLY_USAGE = `usage: decklight <deck.html|deck.decklight|repository url> --no-trust [--port 8788] [--strict]
1141
+ [--root <dir>] [--remote] [--host <addr>] [--audit]
1142
+ [--no-plugins] [--branch <ref>] [--into <dir>]
1143
+
1144
+ opens a deck in no-trust mode — the safe way in for one you did not write,
1145
+ and the only mode a .decklight container opens in. The deck is served from
1146
+ its own directory, under a Content-Security-Policy header, with every file
1147
+ type a deck cannot use and every dotfile refused; every route that writes
1148
+ refuses, and nothing is written. The mode is the run's: it is decided here,
1149
+ when the deck is opened, and never from the page.
1150
+
1151
+ A .decklight container (bundle --deck) is unwrapped in memory and treated
1152
+ exactly like the deck it wraps: same audit, same policy, same strict rule. Its
1153
+ signature is verified and its manifest is printed as what it is — the
1154
+ container's own claim about itself, next to the one thing that was checked.
1155
+ The manifest's origin (repo and commit) is never printed: the signature
1156
+ covers the deck alone, so even on a verified container the origin is whatever
1157
+ the packer wrote, and a provenance line nobody vouches for does not belong
1158
+ one skim away from a verified identity. It stays in the manifest for tooling
1159
+ to read.
1160
+
1161
+ A repository URL (https://github.com/you/talk, git@…, …/talk.git; #path
1162
+ picks a deck inside) is cloned to ./<repo> — or the clone already there,
1163
+ whichever command made it, is opened — and the deck in it played. The
1164
+ clone's upstream is what H checks for the author's newer pushes.
1165
+
1166
+ --branch R the branch or tag to clone (a repository URL)
1167
+ --into D where to clone it (default: ./<repo name>)
1168
+ --port N port to bind; a taken port offers to take over that session
1169
+ (on a TTY) or moves on to the next free one [8788]
1170
+ --strict serve with every script block that is not the runtime removed,
1171
+ along with every inline on*= handler, javascript: URL and srcdoc
1172
+ document. The removal happens on the way out — the file on disk
1173
+ is never touched. Turns itself on when the label finds something.
1174
+ --root D serve D instead of the deck's directory, for a SOURCE deck that
1175
+ reaches up for its runtime (demo/talk.html loading
1176
+ ../dist/decklight.js). The deck must live under D, and everything
1177
+ under D that passes the dotfile and file-type rules becomes
1178
+ fetchable by the deck's own script — which is why widening the
1179
+ root is a flag you type, never something the cwd decides.
1180
+ --remote also listen on the LAN for the phone remote. Off this machine ONLY
1181
+ /deck/remote/* answers, and only with the per-run token the printed URL
1182
+ and its QR carry — the deck itself, and every file beside it, stay
1183
+ unreachable from the LAN whether or not this flag is passed.
1184
+ --host A the address --remote binds [0.0.0.0]
1185
+ --audit print the ingredients label and exit — no server. Exits non-zero
1186
+ if the deck runs any script that is not the runtime — a block or
1187
+ an executable attribute — so CI can gate on a deck before it is
1188
+ forwarded or published.
1189
+ --no-plugins play without your own chrome, whatever is installed.
1190
+ --upstream-every N minutes between upstream checks; 0 turns the check off [10]
1191
+ --no-upstream never look at the upstream — no git, no network
1192
+ --upstream-pull register the update control the deck's H overlay drives.
1193
+ OFF by default: with it on, any script in the deck can
1194
+ fast-forward the clone the deck was served from.
1195
+
1196
+ Your presenter plugins (decklight library add plugin) are layered on at serve time from
1197
+ ~/.decklight/plugins/ — a timer, a teleprompter, a confidence monitor. They
1198
+ are YOURS: the deck on disk is untouched, nothing is written into it, and the
1199
+ same file played on a machine without them is identical slides and no
1200
+ warning. Each one renders inside a sandboxed frame with an opaque origin, so
1201
+ it draws chrome and cannot reach the slides — a plugin that asks for slide
1202
+ content is refused by name, because a deck has to stay a deterministic
1203
+ artifact or two people presenting the same file present different decks.
1204
+
1205
+ A plugin is never part of the ingredients label: the label counts what is in
1206
+ the file, the chrome is listed under it as what it is. Loading one registers
1207
+ no route and does not widen the policy below by a single source.
1208
+
1209
+ Every no-trust start prints the ingredients label: which runtime is
1210
+ embedded and whether its bytes are the ones this install ships, how many
1211
+ inert data blocks the runtime will read, and — named, with line numbers —
1212
+ every script block that will execute and is NOT accounted for, plus every
1213
+ executable attribute (an inline on*= handler, a javascript: or
1214
+ data:text/html URL, an inline srcdoc document — the vectors 'unsafe-inline'
1215
+ below would otherwise let run unnamed). It is an inventory, not a verdict:
1216
+ there is no "safe" here, because the scan is a heuristic over a file someone
1217
+ may have edited and a green check would promise more than it can keep.
1218
+
1219
+ A deck with a detached signature beside it (talk.html.sig) is verified BEFORE
1220
+ it renders, and the terminal names who signed it — an identity you can judge,
1221
+ not a check mark. Sigstore keyless, so there are no keys: the certificate was
1222
+ minted for one signature against the signer's OIDC identity and expired
1223
+ minutes later; the transparency log is what keeps it checkable. A deck with no
1224
+ sidecar is not an alarm — most decks are unsigned, and treating that as a
1225
+ finding would train you to ignore the one that matters. Verifying needs the
1226
+ sigstore client and the network; when it cannot be done here, that is said as
1227
+ its own state and never as a pass.
1228
+
1229
+ When the label finds an unaccounted block — or a signature does not verify,
1230
+ or cannot be checked here — strict mode turns ITSELF on and says so in the
1231
+ terminal. It does not ask, and there is no --force to turn it
1232
+ back off: ten minutes before a talk is the worst possible moment for a
1233
+ refusal, and an escape hatch would be reached for exactly then — so the deck
1234
+ always plays, and the part nobody can account for is the part that doesn't.
1235
+ Removed blocks are named in the terminal, never on the audience's screen.
1236
+
1237
+ What survives strict is what a deck needs to render itself: the runtime, the
1238
+ Decklight.init call, JSON data blocks and templates. Builds, layouts, themes,
1239
+ charts and background media are markup, CSS and attributes — never at risk. A
1240
+ clean deck under --strict is byte-identical to the same deck without it.
1241
+
1242
+ Every response carries this Content-Security-Policy as an HTTP header, which
1243
+ the deck cannot override the way it could a <meta> tag:
1244
+
1245
+ ${CSP.replace(/; /g, ';\n ')}
1246
+
1247
+ Recorded narration from a bucket and external background video still play —
1248
+ that is what the https: sources in media-src/connect-src are for. Live voice
1249
+ does not: synthesis needs the local bridge, which is a write-mode engine and
1250
+ is refused from here.
1251
+
1252
+ Read the policy honestly: script-src carries 'unsafe-inline' because a
1253
+ bundled deck IS inline script, so this does not stop a deck from running
1254
+ code. It stops that code from reaching anywhere it shouldn't.`;
1255
+
1256
+ // `client` is the sigstore client — injectable so a test can drive the
1257
+ // signature states of `--no-trust --audit` without the network; `undefined`
1258
+ // means "go load the real one".
1259
+ export async function editMain(args, { onListen = null, client } = {}) {
1260
+ // /deck/review/incoming's answer, briefly remembered (see the route).
580
1261
  let incomingCache = null;
581
- if (args.includes('--help') || args.includes('-h') || !args.filter((a) => !a.startsWith('-')).length) {
582
- console.log(`usage: node cli/edit.mjs <deck.html> [--port 8788] [--git | --no-git]
1262
+ const wantsHelp = args.includes('--help') || args.includes('-h');
1263
+ if (wantsHelp && args.includes('--no-trust')) { console.log(READ_ONLY_USAGE); return 0; }
1264
+ if (wantsHelp || !args.filter((a) => !a.startsWith('-')).length) {
1265
+ console.log(`usage: node cli/edit.mjs <deck.html> [--no-trust] [--port 8788] [--git | --no-git]
583
1266
  [--commit-every <seconds>] [--agent <name>] [--commit-messages]
584
1267
  serves the cwd, live-reloads the deck on change, and accepts edits from the
585
1268
  player: notes (right-click a slide's background), per-slide layout (L/⇧L),
586
1269
  element edit mode (E, then right-click an element), undo/redo (Z/⇧Z), agent asks (A)
587
1270
  a taken --port offers to take over that session (on a TTY) or moves on to
588
1271
  the next free one
1272
+ --no-trust the same server in no-trust mode: the deck is served from
1273
+ its own directory under a CSP header, the ingredients label
1274
+ runs first, and every edit route refuses
1275
+ (--no-trust --help for that mode's flags)
1276
+ --remote also listen on the LAN for the phone remote (either mode)
589
1277
  --git keep the deck in git (creates the repo if needed): a silent
590
1278
  snapshot on refs/decklight/wip, and K commits when you say so
591
1279
  --no-git never touch git (default outside a repository)
@@ -594,7 +1282,7 @@ export async function editMain(args, { onListen = null } = {}) {
594
1282
  timer the old five-minute cadence, bookends included
595
1283
  off never commit [agent]
596
1284
  --agent <name> preferred AI agent for A (default: first one detected)
597
- the server binds 127.0.0.1 only; for a phone remote use decklight present`);
1285
+ the server binds 127.0.0.1 unless --remote asks for the LAN`);
598
1286
  return;
599
1287
  }
600
1288
  const { opt } = argReader(args);
@@ -603,61 +1291,302 @@ export async function editMain(args, { onListen = null } = {}) {
603
1291
  // `ownCommit` closes over it and editMain CALLS ownCommit synchronously —
604
1292
  // the opening commit, taken when git has never seen this deck. Left where it
605
1293
  // reads better, that call ran while this binding was still in its temporal
606
- // dead zone and `decklight author` died on a ReferenceError before the
1294
+ // dead zone and `decklight <deck>` died on a ReferenceError before the
607
1295
  // server ever came up. It needed both halves to show: a deck git does not
608
1296
  // know, and commit-messages on (only that path reads `agentPref`), which is
609
1297
  // why adding a SECOND deck to a repo was the way to find it.
610
1298
  let agentPref = opt('--agent') ?? preferredAgent();
611
- const port = Number(opt('--port', 8788));
612
- // Refused out loud, not ignored (PRESENT#REMOTE). Someone typing --remote
613
- // wants a clicker; silently binding loopback would leave them holding a phone
614
- // that never connects and no idea why. `present` is where the remote went,
615
- // and the reason it went is worth saying at the moment it is asked for.
616
- const gone = ['--remote', '--host'].filter((f) => args.some((a) => a === f || a.startsWith(f + '=')));
617
- if (gone.length) {
618
- console.error(`author no longer takes ${gone.join(' or ')} — the phone remote moved to \`decklight present\`.`);
619
- console.error(' A clicker used to cost you an editing server on the LAN: /edit/notes, /edit/layout and');
620
- console.error(' /edit/agent were reachable from the same run you were not watching. present has no edit');
621
- console.error(' surface to widen, so that is where it lives.');
622
- console.error(`\n decklight present ${firstPositional(args, ['--port', '--commit-every', '--agent']) ?? '<deck.html>'} --remote`);
623
- process.exitCode = 2;
624
- return;
1299
+ const port = parsePort(opt('--port', 8788));
1300
+ if (port === null) { console.error(`decklight: ${badPort('--port', opt('--port'))}`); process.exitCode = 1; return; }
1301
+ const fail = (msg) => { console.error(`decklight: ${msg}`); process.exitCode = 1; return 1; };
1302
+
1303
+ // ── the mode (PRESENTING) ─────────────────────────────────────────────────
1304
+ // One server, two modes. Write mode is the default: the deck is served from
1305
+ // disk, live-reloaded, and every /deck/edit/* route writes it. Read-only
1306
+ // mode (`--no-trust`, and always for a .decklight container) serves the
1307
+ // bytes the ingredients label described, under the CSP, with the
1308
+ // presenter's chrome layered on, and refuses every route that writes —
1309
+ // /deck/edit/*, the bridges, the review owner's half — by name. The mode is
1310
+ // the run's: decided here, from the flag, and never from the page — a page
1311
+ // that could grant itself write access would make the flag worth nothing
1312
+ // for the deck it exists for, the one you did not write.
1313
+ const deckArg = firstPositional(args, VALUE_FLAGS);
1314
+ const deckPath = resolve(process.cwd(), deckArg);
1315
+ if (!existsSync(deckPath)) return fail(`deck not found: ${deckPath}`);
1316
+ // A .decklight is the same deck with its signature and manifest stapled on
1317
+ // (DECK_FILE), unwrapped here and treated exactly like the HTML it wraps —
1318
+ // same audit, same CSP, same strict rule. Nothing is written to unwrap it:
1319
+ // the payload is a slice of the bytes already read. It never leaves
1320
+ // no-trust mode: there is no file to edit in place.
1321
+ let container = null;
1322
+ if (isContainer(deckPath)) {
1323
+ try { container = readContainer(deckPath); } catch (e) { return fail(e.message); }
1324
+ }
1325
+ const noTrust = args.includes('--no-trust') || !!container;
1326
+
1327
+ // --remote widens the LISTENER and nothing else (NO_TRUST#REMOTE), in either
1328
+ // mode: off this machine only /deck/remote/* answers, with the per-run
1329
+ // token, and the deck itself and every file beside it stay unreachable from
1330
+ // the LAN whether or not the flag is passed. allowRemote is the classifier.
1331
+ const remote = args.includes('--remote') || opt('--host') !== undefined;
1332
+ const host = remote ? opt('--host', '0.0.0.0') : '127.0.0.1';
1333
+ const token = remote ? randomBytes(16).toString('base64url') : null;
1334
+
1335
+ // The served root. In write mode it is the cwd, as it always was: a source
1336
+ // deck reaches up for its runtime (`demo/talk.html` loading
1337
+ // `../dist/decklight.js`) and the author chose where to stand. In no-trust
1338
+ // mode it is the deck's OWN directory, never the cwd: everything under the
1339
+ // root is fetchable by the deck's own script same-origin, and with
1340
+ // `connect-src https:` open, fetchable means exfiltratable — a root
1341
+ // inherited from wherever the command happened to run (a project checkout,
1342
+ // $HOME via file association) would hand a hostile deck whatever lived
1343
+ // there. `--root` widens it, by a flag you typed and printed at startup.
1344
+ const rootArg = opt('--root');
1345
+ const root = noTrust
1346
+ ? (rootArg ? resolve(process.cwd(), rootArg) : dirname(deckPath))
1347
+ : process.cwd();
1348
+ if (!deckPath.startsWith(root + sep)) {
1349
+ return fail(noTrust ? 'deck must live under --root' : 'deck must live under the current directory');
625
1350
  }
626
- const host = '127.0.0.1';
627
- const root = process.cwd();
628
- const deckPath = resolve(root, firstPositional(args, ['--port', '--commit-every', '--agent']));
629
- if (!existsSync(deckPath)) { console.error(`deck not found: ${deckPath}`); process.exitCode = 1; return; }
630
- if (!deckPath.startsWith(root + sep)) { console.error('deck must live under the current directory'); process.exitCode = 1; return; }
631
1351
  const deckUrl = '/' + deckPath.slice(root.length + 1).split(sep).join('/');
632
1352
  const deckRel = deckUrl.slice(1);
633
1353
 
1354
+ // ── the no-trust mode's ingredients (PRESENTING) ─────────────────────────
1355
+ // The audit runs because it is the way in: a standalone `verify` is a step
1356
+ // people skip, so folding it into the command you already use means it runs
1357
+ // every time, at no extra effort. It reads the bytes, names what will
1358
+ // execute, and decides strict — the startup block, reusable, because a
1359
+ // pull (NO_TRUST#UPSTREAM) re-runs it: never new bytes under an old verdict.
1360
+ const readAndAudit = () => {
1361
+ const bytes = container ? readContainer(deckPath).payload : readFileSync(deckPath);
1362
+ const rep = auditDeck(bytes.toString('utf8'));
1363
+ return {
1364
+ payload: bytes,
1365
+ report: rep,
1366
+ strict: args.includes('--strict') || rep.counts.unaccounted > 0 || rep.counts.handlers > 0,
1367
+ };
1368
+ };
1369
+ // The signature, if the deck came with one (INTEGRITY#SIGNING). Costs nothing
1370
+ // when there is no sidecar — the common case returns without touching the
1371
+ // network — and the audit runs either way, because the two answer different
1372
+ // questions: a signature says WHO vouched for these bytes, the label says
1373
+ // what the bytes will do. A signed deck can still run something nobody
1374
+ // should, and the label is what would name it. Verified once, at startup:
1375
+ // it is a sidecar for the file as published, and a deck that changed since
1376
+ // has already invalidated whatever the old one attested.
1377
+ const verifySignature = async () => {
1378
+ if (!container) return verifyFile(deckPath, { client });
1379
+ let sig = container.signature
1380
+ ? await verifyBytes(container.payload, container.signature, { client })
1381
+ : { state: TAMPERED, reason: 'the container carries no signature' };
1382
+ // The manifest is the container's own label. When it does not describe
1383
+ // the deck it is stapled to, something rewrote one half — the same
1384
+ // conclusion as a signature that does not verify, so the same state.
1385
+ if (!container.digestOk && sig.state === VERIFIED) {
1386
+ sig = { state: TAMPERED, reason: 'the manifest digest does not match the payload' };
1387
+ }
1388
+ return sig;
1389
+ };
1390
+ // MUTABLE: a pull may replace all of it. The bytes, the label and `strict`
1391
+ // move together or not at all. Empty in write mode, which never reads it.
1392
+ let audited = null;
1393
+ let signature = { state: UNSIGNED };
1394
+ /** Enter (or re-enter) no-trust mode: read, audit, decide strict. Says whether the deck itself changed. */
1395
+ const audit = () => {
1396
+ const before = audited?.payload ?? null;
1397
+ const next = readAndAudit();
1398
+ const unverified = signature.state !== UNSIGNED && !isVerified(signature);
1399
+ // STRICT RATCHETS within a session: a pull may turn it on and can never
1400
+ // turn it off. A deck that could clear its own strict flag by pulling
1401
+ // could disarm the one mitigation no-trust mode applies unasked.
1402
+ audited = { ...next, strict: next.strict || unverified || (audited?.strict ?? false) };
1403
+ return before === null || !next.payload.equals(before);
1404
+ };
1405
+ if (noTrust) {
1406
+ signature = await verifySignature();
1407
+ audit();
1408
+ }
1409
+
1410
+ // `--audit` prints the ingredients label and exits; `--check` still answers,
1411
+ // unadvertised, from before `check` came to mean the deck lint alone
1412
+ if (args.includes('--audit') || args.includes('--check')) {
1413
+ // No server. The label, the manifest, the signature — and an exit code CI
1414
+ // can gate on: non-zero means "this deck executes something I could not
1415
+ // account for", or "it carries a signature I could not stand behind" —
1416
+ // not "this deck is malicious", which is a call no exit code should make.
1417
+ // `unchecked` counts: a gate that passes when it could not evaluate the
1418
+ // claim is not a gate.
1419
+ if (!noTrust) { signature = await verifySignature(); audit(); }
1420
+ for (const line of formatLabel(audited.report, { indent: '' })) console.log(line);
1421
+ if (container) console.log(formatManifest(container.manifest, { indent: '' }));
1422
+ if (signature.state !== UNSIGNED) console.log(formatSignature(signature, { indent: '' }));
1423
+ return audited.report.counts.unaccounted || audited.report.counts.handlers
1424
+ || (signature.state !== UNSIGNED && !isVerified(signature)) ? 1 : 0;
1425
+ }
1426
+
1427
+ // The presenter's own chrome (NO_TRUST#PLUGINS) — a timer, a teleprompter,
1428
+ // a confidence monitor. It is loaded from ~/.decklight/plugins/, which is
1429
+ // the presenter's library and not the deck's: the installer is the
1430
+ // risk-bearer and nothing here travels. Loaded after `auditDeck` has read
1431
+ // the bytes, so a plugin is never counted as an unaccounted script block in
1432
+ // the label (the label describes the file; a plugin is not in the file),
1433
+ // and injected after `stripUnaccounted`, so strict never strips the chrome
1434
+ // as if the deck had smuggled it in. BOTH modes: it used to be no-trust
1435
+ // only, so presenting your own deck with your own timer meant opening it
1436
+ // without trust (ROADMAP section 5). The chrome is the presenter's, and a
1437
+ // presenter is often the author. `--no-plugins` turns it off in either.
1438
+ const chrome = args.includes('--no-plugins') ? { plugins: [], refused: [] } : loadLibrary();
1439
+ // Consulted per request rather than decided once: after a pull `strict`
1440
+ // may have ratcheted on, and the bytes served have to follow the verdict
1441
+ // printed for them.
1442
+ const strip = (text) => (audited?.strict ? stripUnaccounted(text).html : text);
1443
+ // Only the deck gets chrome. Every OTHER html file under the root still
1444
+ // gets the strict rewrite — strict that stopped at one file would be walked
1445
+ // around by a second page under the same root, and the deck can reach one
1446
+ // (the theme picker, the slide finder and the speaker view all boot
1447
+ // documents into same-origin iframes). Those same iframes are why the
1448
+ // chrome is deck-only: presenter chrome belongs to the document the
1449
+ // presenter is looking at, and the shim removes itself if framed anyway.
1450
+ const rewrite = (text, file) => {
1451
+ const out = strip(text);
1452
+ return file === deckPath ? injectChrome(out, chrome.plugins) : out;
1453
+ };
1454
+ // The deck served from memory below goes through the same seam a file
1455
+ // does: a deck that is only data (#520) gets the runtime referenced on its
1456
+ // way out, and the audit above described the bytes WITHOUT it — which is
1457
+ // the point. `staticFiles` does this for every other page itself.
1458
+ const serveAudited = (text) => linkReferences(linkRuntime(rewrite(text, deckPath)), { dir: dirname(deckPath), deck: basename(deckPath) });
1459
+ // The deck itself, in no-trust mode, is served from MEMORY — container and
1460
+ // plain HTML alike — from the bytes the audit read and the signature
1461
+ // covered. The label, the signature verdict and `strict` were all decided
1462
+ // against those bytes and printed as a verdict; re-reading the file per
1463
+ // request would let a deck edited on disk AFTER that moment ride out under
1464
+ // it (#235). For a container this also avoids the one write this mode does
1465
+ // not make — unpacking to a temp file that would sit somewhere after the
1466
+ // talk. A pull re-audits and re-prints.
1467
+ const servePayload = (req, res) => {
1468
+ if (req.method !== 'GET') return false;
1469
+ const body = Buffer.from(serveAudited(audited.payload.toString('utf8')), 'utf8');
1470
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' });
1471
+ res.end(body);
1472
+ return true;
1473
+ };
1474
+ // Is this URL the deck? Matched on the RESOLVED path, exactly as staticFiles
1475
+ // would resolve it, so a percent-encoded spelling of the same file cannot
1476
+ // slip past this route into the per-request disk read below it.
1477
+ const isDeck = (url) => {
1478
+ if (url.pathname === '/') return true;
1479
+ let rel;
1480
+ try { rel = decodeURIComponent(url.pathname); } catch { return false; }
1481
+ return resolve(root, '.' + rel) === deckPath;
1482
+ };
1483
+
634
1484
  const history = createHistory();
635
1485
  const readDeck = () => readFileSync(deckPath, 'utf8');
636
- // one door for every mutation: snapshot, then write — so Z always works
637
- const applyEdit = (next, before = readDeck()) => {
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
+ };
1506
+ /**
1507
+ * The one door every mutation goes through: snapshot, then write — so Z
1508
+ * always works. Answers whether anything actually changed.
1509
+ *
1510
+ * Takes a TRANSFORM, `applyEdit((html) => setSlideNotes(html, …))`, so the
1511
+ * deck is read exactly ONCE. It used to take the finished html with the
1512
+ * current file as a default argument, which meant every call site spelled
1513
+ * `applyEdit(setX(readDeck(), …))` — one read to transform, a second for the
1514
+ * snapshot. Two reads is not just wasted work: they are two different reads,
1515
+ * and an edit landing between them wrote the second one's bytes back over
1516
+ * the first one's, with the undo entry recording a file that never existed.
1517
+ *
1518
+ * A route that has ALREADY read the deck — the template ones need it for
1519
+ * their own answer — passes the finished html and that same read as
1520
+ * `before`, which is the same single read spelled the other way round.
1521
+ */
1522
+ // Which route is writing, for the reload's reason: set around every
1523
+ // handler (below), read by `writeDeck` — async-safe, so two requests in
1524
+ // flight each name their own.
1525
+ const writing = new AsyncLocalStorage();
1526
+ let lastWrite = null; // { at, what, from } — the server's latest write of the deck, for the watcher
1527
+ const noteWrite = (what, from = null) => { lastWrite = { at: Date.now(), what, from }; };
1528
+ /** The one write of the deck file: atomic, and remembered for the reload it causes. */
1529
+ const writeDeck = (next) => {
1530
+ writeFileAtomic(deckPath, next);
1531
+ const ctx = writing.getStore();
1532
+ let from = null;
1533
+ if (ctx?.body) { try { const f = JSON.parse(ctx.body).from; if (typeof f === 'string') from = f.slice(0, 64); } catch { /* not json, or no page named */ } }
1534
+ noteWrite(whatWrote(ctx?.route), from);
1535
+ };
1536
+ const applyEdit = (change, before = readDeck()) => {
1537
+ const next = typeof change === 'function' ? change(before) : change;
638
1538
  if (next === before) return false;
639
1539
  history.record(before);
640
- writeFileSync(deckPath, next);
1540
+ writeDeck(next);
641
1541
  return true;
642
1542
  };
643
1543
 
644
1544
  // Declared before the git block below, which reads it to hold the cadence
645
1545
  // back while a job is in flight.
646
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
1548
+ // The asks of this session, oldest first, with what came of each — what the
1549
+ // docked agent panel shows. An agent's edit reloads every browser, so the
1550
+ // log lives HERE, not in the page, and rides /deck/ping across the reload.
1551
+ const agentAsks = [];
1552
+ const ASKS_KEPT = 20;
1553
+ let askSeq = 0;
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
1557
+ let lastReview = null; // its last result: { at, agent, findings, failed } — kept for Check deck… to re-ask
647
1558
 
648
1559
  // ── git autocommit — the durable record, independent of undo/redo ──────
649
1560
  const noGit = args.includes('--no-git');
650
1561
  const wantGit = args.includes('--git');
651
1562
  const commitEvery = Math.max(5, Number(opt('--commit-every', 300)) || 300);
652
- // --commit-messages: an agent writes the subject decklight would otherwise
653
- // template. Still never inferred from what happens to be on PATH — but the
654
- // permission can have been GIVEN already: `init` (and author's own first-run
655
- // git offer) asks once, when the repository is created, and stores the answer
656
- // in that repository's git config. The flag on the command line outranks it
657
- // in both directions, so a stored yes is still one `--no-commit-messages`
658
- // away from off for a single session.
659
- const wantMessages = args.includes('--no-commit-messages') ? false
660
- : args.includes('--commit-messages') || storedPref(process.cwd()) === true;
1563
+ // Commit subjects written by an agent, from the deck's diff. Two levels:
1564
+ //
1565
+ // - ON CLICK, by default: the commit window's "write it for me" asks the
1566
+ // agent installed on this machine when — and only when — it is pressed,
1567
+ // and its tooltip names the agent and says the changes go to it (and may
1568
+ // go on to its provider). Nothing leaves without that click.
1569
+ // - AUTOMATIC, with --commit-messages: the window drafts one as it opens,
1570
+ // and every commit decklight makes on its own is given one.
1571
+ //
1572
+ // --no-commit-messages turns both off for the session. Nothing is stored:
1573
+ // the setting is the command line's, and the button is the consent.
1574
+ const subjectsOff = args.includes('--no-commit-messages');
1575
+ const wantMessages = !subjectsOff && args.includes('--commit-messages');
1576
+ // The agent a subject would be asked of — named in the button's tooltip, so
1577
+ // it is the SAME resolution describeWorking makes (agentAsk). Remembered per
1578
+ // preference: commitState goes out on every ping and SSE tick, and probing
1579
+ // PATH that often is waste.
1580
+ let describerFor = null, describerIs = null;
1581
+ const describer = () => {
1582
+ if (subjectsOff) return null;
1583
+ if (describerFor !== (agentPref ?? '')) {
1584
+ const a = agentAsk(agentPref ?? null, 'x');
1585
+ describerIs = a ? { name: a.name, label: a.label } : null;
1586
+ describerFor = agentPref ?? '';
1587
+ }
1588
+ return describerIs;
1589
+ };
661
1590
 
662
1591
  /**
663
1592
  * Every commit decklight authors ITSELF goes through here — the cadence, the
@@ -674,11 +1603,13 @@ export async function editMain(args, { onListen = null } = {}) {
674
1603
  * this returns, which is the whole contract of autocommit — the subject is
675
1604
  * an improvement that arrives late or not at all.
676
1605
  */
677
- function ownCommit(message) {
1606
+ function ownCommit(message, also = []) {
1607
+ const paths = { also: [...alsoNow().also, ...also] };
678
1608
  const made = message === undefined
679
- ? gitAutocommit(deckPath, root)
680
- : gitAutocommit(deckPath, root, message);
1609
+ ? gitAutocommit(deckPath, root, undefined, paths)
1610
+ : gitAutocommit(deckPath, root, message, paths);
681
1611
  if (!made) return false;
1612
+ pendingAttr = null;
682
1613
  // Whatever wrote it — the overlay, an agent, a bookend — this stretch of
683
1614
  // uncommitted work is over, so the nag re-arms for the NEXT one.
684
1615
  resetEpisode();
@@ -708,13 +1639,35 @@ export async function editMain(args, { onListen = null } = {}) {
708
1639
  // could reach, which is also what made it untestable end to end.
709
1640
  const watchEveryMs = Math.min(commitEvery * 1000, WATCH_EVERY_MS);
710
1641
  let dirtySince = 0; // when this stretch of uncommitted work began
711
- let dirtyLines = 0; // how much of the deck differs from HEAD
1642
+ let dirtyLines = 0; // how much of the deck (and its sidecar) differs from HEAD
1643
+ let dirtySlides = null; // { changed, added, removed } against HEAD, or null
1644
+ let dirtyFiles = []; // which of them, by name beside the deck
1645
+ // The review sidecar rides the deck's own commits in write mode (REVIEW):
1646
+ // K, the agent's boundary and the session's bookends stage it beside the
1647
+ // deck when it changed, and the card counts its lines. The snapshot ref
1648
+ // stays deck-only: it is a backup of the thing being edited.
1649
+ const sidecarPath = reviewPathFor(deckPath);
1650
+ const sidecarRel = sidecarPath.slice(root.length + 1).split(sep).join('/');
1651
+ let pendingAttr = null; // a .gitattributes decklight just wrote, until a commit carries it
1652
+ // The attribute's path RELATIVE TO ROOT, asked of git rather than computed
1653
+ // from two absolute paths: `--show-toplevel` answers in forward slashes and
1654
+ // the long form of a path, and `root` may be the short form of the same
1655
+ // directory (a Windows temp dir), so `relative()` between them walks out of
1656
+ // the repository and every git call that takes the result refuses.
1657
+ const attrRel = () => {
1658
+ try {
1659
+ const prefix = execFileSync('git', ['rev-parse', '--show-prefix'], { cwd: root, encoding: 'utf8' }).trim();
1660
+ return '../'.repeat(prefix.split('/').filter(Boolean).length) + '.gitattributes';
1661
+ } catch { return null; }
1662
+ };
1663
+ const alsoNow = () => ({ also: [sidecarPath, ...(pendingAttr ? [pendingAttr] : [])] });
1664
+ const alsoRels = () => [sidecarRel, ...(pendingAttr ? [attrRel()] : [])].filter(Boolean);
712
1665
  let nagged = false; // the episode latch: asked once, then quiet
713
1666
  let nagDismissed = false;
714
1667
  let lastWip = null; // the snapshot sha, so the ping can prove it exists
715
1668
  /** A commit happened: this stretch of uncommitted work is over. */
716
1669
  const resetEpisode = () => {
717
- dirtySince = 0; dirtyLines = 0; nagged = false; nagDismissed = false;
1670
+ dirtySince = 0; dirtyLines = 0; dirtyFiles = []; dirtySlides = null; nagged = false; nagDismissed = false;
718
1671
  };
719
1672
  /**
720
1673
  * Re-read what is uncommitted, right now.
@@ -727,23 +1680,36 @@ export async function editMain(args, { onListen = null } = {}) {
727
1680
  * asking.
728
1681
  */
729
1682
  const measureDirty = () => {
730
- const d = deckDirty(root, deckRel);
731
- if (!d.dirty) { dirtySince = 0; dirtyLines = 0; return d; }
1683
+ const d = deckDirty(root, deckRel, { also: alsoRels() });
1684
+ if (!d.dirty) { dirtySince = 0; dirtyLines = 0; dirtyFiles = []; dirtySlides = null; return d; }
732
1685
  if (!dirtySince) dirtySince = Date.now();
733
1686
  dirtyLines = d.lines;
1687
+ dirtyFiles = (d.files ?? []).map((f) => basename(f));
1688
+ // in slides too, for the chip and the window: a deck's reader thinks in
1689
+ // slides. A change that is only the sidecar touches none.
1690
+ dirtySlides = slidesSinceHead(root, deckRel);
734
1691
  return d;
735
1692
  };
736
1693
  /** What the deck knows about uncommitted work — ping and SSE both send this. */
737
1694
  const commitState = () => ({
738
1695
  dirty: dirtySince > 0,
739
1696
  lines: dirtyLines,
1697
+ files: dirtyFiles,
1698
+ slides: dirtySlides,
740
1699
  sinceMs: dirtySince ? Date.now() - dirtySince : 0,
741
1700
  nag: nagged && !nagDismissed,
742
1701
  wip: lastWip,
743
1702
  canWrite: gitOn && gitMode !== 'off',
744
1703
  messages: wantMessages,
1704
+ // who "write it for me" would ask — null when the session turned subjects
1705
+ // off, or no agent is installed; `subjectsOff` says which
1706
+ describer: describer(),
1707
+ subjectsOff,
745
1708
  });
746
- if (!noGit && (wantGit || inGitRepo(root))) {
1709
+ // Write mode's. A deck in no-trust mode is somebody else's: no repository
1710
+ // is created beside it, no snapshot is taken, nothing of it is committed.
1711
+ function startGit() {
1712
+ if (noGit || !(wantGit || inGitRepo(root))) return;
747
1713
  if (!inGitRepo(root)) {
748
1714
  try {
749
1715
  const wroteIgnore = createRepo(root);
@@ -754,26 +1720,23 @@ export async function editMain(args, { onListen = null } = {}) {
754
1720
  }
755
1721
  if (inGitRepo(root)) {
756
1722
  gitOn = true;
757
- // An answer given on the command line becomes the repository's answer,
758
- // once. This is what makes the first-run question (dev.mjs, asked before
759
- // the repository existed and so with nowhere to write) stick: the next
760
- // session reads it back instead of asking again. Only when nothing is
761
- // stored yet — a later `--no-commit-messages` is one session's override,
762
- // not a silent change to what the repository has been told.
763
- if (storedPref(root) === null
764
- && (args.includes('--commit-messages') || args.includes('--no-commit-messages'))) {
765
- rememberPref(root, wantMessages);
766
- }
767
1723
  // The session bookends are the cadence's siblings: generic subjects for
768
1724
  // moments nobody described, and in the default mode the snapshot covers
769
1725
  // what they were covering. THE FIRST COMMIT IS NOT ONE OF THEM. A
770
- // repository decklight just created has no commits at all, and a deck git
771
- // has never seen is in no commit — in both cases there is no HEAD for the
772
- // snapshot to parent on and nothing in git to recover, so this commit is
773
- // 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.
774
1737
  const opening = deckDirty(root, deckRel);
775
1738
  if (gitMode === 'timer') ownCommit(`decklight: start editing ${basename(deckPath)}`);
776
- else if (opening.firstCommit || opening.untracked) ownCommit(`decklight: add ${basename(deckPath)}`);
1739
+ else if (opening.firstCommit) ownCommit(`decklight: add ${basename(deckPath)}`);
777
1740
  else { measureDirty(); lastWip = snapshotWip(root, deckPath, deckRel) ?? lastWip; }
778
1741
  // The cadence no longer WRITES HISTORY. It used to commit every
779
1742
  // --commit-every seconds, and what that produced was a column of
@@ -793,13 +1756,15 @@ export async function editMain(args, { onListen = null } = {}) {
793
1756
  }, gitMode === 'timer' ? commitEvery * 1000 : watchEveryMs).unref();
794
1757
  startup('git',
795
1758
  gitMode === 'timer'
796
- ? `auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`
797
- : 'commits on your word · snapshot on decklight/wip',
1759
+ ? `auto-commit every ${commitEvery}s`
1760
+ : `snapshots on decklight/wip · ${opening.untracked ? `${basename(deckPath)} is not in git: K adds it` : 'commits on K'}`,
798
1761
  gitMode === 'timer'
799
1762
  ? ` git: auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`
800
- : wipLine(deckRel));
1763
+ : wipLine(deckRel, { untracked: opening.untracked }),
1764
+ 'ok');
801
1765
  }
802
1766
  }
1767
+ if (!noTrust) startGit();
803
1768
  /**
804
1769
  * One tick: refresh the snapshot, and decide whether to ask.
805
1770
  *
@@ -826,7 +1791,7 @@ export async function editMain(args, { onListen = null } = {}) {
826
1791
  // immediately after, so there is no later for an amend to arrive in. The
827
1792
  // bookend keeps its literal subject, which is true anyway.
828
1793
  if (gitMode === 'timer') {
829
- gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`);
1794
+ if (gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`, alsoNow())) pendingAttr = null;
830
1795
  } else {
831
1796
  // Committing work you deliberately did not commit would be the cadence
832
1797
  // again, wearing an exit for a hat. The snapshot is refreshed instead —
@@ -854,16 +1819,71 @@ export async function editMain(args, { onListen = null } = {}) {
854
1819
  // Precedence, like every other saved choice: the flag wins, then what was
855
1820
  // remembered (#125), then the first detected agent.
856
1821
  const agents = detectAgents();
857
- if (agents.length) {
1822
+ // Named at startup in write mode only: no-trust mode refuses the agent
1823
+ // route with the rest of the write family, and a roster line under the
1824
+ // ingredients label would promise a capability that mode does not have.
1825
+ if (agents.length && !noTrust) {
858
1826
  const mark = (a) => a.name + (a.name === agentPref ? ' (preferred)' : '') + (a.installed ? ' (installed)' : '');
859
1827
  startup('agents', agents.map(mark).join(', '),
860
- ` agents: ${agents.map(mark).join(', ')} — “Ask agent” (A) is live`);
1828
+ ` agents: ${agents.map(mark).join(', ')} — “Ask agent” (A) is live`, 'ok');
861
1829
  }
862
1830
  // A remembered agent that is not on this machine is said ONCE, at startup,
863
1831
  // rather than discovered at the moment someone presses A mid-talk.
864
- if (agentPref && !agents.some((a) => a.name === agentPref)) {
1832
+ if (!noTrust && agentPref && !agents.some((a) => a.name === agentPref)) {
865
1833
  console.log(` agent: ${agentUnavailable(agentPref, agents)}`);
866
1834
  }
1835
+ // A deck that EMBEDS a runtime older than this install is served as it is
1836
+ // (the file is the author's), and that runtime probes routes this server
1837
+ // may no longer have: it gets a 404, concludes there is no server, and
1838
+ // hides every write-mode affordance without a word. No-trust mode's label
1839
+ // already says "DIFFERS"; write mode has to say it too, and name the fix,
1840
+ // because a page that silently will not wire up is the one failure nobody
1841
+ // can diagnose from the page. The audit is the same comparison --check
1842
+ // makes: this install's bytes, or a version it cannot vouch for.
1843
+ if (!noTrust) {
1844
+ let rt = null;
1845
+ try { rt = auditDeck(readDeck()).runtime; } catch { /* the deck is read again by every route; a bad read fails there */ }
1846
+ if (rt?.kind === 'inline' && (rt.state === 'differs' || rt.state === 'other-version')) {
1847
+ const what = rt.state === 'other-version'
1848
+ ? `embeds runtime ${rt.version}; this install is ${rt.installedVersion}`
1849
+ : `embeds a runtime that is not this install's build${rt.installedVersion ? ` of ${rt.installedVersion}` : ''}`;
1850
+ startup('runtime',
1851
+ `${basename(deckPath)} ${what} · run: ${selfCommand()} upgrade ${deckRel}`,
1852
+ ` runtime: ${basename(deckPath)} ${what} — the deck may not wire up to this server; run decklight upgrade ${deckRel}`, 'warn');
1853
+ }
1854
+ }
1855
+ // The project's skill, if any, against this install (the same question the
1856
+ // runtime row asks of the deck): an agent that reads a skill written by an
1857
+ // older decklight reads an old contract — commands that went, routes that
1858
+ // moved — and the only place that can be noticed is here, since the agent
1859
+ // itself has no way to know. `decklight skills` refreshes it.
1860
+ if (!noTrust) {
1861
+ const older = [];
1862
+ for (const rel of ['.claude/skills/decklight/SKILL.md', 'AGENTS.md']) {
1863
+ const file = resolve(root, rel);
1864
+ if (!existsSync(file)) continue;
1865
+ let text = '';
1866
+ try { text = readFileSync(file, 'utf8'); } catch { continue; }
1867
+ if (rel === 'AGENTS.md' && !text.includes(AGENTS_MARKER)) continue;
1868
+ const v = skillVersionOf(text);
1869
+ if (v === null || (semverCompare(v, PKG.version) ?? -1) < 0) older.push({ rel, v });
1870
+ }
1871
+ if (older.length) {
1872
+ startup('skill',
1873
+ // the row is the fact and the command to type, nothing else
1874
+ `${older.map((o) => `${basename(o.rel)} ${o.v ? `v${o.v}` : 'before 0.9.0'}`).join(', ')}, older than ${PKG.version} · run: ${selfCommand()} skills`,
1875
+ ` skill: ${older.map((o) => `${o.rel} (${o.v ? `v${o.v}` : 'before 0.9.0'})`).join(', ')} — older than this install (${PKG.version}): an agent reads an old contract; run ${selfCommand()} skills`, 'warn');
1876
+ }
1877
+ }
1878
+ // The presenter's chrome, named here as no-trust mode names it under its
1879
+ // label: what is layered over the slides, and which plugin reads the notes.
1880
+ if (!noTrust && (chrome.plugins.length || chrome.refused.length)) {
1881
+ const names = chrome.plugins.map((pl) => `${pl.name}${pl.needs.includes('notes') ? ' (reads your notes)' : ''}`);
1882
+ const refused = chrome.refused.map((r) => `${r.name} refused`);
1883
+ startup('plugins', [...names, ...refused].join(', ') + ' · --no-plugins plays without them',
1884
+ ` chrome: ${[...names, ...refused].join(', ')} — yours, not in the deck (--no-plugins plays without them)`,
1885
+ refused.length ? 'warn' : 'ok');
1886
+ }
867
1887
  // Said out loud, every session it is on: this is the switch that starts
868
1888
  // sending the deck somewhere, and a capability nobody is reminded of is one
869
1889
  // they stop counting on being off. Printed HERE rather than up with the other
@@ -871,14 +1891,213 @@ export async function editMain(args, { onListen = null } = {}) {
871
1891
  if (gitOn && wantMessages) {
872
1892
  const who = agents.find((a) => a.name === agentPref) ?? agents[0];
873
1893
  startup('git',
874
- who?.name ? `${who.name} writes the subjects` : '--commit-messages needs an agent on PATH',
875
- ` ${messagesLine(who?.name ?? null)}`);
1894
+ who?.name ? `subjects by ${who.name}` : '--commit-messages needs an agent on PATH',
1895
+ ` ${messagesLine(who?.name ?? null)}`, who?.name ? 'ok' : 'warn');
876
1896
  }
877
1897
 
878
1898
  // ── live reload: watch the deck, broadcast SSE (debounced — editors fire
879
1899
  // multiple fs events per save) ─────────────────────────────────────────
880
- const clients = sseChannel();
881
- const broadcast = (event, data) => clients.broadcast(event, data);
1900
+ // The review routes (SPEC REVIEW), the same ones every server that opens a
1901
+ // deck registers: a review can be left in write mode too. The sidecar is
1902
+ // appended, never the deck; here it is not committed by itself, because the
1903
+ // deck's own commits (the snapshot, K) are what this server keeps.
1904
+ // In no-trust mode the sidecar is the ONE file this process writes, and
1905
+ // it is committed by itself as each comment lands when the deck sits in a
1906
+ // repository (`--no-git` leaves the committing to you).
1907
+ const reviewRepo = gitAvailable(dirname(deckPath)) && inGitRepo(dirname(deckPath));
1908
+ const review = createReviewRoutes(deckPath, {
1909
+ inRepo: reviewRepo,
1910
+ gitOn: noTrust && reviewRepo && !noGit,
1911
+ mode: noTrust ? 'no-trust' : 'write',
1912
+ // A record just landed in the sidecar — a resolve naming a reviewer's
1913
+ // comment changes what the incoming listing says is done, so the cached
1914
+ // listing must not outlive it. `wrote` is the .gitattributes the first
1915
+ // record in this repository had to write (REVIEW, merge=union): the
1916
+ // deck's next commit carries it, beside the sidecar.
1917
+ onRecord: (_rec, { wrote } = {}) => { incomingCache = null; if (wrote) pendingAttr = wrote; },
1918
+ // No-trust mode lists back what this reviewer already submitted, from
1919
+ // the remote's review/<me>-* branches (REVIEW), behind the same switches
1920
+ // that silence the author's inbox check, and at most once a minute: M is
1921
+ // a keypress, not a fetch storm.
1922
+ mine: noTrust && reviewRepo && !reviewCheckSuppressed({ args, ci: false }) ? async () => {
1923
+ if (!mineCache || Date.now() - mineCache.at > 60_000) {
1924
+ const { myReviews } = await import('./review-remote.mjs');
1925
+ const { reviewerIdentity } = await import('./review-routes.mjs');
1926
+ const { slugUser } = await import('./review-submit.mjs');
1927
+ mineCache = { at: Date.now(), r: await myReviews(deckPath, slugUser(reviewerIdentity(dirname(deckPath)))) };
1928
+ }
1929
+ return mineCache.r;
1930
+ } : null,
1931
+ });
1932
+ let mineCache = null;
1933
+ // The deck's channel (deck-routes.mjs): the probe and the stream, in both
1934
+ // modes. What the probe carries beyond the mode is `extras`, computed on
1935
+ // every ping like everything else on it: the toast is threshold-driven,
1936
+ // not live.
1937
+ const deck = createDeckRoutes(deckPath, {
1938
+ noTrust,
1939
+ locked: () => noTrust || locked,
1940
+ review,
1941
+ extras: async () => (noTrust ? {
1942
+ // No-trust mode names nothing that edits: no roster, no history, no
1943
+ // git. What the page needs is whether the phone remote is on
1944
+ // (NO_TRUST#REMOTE: the clicker, and the QR in the speaker view) and
1945
+ // whether this deck can ever leave the mode.
1946
+ phone: !!token,
1947
+ container: !!container,
1948
+ } : {
1949
+ deck: deckUrl,
1950
+ phone: !!token,
1951
+ container: !!container,
1952
+ ...history.counts(), git: gitOn,
1953
+ // What the player's one push nudge reads. Computed once, like everything
1954
+ // else on ping: the toast is threshold-driven, not live.
1955
+ remote: gitOn ? remoteState(root) : null,
1956
+ agents: agents.map((a) => ({ name: a.name, label: a.label })),
1957
+ // which one A reaches for, so the picker opens on it rather than
1958
+ // defaulting to the first detected agent every session (#125)
1959
+ preferredAgent: agentPref ?? null,
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,
1965
+ agentAsks,
1966
+ wizards: await configurableEngines(),
1967
+ // What is uncommitted, so a deck that loads mid-session shows the
1968
+ // chip without waiting for the next tick to broadcast one.
1969
+ commit: (gitOn && measureDirty(), commitState()),
1970
+ }),
1971
+ });
1972
+ const clients = deck.channel;
1973
+ const broadcast = deck.broadcast;
1974
+
1975
+ // ── the phone remote (NO_TRUST#REMOTE) ───────────────────────────────────
1976
+ // The relay: controller page, QR, readout channel, the phone's taps onto the
1977
+ // deck's stream. These are the only paths allowRemote lets through from off
1978
+ // this machine, and not one of them writes anything — the phone asks the
1979
+ // deck to move, it never edits. The phone is a different origin from the
1980
+ // deck (a LAN address, not localhost), so the relay's own endpoints need
1981
+ // CORS; nothing else here does.
1982
+ const PHONE_CORS = corsHeaders();
1983
+ let actualPort = null;
1984
+ // The controller answers on loopback in either mode, flag or no flag (a
1985
+ // deck on this machine gets its position readout); only the LAN listener,
1986
+ // and the QR that points a phone at it, are what --remote adds.
1987
+ const relay = createRemoteRelay({
1988
+ deckName: basename(deckPath),
1989
+ token,
1990
+ remoteUrl: () => `http://${lanAddress() ?? host}:${actualPort}/deck/remote?t=${token}`,
1991
+ relayToDeck: (event, data) => broadcast(event, data),
1992
+ deckCount: () => clients.size,
1993
+ CORS: PHONE_CORS,
1994
+ });
1995
+
1996
+ // ── the upstream check (NO_TRUST#UPSTREAM) ───────────────────────────────
1997
+ // A deck opened without trust from a clone: has its author pushed since? Absent
1998
+ // unless the deck is a tracked file in a clone with an upstream — that is
1999
+ // the whole safety argument: a deck you were emailed is a single file and
2000
+ // never reaches any of it. Write mode has H for the deck's own history and
2001
+ // never resolves this; the routes are registered only when it applies.
2002
+ const suppressed = !noTrust ? 'write mode' : upstreamSuppressed({ args, env: process.env });
2003
+ const upstreamCtx = suppressed ? { state: 'disabled' } : await resolveUpstream(deckPath);
2004
+ const upstream = upstreamCtx.state === 'ok' ? upstreamCtx : null;
2005
+ // The PULL is a second, explicit opt-in. Server-side there is no way to tell
2006
+ // "the presenter clicked" from "a script in the deck called fetch()" — a
2007
+ // page's own script is indistinguishable from its user — so the capability
2008
+ // is "a deck served from a clone can update itself from that clone's
2009
+ // upstream", which is a thing someone should have typed rather than
2010
+ // something the cwd decided. And never with --remote: a phone must not move
2011
+ // somebody's repo.
2012
+ const pullArmed = Boolean(upstream) && args.includes('--upstream-pull') && !token;
2013
+ let upstreamStatus = upstream
2014
+ ? { state: 'unchecked', branch: upstream.branch, upstream: upstream.upstream, message: 'not checked yet' }
2015
+ : { state: upstreamCtx.state, message: suppressed || null };
2016
+ let checking = null;
2017
+ const intervalMs = resolveInterval(args);
2018
+ let lastReported = null;
2019
+ const pullOffer = () => (pullArmed
2020
+ ? { offered: true }
2021
+ : { offered: false, reason: !upstream ? upstreamCtx.state : token ? '--remote is on' : 'start with --upstream-pull' });
2022
+ async function refreshUpstream() {
2023
+ if (!upstream) return upstreamStatus;
2024
+ // Single-flight: a script in a loop must not spawn a hundred fetches.
2025
+ if (!checking) {
2026
+ checking = checkUpstream(upstream).then((st) => { upstreamStatus = st; checking = null; return st; });
2027
+ }
2028
+ return checking;
2029
+ }
2030
+ /** The label, re-printed: what the audience gets from here on. */
2031
+ const printLabel = () => {
2032
+ for (const line of formatLabel(audited.report)) console.log(line);
2033
+ if (container) console.log(formatManifest(container.manifest));
2034
+ console.log(formatSignature(signature));
2035
+ };
2036
+ /**
2037
+ * Fast-forward, then re-read, re-audit and RE-PRINT. SPEC's condition on
2038
+ * live reload in no-trust mode is exactly this: never new bytes under the
2039
+ * old verdict. So the label the presenter can see always describes the
2040
+ * bytes being served, and the two move together.
2041
+ */
2042
+ async function doPull() {
2043
+ // Re-checked against a FRESH fetch rather than trusted from the cached
2044
+ // status: what was true ten minutes ago is not a licence to check out now.
2045
+ const fresh = await refreshUpstream();
2046
+ const allowed = canPull(fresh, { offered: pullArmed });
2047
+ if (!allowed.ok) return { ok: false, ...allowed, http: 409 };
2048
+
2049
+ const from = (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: upstream.repoRoot })).stdout;
2050
+ console.log(` upstream: PULL requested by the deck — fast-forward only, onto ${upstream.upstream}`);
2051
+ const merged = await runGit([...SAFE_CONFIG, '-c', `core.hooksPath=${upstream.repoRoot}/.git/decklight-no-hooks`,
2052
+ 'merge', '--ff-only', '--no-verify', '@{upstream}'], { cwd: upstream.repoRoot, timeoutMs: 20000 });
2053
+ if (!merged.ok) {
2054
+ const why = oneline(merged.stderr || merged.err);
2055
+ console.log(` upstream: the fast-forward was refused — ${why}`);
2056
+ return { ok: false, state: 'not-fast-forward', message: why };
2057
+ }
2058
+ const to = (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: upstream.repoRoot })).stdout;
2059
+
2060
+ // An upstream commit must never blank somebody's talk.
2061
+ if (!existsSync(deckPath)) {
2062
+ console.log(` upstream: fast-forwarded ${from} → ${to}, but the deck is gone from that commit`);
2063
+ console.log(' still serving the bytes the label above describes');
2064
+ return { ok: false, state: 'deck-gone', to, message: 'the deck is not in that commit — still serving the old bytes' };
2065
+ }
2066
+
2067
+ const wasStrict = audited.strict;
2068
+ const hadFindings = audited.report.counts.unaccounted > 0 || audited.report.counts.handlers > 0;
2069
+ if (!audit()) {
2070
+ console.log(` upstream: fast-forwarded ${from} → ${to} — the deck itself is unchanged`);
2071
+ await refreshUpstream();
2072
+ return { ok: true, state: 'pulled', from, to, deck: 'unchanged', reload: false, message: `fast-forwarded to ${to} — the deck is unchanged` };
2073
+ }
2074
+ const findings = { unaccounted: audited.report.counts.unaccounted, handlers: audited.report.counts.handlers };
2075
+ const degraded = (findings.unaccounted > 0 || findings.handlers > 0) && !hadFindings;
2076
+
2077
+ console.log(` upstream: fast-forwarded ${from} → ${to}`);
2078
+ console.log(' the deck file changed — re-read and re-audited; the label below replaces the one above');
2079
+ noteWrite(whatWrote('/deck/upstream/pull'));
2080
+ printLabel();
2081
+ if (audited.strict) {
2082
+ console.log(wasStrict && !(findings.unaccounted > 0 || findings.handlers > 0)
2083
+ ? ' still serving strict — a pull cannot turn it off'
2084
+ : ' serving strict — what could not be accounted for is stripped');
2085
+ }
2086
+ console.log(' the label above describes what the audience gets when the deck is reloaded');
2087
+ await refreshUpstream();
2088
+ return {
2089
+ ok: true, state: 'pulled', from, to, deck: 'changed',
2090
+ strict: audited.strict, degraded, findings,
2091
+ // A degraded deck does NOT reload itself: the swap executes nothing (the
2092
+ // browser is still showing the old DOM), so the reload can wait for a
2093
+ // second confirmation that names what was found.
2094
+ reload: !degraded,
2095
+ message: degraded
2096
+ ? `the updated deck runs ${findings.unaccounted} unaccounted script block(s) and `
2097
+ + `${findings.handlers} inline handler(s) — they are stripped. Reload to show it`
2098
+ : `fast-forwarded to ${to}`,
2099
+ };
2100
+ }
882
2101
 
883
2102
  // ── the catalogs, read from cache and never fetched ──────────────────────
884
2103
  const catalogMap = async () => {
@@ -890,8 +2109,16 @@ export async function editMain(args, { onListen = null } = {}) {
890
2109
  }
891
2110
  return out;
892
2111
  };
893
- /** Every theme entry a registered marketplace offers, qualified. */
894
- const browsableThemes = async () => {
2112
+ /**
2113
+ * Every entry of one TYPE a registered marketplace offers, qualified.
2114
+ *
2115
+ * Written for themes and generalised the day templates needed the same list:
2116
+ * the cache reading, the never-fetched marketplaces and the
2117
+ * cloned-but-missing ones are properties of the registry, not of what is
2118
+ * being listed, so a second copy of them would be a second thing to keep
2119
+ * right.
2120
+ */
2121
+ const browsableUnits = async (type) => {
895
2122
  const { loadRegistry, loadCatalog, checkoutPath, classifySource, configHome } = await import('./marketplace.mjs');
896
2123
  const registry = loadRegistry().marketplaces ?? {};
897
2124
  const themes = [];
@@ -913,7 +2140,7 @@ export async function editMain(args, { onListen = null } = {}) {
913
2140
  continue;
914
2141
  }
915
2142
  for (const e of loaded.manifest.entries ?? []) {
916
- if (e.type !== 'theme') continue;
2143
+ if (e.type !== type) continue;
917
2144
  themes.push({
918
2145
  name: e.name, marketplace: market, qualified: `${e.name}@${market}`,
919
2146
  description: e.description ?? '', source: e.source,
@@ -924,9 +2151,9 @@ export async function editMain(args, { onListen = null } = {}) {
924
2151
  };
925
2152
  /**
926
2153
  * Every entry a registered marketplace declares a wizard for, qualified.
927
- * Advertised in /edit/ping beside the agents: the palette's Configure rows
2154
+ * Advertised in /deck/ping beside the agents: the palette's Configure rows
928
2155
  * come from here, so a player never has to guess an engine name to ask
929
- * /edit/wizard about (ENGINES#WIZARD).
2156
+ * /deck/edit/wizard about (ENGINES#WIZARD).
930
2157
  */
931
2158
  const configurableEngines = async () => {
932
2159
  const { loadRegistry, loadCatalog } = await import('./marketplace.mjs');
@@ -1001,6 +2228,7 @@ export async function editMain(args, { onListen = null } = {}) {
1001
2228
  };
1002
2229
 
1003
2230
  let pending = null;
2231
+ let quietWrite = null; // the bytes of a write that updates the page itself (themeMarkRoute, cli/edit-look.mjs)
1004
2232
  // The DIRECTORY, not the file. A path watch follows the inode, and an
1005
2233
  // atomic write — temp file + rename, which is how an agent's editor and
1006
2234
  // most careful tools save — replaces the inode: the watcher then sits deaf
@@ -1012,25 +2240,104 @@ export async function editMain(args, { onListen = null } = {}) {
1012
2240
  if (filename && filename !== basename(deckPath)) return;
1013
2241
  clearTimeout(pending);
1014
2242
  pending = setTimeout(() => {
1015
- clients.raw('data: reload\n\n');
1016
- console.log(` changed → reload × ${clients.size}`);
2243
+ // No-trust mode serves the audited bytes, never the disk: a file that
2244
+ // changed underneath it is not reloaded, because that would be new
2245
+ // bytes under the old label. A pull re-audits.
2246
+ if (noTrust) return;
2247
+ // A QUIET write is one the pages update themselves in place, which must
2248
+ // not reload: a theme marked from the open picker (a reload closes the
2249
+ // picker the author is still choosing in), or a notes save, whose new
2250
+ // notes every page is sent as a `notes` event. Skipped only when
2251
+ // the file is still exactly what that write put there; any other change
2252
+ // since (an editor save, an undo) reloads as it always has.
2253
+ const quiet = quietWrite;
2254
+ quietWrite = null;
2255
+ if (quiet !== null) {
2256
+ let now = null;
2257
+ try { now = readFileSync(deckPath, 'utf8'); } catch { /* gone — reload says so */ }
2258
+ if (now === quiet) { lastWrite = null; console.log(' changed → updated in place, no reload'); return; }
2259
+ }
2260
+ // The message names what wrote the file (`describeReload`): the page
2261
+ // stashes it with its debug log and says it first thing after the
2262
+ // reload. An older page reloads on any message, as it always did.
2263
+ const why = describeReload({ write: lastWrite, agent: agentJob });
2264
+ lastWrite = null;
2265
+ clients.raw(`data: ${JSON.stringify(why)}\n\n`);
2266
+ console.log(` changed → reload × ${clients.size} — ${why.reload}${why.from ? ` (page ${why.from})` : ''}`);
1017
2267
  }, 150);
1018
2268
  });
1019
2269
 
1020
- function runAgent(prompt, name, message) {
1021
- const cmd = agentCommand(name || agentPref, prompt, deckRel);
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 });
1022
2309
  if (!cmd) return null;
2310
+ const ask = {
2311
+ id: ++askSeq, agent: cmd.name, label: cmd.label, prompt,
2312
+ ...(Number.isInteger(slide) && slide > 0 ? { slide } : {}),
2313
+ ...(kind ? { kind } : {}), ...(title ? { title } : {}),
2314
+ startedAt: Date.now(), state: 'running',
2315
+ };
2316
+ agentAsks.push(ask);
2317
+ if (agentAsks.length > ASKS_KEPT) agentAsks.shift();
2318
+ const finish = (d) => Object.assign(ask, { state: 'done', finishedAt: Date.now() }, d);
1023
2319
  // Anything uncommitted at this moment is the PLAYER's work, not the
1024
2320
  // agent's. Sweeping it into its own commit first is what keeps the agent's
1025
2321
  // commit honest: otherwise a hand edit made just before pressing A lands
1026
2322
  // under the agent's message, and a history that misattributes authorship is
1027
2323
  // worse than one that only says "autosave".
1028
2324
  if (gitOn && shouldCommit(gitMode, { kind: 'bookend' })
1029
- && ownCommit(`decklight: save before ${cmd.name} edits ${basename(deckPath)}`)) {
2325
+ && ownCommit(`decklight: save before ${cmd.name} edits ${basename(deckPath)}`, files)) {
1030
2326
  console.log(' git: committed your outstanding changes first');
1031
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
+ }
1032
2336
  const before = readDeck();
1033
- agentJob = { agent: cmd.name, label: cmd.label, prompt, startedAt: Date.now() };
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 } : {}) };
1034
2341
  broadcast('agent', { state: 'start', ...agentJob });
1035
2342
  console.log(` agent: ${cmd.name} ← "${prompt.slice(0, 80)}"`);
1036
2343
  const child = spawn(cmd.bin, cmd.args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
@@ -1046,7 +2353,7 @@ export async function editMain(args, { onListen = null } = {}) {
1046
2353
  let lastSaid = 0;
1047
2354
  const say = (text) => {
1048
2355
  if (!text || !agentJob) return;
1049
- agentJob.activity = text; // /edit/ping carries it across a reload
2356
+ agentJob.activity = text; // /deck/ping carries it across a reload
1050
2357
  broadcast('agent', { state: 'activity', agent: cmd.name, text });
1051
2358
  console.log(` agent: ${text}`);
1052
2359
  };
@@ -1073,22 +2380,39 @@ export async function editMain(args, { onListen = null } = {}) {
1073
2380
  child.stderr.on('data', keep);
1074
2381
  }
1075
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
+ };
1076
2392
  child.on('error', (e) => {
1077
2393
  clearTimeout(timeout);
2394
+ clearTimeout(hard);
1078
2395
  agentJob = null;
1079
- broadcast('agent', { state: 'done', agent: cmd.name, ok: false, changed: false, error: String(e.message || e) });
2396
+ agentStop = null;
2397
+ finish({ ok: false, changed: false, error: String(e.message || e) });
2398
+ broadcast('agent', { state: 'done', id: ask.id, agent: cmd.name, ok: false, changed: false, error: String(e.message || e) });
1080
2399
  });
1081
2400
  child.on('exit', (code) => {
1082
2401
  clearTimeout(timeout);
2402
+ clearTimeout(hard);
2403
+ agentStop = null;
1083
2404
  const after = readDeck();
1084
- const changed = after !== before;
1085
- 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);
1086
2410
  // One commit per completed agent edit, carrying the agent's own summary
1087
2411
  // — the boundary and the message both come from the work, not a clock.
1088
2412
  // A failed run or one that changed nothing commits nothing.
1089
2413
  if (gitOn && shouldCommit(gitMode, { kind: 'agent', ok: code === 0, changed })) {
1090
- const subject = commitSubject(message ?? prompt, `decklight: ${cmd.name} edited ${basename(deckPath)}`);
1091
- if (gitAutocommit(deckPath, root, subject)) 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}"`); }
1092
2416
  }
1093
2417
  // Did the edit orphan, stale, or reshape a recording? A track is
1094
2418
  // minutes of somebody's own voice, and a whole-deck rewrite can drop the
@@ -1110,741 +2434,1072 @@ export async function editMain(args, { onListen = null } = {}) {
1110
2434
  } catch { recordingWarning = null; } // a warning that throws is worse than none
1111
2435
  }
1112
2436
  agentJob = null;
2437
+ // the agent's own words when the stream carried them — raw stream-json
2438
+ // stdout is a wall of JSON nobody should be shown
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 } : {}) });
1113
2447
  broadcast('agent', {
1114
- state: 'done', agent: cmd.name, ok: code === 0, changed, code,
1115
- // the agent's own words when the stream carried them — raw stream-json
1116
- // stdout is a wall of JSON nobody should be shown
1117
- tail: (resultText ?? tail.trim().split('\n').slice(-6).join('\n')).slice(-600),
2448
+ state: 'done', id: ask.id, agent: cmd.name, ok: code === 0, changed, code, tail: said,
2449
+ ...(left.length ? { left } : {}),
2450
+ ...(stopped ? { stopped } : {}),
1118
2451
  ...(recordingWarning ? { recordingWarning } : {}),
1119
2452
  });
1120
- 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'}`);
1121
2454
  if (recordingWarning) console.log(` ${recordingWarning}`);
1122
2455
  });
1123
2456
  return cmd;
1124
2457
  }
1125
2458
 
1126
- const files = staticFiles(root, { index: deckUrl });
1127
- const server = createServer(async (req, res) => {
1128
- // The CSRF gate (#222), before anything runs. A same-machine browser tab is
1129
- // the threat, not an off-machine caller, so the check is the request's
1130
- // `Origin`, not its socket address. A foreign origin is refused here —
1131
- // before the body is read, before any file is written, before an agent is
1132
- // spawned — and refused WITHOUT permissive CORS, so the page cannot even
1133
- // read the refusal. Loopback origins, `null` (file://), and the header's
1134
- // absence (the CLI, the port-conflict probe, curl) pass.
1135
- const origin = req.headers.origin;
1136
- const CORS = corsHeadersFor(origin);
1137
- if (!allowEditRequest(req)) {
1138
- res.writeHead(403, { 'content-type': 'text/plain' });
1139
- res.end('forbidden: the author edit surface answers this machine only, and not a foreign web origin');
1140
- return;
2459
+ // ── the session: what a deck asks on load, and how it ends ───────────────
2460
+
2461
+ // ── the bridges, on this origin (#520) ───────────────────────────────────
2462
+ // A deck served here reaches its live voice at `/deck/tts` (and the sibling
2463
+ // routes the runtime derives from it) and its lip-sync at `/deck/lipsync/*` —
2464
+ // the deck's own origin, never a port it would have to spell (SPEC
2465
+ // NARRATION). The bridges are separate processes on their own ports
2466
+ // (`--tts-port`, `--lipsync-port`); these forward to them, body and
2467
+ // headers both ways, and answer 503 when the bridge is not there, which the
2468
+ // deck takes exactly as it takes no bridge at all.
2469
+ const ttsPort = parsePort(opt('--tts-port', 8787)) ?? 8787;
2470
+ const lipsyncPort = parsePort(opt('--lipsync-port', 8789)) ?? 8789;
2471
+ const proxyTo = (port, name, rewritePath = (p) => p) => ({ req, res, url, body }) => new Promise((done) => {
2472
+ const { host: _host, ...headers } = req.headers;
2473
+ const upstream = httpRequest({
2474
+ host: '127.0.0.1', port, method: req.method, path: rewritePath(url.pathname) + url.search,
2475
+ headers: { ...headers, host: `127.0.0.1:${port}` },
2476
+ }, (up) => {
2477
+ res.writeHead(up.statusCode ?? 502, up.headers);
2478
+ up.pipe(res);
2479
+ up.on('end', done);
2480
+ });
2481
+ upstream.on('error', (e) => {
2482
+ if (!res.headersSent) res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' });
2483
+ res.end(`the ${name} bridge is not running on port ${port} (${e.code ?? e.message})`);
2484
+ done();
2485
+ });
2486
+ // every proxied route is dispatched before the body is read, so the
2487
+ // request streams through — audio for the lip-sync bridge included
2488
+ if (body !== undefined) upstream.end(body); else req.pipe(upstream);
2489
+ });
2490
+ // both bridges serve their routes at their own roots; on the deck's origin
2491
+ // they sit under /deck/, and the prefix comes off on the way through
2492
+ const ttsProxy = proxyTo(ttsPort, 'voice', (p) => p.slice('/deck'.length));
2493
+ const lipsyncProxy = proxyTo(lipsyncPort, 'lip-sync', (p) => p.slice('/deck/lipsync'.length));
2494
+
2495
+ // ── the lock (PRESENTING) ─────────────────────────────────────────────────
2496
+ // Editing is on from the moment write mode answers; the lock is the one
2497
+ // switch that turns changes off, to avoid making one by mistake, and back
2498
+ // on. It lives here, not in a page, so every tab and the agent see the
2499
+ // same state: locked, every POST to /deck/edit/* but this one answers 423,
2500
+ // the ping says so, and the channel tells every open page. No-trust mode
2501
+ // has no lock to turn: the write family refuses there anyway.
2502
+ let locked = false;
2503
+ function lockRoute({ body, json }) {
2504
+ const { locked: want } = JSON.parse(body || '{}');
2505
+ if (typeof want !== 'boolean') return json(400, { ok: false, error: 'locked is true or false' });
2506
+ if (want !== locked) {
2507
+ locked = want;
2508
+ console.log(locked ? ' deck locked — nothing is written until it is unlocked' : ' deck unlocked');
2509
+ broadcast('lock', { locked });
2510
+ }
2511
+ return json(200, { ok: true, locked });
2512
+ }
2513
+ function shutdownRoute({ res, json, CORS }) {
2514
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
2515
+ res.end(JSON.stringify({ ok: true }));
2516
+ // same shutdown a Ctrl-C takes — final autocommit, then actually exit —
2517
+ // once the response has cleared the socket, so the asker sees it land
2518
+ res.once('finish', () => { finalCommit(); process.exit(0); });
2519
+ return;
2520
+ }
2521
+
2522
+ function undoRedoRoute({ url, json }) {
2523
+ const dir = url.pathname.endsWith('undo') ? 'undo' : 'redo';
2524
+ const cur = readDeck();
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 ?? {})) }));
2527
+ if (content === null) return json(409, { ok: false, error: `nothing to ${dir}`, ...history.counts() });
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);
2532
+ console.log(` ${dir} → ${JSON.stringify(history.counts())}`);
2533
+ return json(200, { ok: true, ...history.counts() });
2534
+ }
2535
+
2536
+ // ── review comments (SPEC REVIEW) ─────────────────────────────
2537
+ // The author's side of `decklight <deck> --no-trust`. The same file, the same
2538
+ // append-only rule: this server may add a line (a resolve, a move) and
2539
+ // may not rewrite one, because `merge=union` is what keeps two reviewers
2540
+ // from conflicting and an edit in place is what would break it.
2541
+ // What reviews are waiting on the remote — the M overlay's incoming
2542
+ // section. This one is a fetch the author DID ask for: it runs behind
2543
+ // the keypress that just opened the overlay, on demand and nowhere else.
2544
+ // The 60s cache is what keeps a nervous author tapping M from turning
2545
+ // one gesture into a fetch storm; the off switches still win outright.
2546
+ async function reviewIncomingRoute({ json }) {
2547
+ // ci: false — this fetch is ASKED FOR, behind the keypress that
2548
+ // opened the overlay; only the explicit switches silence it.
2549
+ const skipped = reviewCheckSuppressed({ args, ci: false });
2550
+ if (skipped) return json(200, { ok: true, state: 'suppressed', reason: skipped, reviews: [] });
2551
+ if (!incomingCache || Date.now() - incomingCache.at > 60_000) {
2552
+ const r = await reviewsWaiting(deckPath);
2553
+ incomingCache = { at: Date.now(), r };
2554
+ }
2555
+ return json(200, { ok: true, ...incomingCache.r });
2556
+ }
2557
+
2558
+ // Point the deck at a track the recorder just wrote. The one manual step
2559
+ // in a flow that is otherwise a key and an arrow — and this server
2560
+ // already owns the file, so it can take that step too.
2561
+ function reviewAtRoute({ url, json }) {
2562
+ // The orphan's context: what the slide SAID when the comment was
2563
+ // written — `comments --at`, served, so the overlay can put the dead
2564
+ // slide's prose under the objection that was about it. Read-only, all
2565
+ // local (the commit is already in this clone or the answer is "not
2566
+ // here"), and gated exactly as the CLI gates it.
2567
+ const id = url.searchParams.get('id') ?? '';
2568
+ if (!/^[a-z0-9]{1,12}$/.test(id)) return json(400, { ok: false, error: 'bad comment id' });
2569
+ const store = reviewPathFor(deckPath);
2570
+ if (!existsSync(store)) return json(404, { ok: false, error: 'no comments here' });
2571
+ const c = foldReview(parseReview(readFileSync(store, 'utf8')).records).find((x) => x.id === id);
2572
+ if (!c) return json(404, { ok: false, error: `no comment [${id}]` });
2573
+ if (!c.deck) return json(200, { ok: true, known: false, why: 'written outside a repository — there is no earlier version to show' });
2574
+ if (!gitOn || !knowsCommit(c.deck, root)) {
2575
+ return json(200, { ok: true, known: false, why: `this clone does not have ${c.deck}` });
1141
2576
  }
1142
2577
  try {
1143
- const url = new URL(req.url, 'http://x');
1144
- const json = (code, obj) => {
1145
- res.writeHead(code, { ...CORS, 'content-type': 'application/json' });
1146
- res.end(JSON.stringify(obj));
1147
- };
1148
- if (req.method === 'OPTIONS') { res.writeHead(204, CORS); return res.end(); }
1149
- if (req.method === 'GET' && url.pathname === '/edit/ping') {
1150
- return json(200, {
1151
- ok: true, deck: deckUrl, name: basename(deckPath),
1152
- ...history.counts(), git: gitOn,
1153
- // What the player's one push nudge reads. Computed once, like everything
1154
- // else on ping: the toast is threshold-driven, not live.
1155
- remote: gitOn ? remoteState(root) : null,
1156
- agents: agents.map((a) => ({ name: a.name, label: a.label })),
1157
- // which one A reaches for, so the picker opens on it rather than
1158
- // defaulting to the first detected agent every session (#125)
1159
- preferredAgent: agentPref ?? null,
1160
- agentBusy: agentJob && { agent: agentJob.agent, prompt: agentJob.prompt, startedAt: agentJob.startedAt },
1161
- wizards: await configurableEngines(),
1162
- // What is uncommitted, so a deck that loads mid-session shows the
1163
- // chip without waiting for the next tick to broadcast one.
1164
- commit: (gitOn && measureDirty(), commitState()),
1165
- });
2578
+ const thenHtml = deckAt(deckPath, c.deck, root);
2579
+ const wasAt = indexDeckFile(thenHtml)[(c.slide ?? 0) - 1] ?? null;
2580
+ return json(200, {
2581
+ ok: true,
2582
+ known: true,
2583
+ deck: c.deck,
2584
+ slide: c.slide ?? null,
2585
+ title: wasAt?.title ?? null,
2586
+ text: slideTextOf(thenHtml, c.slide) || '',
2587
+ });
2588
+ } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
2589
+ }
2590
+
2591
+ // ── the engine wizard (ENGINES#WIZARD) ─────────────────────────────
2592
+ // The schema the player renders. Validated on the way OUT as well as on
2593
+ // the way in: a catalog is a file someone else wrote, and handing the
2594
+ // renderer a schema core has not vetted is how "core renders, a plugin
2595
+ // declares" becomes "core renders whatever a plugin sent".
2596
+ async function wizardSchemaRoute({ url, json }) {
2597
+ const engine = url.searchParams.get('engine') ?? '';
2598
+ const hit = await wizardEntry(engine);
2599
+ if (!hit) return json(404, { ok: false, error: `no wizard declared for "${engine}"` });
2600
+ try {
2601
+ const schema = validateSchema(hit.entry.wizard);
2602
+ // Provenance rides BESIDE the schema, never inside it (#232): `from`
2603
+ // is the registry's name for the entry and the sentence pair is
2604
+ // derived here from the vetted schema, so the card can say who is
2605
+ // asking and where the answer goes in words the plugin did not write.
2606
+ return json(200, { ok: true, schema, from: hit.qualified, provenance: provenance(schema, hit.qualified) });
2607
+ } catch (e) {
2608
+ return json(400, { ok: false, error: `${engine} declares a wizard core cannot render: ${e.message}` });
2609
+ }
2610
+ }
2611
+
2612
+ // Author-mode only, and that is structural rather than checked: this
2613
+ // server answers loopback alone, and `--no-trust` registers nothing like
2614
+ // these at all. A credential prompt in a deck you were emailed has
2615
+ // nowhere to post.
2616
+ async function wizardConfigureRoute({ body, json }) {
2617
+ const { engine, answers } = JSON.parse(body);
2618
+ if (typeof engine !== 'string') return json(400, { ok: false, error: 'which engine?' });
2619
+ // "No such engine" is a third answer, not one of the two failures. It is
2620
+ // not an outage to wait out and not a refusal by a provider — it is a
2621
+ // marketplace that was never added, and the fix is named.
2622
+ if (!(await wizardEntry(engine))) {
2623
+ return json(404, { ok: false, state: 'unknown',
2624
+ error: `no engine named "${engine}" declares a wizard in any registered marketplace — try: decklight marketplace add <owner/repo>` });
2625
+ }
2626
+ const r = await configureEngine(engine, answers, {
2627
+ fetchSchema: wizardSchemaFor,
2628
+ validateAnswers: wizardValidate,
2629
+ });
2630
+ if (r.state !== CONFIGURED) {
2631
+ // The three failures stay three: 503 for "could not reach", 400 for
2632
+ // "that was refused", and 412 for "this machine is missing something"
2633
+ // (ENGINES#LIPSYNC). A presenter whose key is wrong must not be told
2634
+ // to check their network, and one who is missing rhubarb must not be
2635
+ // told to check their key — the status code says which it is too.
2636
+ const code = r.state === UNREACHABLE ? 503 : r.state === PREREQUISITE ? 412 : 400;
2637
+ return json(code, { ok: false, state: r.state, error: r.reason, ...(r.unmet ? { unmet: r.unmet } : {}) });
2638
+ }
2639
+ // Redacted on the way out, always — the response is the one place a key
2640
+ // could leak back into a page, a devtools log, or a screen recording.
2641
+ console.log(` wizard: ${engine} configured (${r.file} — ${r.protection.label})`);
2642
+ // A key that could not be restricted is worth an extra line, at the
2643
+ // moment it is stored rather than in a doc nobody reads (#308): what
2644
+ // decklight says about a credential and what is true of it on disk
2645
+ // have to be the same sentence.
2646
+ if (r.protection.state !== 'private') {
2647
+ console.log(` wizard: decklight could NOT restrict that file to your account — ${r.protection.label}`);
2648
+ if (r.protection.why) console.log(` the system said: ${r.protection.why}`);
2649
+ }
2650
+ return json(200, { ok: true, state: r.state, engine, stored: r.stored, protection: r.protection.label });
2651
+ }
2652
+
2653
+ function wizardForgetRoute({ body, json }) {
2654
+ const { engine } = JSON.parse(body);
2655
+ if (typeof engine !== 'string') return json(400, { ok: false, error: 'which engine?' });
2656
+ const had = forgetCredentials(engine);
2657
+ console.log(` wizard: ${engine} ${had ? 'forgotten' : 'was not configured'}`);
2658
+ return json(200, { ok: true, forgotten: had });
2659
+ }
2660
+
2661
+ // ── the recorder's offline recordings — V → Record this deck… (PRESENTING) ───────────────────────────────
2662
+ // The player used to hand every stitched slide to the browser's DOWNLOAD
2663
+ // path, which is why a deck's voice arrived as thirty slide-NN.wav in
2664
+ // whatever folder the OS calls Downloads — never the deck's, and on
2665
+ // Windows not even near it. `bundle` only ever looks NEXT TO THE DECK, so
2666
+ // the recording was finished and in the wrong place, and the last step
2667
+ // was moving files by hand. In write mode the server that already owns
2668
+ // the deck file writes them itself.
2669
+ //
2670
+ // Ahead of the shared body read below because this body is BINARY and
2671
+ // megabytes of it: a slide of speech is ~48 kB a second, so the string
2672
+ // concat and its 1 MB ceiling would both be wrong.
2673
+ async function recordRoute({ req, url, json }) {
2674
+ const slide = Number(url.searchParams.get('slide'));
2675
+ const kind = url.searchParams.get('kind');
2676
+ if (!Number.isInteger(slide) || slide < 1 || slide > 9999) return json(400, { ok: false, error: 'bad slide' });
2677
+ if (kind !== 'wav' && kind !== 'visemes' && kind !== 'manifest') return json(400, { ok: false, error: 'bad kind' });
2678
+ // `seg` is the per-⟨CLICK⟩ file number — the audio that lets a recording
2679
+ // step the builds (slide-NN-KK.wav) and the viseme timeline cut to
2680
+ // match it (slide-NN-KK.visemes.json). Absent means the whole slide.
2681
+ // Bounded and integral like `slide`, and for the same reason: it is
2682
+ // half of a filename this server builds, and the only defence that
2683
+ // survives someone deciding the name should be more flexible one day.
2684
+ const segRaw = url.searchParams.get('seg');
2685
+ const seg = segRaw == null ? null : Number(segRaw);
2686
+ if (seg !== null && (!Number.isInteger(seg) || seg < 1 || seg > 999)) {
2687
+ return json(400, { ok: false, error: 'bad seg' });
2688
+ }
2689
+ // The player names the FOLDER (its own `narration.files`, so a recorded
2690
+ // set lands where that deck already plays from) and nothing else: the
2691
+ // file name is built here, so no request can choose one. The folder is
2692
+ // contained to the served root by the same rule staticFiles reads by —
2693
+ // and `..`, absolute paths and Windows drive letters are refused before
2694
+ // it, because `resolve` would happily swallow all three.
2695
+ const want = url.searchParams.get('dir') || 'voiceover';
2696
+ const bad = want.length > 200 || /^[/\\]/.test(want) || /^[a-zA-Z]:/.test(want)
2697
+ || want.split(/[/\\]/).includes('..');
2698
+ const dir = bad ? null : resolve(deckPath, '..', want);
2699
+ if (!dir || (!dir.startsWith(root + sep) && dir !== root)) {
2700
+ return json(400, { ok: false, error: 'the recording folder must sit inside the deck\'s own directory' });
2701
+ }
2702
+ const name = `slide-${String(slide).padStart(2, '0')}`
2703
+ + (seg === null ? '' : `-${String(seg).padStart(2, '0')}`)
2704
+ + `.${kind === 'wav' ? 'wav' : 'visemes.json'}`;
2705
+ const chunks = [];
2706
+ let size = 0;
2707
+ for await (const chunk of req) {
2708
+ size += chunk.length;
2709
+ if (size > 64e6) return json(413, { ok: false, error: 'recording too large' });
2710
+ chunks.push(chunk);
2711
+ }
2712
+ // The take's manifest (#535), so a folder the deck recorded is a track
2713
+ // `decklight video` renders from, the export offers and the picker
2714
+ // refreshes into — the shape tools/voiceover.mjs writes, hashed the same
2715
+ // way. The runtime says WHICH slides it recorded and their beat numbers;
2716
+ // the notes each hash covers are read from the deck file here, the way
2717
+ // voiceover and video read them, so the three can never disagree on the
2718
+ // text. Written after every slide, so an aborted take is a valid partial.
2719
+ if (kind === 'manifest') {
2720
+ if (size > 1e6) return json(413, { ok: false, error: 'manifest too large' });
2721
+ let req2;
2722
+ try { req2 = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return json(400, { ok: false, error: 'the manifest is not JSON' }); }
2723
+ const str = (v, max = 120) => (typeof v === 'string' && v.length <= max && /^[\w .:+()'-]*$/.test(v) ? v : null);
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' });
2731
+ const from = Number(req2.range?.[0]), to = Number(req2.range?.[1]);
2732
+ if (!Number.isInteger(from) || !Number.isInteger(to) || from < 1 || to < from || to > 9999) return json(400, { ok: false, error: 'bad range' });
2733
+ const recorded = {};
2734
+ for (const [k, v] of Object.entries(req2.slides ?? {})) {
2735
+ const n = Number(k);
2736
+ if (!Number.isInteger(n) || n < from || n > to) continue;
2737
+ recorded[n] = { segments: Array.isArray(v?.segments) ? v.segments.map(Number) : [] };
1166
2738
  }
1167
- // ── committing on the author's word (SPEC PRESENTING) ─────────────────
1168
- // What is uncommitted, right now. The overlay opens on this rather than
1169
- // on whatever the last SSE event said, because K can be pressed at any
1170
- // moment and a stale count is a lie about what you are agreeing to.
1171
- if (req.method === 'GET' && url.pathname === '/edit/commit') {
1172
- if (gitOn) measureDirty(); // the answer must be about NOW, not the last tick
1173
- return json(200, { ok: true, ...commitState(), deck: deckRel });
2739
+ const { recorderManifest, slideTexts, slideBeats } = await import('../tools/narration-manifest.mjs');
2740
+ let prev = null;
2741
+ try { prev = JSON.parse(readFileSync(resolve(dir, 'manifest.json'), 'utf8')); } catch { /* first take here */ }
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);
1174
2749
  }
1175
- // A subject for work that is not committed yet — the overlay's "write one
1176
- // for me". Gated on the same permission as every other diff that leaves
1177
- // the machine: no `--commit-messages`, no ask.
1178
- if (req.method === 'POST' && url.pathname === '/edit/commit/subject') {
1179
- if (!wantMessages) {
1180
- return json(403, { ok: false, error: 'commit subjects are not enabled — decklight author --commit-messages' });
1181
- }
1182
- const subject = await describeWorking({
1183
- cwd: root, deckPath, deckRel, agent: agentPref,
1184
- template: `decklight: autosave ${basename(deckPath)}`,
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
+ });
2755
+ try {
2756
+ mkdirSync(dir, { recursive: true });
2757
+ writeFileSync(resolve(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
2758
+ // the script beside each file, as voiceover writes it — `--reuse-text` reads it back
2759
+ const texts = slideTexts(readDeck());
2760
+ for (const n of Object.keys(recorded)) writeFileSync(resolve(dir, `slide-${String(n).padStart(2, '0')}.txt`), texts[n - 1] ?? '');
2761
+ } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
2762
+ return json(200, { ok: true, dir: want, file: 'manifest.json', slides: manifest.slides.filter(Boolean).length });
2763
+ }
2764
+ try {
2765
+ mkdirSync(dir, { recursive: true });
2766
+ writeFileSync(resolve(dir, name), Buffer.concat(chunks));
2767
+ } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
2768
+ console.log(` recorded ${want}/${name} (${Math.round(size / 1024)} kB)`);
2769
+ return json(200, { ok: true, dir: want, file: name });
2770
+ }
2771
+
2772
+ // What tracks already sit next to this deck. The runtime cannot see the
2773
+ // filesystem — which is why `segments: true` is opt-in at all — so it
2774
+ // cannot know that `voices/rachel` is taken before proposing it. One
2775
+ // question, asked when a recorder opens.
2776
+ function tracksRoute({ json }) {
2777
+ const root2 = resolve(deckPath, '..');
2778
+ const seen = [];
2779
+ const deck = readDeck();
2780
+ const texts = slideTexts(deck);
2781
+ const prior = priorSlideTexts(deck);
2782
+ const look = (rel) => {
2783
+ let entries;
2784
+ try { entries = readdirSync(resolve(root2, rel), { withFileTypes: true }); } catch { return; }
2785
+ const wav = entries.filter((e) => e.isFile() && /^slide-\d+(-\d+)?\.(wav|m4a|mp3)$/.test(e.name));
2786
+ if (wav.length) {
2787
+ let engine = null; let voice = null; let manifest = false; let stale = 0; let mine = false;
2788
+ let drift = [];
2789
+ try {
2790
+ const m = JSON.parse(readFileSync(resolve(root2, rel, 'manifest.json'), 'utf8'));
2791
+ engine = m.engine ?? null; voice = m.voice ?? null; manifest = true; mine = m.recorder === 'mic';
2792
+ // how many of its slides were voiced from other notes than the deck
2793
+ // has now — the export card marks the track with it (#536)
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
+ }
2800
+ } catch { /* a folder recorded by hand has no manifest, and needs none */ }
2801
+ seen.push({
2802
+ dir: rel.split(sep).join('/'),
2803
+ files: wav.length,
2804
+ // the beats are what let a track pace the builds, so whether it
2805
+ // has them is the one fact worth reporting beside the count
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),
2811
+ ext: (wav[0].name.split('.').pop()),
2812
+ engine,
2813
+ voice,
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)),
2821
+ stale,
1185
2822
  });
1186
- return json(200, { ok: true, subject: subject ?? null });
1187
2823
  }
1188
- if (req.method === 'POST' && url.pathname === '/edit/commit/dismiss') {
1189
- // Not the same as committing: the work stays uncommitted and the
1190
- // snapshot keeps running. It only means "stop asking about THIS one".
1191
- nagDismissed = true;
1192
- return json(200, { ok: true, ...commitState() });
2824
+ return entries;
2825
+ };
2826
+ for (const e of look('.') ?? []) {
2827
+ if (!e.isDirectory() || e.name.startsWith('.') || e.name === 'node_modules') continue;
2828
+ const kids = look(e.name) ?? [];
2829
+ // one more level, because the convention is voices/<voice>
2830
+ for (const k of kids) {
2831
+ if (k.isDirectory() && !k.name.startsWith('.')) look(`${e.name}${sep}${k.name}`);
1193
2832
  }
1194
- if (req.method === 'GET' && url.pathname === '/edit/events') {
1195
- clients.add(req, res, CORS);
2833
+ }
2834
+ return json(200, { ok: true, tracks: seen });
2835
+ }
2836
+
2837
+ // ── AI agents — the one-shot editing task behind A ───────────────────────
2838
+
2839
+ // Remember which agent A should reach for (#125, SPEC AGENT_UNITS). A
2840
+ // preference is a choice about this machine, not about the deck, so it
2841
+ // is written beside the unit library and never into the file.
2842
+ function agentPreferRoute({ body, json }) {
2843
+ const { agent } = JSON.parse(body);
2844
+ if (agent !== null && typeof agent !== 'string') throw new Error('bad payload');
2845
+ if (agent && !agents.some((a) => a.name === agent)) {
2846
+ return json(400, { ok: false, error: agentUnavailable(agent, agents) });
2847
+ }
2848
+ setPreferredAgent(agent);
2849
+ agentPref = agent ?? undefined;
2850
+ console.log(` agent: ${agent ? `${agent} remembered as preferred` : 'preference cleared'}`);
2851
+ return json(200, { ok: true, preferredAgent: agent ?? null });
2852
+ }
2853
+
2854
+ // The voiceover script, given ElevenLabs v4's audio tags (cli/enhance.mjs):
2855
+ // the agent drafts, read-only, a few slides at a time; decklight checks each
2856
+ // answer kept the words and beats, and writes them in ONE edit so Z takes
2857
+ // the whole run back. Progress rides the SSE channel as 'enhance' events.
2858
+ async function enhanceRoute({ body, json }) {
2859
+ const { slides, agent, kind: asked } = JSON.parse(body);
2860
+ const kind = asked === 'spoken' ? 'spoken' : 'tags';
2861
+ const which = slides === 'all' ? null
2862
+ : Array.isArray(slides) && slides.length && slides.every((n) => Number.isInteger(n) && n > 0) ? slides : undefined;
2863
+ if (which === undefined) throw new Error('bad payload');
2864
+ if (enhancing) return json(409, { ok: false, error: `already enhancing — ${enhancing.done} of ${enhancing.of} slides done` });
2865
+ if (reviewing) return json(409, { ok: false, error: 'the agent is reviewing the deck — wait for it to finish' });
2866
+ if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is editing the deck — wait for it to finish` });
2867
+ const name = agent ?? agentPref ?? null;
2868
+ const cmd = agentAsk(name, 'x');
2869
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(name, agents) });
2870
+ const { enhanceDeck, applyEnhanced, enhanceable, KINDS } = await import('./enhance.mjs');
2871
+ const verb = KINDS[kind].done;
2872
+ const html = readDeck();
2873
+ const of = enhanceable(html, which).length;
2874
+ if (!of) return json(422, { ok: false, error: which?.length === 1 ? `slide ${which[0]} has no notes to enhance` : 'no notes to enhance' });
2875
+ const stop = new AbortController();
2876
+ enhancing = { of, done: 0, stop: () => stop.abort() };
2877
+ broadcast('enhance', { state: 'start', of, agent: cmd.name, kind });
2878
+ console.log(` enhance: ${of} slide${of === 1 ? '' : 's'}${kind === 'spoken' ? ', written for the ear' : ''} ← ${cmd.name} (read-only)`);
2879
+ enhanceDeck(html, which, {
2880
+ kind, agent: name, cwd: dirname(deckPath), signal: stop.signal,
2881
+ onSlide: (r) => {
2882
+ enhancing.done = r.done;
2883
+ broadcast('enhance', { state: 'slide', ...r });
2884
+ console.log(` enhance: slide ${r.slide} ${r.ok ? (r.changed ? verb : 'unchanged') : `left as it was — ${r.why}`}`);
2885
+ },
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');
1196
2894
  return;
1197
2895
  }
1198
- // ── the deck's durable history (#129): what the R overlay reads ────
1199
- // Loopback-only like every other /edit/* path: this serves arbitrary
1200
- // historical revisions of the deck, which is nobody else's business.
1201
- if (req.method === 'GET' && url.pathname === '/edit/history') {
1202
- if (!gitOn) return json(409, { ok: false, error: 'git is off for this session — there is no history' });
1203
- try {
1204
- // One round trip serves the whole overlay: the commits, which of them
1205
- // exist nowhere but this machine, and where the branch stands. All of
1206
- // it is a LOCAL read — `unpushed` and `@{u}` read remote-tracking
1207
- // refs, so opening the history never touches the network (SPEC
1208
- // PRESENTING).
1209
- // `slides` is what that version WAS, `add`/`del` what it CHANGED —
1210
- // the two questions a hash and a subject cannot answer, and the ones
1211
- // that tell "tightened the wording" apart from "cut four slides"
1212
- // before you restore it rather than after.
1213
- const entries = decorateHistory(deckHistory(deckPath, root), deckPath, root);
1214
- const remote = remoteState(root);
1215
- // `pushed` is null for "not a question worth answering here", and the
1216
- // two cases are different: git could not tell us, or there is no
1217
- // remote at all — in which case EVERY commit is unpushed and marking
1218
- // all of them is a wall of arrows saying what the footer says once.
1219
- const local = ['no-remote', 'ambiguous-remote'].includes(remote.state) ? null : unpushed(root);
1220
- const set = local ? new Set(local) : null;
1221
- for (const e of entries) e.pushed = set ? !set.has(e.full) : null;
1222
- // The LINE is computed here, not in the player: cli/git.mjs is Node
1223
- // (it spawns git), the runtime has zero dependencies and cannot
1224
- // import it, and duplicating the wording in the browser is how the
1225
- // four places that talk about unpushed work start disagreeing.
1226
- return json(200, { ok: true, entries, remote: { ...remote, line: remoteLine(remote) } });
1227
- } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1228
- }
1229
- if (req.method === 'GET' && url.pathname === '/edit/at') {
1230
- if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
1231
- try {
1232
- // <base href="/"> because this is served from /edit/, not the root:
1233
- // without it every relative ../dist and ./casts path in the deck
1234
- // would resolve one directory too deep and the preview would be bare.
1235
- const html = withBaseHref(deckAt(deckPath, url.searchParams.get('ref') || '', root));
1236
- res.writeHead(200, { ...CORS, 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' });
1237
- return res.end(html);
1238
- } catch {
1239
- res.writeHead(404, { ...CORS, 'content-type': 'text/plain' });
1240
- return res.end('no such revision of this deck');
1241
- }
1242
- }
1243
- // ── element edit mode (E, right-click a slide element) — #112 ─────
1244
- // Reads the element's outerHTML fresh from the FILE, never the live
1245
- // DOM: the engine mutates elements in place (pinned-title classes,
1246
- // namespaced SVG ids, chart/code/math subtree replacement), so the DOM
1247
- // the player sees is not what a Save should write back over.
1248
- if (req.method === 'GET' && url.pathname === '/edit/element/source') {
1249
- const slide = Number(url.searchParams.get('slide'));
1250
- const index = Number(url.searchParams.get('index'));
1251
- if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) {
1252
- return json(400, { ok: false, error: 'bad payload' });
1253
- }
1254
- try {
1255
- const { parts, idx, r } = locateElement(readDeck(), slide, index);
1256
- return json(200, { ok: true, html: parts[idx].slice(r.start, r.end) });
1257
- } catch (e) {
1258
- return json(404, { ok: false, error: oneline(e) });
1259
- }
1260
- }
2896
+ let stale = [];
2897
+ // against the deck as it is NOW: a slide edited while the agent thought keeps the edit
2898
+ applyEdit((cur) => { const a = applyEnhanced(cur, answers); stale = a.stale; return a.html; });
2899
+ const changed = results.filter((r) => r.changed && !stale.includes(r.slide)).map((r) => r.slide);
2900
+ const failed = results.filter((r) => !r.ok).map(({ slide, why }) => ({ slide, why }));
2901
+ enhancing = null;
2902
+ broadcast('enhance', { state: 'done', ok: true, changed, failed, stale, kind });
2903
+ console.log(` enhance: done — ${changed.length} ${verb}${failed.length ? `, ${failed.length} left as they were` : ''}`);
2904
+ }).catch((e) => {
2905
+ enhancing = null;
2906
+ broadcast('enhance', { state: 'done', ok: false, error: oneline(e), kind });
2907
+ });
2908
+ return json(200, { ok: true, of, agent: cmd.name, label: cmd.label, kind });
2909
+ }
1261
2910
 
1262
- if (req.method === 'POST' && url.pathname === '/edit/shutdown') {
1263
- res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
1264
- res.end(JSON.stringify({ ok: true }));
1265
- // same shutdown a Ctrl-C takes — final autocommit, then actually exit —
1266
- // once the response has cleared the socket, so the asker sees it land
1267
- res.once('finish', () => { finalCommit(); process.exit(0); });
2911
+ // The notes editor's one box, enhanced without touching the file: the text
2912
+ // goes to the agent (read-only) and comes back checked, for the author to
2913
+ // read and save — or not. Nothing here writes; ⌘⏎ in the editor does.
2914
+ async function enhanceTextRoute({ body, json }) {
2915
+ const { text, agent, kind: asked } = JSON.parse(body);
2916
+ const kind = asked === 'spoken' ? 'spoken' : 'tags';
2917
+ if (typeof text !== 'string') throw new Error('bad payload');
2918
+ if (!text.trim()) return json(422, { ok: false, error: `nothing to ${kind === 'spoken' ? 'rewrite' : 'enhance'} — the notes are empty` });
2919
+ const name = agent ?? agentPref ?? null;
2920
+ const cmd = agentAsk(name, 'x');
2921
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(name, agents) });
2922
+ const { enhanceText } = await import('./enhance.mjs');
2923
+ console.log(` enhance: the notes editor's text${kind === 'spoken' ? ', written for the ear' : ''} ← ${cmd.name} (read-only)`);
2924
+ const r = await enhanceText(text, { kind, agent: name, cwd: dirname(deckPath) });
2925
+ return r.ok
2926
+ ? json(200, { ok: true, text: r.text, changed: r.changed, agent: cmd.name, label: cmd.label })
2927
+ : json(422, { ok: false, error: r.why, agent: cmd.name });
2928
+ }
2929
+
2930
+ // The agent review (cli/agent-review.mjs): the agent reads the deck,
2931
+ // read-only, a few slides at a time, against the rules in REVIEW_RULES;
2932
+ // every answer is checked before it is kept. Nothing here writes: a finding
2933
+ // is fixed by the author's own `f` in Check deck…, which is an ordinary A
2934
+ // edit through agentRoute. Progress rides the SSE channel as 'review' events.
2935
+ async function reviewRoute({ body, json }) {
2936
+ const { agent } = JSON.parse(body || '{}');
2937
+ if (reviewing) return json(409, { ok: false, error: `already reviewing — ${reviewing.done} of ${reviewing.of} batches done` });
2938
+ if (enhancing) return json(409, { ok: false, error: 'the voiceover is being enhanced — wait for it to finish' });
2939
+ if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is editing the deck — wait for it to finish` });
2940
+ const name = agent ?? agentPref ?? null;
2941
+ const cmd = agentAsk(name, 'x');
2942
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(name, agents) });
2943
+ const { reviewDeck, reviewSlides, REVIEW_BATCH } = await import('./agent-review.mjs');
2944
+ const html = readDeck();
2945
+ const of = Math.ceil(reviewSlides(html).length / REVIEW_BATCH);
2946
+ if (!of) return json(422, { ok: false, error: 'no slides to review' });
2947
+ const stop = new AbortController();
2948
+ reviewing = { of, done: 0, stop: () => stop.abort() };
2949
+ broadcast('review', { state: 'start', of, agent: cmd.name });
2950
+ console.log(` review: ${of} batch${of === 1 ? '' : 'es'} ← ${cmd.name} (read-only)`);
2951
+ reviewDeck(html, {
2952
+ agent: name, cwd: dirname(deckPath), signal: stop.signal,
2953
+ onBatch: (r) => { reviewing.done = r.done; broadcast('review', { state: 'batch', ...r }); },
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');
1268
2961
  return;
1269
2962
  }
1270
- if (req.method === 'POST' && /^\/edit\/(undo|redo)$/.test(url.pathname)) {
1271
- const dir = url.pathname.endsWith('undo') ? 'undo' : 'redo';
1272
- const cur = readDeck();
1273
- const content = history[dir](cur);
1274
- if (content === null) return json(409, { ok: false, error: `nothing to ${dir}`, ...history.counts() });
1275
- writeFileSync(deckPath, content);
1276
- console.log(` ${dir} → ${JSON.stringify(history.counts())}`);
1277
- return json(200, { ok: true, ...history.counts() });
1278
- }
1279
- // ── the recorder's offline recordings — V → Record this deck… (PRESENTING) ───────────────────────────────
1280
- // The player used to hand every stitched slide to the browser's DOWNLOAD
1281
- // path, which is why a deck's voice arrived as thirty slide-NN.wav in
1282
- // whatever folder the OS calls Downloads — never the deck's, and on
1283
- // Windows not even near it. `bundle` only ever looks NEXT TO THE DECK, so
1284
- // the recording was finished and in the wrong place, and the last step
1285
- // was moving files by hand. In author mode the server that already owns
1286
- // the deck file writes them itself.
1287
- //
1288
- // Ahead of the shared body read below because this body is BINARY and
1289
- // megabytes of it: a slide of speech is ~48 kB a second, so the string
1290
- // concat and its 1 MB ceiling would both be wrong.
1291
- if (req.method === 'POST' && url.pathname === '/edit/record') {
1292
- const slide = Number(url.searchParams.get('slide'));
1293
- const kind = url.searchParams.get('kind');
1294
- if (!Number.isInteger(slide) || slide < 1 || slide > 9999) return json(400, { ok: false, error: 'bad slide' });
1295
- if (kind !== 'wav' && kind !== 'visemes') return json(400, { ok: false, error: 'bad kind' });
1296
- // `seg` is the per-⟨CLICK⟩ file number — the audio that lets a recording
1297
- // step the builds (slide-NN-KK.wav) and the viseme timeline cut to
1298
- // match it (slide-NN-KK.visemes.json). Absent means the whole slide.
1299
- // Bounded and integral like `slide`, and for the same reason: it is
1300
- // half of a filename this server builds, and the only defence that
1301
- // survives someone deciding the name should be more flexible one day.
1302
- const segRaw = url.searchParams.get('seg');
1303
- const seg = segRaw == null ? null : Number(segRaw);
1304
- if (seg !== null && (!Number.isInteger(seg) || seg < 1 || seg > 999)) {
1305
- return json(400, { ok: false, error: 'bad seg' });
1306
- }
1307
- // The player names the FOLDER (its own `narration.files`, so a recorded
1308
- // set lands where that deck already plays from) and nothing else: the
1309
- // file name is built here, so no request can choose one. The folder is
1310
- // contained to the served root by the same rule staticFiles reads by —
1311
- // and `..`, absolute paths and Windows drive letters are refused before
1312
- // it, because `resolve` would happily swallow all three.
1313
- const want = url.searchParams.get('dir') || 'voiceover';
1314
- const bad = want.length > 200 || /^[/\\]/.test(want) || /^[a-zA-Z]:/.test(want)
1315
- || want.split(/[/\\]/).includes('..');
1316
- const dir = bad ? null : resolve(deckPath, '..', want);
1317
- if (!dir || (!dir.startsWith(root + sep) && dir !== root)) {
1318
- return json(400, { ok: false, error: 'the recording folder must sit inside the deck\'s own directory' });
1319
- }
1320
- const name = `slide-${String(slide).padStart(2, '0')}`
1321
- + (seg === null ? '' : `-${String(seg).padStart(2, '0')}`)
1322
- + `.${kind === 'wav' ? 'wav' : 'visemes.json'}`;
1323
- const chunks = [];
1324
- let size = 0;
1325
- for await (const chunk of req) {
1326
- size += chunk.length;
1327
- if (size > 64e6) return json(413, { ok: false, error: 'recording too large' });
1328
- chunks.push(chunk);
1329
- }
1330
- try {
1331
- mkdirSync(dir, { recursive: true });
1332
- writeFileSync(resolve(dir, name), Buffer.concat(chunks));
1333
- } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1334
- console.log(` recorded ${want}/${name} (${Math.round(size / 1024)} kB)`);
1335
- return json(200, { ok: true, dir: want, file: name });
1336
- }
1337
- let body = '';
1338
- if (req.method === 'POST') {
1339
- for await (const chunk of req) { body += chunk; if (body.length > 1e6) throw new Error('too large'); }
1340
- }
1341
- // The commit the author asked for. The subject is THEIRS — typed, or an
1342
- // agent's sentence they looked at and kept — so it goes through
1343
- // `commitSubject` like every other message that reaches a command line
1344
- // (one line, capped, never a leading `-`) and nothing else rewrites it:
1345
- // `describeCommit`'s amend is for messages decklight authored, and this
1346
- // one has an author.
1347
- if (req.method === 'POST' && url.pathname === '/edit/commit') {
1348
- if (!gitOn) return json(409, { ok: false, error: 'this session is not committing — start author with --git' });
1349
- let msg = '';
1350
- try { msg = String(JSON.parse(body || '{}').message ?? '').trim(); } catch { /* below */ }
1351
- if (!msg) return json(400, { ok: false, error: 'a commit needs a message' });
1352
- const subject = commitSubject(msg, `decklight: autosave ${basename(deckPath)}`);
1353
- // gitAutocommit reports false for "nothing to commit", which is not an
1354
- // error: it is the answer to pressing K twice.
1355
- const made = gitAutocommit(deckPath, root, subject);
1356
- if (!made) return json(200, { ok: true, committed: false, ...commitState() });
1357
- resetEpisode();
1358
- console.log(` git: committed ${deckRel} — "${subject}"`);
1359
- return json(200, {
1360
- ok: true, committed: true, subject, ...history.counts(), ...commitState(),
1361
- });
1362
- }
1363
- // ── review comments (SPEC REVIEW) ─────────────────────────────
1364
- // The author's side of `decklight review`. The same file, the same
1365
- // append-only rule: this server may add a line (a resolve, a reply) and
1366
- // may not rewrite one, because `merge=union` is what keeps two reviewers
1367
- // from conflicting and an edit in place is what would break it.
1368
- if (req.method === 'GET' && url.pathname === '/edit/review') {
1369
- const store = reviewPathFor(deckPath);
1370
- if (!existsSync(store)) return json(200, { ok: true, records: [], skipped: 0 });
1371
- const { records, skipped } = parseReview(readFileSync(store, 'utf8'));
1372
- return json(200, { ok: true, records, skipped });
1373
- }
1374
- // What reviews are waiting on the remote — the M overlay's incoming
1375
- // section. This one is a fetch the author DID ask for: it runs behind
1376
- // the keypress that just opened the overlay, on demand and nowhere else.
1377
- // The 60s cache is what keeps a nervous author tapping M from turning
1378
- // one gesture into a fetch storm; the off switches still win outright.
1379
- if (req.method === 'GET' && url.pathname === '/edit/review/incoming') {
1380
- // ci: false — this fetch is ASKED FOR, behind the keypress that
1381
- // opened the overlay; only the explicit switches silence it.
1382
- const skipped = reviewCheckSuppressed({ args, ci: false });
1383
- if (skipped) return json(200, { ok: true, state: 'suppressed', reason: skipped, reviews: [] });
1384
- if (!incomingCache || Date.now() - incomingCache.at > 60_000) {
1385
- const r = await reviewsWaiting(deckPath);
1386
- incomingCache = { at: Date.now(), r };
1387
- }
1388
- return json(200, { ok: true, ...incomingCache.r });
1389
- }
1390
- // What tracks already sit next to this deck. The runtime cannot see the
1391
- // filesystem — which is why `segments: true` is opt-in at all — so it
1392
- // cannot know that `voices/rachel` is taken before proposing it. One
1393
- // question, asked when a recorder opens.
1394
- if (req.method === 'GET' && url.pathname === '/edit/tracks') {
1395
- const root2 = resolve(deckPath, '..');
1396
- const seen = [];
1397
- const look = (rel) => {
1398
- let entries;
1399
- try { entries = readdirSync(resolve(root2, rel), { withFileTypes: true }); } catch { return; }
1400
- const wav = entries.filter((e) => e.isFile() && /^slide-\d+(-\d+)?\.(wav|m4a|mp3)$/.test(e.name));
1401
- if (wav.length) {
1402
- let engine = null; let voice = null;
1403
- try {
1404
- const m = JSON.parse(readFileSync(resolve(root2, rel, 'manifest.json'), 'utf8'));
1405
- engine = m.engine ?? null; voice = m.voice ?? null;
1406
- } catch { /* a folder recorded by hand has no manifest, and needs none */ }
1407
- seen.push({
1408
- dir: rel.split(sep).join('/'),
1409
- files: wav.length,
1410
- // the beats are what let a track pace the builds, so whether it
1411
- // has them is the one fact worth reporting beside the count
1412
- segments: wav.some((e) => /^slide-\d+-\d+\./.test(e.name)),
1413
- ext: (wav[0].name.split('.').pop()),
1414
- engine,
1415
- voice,
1416
- });
1417
- }
1418
- return entries;
1419
- };
1420
- for (const e of look('.') ?? []) {
1421
- if (!e.isDirectory() || e.name.startsWith('.') || e.name === 'node_modules') continue;
1422
- const kids = look(e.name) ?? [];
1423
- // one more level, because the convention is voices/<voice>
1424
- for (const k of kids) {
1425
- if (k.isDirectory() && !k.name.startsWith('.')) look(`${e.name}${sep}${k.name}`);
1426
- }
1427
- }
1428
- return json(200, { ok: true, tracks: seen });
1429
- }
1430
- // Point the deck at a track the recorder just wrote. The one manual step
1431
- // in a flow that is otherwise a key and an arrow — and this server
1432
- // already owns the file, so it can take that step too.
1433
- if (req.method === 'GET' && url.pathname === '/edit/review/at') {
1434
- // The orphan's context: what the slide SAID when the comment was
1435
- // written — `comments --at`, served, so the overlay can put the dead
1436
- // slide's prose under the objection that was about it. Read-only, all
1437
- // local (the commit is already in this clone or the answer is "not
1438
- // here"), and gated exactly as the CLI gates it.
1439
- const id = url.searchParams.get('id') ?? '';
1440
- if (!/^[a-z0-9]{1,12}$/.test(id)) return json(400, { ok: false, error: 'bad comment id' });
1441
- const store = reviewPathFor(deckPath);
1442
- if (!existsSync(store)) return json(404, { ok: false, error: 'no comments here' });
1443
- const c = foldReview(parseReview(readFileSync(store, 'utf8')).records).find((x) => x.id === id);
1444
- if (!c) return json(404, { ok: false, error: `no comment [${id}]` });
1445
- if (!c.deck) return json(200, { ok: true, known: false, why: 'written outside a repository — there is no earlier version to show' });
1446
- if (!gitOn || !knowsCommit(c.deck, root)) {
1447
- return json(200, { ok: true, known: false, why: `this clone does not have ${c.deck}` });
1448
- }
1449
- try {
1450
- const thenHtml = deckAt(deckPath, c.deck, root);
1451
- const wasAt = indexDeckFile(thenHtml)[(c.slide ?? 0) - 1] ?? null;
1452
- return json(200, {
1453
- ok: true,
1454
- known: true,
1455
- deck: c.deck,
1456
- slide: c.slide ?? null,
1457
- title: wasAt?.title ?? null,
1458
- text: slideTextOf(thenHtml, c.slide) || '',
1459
- });
1460
- } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1461
- }
1462
- if (req.method === 'POST' && url.pathname === '/edit/review/done') {
1463
- // Mark ONE of a reviewer's comments done, or take the mark off. Their
1464
- // comments live on their branch, which is not ours to write, so the
1465
- // mark is kept in this clone's git config — private, never pushed.
1466
- // Your OWN comments do not come through here at all: they already have
1467
- // a way to be finished with, the append-only `resolve` record below,
1468
- // which travels so the reviewer can see you dealt with their point.
1469
- //
1470
- // The branch is looked up in what the incoming reader LISTED, so it is
1471
- // data here and never an argument; the id is shape-checked before it
1472
- // becomes half of a config key.
1473
- const { branch, id, done = true } = JSON.parse(body || '{}');
1474
- const listed = incomingCache?.r?.reviews?.find((v) => v.branch === branch);
1475
- if (!listed) return json(400, { ok: false, error: 'not a review this deck knows about — press M again to refresh' });
1476
- if (!listed.records?.some((r) => r.id === id)) {
1477
- return json(400, { ok: false, error: 'no such comment in that review' });
1478
- }
1479
- if (!setCommentDone(root, branch, id, !!done)) {
1480
- return json(500, { ok: false, error: 'could not write the mark to git config' });
1481
- }
1482
- // the list just changed shape — the cache must not keep the old marks
1483
- incomingCache = null;
1484
- console.log(` review: ${branch} ${id} ${done ? 'marked done' : 'reopened'}`);
1485
- return json(200, { ok: true, branch, id, done: !!done });
2963
+ lastReview = { at: Date.now(), agent: cmd.name, findings, failed };
2964
+ reviewing = null;
2965
+ broadcast('review', { state: 'done', ok: true, found: findings.length, failed });
2966
+ console.log(` review: done — ${findings.length} finding${findings.length === 1 ? '' : 's'}${failed.length ? `, ${failed.length} batch${failed.length === 1 ? '' : 'es'} unanswered` : ''}`);
2967
+ }).catch((e) => {
2968
+ reviewing = null;
2969
+ broadcast('review', { state: 'done', ok: false, error: oneline(e) });
2970
+ });
2971
+ return json(200, { ok: true, of, agent: cmd.name, label: cmd.label });
2972
+ }
2973
+
2974
+ // The last review's findings, against the deck as it is NOW: a slide that
2975
+ // moved keeps its findings, one that was edited (fixed) drops them. Each
2976
+ // carries the instruction `f` hands the A agent, built here because the
2977
+ // rules and their wording live on this side.
2978
+ async function reviewFindingsRoute({ json }) {
2979
+ if (!lastReview) return json(200, { ok: true, reviewed: false, running: !!reviewing, findings: [] });
2980
+ const { currentFindings, fixPrompt, REVIEW_RULES } = await import('./agent-review.mjs');
2981
+ const label = Object.fromEntries(REVIEW_RULES.map((r) => [r.id, r.label]));
2982
+ const findings = currentFindings(readDeck(), lastReview.findings)
2983
+ .map(({ fp, ...f }) => ({ ...f, label: label[f.rule], prompt: fixPrompt(f) }));
2984
+ return json(200, { ok: true, reviewed: true, running: !!reviewing, at: lastReview.at, agent: lastReview.agent, findings, failed: lastReview.failed });
2985
+ }
2986
+
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);
3037
+ if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('bad payload');
3038
+ if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is already running` });
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 });
3043
+ const cmd = runAgent(prompt.trim(), agent, message, slide);
3044
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(agent ?? agentPref, agents) });
3045
+ return json(200, { ok: true, agent: cmd.name, label: cmd.label });
3046
+ }
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');
1486
3172
  }
1487
- if (req.method === 'POST' && url.pathname === '/edit/review') {
1488
- const { op, re, body: text, slide, title, fp } = JSON.parse(body || '{}');
1489
- // A NEW comment — no `op`, no `re`. The author leaving one on their own
1490
- // deck (⇧M), which until now only a `decklight review` server could
1491
- // take: the composer was gated on one answering, so an author had to
1492
- // start a second server on a second port, in a mode that would not let
1493
- // them edit the slide they were commenting on.
1494
- //
1495
- // Same file, same append-only rule, same record shape — through
1496
- // `commentProblem` and `reviewRecord`, which review.mjs already exports
1497
- // and which are the arbiters of what a comment is. Two servers writing
1498
- // two shapes into one union-merged file is how a store stops parsing.
1499
- if (op === undefined && re === undefined) {
1500
- const input = { body: text, slide, title, fp };
1501
- const bad = commentProblem(input);
1502
- if (bad) return json(400, { ok: false, error: bad });
1503
- let deckAt = null;
1504
- try { deckAt = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(); }
1505
- catch { deckAt = null; }
1506
- const rec = reviewRecord(input, {
1507
- by: reviewerName(), at: new Date().toISOString(), deck: deckAt, id: newId(),
1508
- });
1509
- const store_ = reviewPathFor(deckPath);
1510
- try { appendFileSync(store_, `${serializeRecord(rec)}\n`); }
1511
- catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1512
- if (gitOn) {
1513
- gitAutocommit(store_, root,
1514
- commitSubject(`review: ${rec.body}`, `review: a comment on ${basename(deckPath)}`));
1515
- }
1516
- console.log(` review: comment on slide ${rec.slide} → ${basename(store_)}`);
1517
- return json(200, { ok: true, id: rec.id });
1518
- }
1519
- if (typeof re !== 'string' || !/^[a-z0-9]{1,12}$/.test(re)) {
1520
- return json(400, { ok: false, error: 'bad comment id' });
1521
- }
1522
- if (op === 'anchor') {
1523
- // moving a comment to the slide the author is looking at — the
1524
- // reconciliation for a slide that was deleted or rewritten past
1525
- // what fingerprint + title can find
1526
- const n = Number(slide);
1527
- if (!Number.isInteger(n) || n < 1 || n > 9999) return json(400, { ok: false, error: 'an anchor needs a slide' });
1528
- if (title !== undefined && (typeof title !== 'string' || title.length > 500)) return json(400, { ok: false, error: 'bad title' });
1529
- if (fp !== undefined && (typeof fp !== 'string' || !/^[0-9a-f]{1,16}$/.test(fp))) return json(400, { ok: false, error: 'bad fingerprint' });
1530
- } else if (op !== 'resolve' && !(typeof text === 'string' && text.trim() && text.length <= 4000)) {
1531
- return json(400, { ok: false, error: 'a reply needs something in it' });
1532
- }
1533
- const store = reviewPathFor(deckPath);
1534
- // A reply is a new statement about the deck and carries which version it
1535
- // was made against, exactly as a comment does. A resolve does not: it is
1536
- // about the comment, not about the slide.
1537
- let at = null;
1538
- try { at = execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(); }
1539
- catch { at = null; }
1540
- const rec = op === 'anchor'
1541
- ? {
1542
- op: 'anchor',
1543
- re,
1544
- slide: Number(slide),
1545
- ...(title !== undefined ? { title } : {}),
1546
- ...(fp !== undefined ? { fp } : {}),
1547
- at: new Date().toISOString(),
1548
- by: reviewerName(),
1549
- }
1550
- : op === 'resolve'
1551
- ? { op: 'resolve', re, at: new Date().toISOString(), by: reviewerName() }
1552
- : {
1553
- id: newId(),
1554
- at: new Date().toISOString(),
1555
- by: reviewerName(),
1556
- ...(at ? { deck: at } : {}),
1557
- re,
1558
- body: text,
1559
- };
1560
- try { appendFileSync(store, `${serializeRecord(rec)}\n`); }
1561
- catch (e) { return json(500, { ok: false, error: oneline(e) }); }
1562
- if (gitOn) {
1563
- gitAutocommit(store, root, op === 'anchor'
1564
- ? commitSubject(`review: move ${re} to slide ${rec.slide}`, 'review: re-anchor a comment')
1565
- : op === 'resolve'
1566
- ? commitSubject(`review: resolve ${re}`, 'review: resolve a comment')
1567
- : commitSubject(`review: reply to ${re}`, 'review: a reply'));
1568
- }
1569
- console.log(` review: ${op === 'anchor' ? `moved ${re} to slide ${rec.slide}`
1570
- : op === 'resolve' ? `resolved ${re}` : `replied to ${re}`}`);
1571
- return json(200, { ok: true });
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}"`);
1572
3178
  }
1573
- if (req.method === 'POST' && url.pathname === '/edit/narration') {
1574
- const { files, ext, segments } = JSON.parse(body || '{}');
1575
- // The same three shapes /edit/record refuses for a folder, refused
1576
- // again here: this one is written INTO the deck, where a bad value is
1577
- // not a failed request but a deck that no longer plays.
1578
- if (typeof files !== 'string' || !files.trim() || files.length > 200
1579
- || /^[/\\]/.test(files) || /^[a-zA-Z]:/.test(files)
1580
- || files.split(/[/\\]/).includes('..')) {
1581
- return json(400, { ok: false, error: 'bad narration folder' });
1582
- }
1583
- if (ext !== undefined && !/^[a-z0-9]{1,5}$/.test(String(ext))) {
1584
- return json(400, { ok: false, error: 'bad ext' });
1585
- }
1586
- if (segments !== undefined && typeof segments !== 'boolean') {
1587
- return json(400, { ok: false, error: 'bad segments' });
1588
- }
1589
- const { label } = JSON.parse(body || '{}');
1590
- if (label !== undefined && (typeof label !== 'string' || label.length > 120)) {
1591
- return json(400, { ok: false, error: 'bad label' });
1592
- }
1593
- // upsert, never replace: a deck carries as many tracks as you have
1594
- // voices, and writing one must not throw the others away
1595
- const next = upsertNarrationTrack(readDeck(), {
1596
- label: label || files.trim(),
1597
- dir: files.trim(),
1598
- ...(ext === undefined ? {} : { ext }),
1599
- ...(segments === undefined ? {} : { segments }),
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)'}`,
1600
3192
  });
1601
- if (next === null) {
1602
- // Not a failure of this server — a deck whose config is built
1603
- // somewhere else. Say which, so the answer is "paste this line",
1604
- // not "it did not work".
1605
- return json(409, { ok: false,
1606
- error: 'this deck builds its config outside the Decklight.init(…) call, so there is no literal here to edit' });
1607
- }
1608
- const changed = applyEdit(next);
1609
- if (changed) console.log(` narration: ${files} in the deck's config`);
1610
- return json(200, { ok: true, changed, ...history.counts() });
1611
3193
  }
1612
- if (req.method === 'POST' && url.pathname === '/edit/restore') {
1613
- if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
1614
- const { ref } = JSON.parse(body || '{}');
1615
- if (typeof ref !== 'string' || !ref.trim()) throw new Error('bad payload');
1616
- const before = readDeck();
1617
- let result;
1618
- try { result = restoreDeck(deckPath, ref.trim(), root); }
1619
- catch (e) { return json(400, { ok: false, error: oneline(e) }); }
1620
- // Z takes a restore back like any other edit — the git-level move and
1621
- // the keystroke-level stack stay in step rather than disagreeing.
1622
- if (result.changed) history.record(before);
1623
- console.log(` restored ${basename(deckPath)} to ${result.short}`);
1624
- return json(200, { ok: true, ...result, ...history.counts() });
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}` });
1625
3200
  }
1626
- // An intermediate commit point: a multi-step agent calls this when IT
1627
- // decides one logical change is finished, so the boundaries follow the
1628
- // work instead of a clock. The message is the agent's, and untrusted.
1629
- if (req.method === 'POST' && url.pathname === '/edit/commit') {
1630
- if (!gitOn) return json(409, { ok: false, error: 'git is off for this session' });
1631
- const { message } = JSON.parse(body || '{}');
1632
- const subject = commitSubject(message, `decklight: autosave ${basename(deckPath)}`);
1633
- const committed = gitAutocommit(deckPath, root, subject);
1634
- if (committed) console.log(` git: committed "${subject}"`);
1635
- return json(200, { ok: true, committed, subject });
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 });
1636
3211
  }
1637
- // ── theme Browse (THEME_BROWSE#UI) ─────────────────────────────────
1638
- // What the picker's Browse entry lists. Cache-only by construction: this
1639
- // reads the catalogs `marketplace update` already fetched and never
1640
- // fetches one itself, so a deck on a plane lists what it has and says so
1641
- // rather than hanging on a network that is not there.
1642
- if (req.method === 'GET' && url.pathname === '/edit/theme/browse') {
1643
- const { themes, stale } = await browsableThemes();
1644
- return json(200, { ok: true, themes, stale, cacheOnly: true });
1645
- }
1646
- // Installing goes through `theme add`'s own functions — validation, the
1647
- // WCAG gates, the block shape — so a theme refused on the command line is
1648
- // refused here, by the same code, for the same reason.
1649
- if (req.method === 'POST' && url.pathname === '/edit/theme/add') {
1650
- const { ref, name: asName } = JSON.parse(body || '{}');
1651
- if (typeof ref !== 'string' || !ref.trim()) return json(400, { ok: false, error: 'which theme?' });
1652
- const { resolveEntry, MarketplaceError } = await import('./marketplace.mjs');
1653
- const { fetchTheme, installTheme, resolveSource } = await import('./theme.mjs');
1654
- const { validateTheme, themeNameFrom, validThemeName } = await import('../tools/theme-check.mjs');
1655
-
1656
- let hit;
1657
- try { hit = resolveEntry(ref.trim(), await catalogMap()); }
1658
- catch (e) {
1659
- if (e instanceof MarketplaceError) return json(404, { ok: false, error: e.message });
1660
- throw e;
1661
- }
1662
- if (hit.entry.type !== 'theme') {
1663
- return json(400, { ok: false, error: `"${hit.qualified}" is a ${hit.entry.type}, not a theme` });
1664
- }
1665
- const name = asName || hit.entry.name;
1666
- if (!validThemeName(name)) return json(400, { ok: false, error: `not a usable theme name: "${name}"` });
1667
-
1668
- // A manifest's `source` is relative to its MARKETPLACE, not to whoever
1669
- // is installing — resolveSource is where that is worked out, and it lives
1670
- // in theme.mjs because fetching an artifact and fetching a catalog are
1671
- // different permissions on this path.
1672
- const { loadRegistry } = await import('./marketplace.mjs');
1673
- const market = loadRegistry().marketplaces?.[hit.marketplace];
1674
- let src;
1675
- try { src = resolveSource(hit.entry.source, { name: hit.marketplace, source: market?.source }); }
1676
- catch (e) {
1677
- if (e instanceof MarketplaceError) return json(409, { ok: false, error: e.message });
1678
- throw e;
1679
- }
1680
- let css;
1681
- try { css = await fetchTheme(src); }
1682
- catch (e) { return json(502, { ok: false, error: `could not read ${src}: ${oneline(e)}` }); }
1683
-
1684
- const check = validateTheme(css);
1685
- if (!check.ok) {
1686
- // The deck is left byte-for-byte unchanged: a picker that could leave
1687
- // a deck carrying a broken theme would be worse than no picker.
1688
- return json(400, { ok: false, error: `${name} fails the theme contract`, problems: check.errors ?? [] });
1689
- }
1690
- const before = readDeck();
1691
- const out = installTheme(before, name, css);
1692
- if (!out.html) return json(500, { ok: false, error: 'the deck has no </head> to install into' });
1693
- history.record(before); // Z takes an install back like any other edit
1694
- writeFileSync(deckPath, out.html);
1695
- console.log(` theme: ${out.replaced ? 'replaced' : 'installed'} ${name} from ${hit.qualified}`);
1696
- return json(200, { ok: true, name, from: hit.qualified, replaced: out.replaced, ...history.counts() });
1697
- }
1698
- // ── the engine wizard (ENGINES#WIZARD) ─────────────────────────────
1699
- // The schema the player renders. Validated on the way OUT as well as on
1700
- // the way in: a catalog is a file someone else wrote, and handing the
1701
- // renderer a schema core has not vetted is how "core renders, a plugin
1702
- // declares" becomes "core renders whatever a plugin sent".
1703
- if (req.method === 'GET' && url.pathname === '/edit/wizard') {
1704
- const engine = url.searchParams.get('engine') ?? '';
1705
- const hit = await wizardEntry(engine);
1706
- if (!hit) return json(404, { ok: false, error: `no wizard declared for "${engine}"` });
1707
- try {
1708
- const schema = validateSchema(hit.entry.wizard);
1709
- // Provenance rides BESIDE the schema, never inside it (#232): `from`
1710
- // is the registry's name for the entry and the sentence pair is
1711
- // derived here from the vetted schema, so the card can say who is
1712
- // asking and where the answer goes in words the plugin did not write.
1713
- return json(200, { ok: true, schema, from: hit.qualified, provenance: provenance(schema, hit.qualified) });
1714
- } catch (e) {
1715
- return json(400, { ok: false, error: `${engine} declares a wizard core cannot render: ${e.message}` });
1716
- }
1717
- }
1718
- // Author-mode only, and that is structural rather than checked: this
1719
- // server answers loopback alone, and `present` registers nothing like
1720
- // these at all. A credential prompt in a deck you were emailed has
1721
- // nowhere to post.
1722
- if (req.method === 'POST' && url.pathname === '/edit/wizard') {
1723
- const { engine, answers } = JSON.parse(body);
1724
- if (typeof engine !== 'string') return json(400, { ok: false, error: 'which engine?' });
1725
- // "No such engine" is a third answer, not one of the two failures. It is
1726
- // not an outage to wait out and not a refusal by a provider — it is a
1727
- // marketplace that was never added, and the fix is named.
1728
- if (!(await wizardEntry(engine))) {
1729
- return json(404, { ok: false, state: 'unknown',
1730
- error: `no engine named "${engine}" declares a wizard in any registered marketplace — try: decklight marketplace add <owner/repo>` });
1731
- }
1732
- const r = await configureEngine(engine, answers, {
1733
- fetchSchema: wizardSchemaFor,
1734
- validateAnswers: wizardValidate,
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 }; },
1735
3219
  });
1736
- if (r.state !== CONFIGURED) {
1737
- // The three failures stay three: 503 for "could not reach", 400 for
1738
- // "that was refused", and 412 for "this machine is missing something"
1739
- // (ENGINES#LIPSYNC). A presenter whose key is wrong must not be told
1740
- // to check their network, and one who is missing rhubarb must not be
1741
- // told to check their key — the status code says which it is too.
1742
- const code = r.state === UNREACHABLE ? 503 : r.state === PREREQUISITE ? 412 : 400;
1743
- return json(code, { ok: false, state: r.state, error: r.reason, ...(r.unmet ? { unmet: r.unmet } : {}) });
1744
- }
1745
- // Redacted on the way out, always — the response is the one place a key
1746
- // could leak back into a page, a devtools log, or a screen recording.
1747
- console.log(` wizard: ${engine} configured (${r.file} — ${r.protection.label})`);
1748
- // A key that could not be restricted is worth an extra line, at the
1749
- // moment it is stored rather than in a doc nobody reads (#308): what
1750
- // decklight says about a credential and what is true of it on disk
1751
- // have to be the same sentence.
1752
- if (r.protection.state !== 'private') {
1753
- console.log(` wizard: decklight could NOT restrict that file to your account — ${r.protection.label}`);
1754
- if (r.protection.why) console.log(` the system said: ${r.protection.why}`);
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}"`);
1755
3224
  }
1756
- return json(200, { ok: true, state: r.state, engine, stored: r.stored, protection: r.protection.label });
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() });
1757
3228
  }
1758
- if (req.method === 'POST' && url.pathname === '/edit/wizard/forget') {
1759
- const { engine } = JSON.parse(body);
1760
- if (typeof engine !== 'string') return json(400, { ok: false, error: 'which engine?' });
1761
- const had = forgetCredentials(engine);
1762
- console.log(` wizard: ${engine} ${had ? 'forgotten' : 'was not configured'}`);
1763
- return json(200, { ok: true, forgotten: had });
1764
- }
1765
- if (req.method === 'POST' && url.pathname === '/edit/notes') {
1766
- const { slide, text } = JSON.parse(body);
1767
- if (!Number.isInteger(slide) || slide < 1 || typeof text !== 'string') throw new Error('bad payload');
1768
- applyEdit(setSlideNotes(readDeck(), slide, notesTextToAside(text)));
1769
- console.log(` notes saved: slide ${slide} (${text.length} chars)`);
1770
- return json(200, { ok: true, ...history.counts() });
1771
- }
1772
- if (req.method === 'POST' && url.pathname === '/edit/timings') {
1773
- // every slide's rehearsed time in ONE edit — one undo entry, one commit
1774
- const { timings } = JSON.parse(body);
1775
- if (!Array.isArray(timings) || !timings.every((t) => Number.isInteger(t?.slide) && t.slide >= 1 && Number.isFinite(t?.seconds))) throw new Error('bad payload');
1776
- let next = readDeck();
1777
- for (const t of timings) next = setSlideTiming(next, t.slide, t.seconds);
1778
- const changed = applyEdit(next);
1779
- if (changed) console.log(` rehearsal timings saved: ${timings.length} slides`);
1780
- return json(200, { ok: true, changed, ...history.counts() });
3229
+ default:
3230
+ return json(400, { ok: false, error: `${rule} has no quick fix the server applies — ask the agent` });
3231
+ }
3232
+ }
3233
+
3234
+ // ── the route table ──────────────────────────────────────────────────────
3235
+ // Every `/deck/edit/*` surface, keyed `METHOD /path`. This was forty-four
3236
+ // `if (req.method === … && url.pathname === …)` arms in one eleven-hundred
3237
+ // line function: adding a route meant finding a place in the chain, reading
3238
+ // a route meant scrolling to it, and the ORDER of two unrelated routes was
3239
+ // load-bearing by accident rather than by decision. A table has no order to
3240
+ // get wrong — adding a surface is adding a line — and the two places where
3241
+ // sequence DOES still matter say so out loud rather than by position
3242
+ // (`BEFORE_BODY`, and the prefix list below).
3243
+ const routes = new Map(Object.entries({
3244
+ 'POST /deck/edit/lock': lockRoute,
3245
+ // the voice bridge, on this origin (#520): `/deck/tts` speaks, and everything
3246
+ // else of the bridge's lives under `/deck/tts/` (the prefix list below)
3247
+ 'POST /deck/tts': ttsProxy,
3248
+ 'POST /deck/edit/shutdown': shutdownRoute,
3249
+ 'POST /deck/edit/undo': undoRedoRoute,
3250
+ 'POST /deck/edit/redo': undoRedoRoute,
3251
+
3252
+ // the owner's half of a review (REVIEW): registered here alone, beside
3253
+ // the routes both servers share
3254
+ 'GET /deck/review/incoming': reviewIncomingRoute,
3255
+ 'GET /deck/review/at': reviewAtRoute,
3256
+
3257
+ 'GET /deck/edit/wizard': wizardSchemaRoute,
3258
+ 'POST /deck/edit/wizard': wizardConfigureRoute,
3259
+ 'POST /deck/edit/wizard/forget': wizardForgetRoute,
3260
+
3261
+
3262
+ 'POST /deck/edit/narration/record': recordRoute,
3263
+ 'GET /deck/edit/narration/tracks': tracksRoute,
3264
+
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,
3269
+ 'POST /deck/edit/agent/prefer': agentPreferRoute,
3270
+ 'POST /deck/edit/enhance': enhanceRoute,
3271
+ 'POST /deck/edit/enhance/text': enhanceTextRoute,
3272
+ 'POST /deck/edit/review': reviewRoute,
3273
+ 'GET /deck/edit/review': reviewFindingsRoute,
3274
+ }));
3275
+
3276
+ // The slide mutations are a file of their own (cli/edit-slides.mjs): thirteen
3277
+ // routes of one shape — read the deck, run a pure transform over it, put the
3278
+ // result through applyEdit — that between them want four of editMain's
3279
+ // bindings and none of the rest. Handed those four explicitly, they can be
3280
+ // called from a test with a temp deck and no socket at all. `deckPath` is the
3281
+ // odd one: /deck/edit/asset saves a dropped image beside the deck, so it needs to
3282
+ // know where the deck is and not only what it says.
3283
+ registerSlideRoutes(routes, {
3284
+ readDeck, applyEdit, history, deckPath,
3285
+ // a notes save updates every page in place: no reload for that write
3286
+ quiet: (html) => { quietWrite = html; },
3287
+ broadcast: (event, data) => clients.broadcast(event, data),
3288
+ });
3289
+
3290
+ // The deck's look is a file of its own too (cli/edit-look.mjs): the theme
3291
+ // pick and the brand-themes switch, and browsing and marking what the
3292
+ // marketplaces offer a deck to wear — themes, design systems, fonts. They
3293
+ // want the deck's text and the two ways of writing it, the undo stack, the
3294
+ // event channel, and the quiet-write latch, and nothing else of editMain's.
3295
+ registerLookRoutes(routes, {
3296
+ readDeck, applyEdit, writeDeck, history, broadcast, deckPath,
3297
+ // a quiet pick or mark updates the page that asked: no reload for it
3298
+ quiet: (html) => { quietWrite = html; },
3299
+ });
3300
+
3301
+ // Handing the deck over is a third (cli/edit-handover.mjs): export, the
3302
+ // bundle estimate, the inspector's read, and publish. None of them edits
3303
+ // the deck; they read it, write files beside it or push it, and own their
3304
+ // own in-flight flags.
3305
+ registerHandoverRoutes(routes, {
3306
+ readDeck, deckPath, root, broadcast,
3307
+ gitOn: () => gitOn,
3308
+ onExport: (job) => { exportJob = job; },
3309
+ });
3310
+
3311
+ // And git (cli/edit-git.mjs): the commit window and the deck's history. The
3312
+ // commit bookkeeping stays here, because the timer, the agent's commits and
3313
+ // the exit commit share it; the routes reach it through what is handed in,
3314
+ // and the `let`s among it only through getters and setters.
3315
+ registerGitRoutes(routes, {
3316
+ readDeck, history, broadcast, deckPath, deckRel, root,
3317
+ gitOn: () => gitOn,
3318
+ agentPref: () => agentPref,
3319
+ subjectsOff, describer,
3320
+ commitState, measureDirty, resetEpisode, alsoNow, alsoRels, attrRel,
3321
+ pendingAttr: () => pendingAttr,
3322
+ clearPendingAttr: () => { pendingAttr = null; },
3323
+ dismissNag: () => { nagDismissed = true; },
3324
+ });
3325
+
3326
+ // The routes that run BEFORE the shared body read, and the only reason the
3327
+ // dispatcher below has a sequence at all. `/deck/edit/narration/record`'s body is BINARY and
3328
+ // megabytes of it — a slide of speech is ~48 kB a second — so the string
3329
+ // concat and its 1 MB ceiling would both be wrong, and it reads the stream
3330
+ // itself under its own 64 MB limit. `/deck/edit/asset` is the same case with a
3331
+ // different payload — an image dropped on the stage, read under its own
3332
+ // 25 MB limit. The other three carry no body, and never had one read for them.
3333
+ const BEFORE_BODY = new Set([
3334
+ 'POST /deck/tts',
3335
+ 'POST /deck/edit/narration/record', 'POST /deck/edit/asset',
3336
+ 'POST /deck/edit/shutdown', 'POST /deck/edit/undo', 'POST /deck/edit/redo',
3337
+ ]);
3338
+
3339
+ // Prefix routes, tried IN ORDER once the exact table has missed and before
3340
+ // the static fallback — the one dispatch rule a Map cannot express. Every
3341
+ // `/deck/edit/*` path is exact today, so the list is empty; it is declared so the
3342
+ // first route that needs a prefix has somewhere to go other than the bottom
3343
+ // of the dispatcher, where the chain used to grow.
3344
+ const PREFIX_ROUTES = [ // { method, prefix, handler }
3345
+ // the voice bridge's own routes, on this origin: /tts/ping, /tts/engines,
3346
+ // /tts/voices… — forwarded as they are, since the bridge serves the same
3347
+ // paths itself. Nothing of the bridge's sits at the root, where it would
3348
+ // shadow a file beside the deck (`voices/` is the narration's folder).
3349
+ { method: 'GET', prefix: '/deck/tts/', handler: ttsProxy, beforeBody: true },
3350
+ { method: 'POST', prefix: '/deck/tts/', handler: ttsProxy, beforeBody: true },
3351
+ // the lip-sync bridge, on this origin (#520): `/deck/lipsync/ping`, `/viseme`, `/video`
3352
+ // the audio a POST carries is binary and can pass the body cap, so it
3353
+ // streams through unread, like /deck/edit/narration/record's
3354
+ { method: 'GET', prefix: '/deck/lipsync/', handler: lipsyncProxy, beforeBody: true },
3355
+ { method: 'POST', prefix: '/deck/lipsync/', handler: lipsyncProxy, beforeBody: true },
3356
+ ];
3357
+
3358
+ // the deck's channel and the shared review routes, beside this server's own
3359
+ for (const [key, handler] of deck.routes) routes.set(key, handler);
3360
+ for (const key of ['GET /deck/review/comments', 'POST /deck/review/comments', 'POST /deck/review/submit']) {
3361
+ routes.set(key, ({ req, res, url, body }) => review.handle(req, res, url, body ?? ''));
3362
+ }
3363
+ // The upstream routes are REGISTERED ONLY when the deck is a tracked file in
3364
+ // a clone whose branch tracks something (NO_TRUST#UPSTREAM): on a deck you
3365
+ // were emailed they are not refused, they do not exist. The strict origin
3366
+ // gate, not allowEditRequest: `null` is a sandboxed plugin frame's origin,
3367
+ // and presenter chrome must not be able to fast-forward the presenter's
3368
+ // repository.
3369
+ if (upstream) {
3370
+ routes.set('GET /deck/upstream', ({ json }) => json(200, { ok: true, ...upstreamStatus, pull: pullOffer() }));
3371
+ routes.set('POST /deck/upstream/check', ({ req, res, json }) => {
3372
+ if (!isOwnOrigin(req, actualPort)) { res.writeHead(403); res.end('forbidden'); return; }
3373
+ return refreshUpstream().then(() => json(200, { ok: true, ...upstreamStatus, pull: pullOffer() }));
3374
+ });
3375
+ }
3376
+ if (pullArmed) {
3377
+ routes.set('POST /deck/upstream/pull', ({ req, res, json }) => {
3378
+ if (!isOwnOrigin(req, actualPort)) { res.writeHead(403); res.end('forbidden'); return; }
3379
+ // The body is never read. No field of the request reaches git or the
3380
+ // filesystem; the repository, the branch and `@{upstream}` are all
3381
+ // constants resolved before the server existed.
3382
+ return doPull().then((out) => json(out.ok ? 200 : (out.http ?? 409), out));
3383
+ });
3384
+ }
3385
+
3386
+ // What no-trust mode refuses, by name: everything that writes the deck or
3387
+ // reaches a bridge, and the review owner's half. A deck opened without trust used to be
3388
+ // served by a process in which none of this was registered; now it is one
3389
+ // server, and the refusal is the mode's — a 403 that says which mode would
3390
+ // answer, rather than a 405 that pretends the route is unknown.
3391
+ const WRITE_FAMILY = (pathname) => pathname.startsWith('/deck/edit/')
3392
+ || pathname === '/deck/tts' || pathname.startsWith('/deck/tts/') || pathname.startsWith('/deck/lipsync/')
3393
+ || pathname === '/deck/review/incoming' || pathname === '/deck/review/at';
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
+
3398
+ // Two static servers for one root, chosen per request by the mode. Write
3399
+ // mode serves the cwd with the deck at "/" and an author's exotic asset as
3400
+ // octet-stream. No-trust mode refuses every extension the MIME table does
3401
+ // not name (a file beside a travelled deck that is none of them — `id_rsa`,
3402
+ // a `.pem`, a database — is only ever fetched to be exfiltrated), rewrites
3403
+ // every html page on its way out (strict, then the chrome), and has no
3404
+ // index: "/" is the deck, answered from memory before this is consulted.
3405
+ // write mode: the deck gets the presenter's chrome too, every other page none
3406
+ const files = staticFiles(root, { index: deckUrl, html: (text, file) => (file === deckPath ? injectChrome(text, chrome.plugins) : text) });
3407
+ const auditedFiles = staticFiles(root, { html: rewrite, knownTypesOnly: true });
3408
+ const server = createServer(async (req, res) => {
3409
+ // No-trust mode: the policy on EVERY response this server writes — the
3410
+ // deck and its assets, but also the 403/404/405 pages, the control-
3411
+ // channel JSON and SSE, and the remote controller. Set before anything
3412
+ // runs, and writeHead merges it under whatever a route names itself, so
3413
+ // "every response carries the header" holds by construction.
3414
+ if (noTrust) res.setHeader('content-security-policy', CSP);
3415
+ // Loopback always; off-loopback only /deck/remote/* carrying the per-run
3416
+ // token, and only when --remote asked for a listener at all. Every other
3417
+ // path is refused off this machine unconditionally — flag or no flag,
3418
+ // token or no token — which is why the static files and the deck itself
3419
+ // cannot be reached from the LAN even while the remote can.
3420
+ if (!allowRemote(req, token)) {
3421
+ res.writeHead(403);
3422
+ res.end('forbidden: this deck is served to this machine only; off it, only /deck/remote/* answers, with the session token');
3423
+ return;
3424
+ }
3425
+ let url;
3426
+ try { url = new URL(req.url, 'http://x'); } catch { res.writeHead(400); res.end('bad request'); return; }
3427
+ // The phone remote, before the CSRF gate below: the phone's origin is a
3428
+ // LAN address, which that gate rightly refuses for everything else. A
3429
+ // body past 4 KB is a probe, not a request — the socket is destroyed and
3430
+ // the E2BIG never becomes a response.
3431
+ if (url.pathname === '/deck/remote' || url.pathname.startsWith('/deck/remote/')) {
3432
+ let body = '';
3433
+ if (req.method === 'POST') {
3434
+ try { body = (await readBody(req, { max: 4096 })).toString(); } catch { return; }
1781
3435
  }
1782
- if (req.method === 'POST' && url.pathname === '/edit/layout') {
1783
- const { slide, layout } = JSON.parse(body);
1784
- if (!Number.isInteger(slide) || slide < 1 || typeof layout !== 'string') throw new Error('bad payload');
1785
- const changed = applyEdit(setSlideLayout(readDeck(), slide, layout));
1786
- if (changed) console.log(` layout saved: slide ${slide} → ${layout}`);
1787
- return json(200, { ok: true, changed, ...history.counts() });
3436
+ try {
3437
+ if (relay.handle(req, res, url, body)) return;
3438
+ } catch {
3439
+ res.writeHead(400, { ...PHONE_CORS, 'content-type': 'application/json' });
3440
+ res.end(JSON.stringify({ ok: false, error: 'bad payload' }));
3441
+ return;
1788
3442
  }
1789
- if (req.method === 'POST' && url.pathname === '/edit/hidden') {
1790
- const { slide, hidden } = JSON.parse(body);
1791
- if (!Number.isInteger(slide) || slide < 1 || typeof hidden !== 'boolean') throw new Error('bad payload');
1792
- const changed = applyEdit(setSlideHidden(readDeck(), slide, hidden));
1793
- if (changed) console.log(` slide ${slide} ${hidden ? 'hidden' : 'shown again'}`);
1794
- return json(200, { ok: true, changed, ...history.counts() });
3443
+ res.writeHead(405); res.end('method not allowed');
3444
+ return;
3445
+ }
3446
+ // The CSRF gate (#222), before anything runs. A same-machine browser tab is
3447
+ // the threat, not an off-machine caller, so the check is the request's
3448
+ // `Origin`, not its socket address. A foreign origin is refused here —
3449
+ // before the body is read, before any file is written, before an agent is
3450
+ // spawned — and refused WITHOUT permissive CORS, so the page cannot even
3451
+ // read the refusal. Loopback origins, `null` (file://), and the header's
3452
+ // absence (the CLI, the port-conflict probe, curl) pass.
3453
+ const origin = req.headers.origin;
3454
+ const CORS = corsHeadersFor(origin);
3455
+ if (!allowEditRequest(req)) {
3456
+ res.writeHead(403, { 'content-type': 'text/plain' });
3457
+ res.end('forbidden: the deck server answers this machine only, and not a foreign web origin');
3458
+ return;
3459
+ }
3460
+ try {
3461
+ const json = (code, obj, headers = {}) => {
3462
+ res.writeHead(code, { ...CORS, ...headers, 'content-type': 'application/json' });
3463
+ res.end(JSON.stringify(obj));
3464
+ };
3465
+ if (req.method === 'OPTIONS') { res.writeHead(204, CORS); return res.end(); }
3466
+ // no-trust mode: nothing that writes answers, whatever it was aimed at
3467
+ if (noTrust && WRITE_FAMILY(url.pathname)) {
3468
+ return json(403, { ok: false, noTrust: true, error: 'this deck is open without trust — nothing here changes it' });
1795
3469
  }
1796
- // ── element edit mode (E, right-click a slide element) — #112 ─────
1797
- // Same door as layout/notes: a pure (html, slide, index, …) → html
1798
- // transform, through applyEdit, onto the ONE undo/redo stack.
1799
- if (req.method === 'POST' && url.pathname === '/edit/element/remove') {
1800
- const { slide, index } = JSON.parse(body);
1801
- if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) throw new Error('bad payload');
1802
- const changed = applyEdit(removeSlideElement(readDeck(), slide, index));
1803
- if (changed) console.log(` element removed: slide ${slide} #${index}`);
1804
- return json(200, { ok: true, changed, ...history.counts() });
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)) {
3474
+ return json(423, { ok: false, locked: true, error: 'the deck is locked — unlock it from the palette or the lock chip' });
1805
3475
  }
1806
- if (req.method === 'POST' && url.pathname === '/edit/element/content') {
1807
- const { slide, index, html } = JSON.parse(body);
1808
- if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || typeof html !== 'string') {
1809
- throw new Error('bad payload');
1810
- }
1811
- const changed = applyEdit(setSlideElementHtml(readDeck(), slide, index, html));
1812
- if (changed) console.log(` element content saved: slide ${slide} #${index}`);
1813
- return json(200, { ok: true, changed, ...history.counts() });
3476
+ const key = `${req.method} ${url.pathname}`;
3477
+ const prefixed = routes.has(key) ? null
3478
+ : PREFIX_ROUTES.find((r) => r.method === req.method && url.pathname.startsWith(r.prefix));
3479
+ const handler = routes.get(key) ?? prefixed?.handler;
3480
+ if (handler && (BEFORE_BODY.has(key) || prefixed?.beforeBody)) {
3481
+ return await writing.run({ route: url.pathname, body: '' }, () => handler({ req, res, url, json, CORS }));
1814
3482
  }
1815
- if (req.method === 'POST' && url.pathname === '/edit/element/effect') {
1816
- const { slide, index, effect } = JSON.parse(body);
1817
- if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0
1818
- || (effect !== null && typeof effect !== 'string')) {
1819
- throw new Error('bad payload');
1820
- }
1821
- const changed = applyEdit(setSlideElementBuild(readDeck(), slide, index, effect));
1822
- if (changed) console.log(` element effect saved: slide ${slide} #${index} → ${effect ?? '(removed)'}`);
1823
- return json(200, { ok: true, changed, ...history.counts() });
3483
+ // Read for every POST, matched or not — an oversized body is refused
3484
+ // whatever it was aimed at, exactly as the chain refused it.
3485
+ let body = '';
3486
+ if (req.method === 'POST') {
3487
+ for await (const chunk of req) { body += chunk; if (body.length > 1e6) throw new Error('too large'); }
1824
3488
  }
1825
- // Remember which agent A should reach for (#125, SPEC AGENT_UNITS). A
1826
- // preference is a choice about this machine, not about the deck, so it
1827
- // is written beside the unit library and never into the file.
1828
- if (req.method === 'POST' && url.pathname === '/edit/agent/prefer') {
1829
- const { agent } = JSON.parse(body);
1830
- if (agent !== null && typeof agent !== 'string') throw new Error('bad payload');
1831
- if (agent && !agents.some((a) => a.name === agent)) {
1832
- return json(400, { ok: false, error: agentUnavailable(agent, agents) });
3489
+ if (handler) return await writing.run({ route: url.pathname, body }, () => handler({ req, res, url, body, json, CORS }));
3490
+ // ── the deck and the files beside it ──────────────────────────────
3491
+ // No-trust mode answers the deck's own path from the audited bytes
3492
+ // (servePayload above). For a container that also means the URL a
3493
+ // person sees is the file they double-clicked — serving the raw archive
3494
+ // bytes there would hand a browser something it cannot render.
3495
+ if (noTrust) {
3496
+ if (isDeck(url)) {
3497
+ if (servePayload(req, res)) return;
3498
+ res.writeHead(405); res.end('method not allowed'); return;
1833
3499
  }
1834
- setPreferredAgent(agent);
1835
- agentPref = agent ?? undefined;
1836
- console.log(` agent: ${agent ? `${agent} remembered as preferred` : 'preference cleared'}`);
1837
- return json(200, { ok: true, preferredAgent: agent ?? null });
1838
- }
1839
- if (req.method === 'POST' && url.pathname === '/edit/agent') {
1840
- const { prompt, agent, message } = JSON.parse(body);
1841
- if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('bad payload');
1842
- if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is already running` });
1843
- const cmd = runAgent(prompt.trim(), agent, message);
1844
- if (!cmd) return json(400, { ok: false, error: agentUnavailable(agent ?? agentPref, agents) });
1845
- return json(200, { ok: true, agent: cmd.name, label: cmd.label });
3500
+ if (auditedFiles(req, res, url)) return;
3501
+ res.writeHead(405); res.end('method not allowed'); return;
1846
3502
  }
1847
- // ── static files from the cwd (staticFiles, serve.mjs) ───────────
1848
3503
  if (files(req, res, url)) return;
1849
3504
  res.writeHead(405);
1850
3505
  res.end();
@@ -1856,19 +3511,80 @@ export async function editMain(args, { onListen = null } = {}) {
1856
3511
  });
1857
3512
 
1858
3513
  const actual = await listenTakingOverIfNeeded(server, port, host);
1859
- // `decklight record` runs this same server in-process and needs to know
3514
+ actualPort = actual;
3515
+ // `decklight narrate --mic` runs this same server in-process and needs to know
1860
3516
  // WHICH port it ended up on (a taken --port moves to the next free one) and
1861
3517
  // to print its own banner instead of the authoring one.
1862
3518
  if (onListen) onListen({ port: actual, deckUrl, server });
1863
- else if (process.env.DECKLIGHT_BANNER) {
3519
+ else if (noTrust) {
3520
+ // Before the first slide renders, not after — the point of the label is
3521
+ // to be able to decide not to open it. The audience is looking at the
3522
+ // deck; none of this goes on the page.
3523
+ console.log(`decklight · ${basename(deckPath)} on http://127.0.0.1:${actual}${deckUrl} — no trust: its code stripped, CSP enforced. Ctrl-C stops`);
3524
+ console.log(` serving ${root} — ${rootArg ? '--root as given' : "the deck's own directory"};`
3525
+ + ' dotfiles and non-deck file types refused; every edit route refuses, nothing is written');
3526
+ printLabel();
3527
+ if (upstream) {
3528
+ console.log(` upstream: tracking ${upstream.upstream} — ${intervalMs ? `checking every ${intervalMs / 60000} min` : 'checked when asked'}`
3529
+ + (pullArmed ? ', update control ON (--upstream-pull)' : ''));
3530
+ if (!pullArmed && args.includes('--upstream-pull') && token) {
3531
+ console.log(' upstream: --remote is on — the update control is off; pull from your own terminal');
3532
+ }
3533
+ } else if (suppressed && suppressed !== 'write mode') {
3534
+ console.log(` upstream: not checked — ${suppressed}`);
3535
+ }
3536
+ // Reported UNDER the label and never inside it: a plugin is not in the
3537
+ // file. Naming which plugins read the speaker notes is the other half of
3538
+ // `needs: ["notes"]` being a declaration rather than a silent grant.
3539
+ for (const pl of chrome.plugins) {
3540
+ console.log(` chrome: ${pl.name} (${pl.slot}) — yours, not in the deck`
3541
+ + `${pl.needs.includes('notes') ? '; reads your speaker notes' : ''}`);
3542
+ }
3543
+ for (const r of chrome.refused) {
3544
+ console.log(` chrome: ${r.name} REFUSED — not loaded, the deck plays without it`);
3545
+ console.log(` ${r.reason.replace(/\n/g, '\n ')}`);
3546
+ }
3547
+ if (audited.strict) {
3548
+ const n = audited.report.counts.unaccounted, h = audited.report.counts.handlers;
3549
+ if (signature.state !== UNSIGNED && !isVerified(signature)) console.log(' the signature did not verify — serving strict');
3550
+ const removed = [
3551
+ n ? `${n} unaccounted script block${n === 1 ? '' : 's'}` : '',
3552
+ h ? `${h} executable attribute${h === 1 ? '' : 's'}` : '',
3553
+ ].filter(Boolean).join(' and ');
3554
+ console.log(removed
3555
+ ? ` ${removed} stripped — serving strict. The file on disk is untouched`
3556
+ : ` nothing to strip — this deck is served exactly as ${container ? 'the container carries it' : 'it was read from disk'}`);
3557
+ }
3558
+ } else if (process.env.DECKLIGHT_BANNER) {
1864
3559
  // The port is reported rather than assumed: `listenTakingOverIfNeeded` can
1865
- // land somewhere other than the port author resolved, and the URL on the
3560
+ // land somewhere other than the port `open` resolved, and the URL on the
1866
3561
  // banner has to be the one that actually answers.
1867
3562
  console.log(readyLine({
1868
3563
  url: `http://127.0.0.1:${actual}${deckUrl}`,
1869
- keys: 'E edit · L layouts · Z undo · A agent · Ctrl-C stops',
3564
+ keys: 'Ctrl-C stops',
1870
3565
  }));
1871
- } else console.log(`decklight author on http://127.0.0.1:${actual}${deckUrl} — E element edit mode, L layouts, Z undo, A agent. Ctrl-C stops`);
3566
+ } else console.log(`decklight · ${basename(deckPath)} on http://127.0.0.1:${actual}${deckUrl} — editing on, L layouts, Z undo, A agent. Ctrl-C stops`);
3567
+ if (token) {
3568
+ console.log(` remote: listening on ${host} — http://${lanAddress() ?? host}:${actual}/deck/remote?t=${token}`);
3569
+ console.log(' off this machine ONLY /deck/remote/* answers, with that token — the deck itself does not');
3570
+ }
3571
+ // The upstream, said once at startup and then only when it CHANGES. `up to
3572
+ // date` every ten minutes for an hour is noise that trains people to stop
3573
+ // reading the terminal — which is where the ingredients label lives. Kicked
3574
+ // AFTER the last startup line and never awaited: nothing about it can delay
3575
+ // the server coming up or hang a talk on a remote that is down.
3576
+ if (upstream) {
3577
+ const tick = () => refreshUpstream().then((st) => {
3578
+ if (st.state !== lastReported) {
3579
+ lastReported = st.state;
3580
+ console.log(` upstream: ${st.message}`);
3581
+ }
3582
+ }).catch(() => {});
3583
+ tick();
3584
+ // unref'd so a Ctrl-C exits now rather than after an in-flight fetch.
3585
+ // `--upstream-every 0` keeps the manual check and drops only the timer.
3586
+ if (intervalMs > 0) setInterval(tick, intervalMs).unref();
3587
+ }
1872
3588
 
1873
3589
  // Did somebody review this deck? Asked ONCE, after the last startup line,
1874
3590
  // detached and never awaited — the update-check shape: nothing about it can
@@ -1877,7 +3593,7 @@ export async function editMain(args, { onListen = null } = {}) {
1877
3593
  // exception cli/git.mjs names, why it is never on a timer, and why it is
1878
3594
  // nowhere near the SIGINT path (finalCommit above says what lives there and
1879
3595
  // why nothing else may).
1880
- if (!onListen) {
3596
+ if (!onListen && !noTrust) {
1881
3597
  const skipped = reviewCheckSuppressed({ args });
1882
3598
  if (skipped) {
1883
3599
  startup('reviews', `not checked — ${skipped}`, ` reviews: not checked — ${skipped}`);
@@ -1889,14 +3605,28 @@ export async function editMain(args, { onListen = null } = {}) {
1889
3605
  })
1890
3606
  .catch(() => {});
1891
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
+ });
1892
3617
  }
1893
3618
  return { port: actual, deckUrl, host, server };
1894
3619
  }
1895
3620
 
1896
3621
 
1897
3622
  if (isMain(import.meta.url)) {
1898
- // author spawns this module directly, so the leash the dispatcher used to
3623
+ // `open` spawns this module directly, so the leash the dispatcher used to
1899
3624
  // arm is armed here — a no-op unless a supervising parent set it up.
1900
3625
  exitWhenOrphaned();
1901
- editMain(process.argv.slice(2));
3626
+ // Through the one error boundary: a throw used to surface as an unhandled
3627
+ // rejection with a raw stack, in a child whose parent's banner had scrolled by.
3628
+ const code = await runMain('open', () => editMain(process.argv.slice(2)));
3629
+ // editMain sets process.exitCode itself on a refusal and resolves to the
3630
+ // server otherwise, so only a failure runMain reported is written here
3631
+ if (code === 1) process.exitCode = 1;
1902
3632
  }