decklight 0.8.1 → 0.9.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 (133) hide show
  1. package/PLATFORM.md +666 -0
  2. package/README.md +224 -150
  3. package/SPEC.md +732 -886
  4. package/cli/agent-review.mjs +245 -0
  5. package/cli/agents.mjs +25 -5
  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 +183 -0
  10. package/cli/bundle.mjs +383 -31
  11. package/cli/cast.mjs +7 -7
  12. package/cli/check.mjs +961 -0
  13. package/cli/clone-deck.mjs +179 -0
  14. package/cli/commands.mjs +345 -0
  15. package/cli/comments.mjs +64 -18
  16. package/cli/commit-flow.mjs +44 -19
  17. package/cli/commit-message.mjs +51 -74
  18. package/cli/commit-split.mjs +601 -0
  19. package/cli/deck-refs.mjs +59 -0
  20. package/cli/deck-routes.mjs +67 -0
  21. package/cli/deckfile.mjs +3 -5
  22. package/cli/decklight.mjs +68 -289
  23. package/cli/design-system-deps.mjs +209 -0
  24. package/cli/design-system-edit.mjs +194 -0
  25. package/cli/design-system-refs.mjs +409 -0
  26. package/cli/design-system.mjs +429 -0
  27. package/cli/doctor.mjs +115 -0
  28. package/cli/edit-git.mjs +353 -0
  29. package/cli/edit-handover.mjs +445 -0
  30. package/cli/edit-look.mjs +388 -0
  31. package/cli/edit-slides.mjs +683 -0
  32. package/cli/edit.mjs +2126 -842
  33. package/cli/enhance.mjs +483 -0
  34. package/cli/extension.mjs +10 -10
  35. package/cli/font-refs.mjs +273 -0
  36. package/cli/font.mjs +246 -0
  37. package/cli/git-tree.mjs +1 -1
  38. package/cli/git.mjs +65 -11
  39. package/cli/import.mjs +56 -10
  40. package/cli/init.mjs +400 -234
  41. package/cli/library.mjs +127 -0
  42. package/cli/loader.mjs +3 -1
  43. package/cli/marketplace.mjs +215 -21
  44. package/cli/narrate.mjs +176 -0
  45. package/cli/open-browser.mjs +63 -0
  46. package/cli/open.mjs +943 -0
  47. package/cli/pdf.mjs +41 -13
  48. package/cli/pkg.mjs +44 -2
  49. package/cli/plugin.mjs +43 -41
  50. package/cli/port-conflict.mjs +53 -23
  51. package/cli/pptx-export.mjs +57 -24
  52. package/cli/publish.mjs +8 -4
  53. package/cli/qr.mjs +1 -1
  54. package/cli/record.mjs +14 -12
  55. package/cli/remote.mjs +11 -11
  56. package/cli/restore.mjs +11 -4
  57. package/cli/review-ref.mjs +125 -0
  58. package/cli/review-remote.mjs +92 -48
  59. package/cli/review-routes.mjs +254 -0
  60. package/cli/review-store.mjs +47 -7
  61. package/cli/review-submit.mjs +47 -57
  62. package/cli/runtime-link.mjs +560 -0
  63. package/cli/serve.mjs +235 -44
  64. package/cli/setup.mjs +112 -0
  65. package/cli/sign.mjs +1 -1
  66. package/cli/skill-content.mjs +190 -33
  67. package/cli/skills.mjs +107 -24
  68. package/cli/start.mjs +110 -0
  69. package/cli/supervise.mjs +6 -6
  70. package/cli/theme-refs.mjs +515 -0
  71. package/cli/theme.mjs +181 -137
  72. package/cli/trust.mjs +83 -0
  73. package/cli/units.mjs +39 -42
  74. package/cli/update-check.mjs +1 -5
  75. package/cli/upgrade.mjs +194 -28
  76. package/cli/upstream.mjs +4 -3
  77. package/cli/util.mjs +4 -4
  78. package/cli/wizard.mjs +6 -6
  79. package/dist/build-info.json +1 -1
  80. package/dist/decklight.css +1126 -49
  81. package/dist/decklight.js +212 -115
  82. package/dist/decklight.js.map +4 -4
  83. package/docs/GLOSSARY.md +141 -0
  84. package/docs/architecture.svg +17 -17
  85. package/package.json +4 -2
  86. package/themes/README.md +9 -8
  87. package/themes/reveal-solarized.css +10 -0
  88. package/tools/args.mjs +20 -0
  89. package/tools/atomic-write.mjs +48 -0
  90. package/tools/brand-palette.mjs +717 -0
  91. package/tools/bridge.mjs +1 -1
  92. package/tools/build-groups.mjs +42 -0
  93. package/tools/color.mjs +48 -0
  94. package/tools/deck-html.mjs +396 -11
  95. package/tools/design-system-format.mjs +753 -0
  96. package/tools/elevenlabs-tts.mjs +110 -17
  97. package/tools/exec.mjs +1 -1
  98. package/tools/extension-check.mjs +31 -7
  99. package/tools/font-format.mjs +190 -0
  100. package/tools/font-stacks.mjs +24 -0
  101. package/tools/gemini-tts.mjs +3 -0
  102. package/tools/lipsync-config.mjs +103 -0
  103. package/tools/lipsync-engines.mjs +205 -2
  104. package/tools/lipsync-server.mjs +264 -41
  105. package/tools/lipsync.mjs +37 -18
  106. package/tools/local-voice.mjs +32 -42
  107. package/tools/narration-manifest.mjs +196 -0
  108. package/tools/narration-synth.mjs +416 -0
  109. package/tools/pptx.mjs +776 -19
  110. package/tools/publish-targets.mjs +1 -1
  111. package/tools/publish-voices.mjs +3 -3
  112. package/tools/recording-impact.mjs +7 -3
  113. package/tools/render-theme.mjs +33 -0
  114. package/tools/review-anchor.mjs +28 -12
  115. package/tools/semver.mjs +40 -0
  116. package/tools/sentences.mjs +180 -0
  117. package/tools/shot.mjs +14 -7
  118. package/tools/site-voices.mjs +232 -0
  119. package/tools/template-theme.mjs +1 -1
  120. package/tools/test-impact.mjs +17 -10
  121. package/tools/theme-check.mjs +30 -3
  122. package/tools/tts-cache.mjs +4 -3
  123. package/tools/tts-engines.mjs +38 -20
  124. package/tools/tts-setup.mjs +7 -7
  125. package/tools/video-options.mjs +34 -0
  126. package/tools/video.mjs +461 -48
  127. package/tools/voiceover-server.mjs +185 -104
  128. package/tools/voiceover.mjs +119 -261
  129. package/tools/zip.mjs +1 -1
  130. package/cli/dev.mjs +0 -623
  131. package/cli/present.mjs +0 -853
  132. package/cli/review.mjs +0 -361
  133. package/tools/publish-site-voices.mjs +0 -75
package/cli/edit.mjs CHANGED
@@ -2,35 +2,43 @@
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
+ // GET /deck/edit/publish/plan → where publishing would put this deck, without putting it there
28
+ // POST /deck/edit/publish → bundle the deck and push it (the palette's Publish row)
29
+ // GET /deck/edit/export/estimate → ?kind=bundle&theme= how big that file would be, before it is written
30
+ // GET /deck/edit/element/source → ?slide=&index= an element's outerHTML, fresh from the file
31
+ // POST /deck/edit/element/remove → { slide, index } delete that element
32
+ // POST /deck/edit/element/content → { slide, index, html } replace its outerHTML
33
+ // POST /deck/edit/element/effect → { slide, index, effect } write data-build (null strips it)
34
+ // POST /deck/edit/undo → step the deck file back through the edit history
35
+ // POST /deck/edit/redo → step it forward again
36
+ // POST /deck/edit/agent → { prompt, agent?, slide? } one-shot AI agent edit
37
+ // POST /deck/edit/enhance → { slides: [n…]|'all', agent?, kind? } audio tags ('tags') or written for the ear ('spoken')
38
+ // POST /deck/edit/enhance/text → { text, agent?, kind? } → { text } the same, for the notes editor's box (writes nothing)
39
+ // POST /deck/edit/review → { agent? } the agent reads the deck, read-only, for Check deck…'s agent review (writes nothing)
40
+ // GET /deck/edit/review → the last review's findings that still hold, each with the prompt that fixes it
41
+ // POST /deck/edit/shutdown → final autocommit, then exit — same as Ctrl-C, so a
34
42
  // port conflict can take over an old session cleanly
35
43
  //
36
44
  // Every mutation goes through ONE undo history — snapshots of the whole
@@ -41,51 +49,104 @@
41
49
  // agent's edit back exactly like the player's own.
42
50
  //
43
51
  // 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
52
+ // --no-git wasn't passed) the server snapshots the deck silently on
53
+ // refs/decklight/wip and commits it when you say so (K) — an agent's own
54
+ // edit commits itself; --git-mode timer keeps the old commit-every-N-seconds
55
+ // cadence with a final commit on Ctrl-C. --git also creates the repository when none
47
56
  // exists — seeded with a starter .gitignore (createRepo, below).
48
- // `decklight author` asks interactively before passing --git down.
57
+ // `decklight <deck>` asks interactively before passing --git down.
49
58
 
50
- import { createServer } from 'node:http';
59
+ import { createServer, request as httpRequest } from 'node:http';
51
60
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, appendFileSync, watch, existsSync } from 'node:fs';
61
+ // Every write of the DECK goes through this rather than writeFileSync: the
62
+ // edit server rewrites the whole file on every small edit, and a truncate
63
+ // that is interrupted leaves a prefix of a talk where the talk was.
64
+ import { writeFileAtomic } from '../tools/atomic-write.mjs';
52
65
  import { resolve, relative, dirname, sep, basename } from 'node:path';
66
+ import { VIDEO_FORMATS, VIDEO_QUALITIES, VIDEO_SUBTITLES, valuesOf } from '../tools/video-options.mjs';
53
67
  import { spawn, execFileSync } from 'node:child_process';
54
- import { agentCommand, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent, claudeActivity } from './agents.mjs';
68
+ import { AsyncLocalStorage } from 'node:async_hooks';
69
+ import { agentAsk, agentCommand, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent, claudeActivity } from './agents.mjs';
55
70
  import { exitWhenOrphaned } from './supervise.mjs';
56
71
  import { readyLine } from './banner.mjs';
57
72
 
58
73
  /**
59
74
  * Say a startup fact.
60
75
  *
61
- * Under author (DECKLIGHT_BANNER) it becomes a row on the one banner author
76
+ * Under `open` (DECKLIGHT_BANNER) it becomes a row on the one banner author
62
77
  * prints, so it cannot land above the URL. Run standalone — `decklight edit` —
63
78
  * it prints the line it always printed, which is why every call passes both:
64
79
  * the SHORT text a banner row wants, and the full sentence a bare terminal
65
- * needs because it has no banner to sit under.
80
+ * needs because it has no banner to sit under. `mark` is the banner's: 'ok'
81
+ * for something installed and on (a green tick), 'warn' for something to fix.
66
82
  */
67
- const startup = (key, text, human) => {
68
- if (process.env.DECKLIGHT_BANNER) console.log(readyLine({ key, text }));
83
+ const startup = (key, text, human, mark) => {
84
+ if (process.env.DECKLIGHT_BANNER) console.log(readyLine({ key, text, ...(mark ? { mark } : {}) }));
69
85
  else console.log(human);
70
86
  };
71
- import { argReader, firstPositional, isMain } from '../tools/args.mjs';
72
- import { NOTES_ASIDE, locateSlide, sectionChildRanges } from '../tools/deck-html.mjs';
87
+ import { argReader, firstPositional, isMain, parsePort, badPort } from '../tools/args.mjs';
88
+ import { runMain } from './util.mjs';
89
+ import { PKG, AGENTS_MARKER, skillVersionOf } from './skill-content.mjs';
90
+ import { selfCommand } from './pkg.mjs';
91
+ import { slidesSinceHead } from './commit-split.mjs';
92
+ import { semverCompare } from '../tools/semver.mjs';
93
+
94
+ // The flags that take a value, so the deck can be found past them. `--git-mode`
95
+ // was missing, so `edit.mjs --git-mode agent deck.html` refused a deck called
96
+ // "agent". (`decklight <deck>` builds this argv itself and was never affected.)
97
+ const VALUE_FLAGS = ['--port', '--commit-every', '--agent', '--git-mode', '--tts-port', '--lipsync-port',
98
+ '--host', '--root', '--branch', '--into', '--upstream-every'];
99
+ import { NOTES_ASIDE, locateSlide, sectionChildRanges, elementChildRanges, splitOpenTag } from '../tools/deck-html.mjs';
100
+ import { canonMarks, writtenMarks, CLICK_MARK } from '../tools/sentences.mjs';
101
+ import { configBlock, hasEmbeddedRuntime, linkRuntime } from './runtime-link.mjs';
102
+ import { linkReferences } from './deck-refs.mjs';
103
+ import { slideTexts, priorSlideTexts, staleSlides } from '../tools/narration-manifest.mjs';
104
+ // The routes that rewrite a slide, which took three of editMain's bindings and
105
+ // nothing else with them. The import back — edit-slides reaches here for the
106
+ // pure transforms — is a deliberate static cycle and not a dynamic one: this
107
+ // module ends in a top-level `await` (the isMain boot below), so a
108
+ // `await import('./edit-slides.mjs')` from inside editMain would wait on an
109
+ // evaluation that is waiting on IT, and the server would never come up.
110
+ // A static cycle has no such moment: both bodies are function declarations,
111
+ // hoisted before either runs, and nothing is read until a request arrives.
112
+ import { registerSlideRoutes } from './edit-slides.mjs';
113
+ // The route groups split out after it, imported the same way and for the same
114
+ // reason: the deck's look (themes, design systems, fonts), and handing the
115
+ // deck over (export, publish, the inspector's read), and git (the commit
116
+ // window, the deck's history, restore).
117
+ import { registerLookRoutes } from './edit-look.mjs';
118
+ import { registerHandoverRoutes } from './edit-handover.mjs';
119
+ import { registerGitRoutes } from './edit-git.mjs';
73
120
  // the boot-call locator audit and upgrade share — three commands, one answer
74
121
  // about which <script> is the init call
75
- import { classifyScripts } from './audit.mjs';
122
+ import { classifyScripts, auditDeck, formatLabel, stripUnaccounted } from './audit.mjs';
123
+ // The no-trust mode's own ingredients (PRESENTING): the signature beside a
124
+ // deck, the .decklight container, the presenter's chrome, the upstream of a
125
+ // clone, and the phone remote. None of them writes.
126
+ import { randomBytes } from 'node:crypto';
127
+ import { verifyFile, verifyBytes, formatSignature, isVerified, UNSIGNED, TAMPERED, VERIFIED } from './sign.mjs';
128
+ import { isContainer, readContainer, formatManifest } from './deckfile.mjs';
129
+ import { loadLibrary, injectChrome } from './plugin.mjs';
130
+ import {
131
+ SAFE_CONFIG, canPull, checkUpstream, resolveInterval, resolveUpstream, runGit, upstreamSuppressed,
132
+ } from './upstream.mjs';
133
+ import { createRemoteRelay } from './remote.mjs';
134
+ import { corsHeaders, readBody } from '../tools/bridge.mjs';
76
135
  import { reviewPathFor, parseReview, serializeRecord, newId } from './review-store.mjs';
77
- // The arbiters of what a comment IS, shared with the review server so two
136
+ import { createReviewRoutes } from './review-routes.mjs';
137
+ import { createDeckRoutes } from './deck-routes.mjs';
138
+ // The arbiters of what a comment IS, shared with the no-trust mode so two
78
139
  // writers cannot put two shapes into one union-merged file.
79
- import { commentProblem, reviewRecord } from './review.mjs';
140
+ import { commentProblem, reviewRecord } from './review-routes.mjs';
80
141
  import { foldReview } from '../tools/review-anchor.mjs';
81
142
  import { recordingImpact, impactWarning, slidesFromFiles } from '../tools/recording-impact.mjs';
82
143
  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';
144
+ import { deckAt } from './restore.mjs';
145
+ import { escapeHtml, staticFiles, listenTakingOverIfNeeded, allowEditRequest, allowRemote, lanAddress, isOwnOrigin, CSP } from './serve.mjs';
146
+ import { reviewsWaiting, reviewLine, reviewCheckSuppressed } from './review-remote.mjs';
86
147
  import { configureEngine, loadCredentials, forgetCredentials, redactAnswers, validateSchema, provenance, BRIDGE_ADDR, CONFIGURED, UNREACHABLE, PREREQUISITE } from './wizard.mjs';
87
148
 
88
- // The `/edit/*` surface answers loopback only — but "loopback" is the wrong
149
+ // The `/deck/edit/*` surface answers loopback only — but "loopback" is the wrong
89
150
  // boundary for the threat (#222). The dangerous caller is not off-machine: it
90
151
  // is the user's own browser, where any open tab can `fetch()` this port. Binding
91
152
  // 127.0.0.1 does nothing about that, and a wildcard `access-control-allow-origin`
@@ -102,18 +163,26 @@ const corsHeadersFor = (origin) => ({
102
163
  });
103
164
 
104
165
  // ── 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
166
+ // (NO_TRUST in MARKETPLACE.md: `decklight <deck> --no-trust` reuses the same core
167
+ // with the /deck/edit/* routes ABSENT, not merely refused.) Re-exported here so
107
168
  // existing importers — the tests, init.mjs — and SPEC citations keep working.
108
169
  export { isLoopback, lanAddress, escapeHtml } from './serve.mjs';
109
170
 
110
- /** ⟨CLICK⟩-separated plain text → the aside's inner HTML (one <p> per segment). */
171
+ /**
172
+ * Click-separated plain text → the aside's inner HTML: one <p> per paragraph
173
+ * — a blank line apart, as the author wrote them; saving never merges them —
174
+ * and a `<p>[click]</p>` between beats. Every marker spelling is read
175
+ * (`[click]`, `<click>`, `⟨CLICK⟩`…) and each is written back the one way
176
+ * decklight writes them, in square brackets.
177
+ */
111
178
  export function notesTextToAside(text) {
112
- const segs = text.split(/\s*⟨CLICK⟩\s*/).map((s) => s.replace(/\s+/g, ' ').trim());
113
179
  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>`);
180
+ canonMarks(text).split(CLICK_MARK).forEach((seg, i) => {
181
+ if (i > 0) ps.push('<p>[click]</p>');
182
+ for (const para of writtenMarks(seg).split(/\n[ \t]*\n/)) {
183
+ const p = para.replace(/\s+/g, ' ').trim();
184
+ if (p) ps.push(`<p>${escapeHtml(p)}</p>`);
185
+ }
117
186
  });
118
187
  return ps.join('\n ');
119
188
  }
@@ -124,12 +193,187 @@ export function setSlideNotes(html, slide, asideInner) {
124
193
  const aside = `<aside class="notes">\n ${asideInner}\n </aside>`;
125
194
  const seg = parts[idx];
126
195
  parts[idx] = NOTES_ASIDE.test(seg)
127
- ? seg.replace(NOTES_ASIDE, aside)
128
- : seg.replace(/<\/section>/, ` ${aside}\n </section>`);
196
+ // FUNCTION replacers: the notes are the author's text, and a string
197
+ // replacement would read `$1`, `$&`, `` $` `` and `$'` in it as patterns —
198
+ // "$1M" spliced the slide's whole old notes in where it was typed (#646)
199
+ ? seg.replace(NOTES_ASIDE, () => aside)
200
+ : seg.replace(/<\/section>/, () => ` ${aside}\n </section>`);
201
+ return parts.join('');
202
+ }
203
+
204
+ /**
205
+ * A slide's sources as the aside's inner HTML (`SLIDE_SOURCES`), or `null`
206
+ * when there is nothing left to write.
207
+ *
208
+ * Link hrefs are restricted to the schemes a reference can honestly be:
209
+ * `javascript:` and `data:` are executable, and this aside travels — a slide
210
+ * taken from a marketplace template carries its sources into your deck, so an
211
+ * editor that will write an executable link is an editor that will eventually
212
+ * write somebody else's.
213
+ */
214
+ export function sourcesToAside({ facts = [], links = [] } = {}, dropped = []) {
215
+ const clean = (u) => (/^(https?:|mailto:|#|\/|\.{0,2}\/)/i.test(String(u).trim()) ? String(u).trim() : null);
216
+ const pairs = facts.filter(([k, v]) => String(k).trim() && String(v).trim());
217
+ const refs = links.filter((l) => {
218
+ if (!String(l?.title ?? '').trim()) return false;
219
+ if (clean(l?.href)) return true;
220
+ // a link that will not be written is a link the author has to hear about:
221
+ // an empty row is just an empty row, a rejected scheme is a decision
222
+ if (String(l?.href ?? '').trim()) dropped.push(String(l.href).trim());
223
+ return false;
224
+ });
225
+ if (!pairs.length && !refs.length) return null;
226
+ const dl = pairs.length
227
+ ? `<dl>${pairs.map(([k, v]) => `<dt>${escapeHtml(k.trim())}</dt><dd>${escapeHtml(v.trim())}</dd>`).join('')}</dl>`
228
+ : '';
229
+ const ul = refs.length
230
+ ? ['<ul>', ...refs.map((l) => ` <li><a href="${escapeHtml(clean(l.href))}">${escapeHtml(String(l.title).trim())}</a>`
231
+ + `${String(l.note ?? '').trim() ? ` — ${escapeHtml(String(l.note).trim())}` : ''}</li>`), ' </ul>'].join('\n')
232
+ : '';
233
+ return [dl, ul].filter(Boolean).join('\n ');
234
+ }
235
+
236
+ /** Replace, insert, or remove slide N's `<aside class="sources">`. */
237
+ export function setSlideSources(html, slide, asideInner) {
238
+ const { parts, idx } = locateSlide(html, slide);
239
+ const seg = parts[idx];
240
+ const existing = /\n?\s*<aside class="sources">[\s\S]*?<\/aside>/;
241
+ if (!asideInner) {
242
+ parts[idx] = seg.replace(existing, '');
243
+ return parts.join('');
244
+ }
245
+ const aside = `<aside class="sources">\n ${asideInner}\n </aside>`;
246
+ parts[idx] = existing.test(seg)
247
+ ? seg.replace(existing, () => `\n ${aside}`) // the author's text: never a replacement pattern (#646)
248
+ : seg.replace(/<\/section>/, () => ` ${aside}\n </section>`);
129
249
  return parts.join('');
130
250
  }
131
251
 
132
252
  // the same ring the player cycles — the file is the source of truth now
253
+ /**
254
+ * Is this deck already one file — nothing left for the bundler to flatten?
255
+ *
256
+ * `decklight bundle` asks exactly this and refuses when the answer is yes, so
257
+ * the publish route asks it FIRST and passes `--no-bundle` rather than handing
258
+ * a presenter a refusal about a flag. An init-scaffolded deck is this case,
259
+ * which makes it the common one rather than the corner.
260
+ */
261
+ export const alreadyOneFile = (html) =>
262
+ !/<link\b[^>]*rel=["']stylesheet["'][^>]*href=["'][^"']*themes\/[\w-]+\.css["']/i.test(html)
263
+ && /<style\b[^>]*\bdata-theme\b/i.test(html)
264
+ // an imported deck with a derived theme embeds that theme and nothing else
265
+ // (#520): the runtime is still to be bundled in
266
+ && hasEmbeddedRuntime(html);
267
+
268
+ /**
269
+ * The files the palette's hand-over rows can ask for (PRESENTING). Each is one
270
+ * of decklight's own commands, named the way the deck names it to the presenter
271
+ * — `what` IS the wording in the toast, so the row, the terminal line and the
272
+ * message log all say the same words.
273
+ */
274
+ export const EXPORT_KINDS = {
275
+ pptx: { what: 'PowerPoint', variant: null },
276
+ pdf: { what: 'PDF', variant: '' },
277
+ 'pdf-notes': { what: 'PDF with notes', variant: 'notes' },
278
+ 'pdf-handout': { what: 'PDF handout', variant: 'handout' },
279
+ video: { what: 'video', variant: null },
280
+ // the self-contained file `decklight bundle` writes — every marked theme in
281
+ // it, opening on the theme on screen
282
+ bundle: { what: 'one file', variant: null },
283
+ };
284
+
285
+ /**
286
+ * The preview frame's failure, as a page rather than as a bare line of text.
287
+ *
288
+ * This frame is 700px of dark chrome inside the history dialog, and a
289
+ * plain-text body rendered in it reads as a black rectangle — which is how
290
+ * #508 looked to everyone who hit it. Styled here, in the server's own words,
291
+ * so the panel needs no failure branch of its own: whatever went wrong is
292
+ * legible in the place somebody is already looking.
293
+ */
294
+ export function previewError(why) {
295
+ return `<!doctype html><meta charset="utf-8"><title>preview unavailable</title>
296
+ <style>
297
+ :root { color-scheme: dark light; }
298
+ body { margin: 0; display: grid; place-items: center; min-height: 100vh;
299
+ background: #16181d; color: #e8eaee; font: 14px/1.6 system-ui, sans-serif; }
300
+ .box { max-width: 34em; padding: 24px; text-align: center; }
301
+ h1 { margin: 0 0 6px; font-size: 15px; font-weight: 600; }
302
+ p { margin: 0; opacity: .7; }
303
+ </style>
304
+ <div class="box"><h1>this version could not be previewed</h1><p>${escapeHtml(why)}</p></div>
305
+ `;
306
+ }
307
+
308
+ /**
309
+ * What is wrong with a video export request, or null. Every field comes from a
310
+ * page, so every one is checked before anything runs.
311
+ *
312
+ * - `slides` is the command's own `--slides` spelling; `format`, `quality` and
313
+ * `subtitles` its `--format`, `--quality` and `--subtitles`.
314
+ * - The voice is ONE of three: `narration` names a recorded folder (inside the
315
+ * deck's directory, holding a manifest — a render that cannot find its audio
316
+ * should refuse, not come out silent); `synthesize` asks for the live voice
317
+ * to be voiced into a folder first; `silent` is silence by name. None of them
318
+ * is the command's own default: a `voiceover/` beside the deck if there is one.
319
+ * - A synthesized voice never lands on a take somebody recorded. A folder that
320
+ * already holds audio is refreshed only when its manifest says it was this
321
+ * engine and this voice; anything else — a manifest for another voice, or
322
+ * audio with no manifest at all, which is what your own voice leaves — refuses.
323
+ */
324
+ export function videoExportProblem({ slides, narration, synthesize, silent, format, quality, subtitles, allowStale } = {}, deckDir) {
325
+ if (allowStale != null && typeof allowStale !== 'boolean') return 'allowStale is yes or no';
326
+ // the card's rows and the command's flags read one list (src/core/video-options.js)
327
+ for (const [field, value, list] of [['format', format, VIDEO_FORMATS], ['quality', quality, VIDEO_QUALITIES], ['subtitles', subtitles, VIDEO_SUBTITLES]]) {
328
+ if (value != null && !valuesOf(list).includes(value)) return `${field} must be ${valuesOf(list).join(', ')}`;
329
+ }
330
+ if (slides != null && slides !== '' && !(typeof slides === 'string' && /^\d+(?:-\d+)?$/.test(slides))) {
331
+ return 'slides must be a-b or a single slide number';
332
+ }
333
+ const given = [narration, synthesize, silent].filter((v) => v != null && v !== '' && v !== false);
334
+ if (given.length > 1) return 'one voice at a time — a recorded track, a synthesized one, or silence';
335
+ if (synthesize != null) {
336
+ if (typeof synthesize !== 'object') return 'synthesize names an engine, a voice and a folder';
337
+ const { engine, model, voice, style, dir } = synthesize;
338
+ if (typeof engine !== 'string' || !/^[a-z][a-z0-9-]{0,40}$/.test(engine)) return 'name the engine to synthesize with';
339
+ for (const [field, value, max] of [['model', model, 200], ['voice', voice, 200], ['style', style, 2000]]) {
340
+ if (value != null && (typeof value !== 'string' || value.length > max || /\p{Cc}/u.test(value))) {
341
+ return `the ${field} is not one this server will pass on`;
342
+ }
343
+ }
344
+ const bad = folderProblem(dir, deckDir, 'the synthesized voice');
345
+ if (bad) return bad;
346
+ const at = resolve(deckDir, dir);
347
+ let audio = [];
348
+ try { audio = readdirSync(at).filter((f) => /^slide-\d+(-\d+)?\.(wav|m4a|mp3)$/.test(f)); } catch { /* a new folder */ }
349
+ if (audio.length) {
350
+ let m = null;
351
+ try { m = JSON.parse(readFileSync(resolve(at, 'manifest.json'), 'utf8')); } catch { /* recorded by hand */ }
352
+ if (!m || m.engine !== engine || (m.voice ?? null) !== (voice ?? null)) {
353
+ return `${dir}/ already holds ${m?.voice ? `${m.voice}'s recording` : 'a recording'} — synthesizing into it would replace it`;
354
+ }
355
+ }
356
+ return null;
357
+ }
358
+ if (narration == null || narration === '') return null;
359
+ const bad = folderProblem(narration, deckDir, 'the narration');
360
+ if (bad) return bad;
361
+ if (!existsSync(resolve(deckDir, narration, 'manifest.json'))) {
362
+ return `no recorded narration in ${narration}/ — record the deck first (V → Record this deck…)`;
363
+ }
364
+ return null;
365
+ }
366
+
367
+ /** A folder named by a page: relative, inside the deck's own directory. */
368
+ function folderProblem(dir, deckDir, what) {
369
+ if (typeof dir !== 'string' || !dir || dir.length > 200 || /^[a-z][a-z0-9+.-]*:/i.test(dir)) {
370
+ return `${what} is a folder beside the deck, not a URL`;
371
+ }
372
+ const at = resolve(deckDir, dir);
373
+ if (!at.startsWith(resolve(deckDir) + sep)) return `${what} folder must be inside the deck's folder (${dir})`;
374
+ return null;
375
+ }
376
+
133
377
  export const LAYOUTS = ['auto', 'centered', 'pinned', 'top', 'split', 'split-flip'];
134
378
 
135
379
  /** Set (or, for 'auto', remove) slide N's data-layout attribute in the deck html. */
@@ -180,7 +424,7 @@ export function setSlideHidden(html, slide, hidden) {
180
424
  }
181
425
 
182
426
  /** Look up element `index` (raw child position) on slide `slide`, or throw. */
183
- function locateElement(html, slide, index) {
427
+ export function locateElement(html, slide, index) {
184
428
  const { parts, idx } = locateSlide(html, slide);
185
429
  const seg = parts[idx];
186
430
  const ranges = sectionChildRanges(seg);
@@ -196,6 +440,206 @@ export function removeSlideElement(html, slide, index) {
196
440
  return parts.join('');
197
441
  }
198
442
 
443
+ /**
444
+ * Remove ONE element inside slide N's element `index` (PRESENTING, a shape
445
+ * selected inside a diagram): the node at `path`, addressed and checked the
446
+ * way setElementStyles addresses one. `[]` is refused, since that is the
447
+ * whole element and removeSlideElement's job. A node alone on its line takes
448
+ * the line with it, so the file is left without a blank one.
449
+ */
450
+ export function removeNestedElement(html, slide, index, { path, tag }) {
451
+ if (!Array.isArray(path) || !path.length || path.length > 16 || path.some((n) => !Number.isInteger(n) || n < 0)) throw new Error('bad path');
452
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
453
+ const el = seg.slice(r.start, r.end);
454
+ let start = 0; let end = el.length;
455
+ for (const n of path) {
456
+ const kid = elementChildRanges(el.slice(start, end))[n];
457
+ if (!kid) throw stale(`slide ${slide} #${index}: the file has no element at ${path.join('.')} — reload and try again`);
458
+ end = start + kid.end; start += kid.start;
459
+ }
460
+ const found = /^<([a-zA-Z][\w:-]*)/.exec(el.slice(start, end))?.[1]?.toLowerCase();
461
+ 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`);
462
+ const lineStart = el.lastIndexOf('\n', start - 1) + 1;
463
+ const nl = el.indexOf('\n', end);
464
+ const lineEnd = nl < 0 ? el.length : nl;
465
+ if (/^[ \t]*$/.test(el.slice(lineStart, start)) && /^[ \t]*$/.test(el.slice(end, lineEnd)) && nl >= 0) { start = lineStart; end = nl + 1; }
466
+ parts[idx] = seg.slice(0, r.start) + el.slice(0, start) + el.slice(end) + seg.slice(r.end);
467
+ return parts.join('');
468
+ }
469
+
470
+ /**
471
+ * The colours a page may ask this server to write (PRESENTING, element edit
472
+ * mode): a theme token by reference — `var(--d-fill-3)`, so the deck stays
473
+ * theme-aware — a design system's token with ONE hex fallback,
474
+ * `var(--acme-blue, #0056f9)` (SPEC DESIGN_SYSTEMS: the colour survives the
475
+ * design system going missing), or a literal hex colour. Nothing else — no
476
+ * nested var(), no other characters: the value lands inside a style
477
+ * attribute, and a style attribute is markup.
478
+ */
479
+ const STYLE_VALUE = /^(?:var\(--[a-z][a-z0-9-]{0,40}(?:,\s?#[0-9a-f]{3,8})?\)|#[0-9a-f]{3,8})$/i;
480
+ const STYLE_PROPS = new Set(['fill', 'color', 'background-color', 'stroke', 'border-color']);
481
+ // a stroke's width (#717): a number in px, unitless on a shape the way SVG
482
+ // reads it, `px` on a box the way CSS does — never anything that is not one
483
+ const WIDTH_PROPS = new Set(['stroke-width', 'border-width']);
484
+ const WIDTH_VALUE = /^(?:\d{1,2}(?:\.\d{1,2})?)(?:px)?$/;
485
+ // the colour card's Type side: the size in px (deck units: the stage is
486
+ // scaled, not the text), a weight in hundreds, one of the theme's three font
487
+ // roles by reference (never a family name, so the type follows `T` and a
488
+ // deck's marked fonts), and where a line sits. Each a closed shape.
489
+ const TYPE_VALUES = {
490
+ 'font-size': /^(?:[1-9]\d{0,2}(?:\.\d)?)px$/,
491
+ 'font-weight': /^[1-9]00$/,
492
+ 'font-family': /^var\(--font-(?:heading|body|mono)\)$/,
493
+ 'font-style': /^(?:normal|italic)$/,
494
+ 'text-anchor': /^(?:start|middle|end)$/,
495
+ 'text-align': /^(?:left|center|right)$/,
496
+ };
497
+ const kindOf = (prop) => (STYLE_PROPS.has(prop) ? 'colour' : WIDTH_PROPS.has(prop) ? 'width' : Object.hasOwn(TYPE_VALUES, prop) ? prop.replace('-', ' ') : null);
498
+ const valueShape = (prop) => (STYLE_PROPS.has(prop) ? STYLE_VALUE : WIDTH_PROPS.has(prop) ? WIDTH_VALUE : TYPE_VALUES[prop]);
499
+
500
+ /** The page and the file disagree about what is where: a 409, not a bad request. */
501
+ const stale = (message) => Object.assign(new Error(message), { code: 'STALE' });
502
+
503
+ /** `style` text with `prop` set to `value` (null: taken off) — its old declaration replaced, the rest kept in order. */
504
+ export function withStyleProp(style, prop, value) {
505
+ const kept = String(style ?? '').split(';').map((d) => d.trim()).filter(Boolean)
506
+ .filter((d) => d.slice(0, d.indexOf(':')).trim().toLowerCase() !== prop);
507
+ return (value === null ? kept : [...kept, `${prop}: ${value}`]).join('; ');
508
+ }
509
+
510
+ /**
511
+ * Set style properties on elements INSIDE slide N's element `index` — a shape
512
+ * in a diagram and the text on it, in one edit (so `Z` takes both back).
513
+ *
514
+ * Each edit is `{ path, tag, prop, value }`: `path` is the element's
515
+ * child-index path below the slide's top-level element (`[]` is that element
516
+ * itself), counted over the FILE's elements, and `tag` is what the page found
517
+ * there — the live DOM is not the file (the engine adds nodes of its own), so
518
+ * a path that lands on a different tag is refused rather than recoloured.
519
+ * Only the open tag's `style` attribute is touched, textually: every other
520
+ * attribute — `viewBox` and its capitals included — survives byte for byte.
521
+ * A `value` of null takes the declaration back off, and a `style` left empty
522
+ * goes with it. A slot token picked on a nested box still takes its panel's
523
+ * tone (SVG_DIAGRAMS): the pick names the colour family, the engine keeps it
524
+ * legible where it sits — `data-nest="off"` in the markup is the opt-out.
525
+ */
526
+ export function setElementStyles(html, slide, index, edits) {
527
+ if (!Array.isArray(edits) || !edits.length || edits.length > 40) throw new Error('bad edits');
528
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
529
+ let el = seg.slice(r.start, r.end);
530
+ // each edit re-walks from the top: the one before it changed the offsets
531
+ for (const e of edits) {
532
+ if (!Array.isArray(e?.path) || e.path.length > 16 || e.path.some((n) => !Number.isInteger(n) || n < 0)) throw new Error('bad path');
533
+ const kind = kindOf(e.prop);
534
+ if (!kind) throw new Error(`not a property this server writes: ${String(e.prop).slice(0, 40)}`);
535
+ 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)}`);
536
+ let start = 0; let end = el.length;
537
+ for (const n of e.path) {
538
+ const kids = elementChildRanges(el.slice(start, end));
539
+ const kid = kids[n];
540
+ 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`);
541
+ end = start + kid.end; start += kid.start;
542
+ }
543
+ const node = el.slice(start, end);
544
+ const tag = /^<([a-zA-Z][\w:-]*)/.exec(node)?.[1]?.toLowerCase();
545
+ if (e.tag && tag !== String(e.tag).toLowerCase()) {
546
+ throw stale(`slide ${slide} #${index}: the page found <${e.tag}> at ${e.path.join('.') || 'the element'}, the file has <${tag}> — reload and try again`);
547
+ }
548
+ const { attrs, close, rest } = splitOpenTag(node);
549
+ const styleM = /\sstyle\s*=\s*("([^"]*)"|'([^']*)')/i.exec(attrs);
550
+ const style = withStyleProp(styleM ? (styleM[2] ?? styleM[3]) : '', e.prop, e.value).replace(/"/g, "'");
551
+ const attr = style ? ` style="${style}"` : '';
552
+ const head = styleM ? attrs.replace(styleM[0], () => attr) : attrs + attr;
553
+ el = el.slice(0, start) + head + close + rest + el.slice(end);
554
+ }
555
+ parts[idx] = seg.slice(0, r.start) + el + seg.slice(r.end);
556
+ return parts.join('');
557
+ }
558
+
559
+ /**
560
+ * Set or remove ONE attribute on an element below slide N's child `index`,
561
+ * addressed the way setElementStyles addresses one (`path` below the
562
+ * element, `tag` as the page saw it). What this server writes this way is a
563
+ * closed set — `data-concept` (SVG_DIAGRAMS, #718) — with a value that is a
564
+ * name and nothing else; null takes the attribute off.
565
+ */
566
+ const ATTR_NAMES = new Set(['data-concept']);
567
+ const ATTR_VALUE = /^[a-z][a-z0-9-]{0,40}$/i;
568
+ export function setElementAttr(html, slide, index, { path, tag, name, value }) {
569
+ if (!Array.isArray(path) || path.length > 16 || path.some((n) => !Number.isInteger(n) || n < 0)) throw new Error('bad path');
570
+ if (!ATTR_NAMES.has(name)) throw new Error(`not an attribute this server writes: ${name}`);
571
+ if (value !== null && (typeof value !== 'string' || !ATTR_VALUE.test(value))) throw new Error(`not a name: ${String(value).slice(0, 40)}`);
572
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
573
+ let el = seg.slice(r.start, r.end);
574
+ let start = 0; let end = el.length;
575
+ for (const n of path) {
576
+ const kid = elementChildRanges(el.slice(start, end))[n];
577
+ if (!kid) throw stale(`slide ${slide} #${index}: the file has no element at ${path.join('.')} — reload and try again`);
578
+ end = start + kid.end; start += kid.start;
579
+ }
580
+ const node = el.slice(start, end);
581
+ const found = /^<([a-zA-Z][\w:-]*)/.exec(node)?.[1]?.toLowerCase();
582
+ 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`);
583
+ const { attrs, close, rest } = splitOpenTag(node);
584
+ const re = new RegExp(`\\s${name}(?:\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s>]+))?`, 'i');
585
+ const head = value === null ? attrs.replace(re, '') : (re.test(attrs) ? attrs.replace(re, () => ` ${name}="${value}"`) : `${attrs} ${name}="${value}"`);
586
+ el = el.slice(0, start) + head + close + rest + el.slice(end);
587
+ parts[idx] = seg.slice(0, r.start) + el + seg.slice(r.end);
588
+ return parts.join('');
589
+ }
590
+
591
+ /** The text a run of markup reads as: the entities a label is likely to carry, decoded. */
592
+ const decodeText = (s) => String(s).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (m, e) => {
593
+ const k = e.toLowerCase();
594
+ if (k[0] === '#') return String.fromCodePoint(k[1] === 'x' ? parseInt(k.slice(2), 16) : parseInt(k.slice(1), 10));
595
+ return { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }[k];
596
+ });
597
+ const sameWords = (a, b) => String(a).replace(/\s+/g, ' ').trim() === String(b).replace(/\s+/g, ' ').trim();
598
+
599
+ /**
600
+ * Replace the words of ONE diagram label (SVG_DIAGRAMS): the `<text>` or
601
+ * `<tspan>` at `path` below slide N's element `index`, addressed the way
602
+ * setElementStyles addresses a shape. Only what is between its tags changes,
603
+ * and only when that is words: a `<text>` holding `<tspan>` lines is refused,
604
+ * since each line is its own label. `was` is what the page showed there, and
605
+ * a file that says something else is stale (a 409), not overwritten. The
606
+ * whitespace the file has around the words is kept, and `<`, `>` and `&` are
607
+ * escaped on the way in, so the markup around the label survives byte for
608
+ * byte. One line, because SVG text does not wrap.
609
+ */
610
+ const LABEL_TAGS = new Set(['text', 'tspan']);
611
+ export function setElementText(html, slide, index, { path, tag, was, text }) {
612
+ if (!Array.isArray(path) || path.length > 16 || path.some((n) => !Number.isInteger(n) || n < 0)) throw new Error('bad path');
613
+ 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');
614
+ if (typeof was !== 'string') throw new Error('bad payload');
615
+ const { parts, idx, seg, r } = locateElement(html, slide, index);
616
+ let el = seg.slice(r.start, r.end);
617
+ let start = 0; let end = el.length;
618
+ for (const n of path) {
619
+ const kid = elementChildRanges(el.slice(start, end))[n];
620
+ if (!kid) throw stale(`slide ${slide} #${index}: the file has no element at ${path.join('.')} — reload and try again`);
621
+ end = start + kid.end; start += kid.start;
622
+ }
623
+ const node = el.slice(start, end);
624
+ const found = /^<([a-zA-Z][\w:-]*)/.exec(node)?.[1]?.toLowerCase();
625
+ 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`);
626
+ if (!LABEL_TAGS.has(found)) throw new Error(`not a diagram label: <${found}>`);
627
+ const { attrs, close, rest } = splitOpenTag(node);
628
+ const closeAt = rest.toLowerCase().lastIndexOf(`</${found}`);
629
+ if (close.endsWith('/>') || closeAt < 0) throw new Error(`<${found}> has no words to edit`);
630
+ const inner = rest.slice(0, closeAt);
631
+ if (/<(?!!--)/.test(inner)) throw new Error(`this <${found}> holds other elements — edit one line at a time`);
632
+ if (!sameWords(decodeText(inner.replace(/<!--[\s\S]*?-->/g, '')), was)) {
633
+ throw stale(`slide ${slide} #${index}: the file's label is not the one the page showed — reload and try again`);
634
+ }
635
+ const escaped = text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
636
+ const lead = /^\s*/.exec(inner)[0]; const trail = /\s*$/.exec(inner)[0];
637
+ const words = inner.trim() ? lead + escaped + trail : escaped;
638
+ el = el.slice(0, start) + attrs + close + words + rest.slice(closeAt) + el.slice(end);
639
+ parts[idx] = seg.slice(0, r.start) + el + seg.slice(r.end);
640
+ return parts.join('');
641
+ }
642
+
199
643
  /** Replace slide N's element at raw child index `index` with `outerHtml` verbatim. */
200
644
  export function setSlideElementHtml(html, slide, index, outerHtml) {
201
645
  const { parts, idx, seg, r } = locateElement(html, slide, index);
@@ -358,7 +802,7 @@ export function narrationLiteral(cfg) {
358
802
  *
359
803
  * The recorder writes the files and then had to ask you to paste a config line
360
804
  * 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,
805
+ * key and an arrow. The edit server already owns this file (it writes notes,
362
806
  * layouts and element edits), so it can write this too, through the same
363
807
  * applyEdit door: Z undoes it, live-reload shows it.
364
808
  *
@@ -367,11 +811,6 @@ export function narrationLiteral(cfg) {
367
811
  * guessing which `cfg` is meant, in which scope, is how an editor corrupts a
368
812
  * file. That deck keeps the printed line and is told why.
369
813
  */
370
- /** `{ label: 'Rachel · ElevenLabs', dir: 'voices/rachel', ext: 'wav' }` */
371
- export function trackLiteral(track) {
372
- return narrationLiteral(track);
373
- }
374
-
375
814
  /**
376
815
  * Add a recorded track to the deck's `narration.files`, or update it in place.
377
816
  *
@@ -402,6 +841,14 @@ export function trackLiteral(track) {
402
841
  * config built outside the call, or a manifest-only track.
403
842
  */
404
843
  export function configuredTrackDirs(html) {
844
+ // A deck as data (#520): the configuration is JSON, and reads as such.
845
+ const block = configBlock(html);
846
+ if (block) {
847
+ const files = block.config?.narration?.files;
848
+ if (typeof files === 'string') return [files];
849
+ if (!Array.isArray(files)) return [];
850
+ return files.flatMap((e) => (typeof e === 'string' ? [e] : e && typeof e === 'object' && e.dir && !e.manifest ? [e.dir] : []));
851
+ }
405
852
  const arg = initArgument(html);
406
853
  if (!arg) return [];
407
854
  const raw = html.slice(arg.start, arg.end);
@@ -432,6 +879,31 @@ export function configuredTrackDirs(html) {
432
879
  }
433
880
 
434
881
  export function upsertNarrationTrack(html, track) {
882
+ // A deck as data (#520): the block is parsed, changed and written back as
883
+ // JSON — its own formatting goes, its every key survives. Null when the
884
+ // block is not JSON: an editor that guesses at broken data corrupts it.
885
+ const block = configBlock(html);
886
+ if (block) {
887
+ if (!block.config) return null;
888
+ const cfg = block.config;
889
+ if (cfg.narration !== undefined && (typeof cfg.narration !== 'object' || cfg.narration === null || Array.isArray(cfg.narration))) return null;
890
+ const narr = cfg.narration ?? (cfg.narration = {});
891
+ const entry = Object.fromEntries(Object.entries(track).filter(([, v]) => v !== undefined && v !== null));
892
+ let list;
893
+ if (Array.isArray(narr.files)) list = narr.files;
894
+ else if (typeof narr.files === 'string') {
895
+ // the one-string form becomes the first entry, ext/segments moving into it
896
+ const kept = { label: narr.files, dir: narr.files };
897
+ for (const k of ['ext', 'segments']) if (narr[k] !== undefined) { kept[k] = narr[k]; delete narr[k]; }
898
+ list = kept.dir === track.dir ? [] : [kept];
899
+ } else list = [];
900
+ const same = list.findIndex((e) => (typeof e === 'string' ? e : e?.dir) === track.dir);
901
+ if (same >= 0) list[same] = entry; else list.push(entry);
902
+ narr.files = list;
903
+ const indent = /(?:^|\n)([ \t]*)[^\n]*$/.exec(html.slice(0, block.start))?.[1] ?? '';
904
+ const json = JSON.stringify(cfg, null, 2).split('\n').map((l) => indent + l).join('\n');
905
+ return `${html.slice(0, block.innerStart)}\n${json}\n${indent}${html.slice(block.innerEnd)}`;
906
+ }
435
907
  const arg = initArgument(html);
436
908
  if (!arg) return null;
437
909
  const raw = html.slice(arg.start, arg.end);
@@ -531,6 +1003,63 @@ export function setSlideElementBuild(html, slide, index, effect) {
531
1003
  * land on the opposite stack, so nothing is silently lost) and return what
532
1004
  * to write, or null when the stack is empty.
533
1005
  */
1006
+ /**
1007
+ * What a write route did, in the words the page's debug log shows beside a
1008
+ * reload (PRESENTING, debug log). The reload message names it, so a page that
1009
+ * comes back can say WHY it went — "notes saved · this tab" rather than a
1010
+ * bare reload, which is the one thing a log wiped by the reload cannot say.
1011
+ */
1012
+ const WRITE_LABELS = {
1013
+ '/deck/edit/slide/notes': 'notes saved',
1014
+ '/deck/edit/slide/sources': 'sources saved',
1015
+ '/deck/edit/timings': 'rehearsal timings saved',
1016
+ '/deck/edit/slide/layout': 'layout picked',
1017
+ '/deck/edit/slide/template': 'template switched',
1018
+ '/deck/edit/slide/hidden': 'slide hidden or shown',
1019
+ '/deck/edit/slide': 'slides rearranged',
1020
+ '/deck/edit/narration': 'narration track saved',
1021
+ '/deck/edit/narration/record': 'narration recorded',
1022
+ '/deck/edit/element/remove': 'element removed',
1023
+ '/deck/edit/element/content': 'element content saved',
1024
+ '/deck/edit/element/effect': 'build effect set',
1025
+ '/deck/edit/element/style': 'colours saved',
1026
+ '/deck/edit/element/concept': 'concept set',
1027
+ '/deck/edit/element/text': 'text saved',
1028
+ '/deck/edit/element/image': 'image placed',
1029
+ '/deck/edit/concepts': 'concept colours saved',
1030
+ '/deck/edit/asset': 'asset added',
1031
+ '/deck/edit/undo': 'undo (Z)',
1032
+ '/deck/edit/redo': 'redo (⇧Z)',
1033
+ '/deck/edit/restore': 'restored from git',
1034
+ '/deck/edit/theme': 'theme picked',
1035
+ '/deck/edit/brand-themes': 'brand themes set',
1036
+ '/deck/edit/theme/add': 'theme added',
1037
+ '/deck/edit/theme/mark': 'theme marked',
1038
+ '/deck/edit/font/mark': 'font marked',
1039
+ '/deck/edit/design-system/apply': 'design system applied',
1040
+ '/deck/edit/design-system/mark': 'design system marked',
1041
+ '/deck/edit/enhance': 'script enhanced',
1042
+ '/deck/edit/wizard': 'engine set up',
1043
+ '/deck/upstream/pull': 'git pull',
1044
+ };
1045
+ export function whatWrote(pathname) {
1046
+ return WRITE_LABELS[pathname] ?? `${String(pathname ?? '').replace(/^\/deck\/(edit\/)?/, '').replace(/\//g, ' ') || 'the deck'} written`;
1047
+ }
1048
+
1049
+ /**
1050
+ * The reason a reload carries. A write of the server's own within the last
1051
+ * moments is that write; the file changing while an agent runs is the
1052
+ * agent's; anything else changed on disk by a hand this server never saw —
1053
+ * an editor, git, a tool. The page shows it as the first line after the
1054
+ * reload, with "this tab" or "another tab" when the write said which page.
1055
+ */
1056
+ export const RELOAD_WRITE_WINDOW_MS = 2000;
1057
+ export function describeReload({ write = null, agent = null, now = Date.now() } = {}) {
1058
+ if (write && now - write.at <= RELOAD_WRITE_WINDOW_MS) return { reload: write.what, from: write.from ?? null };
1059
+ if (agent) return { reload: `${agent.agent}'s edit`, from: null };
1060
+ return { reload: 'changed on disk — an editor, git, or a tool outside this server', from: null };
1061
+ }
1062
+
534
1063
  export function createHistory(limit = 200) {
535
1064
  const past = [];
536
1065
  const future = [];
@@ -558,14 +1087,14 @@ export function createHistory(limit = 200) {
558
1087
  // The plumbing lives in git.mjs now; imported for editMain's use below and
559
1088
  // re-exported so long-standing importers (init, the tests) keep finding it
560
1089
  // where edit grew it.
561
- import { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit, lastCommitSha, resolveGitMode, shouldCommit, commitSubject, exitPushLine, oneline, remoteLine, remoteState, unpushed } from './git.mjs';
1090
+ import { inGitRepo, gitAvailable, createRepo, STARTER_GITIGNORE, gitAutocommit, lastCommitSha, resolveGitMode, shouldCommit, commitSubject, exitPushLine, oneline, remoteState } from './git.mjs';
562
1091
  import {
563
- describeCommit, describeWorking, messagesLine, rememberPref, storedPref,
1092
+ describeCommit, messagesLine,
564
1093
  } from './commit-message.mjs';
565
1094
  import { WIP_REF, deckDirty, nagText, planNag, snapshotWip, wipLine } from './commit-flow.mjs';
566
1095
  export { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit };
567
1096
 
568
- /** Who the author is, from git's own answer — see cli/review.mjs. */
1097
+ /** Who the author is, from git's own answer — see cli/review-routes.mjs. */
569
1098
  function reviewerName(cwd = process.cwd()) {
570
1099
  const cfg = (key) => {
571
1100
  try { return execFileSync('git', ['config', key], { cwd, encoding: 'utf8' }).trim(); } catch { return ''; }
@@ -575,17 +1104,145 @@ function reviewerName(cwd = process.cwd()) {
575
1104
  return (name && email) ? `${name} <${email}>` : (name || email || '');
576
1105
  }
577
1106
 
578
- export async function editMain(args, { onListen = null } = {}) {
579
- // /edit/review/incoming's answer, briefly remembered (see the route).
1107
+
1108
+ /** `decklight <deck> --no-trust --help`: the no-trust mode's own flags. */
1109
+ const READ_ONLY_USAGE = `usage: decklight <deck.html|deck.decklight|repository url> --no-trust [--port 8788] [--strict]
1110
+ [--root <dir>] [--remote] [--host <addr>] [--audit]
1111
+ [--no-plugins] [--branch <ref>] [--into <dir>]
1112
+
1113
+ opens a deck in no-trust mode — the safe way in for one you did not write,
1114
+ and the only mode a .decklight container opens in. The deck is served from
1115
+ its own directory, under a Content-Security-Policy header, with every file
1116
+ type a deck cannot use and every dotfile refused; every route that writes
1117
+ refuses, and nothing is written. The mode is the run's: it is decided here,
1118
+ when the deck is opened, and never from the page.
1119
+
1120
+ A .decklight container (bundle --deck) is unwrapped in memory and treated
1121
+ exactly like the deck it wraps: same audit, same policy, same strict rule. Its
1122
+ signature is verified and its manifest is printed as what it is — the
1123
+ container's own claim about itself, next to the one thing that was checked.
1124
+ The manifest's origin (repo and commit) is never printed: the signature
1125
+ covers the deck alone, so even on a verified container the origin is whatever
1126
+ the packer wrote, and a provenance line nobody vouches for does not belong
1127
+ one skim away from a verified identity. It stays in the manifest for tooling
1128
+ to read.
1129
+
1130
+ A repository URL (https://github.com/you/talk, git@…, …/talk.git; #path
1131
+ picks a deck inside) is cloned to ./<repo> — or the clone already there,
1132
+ whichever command made it, is opened — and the deck in it played. The
1133
+ clone's upstream is what H checks for the author's newer pushes.
1134
+
1135
+ --branch R the branch or tag to clone (a repository URL)
1136
+ --into D where to clone it (default: ./<repo name>)
1137
+ --port N port to bind; a taken port offers to take over that session
1138
+ (on a TTY) or moves on to the next free one [8788]
1139
+ --strict serve with every script block that is not the runtime removed,
1140
+ along with every inline on*= handler, javascript: URL and srcdoc
1141
+ document. The removal happens on the way out — the file on disk
1142
+ is never touched. Turns itself on when the label finds something.
1143
+ --root D serve D instead of the deck's directory, for a SOURCE deck that
1144
+ reaches up for its runtime (demo/talk.html loading
1145
+ ../dist/decklight.js). The deck must live under D, and everything
1146
+ under D that passes the dotfile and file-type rules becomes
1147
+ fetchable by the deck's own script — which is why widening the
1148
+ root is a flag you type, never something the cwd decides.
1149
+ --remote also listen on the LAN for the phone remote. Off this machine ONLY
1150
+ /deck/remote/* answers, and only with the per-run token the printed URL
1151
+ and its QR carry — the deck itself, and every file beside it, stay
1152
+ unreachable from the LAN whether or not this flag is passed.
1153
+ --host A the address --remote binds [0.0.0.0]
1154
+ --audit print the ingredients label and exit — no server. Exits non-zero
1155
+ if the deck runs any script that is not the runtime — a block or
1156
+ an executable attribute — so CI can gate on a deck before it is
1157
+ forwarded or published.
1158
+ --no-plugins play without your own chrome, whatever is installed.
1159
+ --upstream-every N minutes between upstream checks; 0 turns the check off [10]
1160
+ --no-upstream never look at the upstream — no git, no network
1161
+ --upstream-pull register the update control the deck's H overlay drives.
1162
+ OFF by default: with it on, any script in the deck can
1163
+ fast-forward the clone the deck was served from.
1164
+
1165
+ Your presenter plugins (decklight library add plugin) are layered on at serve time from
1166
+ ~/.decklight/plugins/ — a timer, a teleprompter, a confidence monitor. They
1167
+ are YOURS: the deck on disk is untouched, nothing is written into it, and the
1168
+ same file played on a machine without them is identical slides and no
1169
+ warning. Each one renders inside a sandboxed frame with an opaque origin, so
1170
+ it draws chrome and cannot reach the slides — a plugin that asks for slide
1171
+ content is refused by name, because a deck has to stay a deterministic
1172
+ artifact or two people presenting the same file present different decks.
1173
+
1174
+ A plugin is never part of the ingredients label: the label counts what is in
1175
+ the file, the chrome is listed under it as what it is. Loading one registers
1176
+ no route and does not widen the policy below by a single source.
1177
+
1178
+ Every no-trust start prints the ingredients label: which runtime is
1179
+ embedded and whether its bytes are the ones this install ships, how many
1180
+ inert data blocks the runtime will read, and — named, with line numbers —
1181
+ every script block that will execute and is NOT accounted for, plus every
1182
+ executable attribute (an inline on*= handler, a javascript: or
1183
+ data:text/html URL, an inline srcdoc document — the vectors 'unsafe-inline'
1184
+ below would otherwise let run unnamed). It is an inventory, not a verdict:
1185
+ there is no "safe" here, because the scan is a heuristic over a file someone
1186
+ may have edited and a green check would promise more than it can keep.
1187
+
1188
+ A deck with a detached signature beside it (talk.html.sig) is verified BEFORE
1189
+ it renders, and the terminal names who signed it — an identity you can judge,
1190
+ not a check mark. Sigstore keyless, so there are no keys: the certificate was
1191
+ minted for one signature against the signer's OIDC identity and expired
1192
+ minutes later; the transparency log is what keeps it checkable. A deck with no
1193
+ sidecar is not an alarm — most decks are unsigned, and treating that as a
1194
+ finding would train you to ignore the one that matters. Verifying needs the
1195
+ sigstore client and the network; when it cannot be done here, that is said as
1196
+ its own state and never as a pass.
1197
+
1198
+ When the label finds an unaccounted block — or a signature does not verify,
1199
+ or cannot be checked here — strict mode turns ITSELF on and says so in the
1200
+ terminal. It does not ask, and there is no --force to turn it
1201
+ back off: ten minutes before a talk is the worst possible moment for a
1202
+ refusal, and an escape hatch would be reached for exactly then — so the deck
1203
+ always plays, and the part nobody can account for is the part that doesn't.
1204
+ Removed blocks are named in the terminal, never on the audience's screen.
1205
+
1206
+ What survives strict is what a deck needs to render itself: the runtime, the
1207
+ Decklight.init call, JSON data blocks and templates. Builds, layouts, themes,
1208
+ charts and background media are markup, CSS and attributes — never at risk. A
1209
+ clean deck under --strict is byte-identical to the same deck without it.
1210
+
1211
+ Every response carries this Content-Security-Policy as an HTTP header, which
1212
+ the deck cannot override the way it could a <meta> tag:
1213
+
1214
+ ${CSP.replace(/; /g, ';\n ')}
1215
+
1216
+ Recorded narration from a bucket and external background video still play —
1217
+ that is what the https: sources in media-src/connect-src are for. Live voice
1218
+ does not: synthesis needs the local bridge, which is a write-mode engine and
1219
+ is refused from here.
1220
+
1221
+ Read the policy honestly: script-src carries 'unsafe-inline' because a
1222
+ bundled deck IS inline script, so this does not stop a deck from running
1223
+ code. It stops that code from reaching anywhere it shouldn't.`;
1224
+
1225
+ // `client` is the sigstore client — injectable so a test can drive the
1226
+ // signature states of `--no-trust --audit` without the network; `undefined`
1227
+ // means "go load the real one".
1228
+ export async function editMain(args, { onListen = null, client } = {}) {
1229
+ // /deck/review/incoming's answer, briefly remembered (see the route).
580
1230
  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]
1231
+ const wantsHelp = args.includes('--help') || args.includes('-h');
1232
+ if (wantsHelp && args.includes('--no-trust')) { console.log(READ_ONLY_USAGE); return 0; }
1233
+ if (wantsHelp || !args.filter((a) => !a.startsWith('-')).length) {
1234
+ console.log(`usage: node cli/edit.mjs <deck.html> [--no-trust] [--port 8788] [--git | --no-git]
583
1235
  [--commit-every <seconds>] [--agent <name>] [--commit-messages]
584
1236
  serves the cwd, live-reloads the deck on change, and accepts edits from the
585
1237
  player: notes (right-click a slide's background), per-slide layout (L/⇧L),
586
1238
  element edit mode (E, then right-click an element), undo/redo (Z/⇧Z), agent asks (A)
587
1239
  a taken --port offers to take over that session (on a TTY) or moves on to
588
1240
  the next free one
1241
+ --no-trust the same server in no-trust mode: the deck is served from
1242
+ its own directory under a CSP header, the ingredients label
1243
+ runs first, and every edit route refuses
1244
+ (--no-trust --help for that mode's flags)
1245
+ --remote also listen on the LAN for the phone remote (either mode)
589
1246
  --git keep the deck in git (creates the repo if needed): a silent
590
1247
  snapshot on refs/decklight/wip, and K commits when you say so
591
1248
  --no-git never touch git (default outside a repository)
@@ -594,7 +1251,7 @@ export async function editMain(args, { onListen = null } = {}) {
594
1251
  timer the old five-minute cadence, bookends included
595
1252
  off never commit [agent]
596
1253
  --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`);
1254
+ the server binds 127.0.0.1 unless --remote asks for the LAN`);
598
1255
  return;
599
1256
  }
600
1257
  const { opt } = argReader(args);
@@ -603,61 +1260,280 @@ export async function editMain(args, { onListen = null } = {}) {
603
1260
  // `ownCommit` closes over it and editMain CALLS ownCommit synchronously —
604
1261
  // the opening commit, taken when git has never seen this deck. Left where it
605
1262
  // 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
1263
+ // dead zone and `decklight <deck>` died on a ReferenceError before the
607
1264
  // server ever came up. It needed both halves to show: a deck git does not
608
1265
  // know, and commit-messages on (only that path reads `agentPref`), which is
609
1266
  // why adding a SECOND deck to a repo was the way to find it.
610
1267
  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;
1268
+ const port = parsePort(opt('--port', 8788));
1269
+ if (port === null) { console.error(`decklight: ${badPort('--port', opt('--port'))}`); process.exitCode = 1; return; }
1270
+ const fail = (msg) => { console.error(`decklight: ${msg}`); process.exitCode = 1; return 1; };
1271
+
1272
+ // ── the mode (PRESENTING) ─────────────────────────────────────────────────
1273
+ // One server, two modes. Write mode is the default: the deck is served from
1274
+ // disk, live-reloaded, and every /deck/edit/* route writes it. Read-only
1275
+ // mode (`--no-trust`, and always for a .decklight container) serves the
1276
+ // bytes the ingredients label described, under the CSP, with the
1277
+ // presenter's chrome layered on, and refuses every route that writes —
1278
+ // /deck/edit/*, the bridges, the review owner's half — by name. The mode is
1279
+ // the run's: decided here, from the flag, and never from the page — a page
1280
+ // that could grant itself write access would make the flag worth nothing
1281
+ // for the deck it exists for, the one you did not write.
1282
+ const deckArg = firstPositional(args, VALUE_FLAGS);
1283
+ const deckPath = resolve(process.cwd(), deckArg);
1284
+ if (!existsSync(deckPath)) return fail(`deck not found: ${deckPath}`);
1285
+ // A .decklight is the same deck with its signature and manifest stapled on
1286
+ // (DECK_FILE), unwrapped here and treated exactly like the HTML it wraps —
1287
+ // same audit, same CSP, same strict rule. Nothing is written to unwrap it:
1288
+ // the payload is a slice of the bytes already read. It never leaves
1289
+ // no-trust mode: there is no file to edit in place.
1290
+ let container = null;
1291
+ if (isContainer(deckPath)) {
1292
+ try { container = readContainer(deckPath); } catch (e) { return fail(e.message); }
1293
+ }
1294
+ const noTrust = args.includes('--no-trust') || !!container;
1295
+
1296
+ // --remote widens the LISTENER and nothing else (NO_TRUST#REMOTE), in either
1297
+ // mode: off this machine only /deck/remote/* answers, with the per-run
1298
+ // token, and the deck itself and every file beside it stay unreachable from
1299
+ // the LAN whether or not the flag is passed. allowRemote is the classifier.
1300
+ const remote = args.includes('--remote') || opt('--host') !== undefined;
1301
+ const host = remote ? opt('--host', '0.0.0.0') : '127.0.0.1';
1302
+ const token = remote ? randomBytes(16).toString('base64url') : null;
1303
+
1304
+ // The served root. In write mode it is the cwd, as it always was: a source
1305
+ // deck reaches up for its runtime (`demo/talk.html` loading
1306
+ // `../dist/decklight.js`) and the author chose where to stand. In no-trust
1307
+ // mode it is the deck's OWN directory, never the cwd: everything under the
1308
+ // root is fetchable by the deck's own script same-origin, and with
1309
+ // `connect-src https:` open, fetchable means exfiltratable — a root
1310
+ // inherited from wherever the command happened to run (a project checkout,
1311
+ // $HOME via file association) would hand a hostile deck whatever lived
1312
+ // there. `--root` widens it, by a flag you typed and printed at startup.
1313
+ const rootArg = opt('--root');
1314
+ const root = noTrust
1315
+ ? (rootArg ? resolve(process.cwd(), rootArg) : dirname(deckPath))
1316
+ : process.cwd();
1317
+ if (!deckPath.startsWith(root + sep)) {
1318
+ return fail(noTrust ? 'deck must live under --root' : 'deck must live under the current directory');
625
1319
  }
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
1320
  const deckUrl = '/' + deckPath.slice(root.length + 1).split(sep).join('/');
632
1321
  const deckRel = deckUrl.slice(1);
633
1322
 
1323
+ // ── the no-trust mode's ingredients (PRESENTING) ─────────────────────────
1324
+ // The audit runs because it is the way in: a standalone `verify` is a step
1325
+ // people skip, so folding it into the command you already use means it runs
1326
+ // every time, at no extra effort. It reads the bytes, names what will
1327
+ // execute, and decides strict — the startup block, reusable, because a
1328
+ // pull (NO_TRUST#UPSTREAM) re-runs it: never new bytes under an old verdict.
1329
+ const readAndAudit = () => {
1330
+ const bytes = container ? readContainer(deckPath).payload : readFileSync(deckPath);
1331
+ const rep = auditDeck(bytes.toString('utf8'));
1332
+ return {
1333
+ payload: bytes,
1334
+ report: rep,
1335
+ strict: args.includes('--strict') || rep.counts.unaccounted > 0 || rep.counts.handlers > 0,
1336
+ };
1337
+ };
1338
+ // The signature, if the deck came with one (INTEGRITY#SIGNING). Costs nothing
1339
+ // when there is no sidecar — the common case returns without touching the
1340
+ // network — and the audit runs either way, because the two answer different
1341
+ // questions: a signature says WHO vouched for these bytes, the label says
1342
+ // what the bytes will do. A signed deck can still run something nobody
1343
+ // should, and the label is what would name it. Verified once, at startup:
1344
+ // it is a sidecar for the file as published, and a deck that changed since
1345
+ // has already invalidated whatever the old one attested.
1346
+ const verifySignature = async () => {
1347
+ if (!container) return verifyFile(deckPath, { client });
1348
+ let sig = container.signature
1349
+ ? await verifyBytes(container.payload, container.signature, { client })
1350
+ : { state: TAMPERED, reason: 'the container carries no signature' };
1351
+ // The manifest is the container's own label. When it does not describe
1352
+ // the deck it is stapled to, something rewrote one half — the same
1353
+ // conclusion as a signature that does not verify, so the same state.
1354
+ if (!container.digestOk && sig.state === VERIFIED) {
1355
+ sig = { state: TAMPERED, reason: 'the manifest digest does not match the payload' };
1356
+ }
1357
+ return sig;
1358
+ };
1359
+ // MUTABLE: a pull may replace all of it. The bytes, the label and `strict`
1360
+ // move together or not at all. Empty in write mode, which never reads it.
1361
+ let audited = null;
1362
+ let signature = { state: UNSIGNED };
1363
+ /** Enter (or re-enter) no-trust mode: read, audit, decide strict. Says whether the deck itself changed. */
1364
+ const audit = () => {
1365
+ const before = audited?.payload ?? null;
1366
+ const next = readAndAudit();
1367
+ const unverified = signature.state !== UNSIGNED && !isVerified(signature);
1368
+ // STRICT RATCHETS within a session: a pull may turn it on and can never
1369
+ // turn it off. A deck that could clear its own strict flag by pulling
1370
+ // could disarm the one mitigation no-trust mode applies unasked.
1371
+ audited = { ...next, strict: next.strict || unverified || (audited?.strict ?? false) };
1372
+ return before === null || !next.payload.equals(before);
1373
+ };
1374
+ if (noTrust) {
1375
+ signature = await verifySignature();
1376
+ audit();
1377
+ }
1378
+
1379
+ // `--audit` prints the ingredients label and exits; `--check` still answers,
1380
+ // unadvertised, from before `check` came to mean the deck lint alone
1381
+ if (args.includes('--audit') || args.includes('--check')) {
1382
+ // No server. The label, the manifest, the signature — and an exit code CI
1383
+ // can gate on: non-zero means "this deck executes something I could not
1384
+ // account for", or "it carries a signature I could not stand behind" —
1385
+ // not "this deck is malicious", which is a call no exit code should make.
1386
+ // `unchecked` counts: a gate that passes when it could not evaluate the
1387
+ // claim is not a gate.
1388
+ if (!noTrust) { signature = await verifySignature(); audit(); }
1389
+ for (const line of formatLabel(audited.report, { indent: '' })) console.log(line);
1390
+ if (container) console.log(formatManifest(container.manifest, { indent: '' }));
1391
+ if (signature.state !== UNSIGNED) console.log(formatSignature(signature, { indent: '' }));
1392
+ return audited.report.counts.unaccounted || audited.report.counts.handlers
1393
+ || (signature.state !== UNSIGNED && !isVerified(signature)) ? 1 : 0;
1394
+ }
1395
+
1396
+ // The presenter's own chrome (NO_TRUST#PLUGINS) — a timer, a teleprompter,
1397
+ // a confidence monitor. It is loaded from ~/.decklight/plugins/, which is
1398
+ // the presenter's library and not the deck's: the installer is the
1399
+ // risk-bearer and nothing here travels. Loaded after `auditDeck` has read
1400
+ // the bytes, so a plugin is never counted as an unaccounted script block in
1401
+ // the label (the label describes the file; a plugin is not in the file),
1402
+ // and injected after `stripUnaccounted`, so strict never strips the chrome
1403
+ // as if the deck had smuggled it in. BOTH modes: it used to be no-trust
1404
+ // only, so presenting your own deck with your own timer meant opening it
1405
+ // without trust (ROADMAP section 5). The chrome is the presenter's, and a
1406
+ // presenter is often the author. `--no-plugins` turns it off in either.
1407
+ const chrome = args.includes('--no-plugins') ? { plugins: [], refused: [] } : loadLibrary();
1408
+ // Consulted per request rather than decided once: after a pull `strict`
1409
+ // may have ratcheted on, and the bytes served have to follow the verdict
1410
+ // printed for them.
1411
+ const strip = (text) => (audited?.strict ? stripUnaccounted(text).html : text);
1412
+ // Only the deck gets chrome. Every OTHER html file under the root still
1413
+ // gets the strict rewrite — strict that stopped at one file would be walked
1414
+ // around by a second page under the same root, and the deck can reach one
1415
+ // (the theme picker, the slide finder and the speaker view all boot
1416
+ // documents into same-origin iframes). Those same iframes are why the
1417
+ // chrome is deck-only: presenter chrome belongs to the document the
1418
+ // presenter is looking at, and the shim removes itself if framed anyway.
1419
+ const rewrite = (text, file) => {
1420
+ const out = strip(text);
1421
+ return file === deckPath ? injectChrome(out, chrome.plugins) : out;
1422
+ };
1423
+ // The deck served from memory below goes through the same seam a file
1424
+ // does: a deck that is only data (#520) gets the runtime referenced on its
1425
+ // way out, and the audit above described the bytes WITHOUT it — which is
1426
+ // the point. `staticFiles` does this for every other page itself.
1427
+ const serveAudited = (text) => linkReferences(linkRuntime(rewrite(text, deckPath)));
1428
+ // The deck itself, in no-trust mode, is served from MEMORY — container and
1429
+ // plain HTML alike — from the bytes the audit read and the signature
1430
+ // covered. The label, the signature verdict and `strict` were all decided
1431
+ // against those bytes and printed as a verdict; re-reading the file per
1432
+ // request would let a deck edited on disk AFTER that moment ride out under
1433
+ // it (#235). For a container this also avoids the one write this mode does
1434
+ // not make — unpacking to a temp file that would sit somewhere after the
1435
+ // talk. A pull re-audits and re-prints.
1436
+ const servePayload = (req, res) => {
1437
+ if (req.method !== 'GET') return false;
1438
+ const body = Buffer.from(serveAudited(audited.payload.toString('utf8')), 'utf8');
1439
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-cache' });
1440
+ res.end(body);
1441
+ return true;
1442
+ };
1443
+ // Is this URL the deck? Matched on the RESOLVED path, exactly as staticFiles
1444
+ // would resolve it, so a percent-encoded spelling of the same file cannot
1445
+ // slip past this route into the per-request disk read below it.
1446
+ const isDeck = (url) => {
1447
+ if (url.pathname === '/') return true;
1448
+ let rel;
1449
+ try { rel = decodeURIComponent(url.pathname); } catch { return false; }
1450
+ return resolve(root, '.' + rel) === deckPath;
1451
+ };
1452
+
634
1453
  const history = createHistory();
635
1454
  const readDeck = () => readFileSync(deckPath, 'utf8');
636
- // one door for every mutation: snapshot, then write — so Z always works
637
- const applyEdit = (next, before = readDeck()) => {
1455
+ /**
1456
+ * The one door every mutation goes through: snapshot, then write — so Z
1457
+ * always works. Answers whether anything actually changed.
1458
+ *
1459
+ * Takes a TRANSFORM, `applyEdit((html) => setSlideNotes(html, …))`, so the
1460
+ * deck is read exactly ONCE. It used to take the finished html with the
1461
+ * current file as a default argument, which meant every call site spelled
1462
+ * `applyEdit(setX(readDeck(), …))` — one read to transform, a second for the
1463
+ * snapshot. Two reads is not just wasted work: they are two different reads,
1464
+ * and an edit landing between them wrote the second one's bytes back over
1465
+ * the first one's, with the undo entry recording a file that never existed.
1466
+ *
1467
+ * A route that has ALREADY read the deck — the template ones need it for
1468
+ * their own answer — passes the finished html and that same read as
1469
+ * `before`, which is the same single read spelled the other way round.
1470
+ */
1471
+ // Which route is writing, for the reload's reason: set around every
1472
+ // handler (below), read by `writeDeck` — async-safe, so two requests in
1473
+ // flight each name their own.
1474
+ const writing = new AsyncLocalStorage();
1475
+ let lastWrite = null; // { at, what, from } — the server's latest write of the deck, for the watcher
1476
+ const noteWrite = (what, from = null) => { lastWrite = { at: Date.now(), what, from }; };
1477
+ /** The one write of the deck file: atomic, and remembered for the reload it causes. */
1478
+ const writeDeck = (next) => {
1479
+ writeFileAtomic(deckPath, next);
1480
+ const ctx = writing.getStore();
1481
+ let from = null;
1482
+ 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 */ } }
1483
+ noteWrite(whatWrote(ctx?.route), from);
1484
+ };
1485
+ const applyEdit = (change, before = readDeck()) => {
1486
+ const next = typeof change === 'function' ? change(before) : change;
638
1487
  if (next === before) return false;
639
1488
  history.record(before);
640
- writeFileSync(deckPath, next);
1489
+ writeDeck(next);
641
1490
  return true;
642
1491
  };
643
1492
 
644
1493
  // Declared before the git block below, which reads it to hold the cadence
645
1494
  // back while a job is in flight.
646
1495
  let agentJob = null; // { name, prompt, startedAt } — strictly one at a time
1496
+ // The asks of this session, oldest first, with what came of each — what the
1497
+ // docked agent panel shows. An agent's edit reloads every browser, so the
1498
+ // log lives HERE, not in the page, and rides /deck/ping across the reload.
1499
+ const agentAsks = [];
1500
+ const ASKS_KEPT = 20;
1501
+ let askSeq = 0;
1502
+ let enhancing = null; // a script enhancement in flight: { of, done } — one at a time
1503
+ let reviewing = null; // an agent review in flight: { of, done } — one at a time
1504
+ let lastReview = null; // its last result: { at, agent, findings, failed } — kept for Check deck… to re-ask
647
1505
 
648
1506
  // ── git autocommit — the durable record, independent of undo/redo ──────
649
1507
  const noGit = args.includes('--no-git');
650
1508
  const wantGit = args.includes('--git');
651
1509
  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;
1510
+ // Commit subjects written by an agent, from the deck's diff. Two levels:
1511
+ //
1512
+ // - ON CLICK, by default: the commit window's "write them for me" asks the
1513
+ // agent installed on this machine when — and only when — it is pressed,
1514
+ // and its tooltip names the agent and says the changes go to it (and may
1515
+ // go on to its provider). Nothing leaves without that click.
1516
+ // - AUTOMATIC, with --commit-messages: the window drafts one as it opens,
1517
+ // and every commit decklight makes on its own is given one.
1518
+ //
1519
+ // --no-commit-messages turns both off for the session. Nothing is stored:
1520
+ // the setting is the command line's, and the button is the consent.
1521
+ const subjectsOff = args.includes('--no-commit-messages');
1522
+ const wantMessages = !subjectsOff && args.includes('--commit-messages');
1523
+ // The agent a subject would be asked of — named in the button's tooltip, so
1524
+ // it is the SAME resolution describeWorking makes (agentAsk). Remembered per
1525
+ // preference: commitState goes out on every ping and SSE tick, and probing
1526
+ // PATH that often is waste.
1527
+ let describerFor = null, describerIs = null;
1528
+ const describer = () => {
1529
+ if (subjectsOff) return null;
1530
+ if (describerFor !== (agentPref ?? '')) {
1531
+ const a = agentAsk(agentPref ?? null, 'x');
1532
+ describerIs = a ? { name: a.name, label: a.label } : null;
1533
+ describerFor = agentPref ?? '';
1534
+ }
1535
+ return describerIs;
1536
+ };
661
1537
 
662
1538
  /**
663
1539
  * Every commit decklight authors ITSELF goes through here — the cadence, the
@@ -676,9 +1552,10 @@ export async function editMain(args, { onListen = null } = {}) {
676
1552
  */
677
1553
  function ownCommit(message) {
678
1554
  const made = message === undefined
679
- ? gitAutocommit(deckPath, root)
680
- : gitAutocommit(deckPath, root, message);
1555
+ ? gitAutocommit(deckPath, root, undefined, alsoNow())
1556
+ : gitAutocommit(deckPath, root, message, alsoNow());
681
1557
  if (!made) return false;
1558
+ pendingAttr = null;
682
1559
  // Whatever wrote it — the overlay, an agent, a bookend — this stretch of
683
1560
  // uncommitted work is over, so the nag re-arms for the NEXT one.
684
1561
  resetEpisode();
@@ -708,13 +1585,35 @@ export async function editMain(args, { onListen = null } = {}) {
708
1585
  // could reach, which is also what made it untestable end to end.
709
1586
  const watchEveryMs = Math.min(commitEvery * 1000, WATCH_EVERY_MS);
710
1587
  let dirtySince = 0; // when this stretch of uncommitted work began
711
- let dirtyLines = 0; // how much of the deck differs from HEAD
1588
+ let dirtyLines = 0; // how much of the deck (and its sidecar) differs from HEAD
1589
+ let dirtySlides = null; // { changed, added, removed } against HEAD, or null
1590
+ let dirtyFiles = []; // which of them, by name beside the deck
1591
+ // The review sidecar rides the deck's own commits in write mode (REVIEW):
1592
+ // K, the agent's boundary and the session's bookends stage it beside the
1593
+ // deck when it changed, and the card counts its lines. The snapshot ref
1594
+ // stays deck-only: it is a backup of the thing being edited.
1595
+ const sidecarPath = reviewPathFor(deckPath);
1596
+ const sidecarRel = sidecarPath.slice(root.length + 1).split(sep).join('/');
1597
+ let pendingAttr = null; // a .gitattributes decklight just wrote, until a commit carries it
1598
+ // The attribute's path RELATIVE TO ROOT, asked of git rather than computed
1599
+ // from two absolute paths: `--show-toplevel` answers in forward slashes and
1600
+ // the long form of a path, and `root` may be the short form of the same
1601
+ // directory (a Windows temp dir), so `relative()` between them walks out of
1602
+ // the repository and every git call that takes the result refuses.
1603
+ const attrRel = () => {
1604
+ try {
1605
+ const prefix = execFileSync('git', ['rev-parse', '--show-prefix'], { cwd: root, encoding: 'utf8' }).trim();
1606
+ return '../'.repeat(prefix.split('/').filter(Boolean).length) + '.gitattributes';
1607
+ } catch { return null; }
1608
+ };
1609
+ const alsoNow = () => ({ also: [sidecarPath, ...(pendingAttr ? [pendingAttr] : [])] });
1610
+ const alsoRels = () => [sidecarRel, ...(pendingAttr ? [attrRel()] : [])].filter(Boolean);
712
1611
  let nagged = false; // the episode latch: asked once, then quiet
713
1612
  let nagDismissed = false;
714
1613
  let lastWip = null; // the snapshot sha, so the ping can prove it exists
715
1614
  /** A commit happened: this stretch of uncommitted work is over. */
716
1615
  const resetEpisode = () => {
717
- dirtySince = 0; dirtyLines = 0; nagged = false; nagDismissed = false;
1616
+ dirtySince = 0; dirtyLines = 0; dirtyFiles = []; dirtySlides = null; nagged = false; nagDismissed = false;
718
1617
  };
719
1618
  /**
720
1619
  * Re-read what is uncommitted, right now.
@@ -727,23 +1626,36 @@ export async function editMain(args, { onListen = null } = {}) {
727
1626
  * asking.
728
1627
  */
729
1628
  const measureDirty = () => {
730
- const d = deckDirty(root, deckRel);
731
- if (!d.dirty) { dirtySince = 0; dirtyLines = 0; return d; }
1629
+ const d = deckDirty(root, deckRel, { also: alsoRels() });
1630
+ if (!d.dirty) { dirtySince = 0; dirtyLines = 0; dirtyFiles = []; dirtySlides = null; return d; }
732
1631
  if (!dirtySince) dirtySince = Date.now();
733
1632
  dirtyLines = d.lines;
1633
+ dirtyFiles = (d.files ?? []).map((f) => basename(f));
1634
+ // in slides too, for the chip and the window: a deck's reader thinks in
1635
+ // slides. A change that is only the sidecar touches none.
1636
+ dirtySlides = slidesSinceHead(root, deckRel);
734
1637
  return d;
735
1638
  };
736
1639
  /** What the deck knows about uncommitted work — ping and SSE both send this. */
737
1640
  const commitState = () => ({
738
1641
  dirty: dirtySince > 0,
739
1642
  lines: dirtyLines,
1643
+ files: dirtyFiles,
1644
+ slides: dirtySlides,
740
1645
  sinceMs: dirtySince ? Date.now() - dirtySince : 0,
741
1646
  nag: nagged && !nagDismissed,
742
1647
  wip: lastWip,
743
1648
  canWrite: gitOn && gitMode !== 'off',
744
1649
  messages: wantMessages,
1650
+ // who "write them for me" would ask — null when the session turned subjects
1651
+ // off, or no agent is installed; `subjectsOff` says which
1652
+ describer: describer(),
1653
+ subjectsOff,
745
1654
  });
746
- if (!noGit && (wantGit || inGitRepo(root))) {
1655
+ // Write mode's. A deck in no-trust mode is somebody else's: no repository
1656
+ // is created beside it, no snapshot is taken, nothing of it is committed.
1657
+ function startGit() {
1658
+ if (noGit || !(wantGit || inGitRepo(root))) return;
747
1659
  if (!inGitRepo(root)) {
748
1660
  try {
749
1661
  const wroteIgnore = createRepo(root);
@@ -754,16 +1666,6 @@ export async function editMain(args, { onListen = null } = {}) {
754
1666
  }
755
1667
  if (inGitRepo(root)) {
756
1668
  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
1669
  // The session bookends are the cadence's siblings: generic subjects for
768
1670
  // moments nobody described, and in the default mode the snapshot covers
769
1671
  // what they were covering. THE FIRST COMMIT IS NOT ONE OF THEM. A
@@ -793,13 +1695,15 @@ export async function editMain(args, { onListen = null } = {}) {
793
1695
  }, gitMode === 'timer' ? commitEvery * 1000 : watchEveryMs).unref();
794
1696
  startup('git',
795
1697
  gitMode === 'timer'
796
- ? `auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`
797
- : 'commits on your word · snapshot on decklight/wip',
1698
+ ? `auto-commit every ${commitEvery}s`
1699
+ : 'snapshots on decklight/wip · commits on K',
798
1700
  gitMode === 'timer'
799
1701
  ? ` git: auto-committing ${deckRel} every ${commitEvery}s (and on Ctrl-C)`
800
- : wipLine(deckRel));
1702
+ : wipLine(deckRel),
1703
+ 'ok');
801
1704
  }
802
1705
  }
1706
+ if (!noTrust) startGit();
803
1707
  /**
804
1708
  * One tick: refresh the snapshot, and decide whether to ask.
805
1709
  *
@@ -826,7 +1730,7 @@ export async function editMain(args, { onListen = null } = {}) {
826
1730
  // immediately after, so there is no later for an amend to arrive in. The
827
1731
  // bookend keeps its literal subject, which is true anyway.
828
1732
  if (gitMode === 'timer') {
829
- gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`);
1733
+ if (gitAutocommit(deckPath, root, `decklight: stop editing ${basename(deckPath)}`, alsoNow())) pendingAttr = null;
830
1734
  } else {
831
1735
  // Committing work you deliberately did not commit would be the cadence
832
1736
  // again, wearing an exit for a hat. The snapshot is refreshed instead —
@@ -854,16 +1758,71 @@ export async function editMain(args, { onListen = null } = {}) {
854
1758
  // Precedence, like every other saved choice: the flag wins, then what was
855
1759
  // remembered (#125), then the first detected agent.
856
1760
  const agents = detectAgents();
857
- if (agents.length) {
1761
+ // Named at startup in write mode only: no-trust mode refuses the agent
1762
+ // route with the rest of the write family, and a roster line under the
1763
+ // ingredients label would promise a capability that mode does not have.
1764
+ if (agents.length && !noTrust) {
858
1765
  const mark = (a) => a.name + (a.name === agentPref ? ' (preferred)' : '') + (a.installed ? ' (installed)' : '');
859
1766
  startup('agents', agents.map(mark).join(', '),
860
- ` agents: ${agents.map(mark).join(', ')} — “Ask agent” (A) is live`);
1767
+ ` agents: ${agents.map(mark).join(', ')} — “Ask agent” (A) is live`, 'ok');
861
1768
  }
862
1769
  // A remembered agent that is not on this machine is said ONCE, at startup,
863
1770
  // rather than discovered at the moment someone presses A mid-talk.
864
- if (agentPref && !agents.some((a) => a.name === agentPref)) {
1771
+ if (!noTrust && agentPref && !agents.some((a) => a.name === agentPref)) {
865
1772
  console.log(` agent: ${agentUnavailable(agentPref, agents)}`);
866
1773
  }
1774
+ // A deck that EMBEDS a runtime older than this install is served as it is
1775
+ // (the file is the author's), and that runtime probes routes this server
1776
+ // may no longer have: it gets a 404, concludes there is no server, and
1777
+ // hides every write-mode affordance without a word. No-trust mode's label
1778
+ // already says "DIFFERS"; write mode has to say it too, and name the fix,
1779
+ // because a page that silently will not wire up is the one failure nobody
1780
+ // can diagnose from the page. The audit is the same comparison --check
1781
+ // makes: this install's bytes, or a version it cannot vouch for.
1782
+ if (!noTrust) {
1783
+ let rt = null;
1784
+ try { rt = auditDeck(readDeck()).runtime; } catch { /* the deck is read again by every route; a bad read fails there */ }
1785
+ if (rt?.kind === 'inline' && (rt.state === 'differs' || rt.state === 'other-version')) {
1786
+ const what = rt.state === 'other-version'
1787
+ ? `embeds runtime ${rt.version}; this install is ${rt.installedVersion}`
1788
+ : `embeds a runtime that is not this install's build${rt.installedVersion ? ` of ${rt.installedVersion}` : ''}`;
1789
+ startup('runtime',
1790
+ `${basename(deckPath)} ${what} · run: ${selfCommand()} upgrade ${deckRel}`,
1791
+ ` runtime: ${basename(deckPath)} ${what} — the deck may not wire up to this server; run decklight upgrade ${deckRel}`, 'warn');
1792
+ }
1793
+ }
1794
+ // The project's skill, if any, against this install (the same question the
1795
+ // runtime row asks of the deck): an agent that reads a skill written by an
1796
+ // older decklight reads an old contract — commands that went, routes that
1797
+ // moved — and the only place that can be noticed is here, since the agent
1798
+ // itself has no way to know. `decklight skills` refreshes it.
1799
+ if (!noTrust) {
1800
+ const older = [];
1801
+ for (const rel of ['.claude/skills/decklight/SKILL.md', 'AGENTS.md']) {
1802
+ const file = resolve(root, rel);
1803
+ if (!existsSync(file)) continue;
1804
+ let text = '';
1805
+ try { text = readFileSync(file, 'utf8'); } catch { continue; }
1806
+ if (rel === 'AGENTS.md' && !text.includes(AGENTS_MARKER)) continue;
1807
+ const v = skillVersionOf(text);
1808
+ if (v === null || (semverCompare(v, PKG.version) ?? -1) < 0) older.push({ rel, v });
1809
+ }
1810
+ if (older.length) {
1811
+ startup('skill',
1812
+ // the row is the fact and the command to type, nothing else
1813
+ `${older.map((o) => `${basename(o.rel)} ${o.v ? `v${o.v}` : 'before 0.9.0'}`).join(', ')}, older than ${PKG.version} · run: ${selfCommand()} skills`,
1814
+ ` 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');
1815
+ }
1816
+ }
1817
+ // The presenter's chrome, named here as no-trust mode names it under its
1818
+ // label: what is layered over the slides, and which plugin reads the notes.
1819
+ if (!noTrust && (chrome.plugins.length || chrome.refused.length)) {
1820
+ const names = chrome.plugins.map((pl) => `${pl.name}${pl.needs.includes('notes') ? ' (reads your notes)' : ''}`);
1821
+ const refused = chrome.refused.map((r) => `${r.name} refused`);
1822
+ startup('plugins', [...names, ...refused].join(', ') + ' · --no-plugins plays without them',
1823
+ ` chrome: ${[...names, ...refused].join(', ')} — yours, not in the deck (--no-plugins plays without them)`,
1824
+ refused.length ? 'warn' : 'ok');
1825
+ }
867
1826
  // Said out loud, every session it is on: this is the switch that starts
868
1827
  // sending the deck somewhere, and a capability nobody is reminded of is one
869
1828
  // they stop counting on being off. Printed HERE rather than up with the other
@@ -871,14 +1830,209 @@ export async function editMain(args, { onListen = null } = {}) {
871
1830
  if (gitOn && wantMessages) {
872
1831
  const who = agents.find((a) => a.name === agentPref) ?? agents[0];
873
1832
  startup('git',
874
- who?.name ? `${who.name} writes the subjects` : '--commit-messages needs an agent on PATH',
875
- ` ${messagesLine(who?.name ?? null)}`);
1833
+ who?.name ? `subjects by ${who.name}` : '--commit-messages needs an agent on PATH',
1834
+ ` ${messagesLine(who?.name ?? null)}`, who?.name ? 'ok' : 'warn');
876
1835
  }
877
1836
 
878
1837
  // ── live reload: watch the deck, broadcast SSE (debounced — editors fire
879
1838
  // multiple fs events per save) ─────────────────────────────────────────
880
- const clients = sseChannel();
881
- const broadcast = (event, data) => clients.broadcast(event, data);
1839
+ // The review routes (SPEC REVIEW), the same ones every server that opens a
1840
+ // deck registers: a review can be left in write mode too. The sidecar is
1841
+ // appended, never the deck; here it is not committed by itself, because the
1842
+ // deck's own commits (the snapshot, K) are what this server keeps.
1843
+ // In no-trust mode the sidecar is the ONE file this process writes, and
1844
+ // it is committed by itself as each comment lands when the deck sits in a
1845
+ // repository (`--no-git` leaves the committing to you).
1846
+ const reviewRepo = gitAvailable(dirname(deckPath)) && inGitRepo(dirname(deckPath));
1847
+ const review = createReviewRoutes(deckPath, {
1848
+ inRepo: reviewRepo,
1849
+ gitOn: noTrust && reviewRepo && !noGit,
1850
+ mode: noTrust ? 'no-trust' : 'write',
1851
+ // A record just landed in the sidecar — a resolve naming a reviewer's
1852
+ // comment changes what the incoming listing says is done, so the cached
1853
+ // listing must not outlive it. `wrote` is the .gitattributes the first
1854
+ // record in this repository had to write (REVIEW, merge=union): the
1855
+ // deck's next commit carries it, beside the sidecar.
1856
+ onRecord: (_rec, { wrote } = {}) => { incomingCache = null; if (wrote) pendingAttr = wrote; },
1857
+ // No-trust mode lists back what this reviewer already submitted, from
1858
+ // the remote's review/<me>-* branches (REVIEW), behind the same switches
1859
+ // that silence the author's inbox check, and at most once a minute: M is
1860
+ // a keypress, not a fetch storm.
1861
+ mine: noTrust && reviewRepo && !reviewCheckSuppressed({ args, ci: false }) ? async () => {
1862
+ if (!mineCache || Date.now() - mineCache.at > 60_000) {
1863
+ const { myReviews } = await import('./review-remote.mjs');
1864
+ const { reviewerIdentity } = await import('./review-routes.mjs');
1865
+ const { slugUser } = await import('./review-submit.mjs');
1866
+ mineCache = { at: Date.now(), r: await myReviews(deckPath, slugUser(reviewerIdentity(dirname(deckPath)))) };
1867
+ }
1868
+ return mineCache.r;
1869
+ } : null,
1870
+ });
1871
+ let mineCache = null;
1872
+ // The deck's channel (deck-routes.mjs): the probe and the stream, in both
1873
+ // modes. What the probe carries beyond the mode is `extras`, computed on
1874
+ // every ping like everything else on it: the toast is threshold-driven,
1875
+ // not live.
1876
+ const deck = createDeckRoutes(deckPath, {
1877
+ noTrust,
1878
+ locked: () => noTrust || locked,
1879
+ review,
1880
+ extras: async () => (noTrust ? {
1881
+ // No-trust mode names nothing that edits: no roster, no history, no
1882
+ // git. What the page needs is whether the phone remote is on
1883
+ // (NO_TRUST#REMOTE: the clicker, and the QR in the speaker view) and
1884
+ // whether this deck can ever leave the mode.
1885
+ phone: !!token,
1886
+ container: !!container,
1887
+ } : {
1888
+ deck: deckUrl,
1889
+ phone: !!token,
1890
+ container: !!container,
1891
+ ...history.counts(), git: gitOn,
1892
+ // What the player's one push nudge reads. Computed once, like everything
1893
+ // else on ping: the toast is threshold-driven, not live.
1894
+ remote: gitOn ? remoteState(root) : null,
1895
+ agents: agents.map((a) => ({ name: a.name, label: a.label })),
1896
+ // which one A reaches for, so the picker opens on it rather than
1897
+ // defaulting to the first detected agent every session (#125)
1898
+ preferredAgent: agentPref ?? null,
1899
+ agentBusy: agentJob && { agent: agentJob.agent, prompt: agentJob.prompt, startedAt: agentJob.startedAt, id: agentJob.id },
1900
+ agentAsks,
1901
+ wizards: await configurableEngines(),
1902
+ // What is uncommitted, so a deck that loads mid-session shows the
1903
+ // chip without waiting for the next tick to broadcast one.
1904
+ commit: (gitOn && measureDirty(), commitState()),
1905
+ }),
1906
+ });
1907
+ const clients = deck.channel;
1908
+ const broadcast = deck.broadcast;
1909
+
1910
+ // ── the phone remote (NO_TRUST#REMOTE) ───────────────────────────────────
1911
+ // The relay: controller page, QR, readout channel, the phone's taps onto the
1912
+ // deck's stream. These are the only paths allowRemote lets through from off
1913
+ // this machine, and not one of them writes anything — the phone asks the
1914
+ // deck to move, it never edits. The phone is a different origin from the
1915
+ // deck (a LAN address, not localhost), so the relay's own endpoints need
1916
+ // CORS; nothing else here does.
1917
+ const PHONE_CORS = corsHeaders();
1918
+ let actualPort = null;
1919
+ // The controller answers on loopback in either mode, flag or no flag (a
1920
+ // deck on this machine gets its position readout); only the LAN listener,
1921
+ // and the QR that points a phone at it, are what --remote adds.
1922
+ const relay = createRemoteRelay({
1923
+ deckName: basename(deckPath),
1924
+ token,
1925
+ remoteUrl: () => `http://${lanAddress() ?? host}:${actualPort}/deck/remote?t=${token}`,
1926
+ relayToDeck: (event, data) => broadcast(event, data),
1927
+ deckCount: () => clients.size,
1928
+ CORS: PHONE_CORS,
1929
+ });
1930
+
1931
+ // ── the upstream check (NO_TRUST#UPSTREAM) ───────────────────────────────
1932
+ // A deck opened without trust from a clone: has its author pushed since? Absent
1933
+ // unless the deck is a tracked file in a clone with an upstream — that is
1934
+ // the whole safety argument: a deck you were emailed is a single file and
1935
+ // never reaches any of it. Write mode has H for the deck's own history and
1936
+ // never resolves this; the routes are registered only when it applies.
1937
+ const suppressed = !noTrust ? 'write mode' : upstreamSuppressed({ args, env: process.env });
1938
+ const upstreamCtx = suppressed ? { state: 'disabled' } : await resolveUpstream(deckPath);
1939
+ const upstream = upstreamCtx.state === 'ok' ? upstreamCtx : null;
1940
+ // The PULL is a second, explicit opt-in. Server-side there is no way to tell
1941
+ // "the presenter clicked" from "a script in the deck called fetch()" — a
1942
+ // page's own script is indistinguishable from its user — so the capability
1943
+ // is "a deck served from a clone can update itself from that clone's
1944
+ // upstream", which is a thing someone should have typed rather than
1945
+ // something the cwd decided. And never with --remote: a phone must not move
1946
+ // somebody's repo.
1947
+ const pullArmed = Boolean(upstream) && args.includes('--upstream-pull') && !token;
1948
+ let upstreamStatus = upstream
1949
+ ? { state: 'unchecked', branch: upstream.branch, upstream: upstream.upstream, message: 'not checked yet' }
1950
+ : { state: upstreamCtx.state, message: suppressed || null };
1951
+ let checking = null;
1952
+ const intervalMs = resolveInterval(args);
1953
+ let lastReported = null;
1954
+ const pullOffer = () => (pullArmed
1955
+ ? { offered: true }
1956
+ : { offered: false, reason: !upstream ? upstreamCtx.state : token ? '--remote is on' : 'start with --upstream-pull' });
1957
+ async function refreshUpstream() {
1958
+ if (!upstream) return upstreamStatus;
1959
+ // Single-flight: a script in a loop must not spawn a hundred fetches.
1960
+ if (!checking) {
1961
+ checking = checkUpstream(upstream).then((st) => { upstreamStatus = st; checking = null; return st; });
1962
+ }
1963
+ return checking;
1964
+ }
1965
+ /** The label, re-printed: what the audience gets from here on. */
1966
+ const printLabel = () => {
1967
+ for (const line of formatLabel(audited.report)) console.log(line);
1968
+ if (container) console.log(formatManifest(container.manifest));
1969
+ console.log(formatSignature(signature));
1970
+ };
1971
+ /**
1972
+ * Fast-forward, then re-read, re-audit and RE-PRINT. SPEC's condition on
1973
+ * live reload in no-trust mode is exactly this: never new bytes under the
1974
+ * old verdict. So the label the presenter can see always describes the
1975
+ * bytes being served, and the two move together.
1976
+ */
1977
+ async function doPull() {
1978
+ // Re-checked against a FRESH fetch rather than trusted from the cached
1979
+ // status: what was true ten minutes ago is not a licence to check out now.
1980
+ const fresh = await refreshUpstream();
1981
+ const allowed = canPull(fresh, { offered: pullArmed });
1982
+ if (!allowed.ok) return { ok: false, ...allowed, http: 409 };
1983
+
1984
+ const from = (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: upstream.repoRoot })).stdout;
1985
+ console.log(` upstream: PULL requested by the deck — fast-forward only, onto ${upstream.upstream}`);
1986
+ const merged = await runGit([...SAFE_CONFIG, '-c', `core.hooksPath=${upstream.repoRoot}/.git/decklight-no-hooks`,
1987
+ 'merge', '--ff-only', '--no-verify', '@{upstream}'], { cwd: upstream.repoRoot, timeoutMs: 20000 });
1988
+ if (!merged.ok) {
1989
+ const why = oneline(merged.stderr || merged.err);
1990
+ console.log(` upstream: the fast-forward was refused — ${why}`);
1991
+ return { ok: false, state: 'not-fast-forward', message: why };
1992
+ }
1993
+ const to = (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: upstream.repoRoot })).stdout;
1994
+
1995
+ // An upstream commit must never blank somebody's talk.
1996
+ if (!existsSync(deckPath)) {
1997
+ console.log(` upstream: fast-forwarded ${from} → ${to}, but the deck is gone from that commit`);
1998
+ console.log(' still serving the bytes the label above describes');
1999
+ return { ok: false, state: 'deck-gone', to, message: 'the deck is not in that commit — still serving the old bytes' };
2000
+ }
2001
+
2002
+ const wasStrict = audited.strict;
2003
+ const hadFindings = audited.report.counts.unaccounted > 0 || audited.report.counts.handlers > 0;
2004
+ if (!audit()) {
2005
+ console.log(` upstream: fast-forwarded ${from} → ${to} — the deck itself is unchanged`);
2006
+ await refreshUpstream();
2007
+ return { ok: true, state: 'pulled', from, to, deck: 'unchanged', reload: false, message: `fast-forwarded to ${to} — the deck is unchanged` };
2008
+ }
2009
+ const findings = { unaccounted: audited.report.counts.unaccounted, handlers: audited.report.counts.handlers };
2010
+ const degraded = (findings.unaccounted > 0 || findings.handlers > 0) && !hadFindings;
2011
+
2012
+ console.log(` upstream: fast-forwarded ${from} → ${to}`);
2013
+ console.log(' the deck file changed — re-read and re-audited; the label below replaces the one above');
2014
+ noteWrite(whatWrote('/deck/upstream/pull'));
2015
+ printLabel();
2016
+ if (audited.strict) {
2017
+ console.log(wasStrict && !(findings.unaccounted > 0 || findings.handlers > 0)
2018
+ ? ' still serving strict — a pull cannot turn it off'
2019
+ : ' serving strict — what could not be accounted for is stripped');
2020
+ }
2021
+ console.log(' the label above describes what the audience gets when the deck is reloaded');
2022
+ await refreshUpstream();
2023
+ return {
2024
+ ok: true, state: 'pulled', from, to, deck: 'changed',
2025
+ strict: audited.strict, degraded, findings,
2026
+ // A degraded deck does NOT reload itself: the swap executes nothing (the
2027
+ // browser is still showing the old DOM), so the reload can wait for a
2028
+ // second confirmation that names what was found.
2029
+ reload: !degraded,
2030
+ message: degraded
2031
+ ? `the updated deck runs ${findings.unaccounted} unaccounted script block(s) and `
2032
+ + `${findings.handlers} inline handler(s) — they are stripped. Reload to show it`
2033
+ : `fast-forwarded to ${to}`,
2034
+ };
2035
+ }
882
2036
 
883
2037
  // ── the catalogs, read from cache and never fetched ──────────────────────
884
2038
  const catalogMap = async () => {
@@ -890,8 +2044,16 @@ export async function editMain(args, { onListen = null } = {}) {
890
2044
  }
891
2045
  return out;
892
2046
  };
893
- /** Every theme entry a registered marketplace offers, qualified. */
894
- const browsableThemes = async () => {
2047
+ /**
2048
+ * Every entry of one TYPE a registered marketplace offers, qualified.
2049
+ *
2050
+ * Written for themes and generalised the day templates needed the same list:
2051
+ * the cache reading, the never-fetched marketplaces and the
2052
+ * cloned-but-missing ones are properties of the registry, not of what is
2053
+ * being listed, so a second copy of them would be a second thing to keep
2054
+ * right.
2055
+ */
2056
+ const browsableUnits = async (type) => {
895
2057
  const { loadRegistry, loadCatalog, checkoutPath, classifySource, configHome } = await import('./marketplace.mjs');
896
2058
  const registry = loadRegistry().marketplaces ?? {};
897
2059
  const themes = [];
@@ -913,7 +2075,7 @@ export async function editMain(args, { onListen = null } = {}) {
913
2075
  continue;
914
2076
  }
915
2077
  for (const e of loaded.manifest.entries ?? []) {
916
- if (e.type !== 'theme') continue;
2078
+ if (e.type !== type) continue;
917
2079
  themes.push({
918
2080
  name: e.name, marketplace: market, qualified: `${e.name}@${market}`,
919
2081
  description: e.description ?? '', source: e.source,
@@ -924,9 +2086,9 @@ export async function editMain(args, { onListen = null } = {}) {
924
2086
  };
925
2087
  /**
926
2088
  * Every entry a registered marketplace declares a wizard for, qualified.
927
- * Advertised in /edit/ping beside the agents: the palette's Configure rows
2089
+ * Advertised in /deck/ping beside the agents: the palette's Configure rows
928
2090
  * come from here, so a player never has to guess an engine name to ask
929
- * /edit/wizard about (ENGINES#WIZARD).
2091
+ * /deck/edit/wizard about (ENGINES#WIZARD).
930
2092
  */
931
2093
  const configurableEngines = async () => {
932
2094
  const { loadRegistry, loadCatalog } = await import('./marketplace.mjs');
@@ -1001,6 +2163,7 @@ export async function editMain(args, { onListen = null } = {}) {
1001
2163
  };
1002
2164
 
1003
2165
  let pending = null;
2166
+ let quietWrite = null; // the bytes of a write that updates the page itself (themeMarkRoute, cli/edit-look.mjs)
1004
2167
  // The DIRECTORY, not the file. A path watch follows the inode, and an
1005
2168
  // atomic write — temp file + rename, which is how an agent's editor and
1006
2169
  // most careful tools save — replaces the inode: the watcher then sits deaf
@@ -1012,14 +2175,44 @@ export async function editMain(args, { onListen = null } = {}) {
1012
2175
  if (filename && filename !== basename(deckPath)) return;
1013
2176
  clearTimeout(pending);
1014
2177
  pending = setTimeout(() => {
1015
- clients.raw('data: reload\n\n');
1016
- console.log(` changed → reload × ${clients.size}`);
2178
+ // No-trust mode serves the audited bytes, never the disk: a file that
2179
+ // changed underneath it is not reloaded, because that would be new
2180
+ // bytes under the old label. A pull re-audits.
2181
+ if (noTrust) return;
2182
+ // A QUIET write is one the pages update themselves in place, which must
2183
+ // not reload: a theme marked from the open picker (a reload closes the
2184
+ // picker the author is still choosing in), or a notes save, whose new
2185
+ // notes every page is sent as a `notes` event. Skipped only when
2186
+ // the file is still exactly what that write put there; any other change
2187
+ // since (an editor save, an undo) reloads as it always has.
2188
+ const quiet = quietWrite;
2189
+ quietWrite = null;
2190
+ if (quiet !== null) {
2191
+ let now = null;
2192
+ try { now = readFileSync(deckPath, 'utf8'); } catch { /* gone — reload says so */ }
2193
+ if (now === quiet) { lastWrite = null; console.log(' changed → updated in place, no reload'); return; }
2194
+ }
2195
+ // The message names what wrote the file (`describeReload`): the page
2196
+ // stashes it with its debug log and says it first thing after the
2197
+ // reload. An older page reloads on any message, as it always did.
2198
+ const why = describeReload({ write: lastWrite, agent: agentJob });
2199
+ lastWrite = null;
2200
+ clients.raw(`data: ${JSON.stringify(why)}\n\n`);
2201
+ console.log(` changed → reload × ${clients.size} — ${why.reload}${why.from ? ` (page ${why.from})` : ''}`);
1017
2202
  }, 150);
1018
2203
  });
1019
2204
 
1020
- function runAgent(prompt, name, message) {
1021
- const cmd = agentCommand(name || agentPref, prompt, deckRel);
2205
+ function runAgent(prompt, name, message, slide) {
2206
+ const cmd = agentCommand(name || agentPref, prompt, deckRel, { slide });
1022
2207
  if (!cmd) return null;
2208
+ const ask = {
2209
+ id: ++askSeq, agent: cmd.name, label: cmd.label, prompt,
2210
+ ...(Number.isInteger(slide) && slide > 0 ? { slide } : {}),
2211
+ startedAt: Date.now(), state: 'running',
2212
+ };
2213
+ agentAsks.push(ask);
2214
+ if (agentAsks.length > ASKS_KEPT) agentAsks.shift();
2215
+ const finish = (d) => Object.assign(ask, { state: 'done', finishedAt: Date.now() }, d);
1023
2216
  // Anything uncommitted at this moment is the PLAYER's work, not the
1024
2217
  // agent's. Sweeping it into its own commit first is what keeps the agent's
1025
2218
  // commit honest: otherwise a hand edit made just before pressing A lands
@@ -1030,7 +2223,7 @@ export async function editMain(args, { onListen = null } = {}) {
1030
2223
  console.log(' git: committed your outstanding changes first');
1031
2224
  }
1032
2225
  const before = readDeck();
1033
- agentJob = { agent: cmd.name, label: cmd.label, prompt, startedAt: Date.now() };
2226
+ agentJob = { agent: cmd.name, label: cmd.label, prompt, startedAt: ask.startedAt, id: ask.id, slide: ask.slide };
1034
2227
  broadcast('agent', { state: 'start', ...agentJob });
1035
2228
  console.log(` agent: ${cmd.name} ← "${prompt.slice(0, 80)}"`);
1036
2229
  const child = spawn(cmd.bin, cmd.args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
@@ -1046,7 +2239,7 @@ export async function editMain(args, { onListen = null } = {}) {
1046
2239
  let lastSaid = 0;
1047
2240
  const say = (text) => {
1048
2241
  if (!text || !agentJob) return;
1049
- agentJob.activity = text; // /edit/ping carries it across a reload
2242
+ agentJob.activity = text; // /deck/ping carries it across a reload
1050
2243
  broadcast('agent', { state: 'activity', agent: cmd.name, text });
1051
2244
  console.log(` agent: ${text}`);
1052
2245
  };
@@ -1076,7 +2269,8 @@ export async function editMain(args, { onListen = null } = {}) {
1076
2269
  child.on('error', (e) => {
1077
2270
  clearTimeout(timeout);
1078
2271
  agentJob = null;
1079
- broadcast('agent', { state: 'done', agent: cmd.name, ok: false, changed: false, error: String(e.message || e) });
2272
+ finish({ ok: false, changed: false, error: String(e.message || e) });
2273
+ broadcast('agent', { state: 'done', id: ask.id, agent: cmd.name, ok: false, changed: false, error: String(e.message || e) });
1080
2274
  });
1081
2275
  child.on('exit', (code) => {
1082
2276
  clearTimeout(timeout);
@@ -1088,7 +2282,7 @@ export async function editMain(args, { onListen = null } = {}) {
1088
2282
  // A failed run or one that changed nothing commits nothing.
1089
2283
  if (gitOn && shouldCommit(gitMode, { kind: 'agent', ok: code === 0, changed })) {
1090
2284
  const subject = commitSubject(message ?? prompt, `decklight: ${cmd.name} edited ${basename(deckPath)}`);
1091
- if (gitAutocommit(deckPath, root, subject)) console.log(` git: committed "${subject}"`);
2285
+ if (gitAutocommit(deckPath, root, subject, alsoNow())) { pendingAttr = null; console.log(` git: committed "${subject}"`); }
1092
2286
  }
1093
2287
  // Did the edit orphan, stale, or reshape a recording? A track is
1094
2288
  // minutes of somebody's own voice, and a whole-deck rewrite can drop the
@@ -1110,11 +2304,12 @@ export async function editMain(args, { onListen = null } = {}) {
1110
2304
  } catch { recordingWarning = null; } // a warning that throws is worse than none
1111
2305
  }
1112
2306
  agentJob = null;
2307
+ // the agent's own words when the stream carried them — raw stream-json
2308
+ // stdout is a wall of JSON nobody should be shown
2309
+ const said = (resultText ?? tail.trim().split('\n').slice(-6).join('\n')).slice(-600);
2310
+ finish({ ok: code === 0, changed, code, tail: said });
1113
2311
  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),
2312
+ state: 'done', id: ask.id, agent: cmd.name, ok: code === 0, changed, code, tail: said,
1118
2313
  ...(recordingWarning ? { recordingWarning } : {}),
1119
2314
  });
1120
2315
  console.log(` agent: ${cmd.name} exited (${code}) — deck ${changed ? 'changed' : 'unchanged'}`);
@@ -1123,8 +2318,695 @@ export async function editMain(args, { onListen = null } = {}) {
1123
2318
  return cmd;
1124
2319
  }
1125
2320
 
1126
- const files = staticFiles(root, { index: deckUrl });
2321
+ // ── the session: what a deck asks on load, and how it ends ───────────────
2322
+
2323
+ // ── the bridges, on this origin (#520) ───────────────────────────────────
2324
+ // A deck served here reaches its live voice at `/deck/tts` (and the sibling
2325
+ // routes the runtime derives from it) and its lip-sync at `/deck/lipsync/*` —
2326
+ // the deck's own origin, never a port it would have to spell (SPEC
2327
+ // NARRATION). The bridges are separate processes on their own ports
2328
+ // (`--tts-port`, `--lipsync-port`); these forward to them, body and
2329
+ // headers both ways, and answer 503 when the bridge is not there, which the
2330
+ // deck takes exactly as it takes no bridge at all.
2331
+ const ttsPort = parsePort(opt('--tts-port', 8787)) ?? 8787;
2332
+ const lipsyncPort = parsePort(opt('--lipsync-port', 8789)) ?? 8789;
2333
+ const proxyTo = (port, name, rewritePath = (p) => p) => ({ req, res, url, body }) => new Promise((done) => {
2334
+ const { host: _host, ...headers } = req.headers;
2335
+ const upstream = httpRequest({
2336
+ host: '127.0.0.1', port, method: req.method, path: rewritePath(url.pathname) + url.search,
2337
+ headers: { ...headers, host: `127.0.0.1:${port}` },
2338
+ }, (up) => {
2339
+ res.writeHead(up.statusCode ?? 502, up.headers);
2340
+ up.pipe(res);
2341
+ up.on('end', done);
2342
+ });
2343
+ upstream.on('error', (e) => {
2344
+ if (!res.headersSent) res.writeHead(503, { 'content-type': 'text/plain; charset=utf-8' });
2345
+ res.end(`the ${name} bridge is not running on port ${port} (${e.code ?? e.message})`);
2346
+ done();
2347
+ });
2348
+ // every proxied route is dispatched before the body is read, so the
2349
+ // request streams through — audio for the lip-sync bridge included
2350
+ if (body !== undefined) upstream.end(body); else req.pipe(upstream);
2351
+ });
2352
+ // both bridges serve their routes at their own roots; on the deck's origin
2353
+ // they sit under /deck/, and the prefix comes off on the way through
2354
+ const ttsProxy = proxyTo(ttsPort, 'voice', (p) => p.slice('/deck'.length));
2355
+ const lipsyncProxy = proxyTo(lipsyncPort, 'lip-sync', (p) => p.slice('/deck/lipsync'.length));
2356
+
2357
+ // ── the lock (PRESENTING) ─────────────────────────────────────────────────
2358
+ // Editing is on from the moment write mode answers; the lock is the one
2359
+ // switch that turns changes off, to avoid making one by mistake, and back
2360
+ // on. It lives here, not in a page, so every tab and the agent see the
2361
+ // same state: locked, every POST to /deck/edit/* but this one answers 423,
2362
+ // the ping says so, and the channel tells every open page. No-trust mode
2363
+ // has no lock to turn: the write family refuses there anyway.
2364
+ let locked = false;
2365
+ function lockRoute({ body, json }) {
2366
+ const { locked: want } = JSON.parse(body || '{}');
2367
+ if (typeof want !== 'boolean') return json(400, { ok: false, error: 'locked is true or false' });
2368
+ if (want !== locked) {
2369
+ locked = want;
2370
+ console.log(locked ? ' deck locked — nothing is written until it is unlocked' : ' deck unlocked');
2371
+ broadcast('lock', { locked });
2372
+ }
2373
+ return json(200, { ok: true, locked });
2374
+ }
2375
+ function shutdownRoute({ res, json, CORS }) {
2376
+ res.writeHead(200, { ...CORS, 'content-type': 'application/json' });
2377
+ res.end(JSON.stringify({ ok: true }));
2378
+ // same shutdown a Ctrl-C takes — final autocommit, then actually exit —
2379
+ // once the response has cleared the socket, so the asker sees it land
2380
+ res.once('finish', () => { finalCommit(); process.exit(0); });
2381
+ return;
2382
+ }
2383
+
2384
+ function undoRedoRoute({ url, json }) {
2385
+ const dir = url.pathname.endsWith('undo') ? 'undo' : 'redo';
2386
+ const cur = readDeck();
2387
+ const content = history[dir](cur);
2388
+ if (content === null) return json(409, { ok: false, error: `nothing to ${dir}`, ...history.counts() });
2389
+ writeDeck(content);
2390
+ console.log(` ${dir} → ${JSON.stringify(history.counts())}`);
2391
+ return json(200, { ok: true, ...history.counts() });
2392
+ }
2393
+
2394
+ // ── review comments (SPEC REVIEW) ─────────────────────────────
2395
+ // The author's side of `decklight <deck> --no-trust`. The same file, the same
2396
+ // append-only rule: this server may add a line (a resolve, a move) and
2397
+ // may not rewrite one, because `merge=union` is what keeps two reviewers
2398
+ // from conflicting and an edit in place is what would break it.
2399
+ // What reviews are waiting on the remote — the M overlay's incoming
2400
+ // section. This one is a fetch the author DID ask for: it runs behind
2401
+ // the keypress that just opened the overlay, on demand and nowhere else.
2402
+ // The 60s cache is what keeps a nervous author tapping M from turning
2403
+ // one gesture into a fetch storm; the off switches still win outright.
2404
+ async function reviewIncomingRoute({ json }) {
2405
+ // ci: false — this fetch is ASKED FOR, behind the keypress that
2406
+ // opened the overlay; only the explicit switches silence it.
2407
+ const skipped = reviewCheckSuppressed({ args, ci: false });
2408
+ if (skipped) return json(200, { ok: true, state: 'suppressed', reason: skipped, reviews: [] });
2409
+ if (!incomingCache || Date.now() - incomingCache.at > 60_000) {
2410
+ const r = await reviewsWaiting(deckPath);
2411
+ incomingCache = { at: Date.now(), r };
2412
+ }
2413
+ return json(200, { ok: true, ...incomingCache.r });
2414
+ }
2415
+
2416
+ // Point the deck at a track the recorder just wrote. The one manual step
2417
+ // in a flow that is otherwise a key and an arrow — and this server
2418
+ // already owns the file, so it can take that step too.
2419
+ function reviewAtRoute({ url, json }) {
2420
+ // The orphan's context: what the slide SAID when the comment was
2421
+ // written — `comments --at`, served, so the overlay can put the dead
2422
+ // slide's prose under the objection that was about it. Read-only, all
2423
+ // local (the commit is already in this clone or the answer is "not
2424
+ // here"), and gated exactly as the CLI gates it.
2425
+ const id = url.searchParams.get('id') ?? '';
2426
+ if (!/^[a-z0-9]{1,12}$/.test(id)) return json(400, { ok: false, error: 'bad comment id' });
2427
+ const store = reviewPathFor(deckPath);
2428
+ if (!existsSync(store)) return json(404, { ok: false, error: 'no comments here' });
2429
+ const c = foldReview(parseReview(readFileSync(store, 'utf8')).records).find((x) => x.id === id);
2430
+ if (!c) return json(404, { ok: false, error: `no comment [${id}]` });
2431
+ if (!c.deck) return json(200, { ok: true, known: false, why: 'written outside a repository — there is no earlier version to show' });
2432
+ if (!gitOn || !knowsCommit(c.deck, root)) {
2433
+ return json(200, { ok: true, known: false, why: `this clone does not have ${c.deck}` });
2434
+ }
2435
+ try {
2436
+ const thenHtml = deckAt(deckPath, c.deck, root);
2437
+ const wasAt = indexDeckFile(thenHtml)[(c.slide ?? 0) - 1] ?? null;
2438
+ return json(200, {
2439
+ ok: true,
2440
+ known: true,
2441
+ deck: c.deck,
2442
+ slide: c.slide ?? null,
2443
+ title: wasAt?.title ?? null,
2444
+ text: slideTextOf(thenHtml, c.slide) || '',
2445
+ });
2446
+ } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
2447
+ }
2448
+
2449
+ // ── the engine wizard (ENGINES#WIZARD) ─────────────────────────────
2450
+ // The schema the player renders. Validated on the way OUT as well as on
2451
+ // the way in: a catalog is a file someone else wrote, and handing the
2452
+ // renderer a schema core has not vetted is how "core renders, a plugin
2453
+ // declares" becomes "core renders whatever a plugin sent".
2454
+ async function wizardSchemaRoute({ url, json }) {
2455
+ const engine = url.searchParams.get('engine') ?? '';
2456
+ const hit = await wizardEntry(engine);
2457
+ if (!hit) return json(404, { ok: false, error: `no wizard declared for "${engine}"` });
2458
+ try {
2459
+ const schema = validateSchema(hit.entry.wizard);
2460
+ // Provenance rides BESIDE the schema, never inside it (#232): `from`
2461
+ // is the registry's name for the entry and the sentence pair is
2462
+ // derived here from the vetted schema, so the card can say who is
2463
+ // asking and where the answer goes in words the plugin did not write.
2464
+ return json(200, { ok: true, schema, from: hit.qualified, provenance: provenance(schema, hit.qualified) });
2465
+ } catch (e) {
2466
+ return json(400, { ok: false, error: `${engine} declares a wizard core cannot render: ${e.message}` });
2467
+ }
2468
+ }
2469
+
2470
+ // Author-mode only, and that is structural rather than checked: this
2471
+ // server answers loopback alone, and `--no-trust` registers nothing like
2472
+ // these at all. A credential prompt in a deck you were emailed has
2473
+ // nowhere to post.
2474
+ async function wizardConfigureRoute({ body, json }) {
2475
+ const { engine, answers } = JSON.parse(body);
2476
+ if (typeof engine !== 'string') return json(400, { ok: false, error: 'which engine?' });
2477
+ // "No such engine" is a third answer, not one of the two failures. It is
2478
+ // not an outage to wait out and not a refusal by a provider — it is a
2479
+ // marketplace that was never added, and the fix is named.
2480
+ if (!(await wizardEntry(engine))) {
2481
+ return json(404, { ok: false, state: 'unknown',
2482
+ error: `no engine named "${engine}" declares a wizard in any registered marketplace — try: decklight marketplace add <owner/repo>` });
2483
+ }
2484
+ const r = await configureEngine(engine, answers, {
2485
+ fetchSchema: wizardSchemaFor,
2486
+ validateAnswers: wizardValidate,
2487
+ });
2488
+ if (r.state !== CONFIGURED) {
2489
+ // The three failures stay three: 503 for "could not reach", 400 for
2490
+ // "that was refused", and 412 for "this machine is missing something"
2491
+ // (ENGINES#LIPSYNC). A presenter whose key is wrong must not be told
2492
+ // to check their network, and one who is missing rhubarb must not be
2493
+ // told to check their key — the status code says which it is too.
2494
+ const code = r.state === UNREACHABLE ? 503 : r.state === PREREQUISITE ? 412 : 400;
2495
+ return json(code, { ok: false, state: r.state, error: r.reason, ...(r.unmet ? { unmet: r.unmet } : {}) });
2496
+ }
2497
+ // Redacted on the way out, always — the response is the one place a key
2498
+ // could leak back into a page, a devtools log, or a screen recording.
2499
+ console.log(` wizard: ${engine} configured (${r.file} — ${r.protection.label})`);
2500
+ // A key that could not be restricted is worth an extra line, at the
2501
+ // moment it is stored rather than in a doc nobody reads (#308): what
2502
+ // decklight says about a credential and what is true of it on disk
2503
+ // have to be the same sentence.
2504
+ if (r.protection.state !== 'private') {
2505
+ console.log(` wizard: decklight could NOT restrict that file to your account — ${r.protection.label}`);
2506
+ if (r.protection.why) console.log(` the system said: ${r.protection.why}`);
2507
+ }
2508
+ return json(200, { ok: true, state: r.state, engine, stored: r.stored, protection: r.protection.label });
2509
+ }
2510
+
2511
+ function wizardForgetRoute({ body, json }) {
2512
+ const { engine } = JSON.parse(body);
2513
+ if (typeof engine !== 'string') return json(400, { ok: false, error: 'which engine?' });
2514
+ const had = forgetCredentials(engine);
2515
+ console.log(` wizard: ${engine} ${had ? 'forgotten' : 'was not configured'}`);
2516
+ return json(200, { ok: true, forgotten: had });
2517
+ }
2518
+
2519
+ // ── the recorder's offline recordings — V → Record this deck… (PRESENTING) ───────────────────────────────
2520
+ // The player used to hand every stitched slide to the browser's DOWNLOAD
2521
+ // path, which is why a deck's voice arrived as thirty slide-NN.wav in
2522
+ // whatever folder the OS calls Downloads — never the deck's, and on
2523
+ // Windows not even near it. `bundle` only ever looks NEXT TO THE DECK, so
2524
+ // the recording was finished and in the wrong place, and the last step
2525
+ // was moving files by hand. In write mode the server that already owns
2526
+ // the deck file writes them itself.
2527
+ //
2528
+ // Ahead of the shared body read below because this body is BINARY and
2529
+ // megabytes of it: a slide of speech is ~48 kB a second, so the string
2530
+ // concat and its 1 MB ceiling would both be wrong.
2531
+ async function recordRoute({ req, url, json }) {
2532
+ const slide = Number(url.searchParams.get('slide'));
2533
+ const kind = url.searchParams.get('kind');
2534
+ if (!Number.isInteger(slide) || slide < 1 || slide > 9999) return json(400, { ok: false, error: 'bad slide' });
2535
+ if (kind !== 'wav' && kind !== 'visemes' && kind !== 'manifest') return json(400, { ok: false, error: 'bad kind' });
2536
+ // `seg` is the per-⟨CLICK⟩ file number — the audio that lets a recording
2537
+ // step the builds (slide-NN-KK.wav) and the viseme timeline cut to
2538
+ // match it (slide-NN-KK.visemes.json). Absent means the whole slide.
2539
+ // Bounded and integral like `slide`, and for the same reason: it is
2540
+ // half of a filename this server builds, and the only defence that
2541
+ // survives someone deciding the name should be more flexible one day.
2542
+ const segRaw = url.searchParams.get('seg');
2543
+ const seg = segRaw == null ? null : Number(segRaw);
2544
+ if (seg !== null && (!Number.isInteger(seg) || seg < 1 || seg > 999)) {
2545
+ return json(400, { ok: false, error: 'bad seg' });
2546
+ }
2547
+ // The player names the FOLDER (its own `narration.files`, so a recorded
2548
+ // set lands where that deck already plays from) and nothing else: the
2549
+ // file name is built here, so no request can choose one. The folder is
2550
+ // contained to the served root by the same rule staticFiles reads by —
2551
+ // and `..`, absolute paths and Windows drive letters are refused before
2552
+ // it, because `resolve` would happily swallow all three.
2553
+ const want = url.searchParams.get('dir') || 'voiceover';
2554
+ const bad = want.length > 200 || /^[/\\]/.test(want) || /^[a-zA-Z]:/.test(want)
2555
+ || want.split(/[/\\]/).includes('..');
2556
+ const dir = bad ? null : resolve(deckPath, '..', want);
2557
+ if (!dir || (!dir.startsWith(root + sep) && dir !== root)) {
2558
+ return json(400, { ok: false, error: 'the recording folder must sit inside the deck\'s own directory' });
2559
+ }
2560
+ const name = `slide-${String(slide).padStart(2, '0')}`
2561
+ + (seg === null ? '' : `-${String(seg).padStart(2, '0')}`)
2562
+ + `.${kind === 'wav' ? 'wav' : 'visemes.json'}`;
2563
+ const chunks = [];
2564
+ let size = 0;
2565
+ for await (const chunk of req) {
2566
+ size += chunk.length;
2567
+ if (size > 64e6) return json(413, { ok: false, error: 'recording too large' });
2568
+ chunks.push(chunk);
2569
+ }
2570
+ // The take's manifest (#535), so a folder the deck recorded is a track
2571
+ // `decklight video` renders from, the export offers and the picker
2572
+ // refreshes into — the shape tools/voiceover.mjs writes, hashed the same
2573
+ // way. The runtime says WHICH slides it recorded and their beat numbers;
2574
+ // the notes each hash covers are read from the deck file here, the way
2575
+ // voiceover and video read them, so the three can never disagree on the
2576
+ // text. Written after every slide, so an aborted take is a valid partial.
2577
+ if (kind === 'manifest') {
2578
+ if (size > 1e6) return json(413, { ok: false, error: 'manifest too large' });
2579
+ let req2;
2580
+ try { req2 = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return json(400, { ok: false, error: 'the manifest is not JSON' }); }
2581
+ const str = (v, max = 120) => (typeof v === 'string' && v.length <= max && /^[\w .:+()'-]*$/.test(v) ? v : null);
2582
+ const header = { engine: str(req2.engine, 40), model: str(req2.model), voice: str(req2.voice), style: typeof req2.style === 'string' && req2.style.length <= 400 ? req2.style : null };
2583
+ if (!header.engine) return json(400, { ok: false, error: 'the manifest names no engine' });
2584
+ const from = Number(req2.range?.[0]), to = Number(req2.range?.[1]);
2585
+ if (!Number.isInteger(from) || !Number.isInteger(to) || from < 1 || to < from || to > 9999) return json(400, { ok: false, error: 'bad range' });
2586
+ const recorded = {};
2587
+ for (const [k, v] of Object.entries(req2.slides ?? {})) {
2588
+ const n = Number(k);
2589
+ if (!Number.isInteger(n) || n < from || n > to) continue;
2590
+ recorded[n] = { segments: Array.isArray(v?.segments) ? v.segments.map(Number) : [] };
2591
+ }
2592
+ const { recorderManifest, slideTexts } = await import('../tools/narration-manifest.mjs');
2593
+ let prev = null;
2594
+ try { prev = JSON.parse(readFileSync(resolve(dir, 'manifest.json'), 'utf8')); } catch { /* first take here */ }
2595
+ const manifest = recorderManifest({ prev: Array.isArray(prev?.slides) ? prev : null, header, texts: slideTexts(readDeck()), range: { from, to }, recorded });
2596
+ try {
2597
+ mkdirSync(dir, { recursive: true });
2598
+ writeFileSync(resolve(dir, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');
2599
+ // the script beside each file, as voiceover writes it — `--reuse-text` reads it back
2600
+ const texts = slideTexts(readDeck());
2601
+ for (const n of Object.keys(recorded)) writeFileSync(resolve(dir, `slide-${String(n).padStart(2, '0')}.txt`), texts[n - 1] ?? '');
2602
+ } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
2603
+ return json(200, { ok: true, dir: want, file: 'manifest.json', slides: manifest.slides.filter(Boolean).length });
2604
+ }
2605
+ try {
2606
+ mkdirSync(dir, { recursive: true });
2607
+ writeFileSync(resolve(dir, name), Buffer.concat(chunks));
2608
+ } catch (e) { return json(500, { ok: false, error: oneline(e) }); }
2609
+ console.log(` recorded ${want}/${name} (${Math.round(size / 1024)} kB)`);
2610
+ return json(200, { ok: true, dir: want, file: name });
2611
+ }
2612
+
2613
+ // What tracks already sit next to this deck. The runtime cannot see the
2614
+ // filesystem — which is why `segments: true` is opt-in at all — so it
2615
+ // cannot know that `voices/rachel` is taken before proposing it. One
2616
+ // question, asked when a recorder opens.
2617
+ function tracksRoute({ json }) {
2618
+ const root2 = resolve(deckPath, '..');
2619
+ const seen = [];
2620
+ const deck = readDeck();
2621
+ const texts = slideTexts(deck);
2622
+ const prior = priorSlideTexts(deck);
2623
+ const look = (rel) => {
2624
+ let entries;
2625
+ try { entries = readdirSync(resolve(root2, rel), { withFileTypes: true }); } catch { return; }
2626
+ const wav = entries.filter((e) => e.isFile() && /^slide-\d+(-\d+)?\.(wav|m4a|mp3)$/.test(e.name));
2627
+ if (wav.length) {
2628
+ let engine = null; let voice = null; let manifest = false; let stale = 0;
2629
+ try {
2630
+ const m = JSON.parse(readFileSync(resolve(root2, rel, 'manifest.json'), 'utf8'));
2631
+ engine = m.engine ?? null; voice = m.voice ?? null; manifest = true;
2632
+ // how many of its slides were voiced from other notes than the deck
2633
+ // has now — the export card marks the track with it (#536)
2634
+ if (Array.isArray(m.slides)) stale = staleSlides(m, texts, null, prior).stale.length;
2635
+ } catch { /* a folder recorded by hand has no manifest, and needs none */ }
2636
+ seen.push({
2637
+ dir: rel.split(sep).join('/'),
2638
+ files: wav.length,
2639
+ // the beats are what let a track pace the builds, so whether it
2640
+ // has them is the one fact worth reporting beside the count
2641
+ segments: wav.some((e) => /^slide-\d+-\d+\./.test(e.name)),
2642
+ ext: (wav[0].name.split('.').pop()),
2643
+ engine,
2644
+ voice,
2645
+ // only a folder with a manifest is one `decklight video` can render
2646
+ // from — your own voice leaves none, and the export must not offer it
2647
+ manifest,
2648
+ stale,
2649
+ });
2650
+ }
2651
+ return entries;
2652
+ };
2653
+ for (const e of look('.') ?? []) {
2654
+ if (!e.isDirectory() || e.name.startsWith('.') || e.name === 'node_modules') continue;
2655
+ const kids = look(e.name) ?? [];
2656
+ // one more level, because the convention is voices/<voice>
2657
+ for (const k of kids) {
2658
+ if (k.isDirectory() && !k.name.startsWith('.')) look(`${e.name}${sep}${k.name}`);
2659
+ }
2660
+ }
2661
+ return json(200, { ok: true, tracks: seen });
2662
+ }
2663
+
2664
+ // ── AI agents — the one-shot editing task behind A ───────────────────────
2665
+
2666
+ // Remember which agent A should reach for (#125, SPEC AGENT_UNITS). A
2667
+ // preference is a choice about this machine, not about the deck, so it
2668
+ // is written beside the unit library and never into the file.
2669
+ function agentPreferRoute({ body, json }) {
2670
+ const { agent } = JSON.parse(body);
2671
+ if (agent !== null && typeof agent !== 'string') throw new Error('bad payload');
2672
+ if (agent && !agents.some((a) => a.name === agent)) {
2673
+ return json(400, { ok: false, error: agentUnavailable(agent, agents) });
2674
+ }
2675
+ setPreferredAgent(agent);
2676
+ agentPref = agent ?? undefined;
2677
+ console.log(` agent: ${agent ? `${agent} remembered as preferred` : 'preference cleared'}`);
2678
+ return json(200, { ok: true, preferredAgent: agent ?? null });
2679
+ }
2680
+
2681
+ // The voiceover script, given ElevenLabs v4's audio tags (cli/enhance.mjs):
2682
+ // the agent drafts, read-only, a few slides at a time; decklight checks each
2683
+ // answer kept the words and beats, and writes them in ONE edit so Z takes
2684
+ // the whole run back. Progress rides the SSE channel as 'enhance' events.
2685
+ async function enhanceRoute({ body, json }) {
2686
+ const { slides, agent, kind: asked } = JSON.parse(body);
2687
+ const kind = asked === 'spoken' ? 'spoken' : 'tags';
2688
+ const which = slides === 'all' ? null
2689
+ : Array.isArray(slides) && slides.length && slides.every((n) => Number.isInteger(n) && n > 0) ? slides : undefined;
2690
+ if (which === undefined) throw new Error('bad payload');
2691
+ if (enhancing) return json(409, { ok: false, error: `already enhancing — ${enhancing.done} of ${enhancing.of} slides done` });
2692
+ if (reviewing) return json(409, { ok: false, error: 'the agent is reviewing the deck — wait for it to finish' });
2693
+ if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is editing the deck — wait for it to finish` });
2694
+ const name = agent ?? agentPref ?? null;
2695
+ const cmd = agentAsk(name, 'x');
2696
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(name, agents) });
2697
+ const { enhanceDeck, applyEnhanced, enhanceable, KINDS } = await import('./enhance.mjs');
2698
+ const verb = KINDS[kind].done;
2699
+ const html = readDeck();
2700
+ const of = enhanceable(html, which).length;
2701
+ if (!of) return json(422, { ok: false, error: which?.length === 1 ? `slide ${which[0]} has no notes to enhance` : 'no notes to enhance' });
2702
+ enhancing = { of, done: 0 };
2703
+ broadcast('enhance', { state: 'start', of, agent: cmd.name, kind });
2704
+ console.log(` enhance: ${of} slide${of === 1 ? '' : 's'}${kind === 'spoken' ? ', written for the ear' : ''} ← ${cmd.name} (read-only)`);
2705
+ enhanceDeck(html, which, {
2706
+ kind, agent: name, cwd: dirname(deckPath),
2707
+ onSlide: (r) => {
2708
+ enhancing.done = r.done;
2709
+ broadcast('enhance', { state: 'slide', ...r });
2710
+ console.log(` enhance: slide ${r.slide} ${r.ok ? (r.changed ? verb : 'unchanged') : `left as it was — ${r.why}`}`);
2711
+ },
2712
+ }).then(({ answers, results }) => {
2713
+ let stale = [];
2714
+ // against the deck as it is NOW: a slide edited while the agent thought keeps the edit
2715
+ applyEdit((cur) => { const a = applyEnhanced(cur, answers); stale = a.stale; return a.html; });
2716
+ const changed = results.filter((r) => r.changed && !stale.includes(r.slide)).map((r) => r.slide);
2717
+ const failed = results.filter((r) => !r.ok).map(({ slide, why }) => ({ slide, why }));
2718
+ enhancing = null;
2719
+ broadcast('enhance', { state: 'done', ok: true, changed, failed, stale, kind });
2720
+ console.log(` enhance: done — ${changed.length} ${verb}${failed.length ? `, ${failed.length} left as they were` : ''}`);
2721
+ }).catch((e) => {
2722
+ enhancing = null;
2723
+ broadcast('enhance', { state: 'done', ok: false, error: oneline(e), kind });
2724
+ });
2725
+ return json(200, { ok: true, of, agent: cmd.name, label: cmd.label, kind });
2726
+ }
2727
+
2728
+ // The notes editor's one box, enhanced without touching the file: the text
2729
+ // goes to the agent (read-only) and comes back checked, for the author to
2730
+ // read and save — or not. Nothing here writes; ⌘⏎ in the editor does.
2731
+ async function enhanceTextRoute({ body, json }) {
2732
+ const { text, agent, kind: asked } = JSON.parse(body);
2733
+ const kind = asked === 'spoken' ? 'spoken' : 'tags';
2734
+ if (typeof text !== 'string') throw new Error('bad payload');
2735
+ if (!text.trim()) return json(422, { ok: false, error: `nothing to ${kind === 'spoken' ? 'rewrite' : 'enhance'} — the notes are empty` });
2736
+ const name = agent ?? agentPref ?? null;
2737
+ const cmd = agentAsk(name, 'x');
2738
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(name, agents) });
2739
+ const { enhanceText } = await import('./enhance.mjs');
2740
+ console.log(` enhance: the notes editor's text${kind === 'spoken' ? ', written for the ear' : ''} ← ${cmd.name} (read-only)`);
2741
+ const r = await enhanceText(text, { kind, agent: name, cwd: dirname(deckPath) });
2742
+ return r.ok
2743
+ ? json(200, { ok: true, text: r.text, changed: r.changed, agent: cmd.name, label: cmd.label })
2744
+ : json(422, { ok: false, error: r.why, agent: cmd.name });
2745
+ }
2746
+
2747
+ // The agent review (cli/agent-review.mjs): the agent reads the deck,
2748
+ // read-only, a few slides at a time, against the rules in REVIEW_RULES;
2749
+ // every answer is checked before it is kept. Nothing here writes: a finding
2750
+ // is fixed by the author's own `f` in Check deck…, which is an ordinary A
2751
+ // edit through agentRoute. Progress rides the SSE channel as 'review' events.
2752
+ async function reviewRoute({ body, json }) {
2753
+ const { agent } = JSON.parse(body || '{}');
2754
+ if (reviewing) return json(409, { ok: false, error: `already reviewing — ${reviewing.done} of ${reviewing.of} batches done` });
2755
+ if (enhancing) return json(409, { ok: false, error: 'the voiceover is being enhanced — wait for it to finish' });
2756
+ if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is editing the deck — wait for it to finish` });
2757
+ const name = agent ?? agentPref ?? null;
2758
+ const cmd = agentAsk(name, 'x');
2759
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(name, agents) });
2760
+ const { reviewDeck, reviewSlides, REVIEW_BATCH } = await import('./agent-review.mjs');
2761
+ const html = readDeck();
2762
+ const of = Math.ceil(reviewSlides(html).length / REVIEW_BATCH);
2763
+ if (!of) return json(422, { ok: false, error: 'no slides to review' });
2764
+ reviewing = { of, done: 0 };
2765
+ broadcast('review', { state: 'start', of, agent: cmd.name });
2766
+ console.log(` review: ${of} batch${of === 1 ? '' : 'es'} ← ${cmd.name} (read-only)`);
2767
+ reviewDeck(html, {
2768
+ agent: name, cwd: dirname(deckPath),
2769
+ onBatch: (r) => { reviewing.done = r.done; broadcast('review', { state: 'batch', ...r }); },
2770
+ }).then(({ findings, failed }) => {
2771
+ lastReview = { at: Date.now(), agent: cmd.name, findings, failed };
2772
+ reviewing = null;
2773
+ broadcast('review', { state: 'done', ok: true, found: findings.length, failed });
2774
+ console.log(` review: done — ${findings.length} finding${findings.length === 1 ? '' : 's'}${failed.length ? `, ${failed.length} batch${failed.length === 1 ? '' : 'es'} unanswered` : ''}`);
2775
+ }).catch((e) => {
2776
+ reviewing = null;
2777
+ broadcast('review', { state: 'done', ok: false, error: oneline(e) });
2778
+ });
2779
+ return json(200, { ok: true, of, agent: cmd.name, label: cmd.label });
2780
+ }
2781
+
2782
+ // The last review's findings, against the deck as it is NOW: a slide that
2783
+ // moved keeps its findings, one that was edited (fixed) drops them. Each
2784
+ // carries the instruction `f` hands the A agent, built here because the
2785
+ // rules and their wording live on this side.
2786
+ async function reviewFindingsRoute({ json }) {
2787
+ if (!lastReview) return json(200, { ok: true, reviewed: false, running: !!reviewing, findings: [] });
2788
+ const { currentFindings, fixPrompt, REVIEW_RULES } = await import('./agent-review.mjs');
2789
+ const label = Object.fromEntries(REVIEW_RULES.map((r) => [r.id, r.label]));
2790
+ const findings = currentFindings(readDeck(), lastReview.findings)
2791
+ .map(({ fp, ...f }) => ({ ...f, label: label[f.rule], prompt: fixPrompt(f) }));
2792
+ return json(200, { ok: true, reviewed: true, running: !!reviewing, at: lastReview.at, agent: lastReview.agent, findings, failed: lastReview.failed });
2793
+ }
2794
+
2795
+ function agentRoute({ body, json }) {
2796
+ const { prompt, agent, message, slide } = JSON.parse(body);
2797
+ if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('bad payload');
2798
+ if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is already running` });
2799
+ if (reviewing) return json(409, { ok: false, error: 'the agent is reviewing the deck — wait for it to finish' });
2800
+ const cmd = runAgent(prompt.trim(), agent, message, slide);
2801
+ if (!cmd) return json(400, { ok: false, error: agentUnavailable(agent ?? agentPref, agents) });
2802
+ return json(200, { ok: true, agent: cmd.name, label: cmd.label });
2803
+ }
2804
+
2805
+ // ── the route table ──────────────────────────────────────────────────────
2806
+ // Every `/deck/edit/*` surface, keyed `METHOD /path`. This was forty-four
2807
+ // `if (req.method === … && url.pathname === …)` arms in one eleven-hundred
2808
+ // line function: adding a route meant finding a place in the chain, reading
2809
+ // a route meant scrolling to it, and the ORDER of two unrelated routes was
2810
+ // load-bearing by accident rather than by decision. A table has no order to
2811
+ // get wrong — adding a surface is adding a line — and the two places where
2812
+ // sequence DOES still matter say so out loud rather than by position
2813
+ // (`BEFORE_BODY`, and the prefix list below).
2814
+ const routes = new Map(Object.entries({
2815
+ 'POST /deck/edit/lock': lockRoute,
2816
+ // the voice bridge, on this origin (#520): `/deck/tts` speaks, and everything
2817
+ // else of the bridge's lives under `/deck/tts/` (the prefix list below)
2818
+ 'POST /deck/tts': ttsProxy,
2819
+ 'POST /deck/edit/shutdown': shutdownRoute,
2820
+ 'POST /deck/edit/undo': undoRedoRoute,
2821
+ 'POST /deck/edit/redo': undoRedoRoute,
2822
+
2823
+ // the owner's half of a review (REVIEW): registered here alone, beside
2824
+ // the routes both servers share
2825
+ 'GET /deck/review/incoming': reviewIncomingRoute,
2826
+ 'GET /deck/review/at': reviewAtRoute,
2827
+
2828
+ 'GET /deck/edit/wizard': wizardSchemaRoute,
2829
+ 'POST /deck/edit/wizard': wizardConfigureRoute,
2830
+ 'POST /deck/edit/wizard/forget': wizardForgetRoute,
2831
+
2832
+
2833
+ 'POST /deck/edit/narration/record': recordRoute,
2834
+ 'GET /deck/edit/narration/tracks': tracksRoute,
2835
+
2836
+ 'POST /deck/edit/agent': agentRoute,
2837
+ 'POST /deck/edit/agent/prefer': agentPreferRoute,
2838
+ 'POST /deck/edit/enhance': enhanceRoute,
2839
+ 'POST /deck/edit/enhance/text': enhanceTextRoute,
2840
+ 'POST /deck/edit/review': reviewRoute,
2841
+ 'GET /deck/edit/review': reviewFindingsRoute,
2842
+ }));
2843
+
2844
+ // The slide mutations are a file of their own (cli/edit-slides.mjs): thirteen
2845
+ // routes of one shape — read the deck, run a pure transform over it, put the
2846
+ // result through applyEdit — that between them want four of editMain's
2847
+ // bindings and none of the rest. Handed those four explicitly, they can be
2848
+ // called from a test with a temp deck and no socket at all. `deckPath` is the
2849
+ // odd one: /deck/edit/asset saves a dropped image beside the deck, so it needs to
2850
+ // know where the deck is and not only what it says.
2851
+ registerSlideRoutes(routes, {
2852
+ readDeck, applyEdit, history, deckPath,
2853
+ // a notes save updates every page in place: no reload for that write
2854
+ quiet: (html) => { quietWrite = html; },
2855
+ broadcast: (event, data) => clients.broadcast(event, data),
2856
+ });
2857
+
2858
+ // The deck's look is a file of its own too (cli/edit-look.mjs): the theme
2859
+ // pick and the brand-themes switch, and browsing and marking what the
2860
+ // marketplaces offer a deck to wear — themes, design systems, fonts. They
2861
+ // want the deck's text and the two ways of writing it, the undo stack, the
2862
+ // event channel, and the quiet-write latch, and nothing else of editMain's.
2863
+ registerLookRoutes(routes, {
2864
+ readDeck, applyEdit, writeDeck, history, broadcast,
2865
+ // a quiet pick or mark updates the page that asked: no reload for it
2866
+ quiet: (html) => { quietWrite = html; },
2867
+ });
2868
+
2869
+ // Handing the deck over is a third (cli/edit-handover.mjs): export, the
2870
+ // bundle estimate, the inspector's read, and publish. None of them edits
2871
+ // the deck; they read it, write files beside it or push it, and own their
2872
+ // own in-flight flags.
2873
+ registerHandoverRoutes(routes, {
2874
+ readDeck, deckPath, root, broadcast,
2875
+ gitOn: () => gitOn,
2876
+ });
2877
+
2878
+ // And git (cli/edit-git.mjs): the commit window and the deck's history. The
2879
+ // commit bookkeeping stays here, because the timer, the agent's commits and
2880
+ // the exit commit share it; the routes reach it through what is handed in,
2881
+ // and the `let`s among it only through getters and setters.
2882
+ registerGitRoutes(routes, {
2883
+ readDeck, history, broadcast, deckPath, deckRel, root,
2884
+ gitOn: () => gitOn,
2885
+ agentPref: () => agentPref,
2886
+ subjectsOff, describer,
2887
+ commitState, measureDirty, resetEpisode, alsoNow, alsoRels, attrRel,
2888
+ pendingAttr: () => pendingAttr,
2889
+ clearPendingAttr: () => { pendingAttr = null; },
2890
+ dismissNag: () => { nagDismissed = true; },
2891
+ });
2892
+
2893
+ // The routes that run BEFORE the shared body read, and the only reason the
2894
+ // dispatcher below has a sequence at all. `/deck/edit/narration/record`'s body is BINARY and
2895
+ // megabytes of it — a slide of speech is ~48 kB a second — so the string
2896
+ // concat and its 1 MB ceiling would both be wrong, and it reads the stream
2897
+ // itself under its own 64 MB limit. `/deck/edit/asset` is the same case with a
2898
+ // different payload — an image dropped on the stage, read under its own
2899
+ // 25 MB limit. The other three carry no body, and never had one read for them.
2900
+ const BEFORE_BODY = new Set([
2901
+ 'POST /deck/tts',
2902
+ 'POST /deck/edit/narration/record', 'POST /deck/edit/asset',
2903
+ 'POST /deck/edit/shutdown', 'POST /deck/edit/undo', 'POST /deck/edit/redo',
2904
+ ]);
2905
+
2906
+ // Prefix routes, tried IN ORDER once the exact table has missed and before
2907
+ // the static fallback — the one dispatch rule a Map cannot express. Every
2908
+ // `/deck/edit/*` path is exact today, so the list is empty; it is declared so the
2909
+ // first route that needs a prefix has somewhere to go other than the bottom
2910
+ // of the dispatcher, where the chain used to grow.
2911
+ const PREFIX_ROUTES = [ // { method, prefix, handler }
2912
+ // the voice bridge's own routes, on this origin: /tts/ping, /tts/engines,
2913
+ // /tts/voices… — forwarded as they are, since the bridge serves the same
2914
+ // paths itself. Nothing of the bridge's sits at the root, where it would
2915
+ // shadow a file beside the deck (`voices/` is the narration's folder).
2916
+ { method: 'GET', prefix: '/deck/tts/', handler: ttsProxy, beforeBody: true },
2917
+ { method: 'POST', prefix: '/deck/tts/', handler: ttsProxy, beforeBody: true },
2918
+ // the lip-sync bridge, on this origin (#520): `/deck/lipsync/ping`, `/viseme`, `/video`
2919
+ // the audio a POST carries is binary and can pass the body cap, so it
2920
+ // streams through unread, like /deck/edit/narration/record's
2921
+ { method: 'GET', prefix: '/deck/lipsync/', handler: lipsyncProxy, beforeBody: true },
2922
+ { method: 'POST', prefix: '/deck/lipsync/', handler: lipsyncProxy, beforeBody: true },
2923
+ ];
2924
+
2925
+ // the deck's channel and the shared review routes, beside this server's own
2926
+ for (const [key, handler] of deck.routes) routes.set(key, handler);
2927
+ for (const key of ['GET /deck/review/comments', 'POST /deck/review/comments', 'POST /deck/review/submit']) {
2928
+ routes.set(key, ({ req, res, url, body }) => review.handle(req, res, url, body ?? ''));
2929
+ }
2930
+ // The upstream routes are REGISTERED ONLY when the deck is a tracked file in
2931
+ // a clone whose branch tracks something (NO_TRUST#UPSTREAM): on a deck you
2932
+ // were emailed they are not refused, they do not exist. The strict origin
2933
+ // gate, not allowEditRequest: `null` is a sandboxed plugin frame's origin,
2934
+ // and presenter chrome must not be able to fast-forward the presenter's
2935
+ // repository.
2936
+ if (upstream) {
2937
+ routes.set('GET /deck/upstream', ({ json }) => json(200, { ok: true, ...upstreamStatus, pull: pullOffer() }));
2938
+ routes.set('POST /deck/upstream/check', ({ req, res, json }) => {
2939
+ if (!isOwnOrigin(req, actualPort)) { res.writeHead(403); res.end('forbidden'); return; }
2940
+ return refreshUpstream().then(() => json(200, { ok: true, ...upstreamStatus, pull: pullOffer() }));
2941
+ });
2942
+ }
2943
+ if (pullArmed) {
2944
+ routes.set('POST /deck/upstream/pull', ({ req, res, json }) => {
2945
+ if (!isOwnOrigin(req, actualPort)) { res.writeHead(403); res.end('forbidden'); return; }
2946
+ // The body is never read. No field of the request reaches git or the
2947
+ // filesystem; the repository, the branch and `@{upstream}` are all
2948
+ // constants resolved before the server existed.
2949
+ return doPull().then((out) => json(out.ok ? 200 : (out.http ?? 409), out));
2950
+ });
2951
+ }
2952
+
2953
+ // What no-trust mode refuses, by name: everything that writes the deck or
2954
+ // reaches a bridge, and the review owner's half. A deck opened without trust used to be
2955
+ // served by a process in which none of this was registered; now it is one
2956
+ // server, and the refusal is the mode's — a 403 that says which mode would
2957
+ // answer, rather than a 405 that pretends the route is unknown.
2958
+ const WRITE_FAMILY = (pathname) => pathname.startsWith('/deck/edit/')
2959
+ || pathname === '/deck/tts' || pathname.startsWith('/deck/tts/') || pathname.startsWith('/deck/lipsync/')
2960
+ || pathname === '/deck/review/incoming' || pathname === '/deck/review/at';
2961
+
2962
+ // Two static servers for one root, chosen per request by the mode. Write
2963
+ // mode serves the cwd with the deck at "/" and an author's exotic asset as
2964
+ // octet-stream. No-trust mode refuses every extension the MIME table does
2965
+ // not name (a file beside a travelled deck that is none of them — `id_rsa`,
2966
+ // a `.pem`, a database — is only ever fetched to be exfiltrated), rewrites
2967
+ // every html page on its way out (strict, then the chrome), and has no
2968
+ // index: "/" is the deck, answered from memory before this is consulted.
2969
+ // write mode: the deck gets the presenter's chrome too, every other page none
2970
+ const files = staticFiles(root, { index: deckUrl, html: (text, file) => (file === deckPath ? injectChrome(text, chrome.plugins) : text) });
2971
+ const auditedFiles = staticFiles(root, { html: rewrite, knownTypesOnly: true });
1127
2972
  const server = createServer(async (req, res) => {
2973
+ // No-trust mode: the policy on EVERY response this server writes — the
2974
+ // deck and its assets, but also the 403/404/405 pages, the control-
2975
+ // channel JSON and SSE, and the remote controller. Set before anything
2976
+ // runs, and writeHead merges it under whatever a route names itself, so
2977
+ // "every response carries the header" holds by construction.
2978
+ if (noTrust) res.setHeader('content-security-policy', CSP);
2979
+ // Loopback always; off-loopback only /deck/remote/* carrying the per-run
2980
+ // token, and only when --remote asked for a listener at all. Every other
2981
+ // path is refused off this machine unconditionally — flag or no flag,
2982
+ // token or no token — which is why the static files and the deck itself
2983
+ // cannot be reached from the LAN even while the remote can.
2984
+ if (!allowRemote(req, token)) {
2985
+ res.writeHead(403);
2986
+ res.end('forbidden: this deck is served to this machine only; off it, only /deck/remote/* answers, with the session token');
2987
+ return;
2988
+ }
2989
+ let url;
2990
+ try { url = new URL(req.url, 'http://x'); } catch { res.writeHead(400); res.end('bad request'); return; }
2991
+ // The phone remote, before the CSRF gate below: the phone's origin is a
2992
+ // LAN address, which that gate rightly refuses for everything else. A
2993
+ // body past 4 KB is a probe, not a request — the socket is destroyed and
2994
+ // the E2BIG never becomes a response.
2995
+ if (url.pathname === '/deck/remote' || url.pathname.startsWith('/deck/remote/')) {
2996
+ let body = '';
2997
+ if (req.method === 'POST') {
2998
+ try { body = (await readBody(req, { max: 4096 })).toString(); } catch { return; }
2999
+ }
3000
+ try {
3001
+ if (relay.handle(req, res, url, body)) return;
3002
+ } catch {
3003
+ res.writeHead(400, { ...PHONE_CORS, 'content-type': 'application/json' });
3004
+ res.end(JSON.stringify({ ok: false, error: 'bad payload' }));
3005
+ return;
3006
+ }
3007
+ res.writeHead(405); res.end('method not allowed');
3008
+ return;
3009
+ }
1128
3010
  // The CSRF gate (#222), before anything runs. A same-machine browser tab is
1129
3011
  // the threat, not an off-machine caller, so the check is the request's
1130
3012
  // `Origin`, not its socket address. A foreign origin is refused here —
@@ -1136,715 +3018,51 @@ export async function editMain(args, { onListen = null } = {}) {
1136
3018
  const CORS = corsHeadersFor(origin);
1137
3019
  if (!allowEditRequest(req)) {
1138
3020
  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');
3021
+ res.end('forbidden: the deck server answers this machine only, and not a foreign web origin');
1140
3022
  return;
1141
3023
  }
1142
3024
  try {
1143
- const url = new URL(req.url, 'http://x');
1144
- const json = (code, obj) => {
1145
- res.writeHead(code, { ...CORS, 'content-type': 'application/json' });
3025
+ const json = (code, obj, headers = {}) => {
3026
+ res.writeHead(code, { ...CORS, ...headers, 'content-type': 'application/json' });
1146
3027
  res.end(JSON.stringify(obj));
1147
3028
  };
1148
3029
  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
- });
1166
- }
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 });
1174
- }
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)}`,
1185
- });
1186
- return json(200, { ok: true, subject: subject ?? null });
1187
- }
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() });
1193
- }
1194
- if (req.method === 'GET' && url.pathname === '/edit/events') {
1195
- clients.add(req, res, CORS);
1196
- return;
1197
- }
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
- }
1261
-
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); });
1268
- return;
3030
+ // no-trust mode: nothing that writes answers, whatever it was aimed at
3031
+ if (noTrust && WRITE_FAMILY(url.pathname)) {
3032
+ return json(403, { ok: false, noTrust: true, error: 'this deck is open without trust — nothing here changes it' });
1269
3033
  }
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() });
3034
+ // locked: no edit route writes, whatever it was aimed at — the one
3035
+ // POST that still answers is the lock itself, so it can be lifted
3036
+ if (locked && req.method === 'POST' && url.pathname.startsWith('/deck/edit/') && url.pathname !== '/deck/edit/lock') {
3037
+ return json(423, { ok: false, locked: true, error: 'the deck is locked — unlock it from the palette or the lock chip' });
1278
3038
  }
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 });
3039
+ const key = `${req.method} ${url.pathname}`;
3040
+ const prefixed = routes.has(key) ? null
3041
+ : PREFIX_ROUTES.find((r) => r.method === req.method && url.pathname.startsWith(r.prefix));
3042
+ const handler = routes.get(key) ?? prefixed?.handler;
3043
+ if (handler && (BEFORE_BODY.has(key) || prefixed?.beforeBody)) {
3044
+ return await writing.run({ route: url.pathname, body: '' }, () => handler({ req, res, url, json, CORS }));
1336
3045
  }
3046
+ // Read for every POST, matched or not — an oversized body is refused
3047
+ // whatever it was aimed at, exactly as the chain refused it.
1337
3048
  let body = '';
1338
3049
  if (req.method === 'POST') {
1339
3050
  for await (const chunk of req) { body += chunk; if (body.length > 1e6) throw new Error('too large'); }
1340
3051
  }
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 };
3052
+ if (handler) return await writing.run({ route: url.pathname, body }, () => handler({ req, res, url, body, json, CORS }));
3053
+ // ── the deck and the files beside it ──────────────────────────────
3054
+ // No-trust mode answers the deck's own path from the audited bytes
3055
+ // (servePayload above). For a container that also means the URL a
3056
+ // person sees is the file they double-clicked — serving the raw archive
3057
+ // bytes there would hand a browser something it cannot render.
3058
+ if (noTrust) {
3059
+ if (isDeck(url)) {
3060
+ if (servePayload(req, res)) return;
3061
+ res.writeHead(405); res.end('method not allowed'); return;
1387
3062
  }
1388
- return json(200, { ok: true, ...incomingCache.r });
3063
+ if (auditedFiles(req, res, url)) return;
3064
+ res.writeHead(405); res.end('method not allowed'); return;
1389
3065
  }
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 });
1486
- }
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 });
1572
- }
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 }),
1600
- });
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
- }
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() });
1625
- }
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 });
1636
- }
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,
1735
- });
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}`);
1755
- }
1756
- return json(200, { ok: true, state: r.state, engine, stored: r.stored, protection: r.protection.label });
1757
- }
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() });
1781
- }
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() });
1788
- }
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() });
1795
- }
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() });
1805
- }
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() });
1814
- }
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() });
1824
- }
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) });
1833
- }
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 });
1846
- }
1847
- // ── static files from the cwd (staticFiles, serve.mjs) ───────────
1848
3066
  if (files(req, res, url)) return;
1849
3067
  res.writeHead(405);
1850
3068
  res.end();
@@ -1856,19 +3074,80 @@ export async function editMain(args, { onListen = null } = {}) {
1856
3074
  });
1857
3075
 
1858
3076
  const actual = await listenTakingOverIfNeeded(server, port, host);
1859
- // `decklight record` runs this same server in-process and needs to know
3077
+ actualPort = actual;
3078
+ // `decklight narrate --mic` runs this same server in-process and needs to know
1860
3079
  // WHICH port it ended up on (a taken --port moves to the next free one) and
1861
3080
  // to print its own banner instead of the authoring one.
1862
3081
  if (onListen) onListen({ port: actual, deckUrl, server });
1863
- else if (process.env.DECKLIGHT_BANNER) {
3082
+ else if (noTrust) {
3083
+ // Before the first slide renders, not after — the point of the label is
3084
+ // to be able to decide not to open it. The audience is looking at the
3085
+ // deck; none of this goes on the page.
3086
+ console.log(`decklight · ${basename(deckPath)} on http://127.0.0.1:${actual}${deckUrl} — no trust: its code stripped, CSP enforced. Ctrl-C stops`);
3087
+ console.log(` serving ${root} — ${rootArg ? '--root as given' : "the deck's own directory"};`
3088
+ + ' dotfiles and non-deck file types refused; every edit route refuses, nothing is written');
3089
+ printLabel();
3090
+ if (upstream) {
3091
+ console.log(` upstream: tracking ${upstream.upstream} — ${intervalMs ? `checking every ${intervalMs / 60000} min` : 'checked when asked'}`
3092
+ + (pullArmed ? ', update control ON (--upstream-pull)' : ''));
3093
+ if (!pullArmed && args.includes('--upstream-pull') && token) {
3094
+ console.log(' upstream: --remote is on — the update control is off; pull from your own terminal');
3095
+ }
3096
+ } else if (suppressed && suppressed !== 'write mode') {
3097
+ console.log(` upstream: not checked — ${suppressed}`);
3098
+ }
3099
+ // Reported UNDER the label and never inside it: a plugin is not in the
3100
+ // file. Naming which plugins read the speaker notes is the other half of
3101
+ // `needs: ["notes"]` being a declaration rather than a silent grant.
3102
+ for (const pl of chrome.plugins) {
3103
+ console.log(` chrome: ${pl.name} (${pl.slot}) — yours, not in the deck`
3104
+ + `${pl.needs.includes('notes') ? '; reads your speaker notes' : ''}`);
3105
+ }
3106
+ for (const r of chrome.refused) {
3107
+ console.log(` chrome: ${r.name} REFUSED — not loaded, the deck plays without it`);
3108
+ console.log(` ${r.reason.replace(/\n/g, '\n ')}`);
3109
+ }
3110
+ if (audited.strict) {
3111
+ const n = audited.report.counts.unaccounted, h = audited.report.counts.handlers;
3112
+ if (signature.state !== UNSIGNED && !isVerified(signature)) console.log(' the signature did not verify — serving strict');
3113
+ const removed = [
3114
+ n ? `${n} unaccounted script block${n === 1 ? '' : 's'}` : '',
3115
+ h ? `${h} executable attribute${h === 1 ? '' : 's'}` : '',
3116
+ ].filter(Boolean).join(' and ');
3117
+ console.log(removed
3118
+ ? ` ${removed} stripped — serving strict. The file on disk is untouched`
3119
+ : ` nothing to strip — this deck is served exactly as ${container ? 'the container carries it' : 'it was read from disk'}`);
3120
+ }
3121
+ } else if (process.env.DECKLIGHT_BANNER) {
1864
3122
  // The port is reported rather than assumed: `listenTakingOverIfNeeded` can
1865
- // land somewhere other than the port author resolved, and the URL on the
3123
+ // land somewhere other than the port `open` resolved, and the URL on the
1866
3124
  // banner has to be the one that actually answers.
1867
3125
  console.log(readyLine({
1868
3126
  url: `http://127.0.0.1:${actual}${deckUrl}`,
1869
- keys: 'E edit · L layouts · Z undo · A agent · Ctrl-C stops',
3127
+ keys: 'Ctrl-C stops',
1870
3128
  }));
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`);
3129
+ } 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`);
3130
+ if (token) {
3131
+ console.log(` remote: listening on ${host} — http://${lanAddress() ?? host}:${actual}/deck/remote?t=${token}`);
3132
+ console.log(' off this machine ONLY /deck/remote/* answers, with that token — the deck itself does not');
3133
+ }
3134
+ // The upstream, said once at startup and then only when it CHANGES. `up to
3135
+ // date` every ten minutes for an hour is noise that trains people to stop
3136
+ // reading the terminal — which is where the ingredients label lives. Kicked
3137
+ // AFTER the last startup line and never awaited: nothing about it can delay
3138
+ // the server coming up or hang a talk on a remote that is down.
3139
+ if (upstream) {
3140
+ const tick = () => refreshUpstream().then((st) => {
3141
+ if (st.state !== lastReported) {
3142
+ lastReported = st.state;
3143
+ console.log(` upstream: ${st.message}`);
3144
+ }
3145
+ }).catch(() => {});
3146
+ tick();
3147
+ // unref'd so a Ctrl-C exits now rather than after an in-flight fetch.
3148
+ // `--upstream-every 0` keeps the manual check and drops only the timer.
3149
+ if (intervalMs > 0) setInterval(tick, intervalMs).unref();
3150
+ }
1872
3151
 
1873
3152
  // Did somebody review this deck? Asked ONCE, after the last startup line,
1874
3153
  // detached and never awaited — the update-check shape: nothing about it can
@@ -1877,7 +3156,7 @@ export async function editMain(args, { onListen = null } = {}) {
1877
3156
  // exception cli/git.mjs names, why it is never on a timer, and why it is
1878
3157
  // nowhere near the SIGINT path (finalCommit above says what lives there and
1879
3158
  // why nothing else may).
1880
- if (!onListen) {
3159
+ if (!onListen && !noTrust) {
1881
3160
  const skipped = reviewCheckSuppressed({ args });
1882
3161
  if (skipped) {
1883
3162
  startup('reviews', `not checked — ${skipped}`, ` reviews: not checked — ${skipped}`);
@@ -1895,8 +3174,13 @@ export async function editMain(args, { onListen = null } = {}) {
1895
3174
 
1896
3175
 
1897
3176
  if (isMain(import.meta.url)) {
1898
- // author spawns this module directly, so the leash the dispatcher used to
3177
+ // `open` spawns this module directly, so the leash the dispatcher used to
1899
3178
  // arm is armed here — a no-op unless a supervising parent set it up.
1900
3179
  exitWhenOrphaned();
1901
- editMain(process.argv.slice(2));
3180
+ // Through the one error boundary: a throw used to surface as an unhandled
3181
+ // rejection with a raw stack, in a child whose parent's banner had scrolled by.
3182
+ const code = await runMain('open', () => editMain(process.argv.slice(2)));
3183
+ // editMain sets process.exitCode itself on a refusal and resolves to the
3184
+ // server otherwise, so only a failure runMain reported is written here
3185
+ if (code === 1) process.exitCode = 1;
1902
3186
  }