@litfamily/litcodex 1.0.28 → 1.0.29

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 (158) hide show
  1. package/README-Ko-KR.md +10 -10
  2. package/README.md +10 -10
  3. package/dist/cli.js +1 -1
  4. package/dist/config-migration/cli.js +11 -3
  5. package/dist/install/generated-skill-payload-hashes.d.ts +56 -28
  6. package/dist/install/generated-skill-payload-hashes.js +56 -28
  7. package/dist/install/index.js +1 -1
  8. package/dist/install/motion-runtime.d.ts +4 -1
  9. package/dist/install/motion-runtime.js +15 -4
  10. package/dist/install/office-runtime.d.ts +10 -11
  11. package/dist/install/office-runtime.js +8 -3
  12. package/dist/install/skill-catalog.d.ts +1 -1
  13. package/dist/install/skill-catalog.js +1 -0
  14. package/dist/postinstall.js +4 -2
  15. package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +1 -1
  16. package/marketplace/plugins/litcodex/components/auto-update/dist/auto-update.d.ts +12 -0
  17. package/marketplace/plugins/litcodex/components/auto-update/dist/auto-update.js +31 -2
  18. package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
  19. package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
  20. package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
  21. package/marketplace/plugins/litcodex/components/lit-loop/directive.md +2 -1
  22. package/marketplace/plugins/litcodex/components/lit-loop/directives/deep-interview.md +2 -0
  23. package/marketplace/plugins/litcodex/components/lit-loop/directives/lit-brainstorm.md +216 -0
  24. package/marketplace/plugins/litcodex/components/lit-loop/directives/litgoal.md +8 -1
  25. package/marketplace/plugins/litcodex/components/lit-loop/directives/review-work.md +12 -4
  26. package/marketplace/plugins/litcodex/components/lit-loop/dist/codex-hook.d.ts +6 -1
  27. package/marketplace/plugins/litcodex/components/lit-loop/dist/codex-hook.js +16 -5
  28. package/marketplace/plugins/litcodex/components/lit-loop/dist/guards.d.ts +3 -1
  29. package/marketplace/plugins/litcodex/components/lit-loop/dist/guards.js +5 -2
  30. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.d.ts +2 -0
  31. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +26 -8
  32. package/marketplace/plugins/litcodex/components/lit-loop/dist/markers.d.ts +2 -0
  33. package/marketplace/plugins/litcodex/components/lit-loop/dist/markers.js +2 -0
  34. package/marketplace/plugins/litcodex/components/lit-loop/dist/modes.d.ts +1 -1
  35. package/marketplace/plugins/litcodex/components/lit-loop/dist/modes.js +9 -1
  36. package/marketplace/plugins/litcodex/components/lit-loop/dist/motion-route.js +2 -0
  37. package/marketplace/plugins/litcodex/components/lit-loop/dist/plan-persistence.d.ts +2 -0
  38. package/marketplace/plugins/litcodex/components/lit-loop/dist/plan-persistence.js +8 -0
  39. package/marketplace/plugins/litcodex/components/lit-loop/dist/reentry.d.ts +56 -0
  40. package/marketplace/plugins/litcodex/components/lit-loop/dist/reentry.js +171 -0
  41. package/marketplace/plugins/litcodex/components/lit-loop/dist/route-context.js +5 -2
  42. package/marketplace/plugins/litcodex/components/lit-loop/dist/route-heads.js +35 -15
  43. package/marketplace/plugins/litcodex/components/lit-loop/dist/skill-mention-scope.js +2 -0
  44. package/marketplace/plugins/litcodex/components/lit-loop/dist/trigger.d.ts +2 -2
  45. package/marketplace/plugins/litcodex/components/lit-loop/dist/trigger.js +15 -5
  46. package/marketplace/plugins/litcodex/components/lit-loop/dist/workflow-map.js +1 -0
  47. package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
  48. package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
  49. package/marketplace/plugins/litcodex/components/rules/dist/model-metadata.d.ts +16 -0
  50. package/marketplace/plugins/litcodex/components/rules/dist/model-metadata.js +37 -1
  51. package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
  52. package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
  53. package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
  54. package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
  55. package/marketplace/plugins/litcodex/skills/browser-drive/scripts/capability-probe.mjs +24 -4
  56. package/marketplace/plugins/litcodex/skills/deep-interview/SKILL.md +3 -1
  57. package/marketplace/plugins/litcodex/skills/lit-brainstorm/SKILL.md +271 -0
  58. package/marketplace/plugins/litcodex/skills/lit-brainstorm/agents/openai.yaml +6 -0
  59. package/marketplace/plugins/litcodex/skills/lit-diagram-drawer/scripts/doctor.mjs +4 -3
  60. package/marketplace/plugins/litcodex/skills/lit-diagram-drawer/scripts/export.mjs +6 -5
  61. package/marketplace/plugins/litcodex/skills/lit-diagram-drawer/scripts/runtime-probes.mjs +25 -0
  62. package/marketplace/plugins/litcodex/skills/lit-docx/scripts/convert_md_to_pdf.py +31 -1
  63. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/acs/template.tex +2 -0
  64. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/elsevier/template.tex +2 -0
  65. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/ieee/template.tex +2 -0
  66. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/korean-generic/template.tex +2 -0
  67. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/nature/template.tex +2 -0
  68. package/marketplace/plugins/litcodex/skills/lit-loop/SKILL.md +8 -1
  69. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/office-run.mjs +42 -10
  70. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/SKILL.md +11 -9
  71. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/agents/openai.yaml +3 -0
  72. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/THIRD_PARTY_NOTICES +4 -0
  73. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/constants.mjs +38 -0
  74. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-assets.mjs +113 -0
  75. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-capture.mjs +161 -0
  76. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-gate.mjs +327 -0
  77. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-image.mjs +136 -0
  78. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-init.js +43 -0
  79. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-sheet.mjs +69 -0
  80. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-treatment.mjs +102 -0
  81. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-worker.mjs +21 -0
  82. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover.mjs +352 -0
  83. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/driver.mjs +19 -1
  84. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/fonts.mjs +11 -0
  85. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/look.mjs +128 -2
  86. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/loop-kit.js +104 -0
  87. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/runtime.mjs +92 -18
  88. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/stage.mjs +2 -0
  89. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/treatment.mjs +3 -2
  90. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/webp.mjs +140 -0
  91. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/fonts/jetbrains-mono/JetBrainsMono-wght-latin.woff2 +0 -0
  92. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/fonts/jetbrains-mono/OFL.txt +93 -0
  93. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/card-scenes/expected.json +16 -0
  94. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/card-scenes/index.html +42 -0
  95. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/reset-sweep/expected.json +16 -0
  96. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/reset-sweep/index.html +27 -0
  97. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/still-glow/expected.json +17 -0
  98. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/still-glow/index.html +29 -0
  99. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/title-slam/expected.json +17 -0
  100. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/title-slam/index.html +44 -0
  101. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/orbit-loop/expected.json +67 -0
  102. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/orbit-loop/index.html +182 -0
  103. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/painted-light/expected.json +95 -0
  104. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/painted-light/index.html +231 -0
  105. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/weight-tide/expected.json +67 -0
  106. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/weight-tide/index.html +103 -0
  107. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/cover.md +389 -0
  108. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/quality-gate.md +4 -0
  109. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/runtime.md +7 -6
  110. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/stage.md +3 -1
  111. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/treatment.md +2 -0
  112. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/scripts/render.mjs +37 -5
  113. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/scripts/runtime.mjs +1 -1
  114. package/marketplace/plugins/litcodex/skills/litgoal/SKILL.md +8 -3
  115. package/marketplace/plugins/litcodex/skills/lsp-setup/scripts/verify-lsp.ts +43 -7
  116. package/marketplace/plugins/litcodex/skills/review-work/SKILL.md +21 -4
  117. package/node_modules/@litcodex/lit-loop/CHANGELOG.md +7 -0
  118. package/node_modules/@litcodex/lit-loop/README.md +6 -0
  119. package/node_modules/@litcodex/lit-loop/directive.md +2 -1
  120. package/node_modules/@litcodex/lit-loop/directives/deep-interview.md +2 -0
  121. package/node_modules/@litcodex/lit-loop/directives/lit-brainstorm.md +216 -0
  122. package/node_modules/@litcodex/lit-loop/directives/litgoal.md +8 -1
  123. package/node_modules/@litcodex/lit-loop/directives/review-work.md +12 -4
  124. package/node_modules/@litcodex/lit-loop/dist/codex-hook.d.ts +6 -1
  125. package/node_modules/@litcodex/lit-loop/dist/codex-hook.js +16 -5
  126. package/node_modules/@litcodex/lit-loop/dist/guards.d.ts +3 -1
  127. package/node_modules/@litcodex/lit-loop/dist/guards.js +5 -2
  128. package/node_modules/@litcodex/lit-loop/dist/hook-cli.d.ts +2 -0
  129. package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +26 -8
  130. package/node_modules/@litcodex/lit-loop/dist/markers.d.ts +2 -0
  131. package/node_modules/@litcodex/lit-loop/dist/markers.js +2 -0
  132. package/node_modules/@litcodex/lit-loop/dist/modes.d.ts +1 -1
  133. package/node_modules/@litcodex/lit-loop/dist/modes.js +9 -1
  134. package/node_modules/@litcodex/lit-loop/dist/motion-route.js +2 -0
  135. package/node_modules/@litcodex/lit-loop/dist/plan-persistence.d.ts +2 -0
  136. package/node_modules/@litcodex/lit-loop/dist/plan-persistence.js +8 -0
  137. package/node_modules/@litcodex/lit-loop/dist/reentry.d.ts +56 -0
  138. package/node_modules/@litcodex/lit-loop/dist/reentry.js +171 -0
  139. package/node_modules/@litcodex/lit-loop/dist/route-context.js +5 -2
  140. package/node_modules/@litcodex/lit-loop/dist/route-heads.js +35 -15
  141. package/node_modules/@litcodex/lit-loop/dist/skill-mention-scope.js +2 -0
  142. package/node_modules/@litcodex/lit-loop/dist/trigger.d.ts +2 -2
  143. package/node_modules/@litcodex/lit-loop/dist/trigger.js +15 -5
  144. package/node_modules/@litcodex/lit-loop/dist/workflow-map.js +1 -0
  145. package/node_modules/@litcodex/lit-loop/package.json +1 -1
  146. package/node_modules/@litcodex/lit-loop/skills/browser-drive/scripts/capability-probe.mjs +24 -4
  147. package/node_modules/@litcodex/lit-loop/skills/deep-interview/SKILL.md +3 -1
  148. package/node_modules/@litcodex/lit-loop/skills/lit-brainstorm/SKILL.md +271 -0
  149. package/node_modules/@litcodex/lit-loop/skills/lit-loop/SKILL.md +8 -1
  150. package/node_modules/@litcodex/lit-loop/skills/litgoal/SKILL.md +8 -3
  151. package/node_modules/@litcodex/lit-loop/skills/review-work/SKILL.md +21 -4
  152. package/package.json +2 -2
  153. package/readme-assets/badge-version.svg +1 -1
  154. package/readme-assets/cover-motion-still.webp +0 -0
  155. package/readme-assets/cover-motion.webp +0 -0
  156. package/readme-assets/cover.webp +0 -0
  157. package/readme-assets/litfamily-machines.png +0 -0
  158. package/readme-assets/skills/lit-brainstorm.webp +0 -0
@@ -2,11 +2,15 @@
2
2
  // round is stamped with the SHA-256 of the stills manifest it looked at and of every frame it
3
3
  // lists, and it refuses frames that are not in the latest stills set and bare yes/no answers. The
4
4
  // done-check then needs gate PASS, a valid treatment, at least two rounds (the round-1 stills round
5
- // with a change, then a last round on the final render's stills) and full viewing coverage.
5
+ // with a change, then a last round on the final render's stills) and full viewing coverage. A cover
6
+ // (treatment mode: cover) has its own eight questions, up to three timed defects per round, and its own
7
+ // done: the decoded cover at every TARGET gate and a last round that viewed the sheet, poster and seam.
6
8
  import { createHash } from "node:crypto";
7
9
  import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
8
10
  import { join } from "node:path";
9
- import { EXIT, Exit, MAX_ROUNDS } from "./constants.mjs";
11
+ import { COVER, EXIT, Exit, MAX_ROUNDS } from "./constants.mjs";
12
+ import { generatedLabels } from "./cover-assets.mjs";
13
+ import { validateCoverTreatment } from "./cover-treatment.mjs";
10
14
  import { loadTreatment, TreatmentError } from "./treatment.mjs";
11
15
 
12
16
  export const QUESTIONS = Object.freeze([
@@ -23,6 +27,19 @@ export const QUESTIONS = Object.freeze([
23
27
  // The answer that asks for another round, per question: "no" on 1, 2, 3, 5, 6; "yes" on 4, 7, 8, 9.
24
28
  const REVISE_ON = Object.freeze({ 1: "no", 2: "no", 3: "no", 4: "yes", 5: "no", 6: "no", 7: "yes", 8: "yes", 9: "yes" });
25
29
  const COVERAGE_KINDS = new Set(["poster", "sheet", "beat", "strip"]);
30
+ // Cover mode asks about motion, the seam and damage instead of purpose and beats (references/cover.md).
31
+ export const COVER_QUESTIONS = Object.freeze([
32
+ "Is something moving in every half-second window (the sheet's plot never lies flat on the red still line)?",
33
+ "Does the seam disappear in the decoded file (seam.png, the right end of the plot)?",
34
+ "Does it still move after encoding, with no region that freezes and then pops?",
35
+ "Is the brand word present, legible and in place in every frame, never faded or swapped?",
36
+ "Are all three speed layers visible: a slow perpetual layer, a mid swell and beat events?",
37
+ "Does anything read as a slide, a card swap, a title fade or an end card?",
38
+ "Is any glyph, glint or glow damaged: a colour block, a dark disc, a visible box?",
39
+ "Name one thing a skilled motion designer would add or remove. Can you name one?",
40
+ ]);
41
+ const COVER_REVISE_ON = Object.freeze({ 1: "no", 2: "no", 3: "no", 4: "no", 5: "no", 6: "yes", 7: "yes", 8: "yes" });
42
+ const COVER_VIEWS = new Set(["sheet", "poster", "seam"]);
26
43
  const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
27
44
  const refuse = (message) => {
28
45
  throw new Exit(EXIT.USAGE, `look refused: ${message}`);
@@ -67,6 +84,8 @@ export function recordLook(outDir, round, answersPath) {
67
84
  return entry;
68
85
  }
69
86
  if (stills.manifest.round !== round) refuse(`the latest stills set is from round ${stills.manifest.round}; look at the stills of round ${round} (render it first)`);
87
+ if (stills.manifest.mode === "cover") return recordCoverLook({ outDir, round, body, stills, look });
88
+ if (body.defects !== undefined) refuse("defects are a cover-mode record; a film round names its weakest beat instead");
70
89
  if (round === 1 && stills.manifest.kind !== "stills-only") refuse("round 1 is a stills round: run the render with --stills-only --round 1 first");
71
90
  const name = (file) => String(file ?? "").replace(/^stills\//u, "");
72
91
  const viewed = Array.isArray(body.viewed) ? body.viewed.map(name) : [];
@@ -107,6 +126,70 @@ export function recordLook(outDir, round, answersPath) {
107
126
  return entry;
108
127
  }
109
128
 
129
+ /** Check every stills file a round names and stamp it with its SHA-256; refuses files outside the set. */
130
+ function stampFrames(outDir, stills, files) {
131
+ const unknown = [...new Set(files)].filter((file) => !stills.files.has(file));
132
+ if (unknown.length) refuse(`not in the latest stills set: ${unknown.join(", ")}`);
133
+ const frames = {};
134
+ for (const file of new Set(files)) {
135
+ const bytes = readFileSync(join(outDir, "stills", file));
136
+ if (sha256(bytes) !== stills.files.get(file).sha256) refuse(`${file} changed after the stills manifest was written; render again`);
137
+ frames[file] = sha256(bytes);
138
+ }
139
+ return frames;
140
+ }
141
+
142
+ /**
143
+ * Cover defects: at most COVER.maxDefects per round, worst first, each { t, region, frame, observed,
144
+ * cause, fix }: the loop time in seconds where it shows, the [x, y, w, h] it covers in cover pixels,
145
+ * and a file of the current stills set that shows it. `render.mjs cover --window` checks the fix.
146
+ */
147
+ function coverDefects(list, stills) {
148
+ if (list === undefined) return [];
149
+ if (!Array.isArray(list)) refuse("defects must be an array");
150
+ if (list.length > COVER.maxDefects) refuse(`at most ${COVER.maxDefects} defects per round; fix the worst first`);
151
+ const { width, height, durationSec } = stills.manifest;
152
+ const name = (file) => String(file ?? "").replace(/^stills\//u, "");
153
+ return list.map((d, i) => {
154
+ const at = `defect ${i + 1}`;
155
+ if (!d || typeof d !== "object") refuse(`${at} must be an object`);
156
+ if (typeof d.t !== "number" || !(d.t >= 0 && d.t < durationSec)) refuse(`${at}: t must be the loop time in seconds (0 to ${durationSec}) where the defect shows`);
157
+ const r = d.region;
158
+ if (!Array.isArray(r) || r.length !== 4 || !r.every(Number.isInteger) || r[0] < 0 || r[1] < 0 || r[2] <= 0 || r[3] <= 0 || r[0] + r[2] > width || r[1] + r[3] > height) refuse(`${at}: region must be [x, y, w, h] in whole pixels inside the ${width}x${height} cover`);
159
+ if (!stills.files.has(name(d.frame))) refuse(`${at}: frame ${JSON.stringify(d.frame)} is not in the latest stills set`);
160
+ if (!sentence(d.observed)) refuse(`${at}: observed must be a sentence naming what is visible there`);
161
+ if (![d.cause, d.fix].every((x) => typeof x === "string" && x.trim().split(/\s+/u).length >= 3)) refuse(`${at}: cause and fix must each say something concrete`);
162
+ return { t: d.t, region: r, frame: name(d.frame), observed: d.observed.trim(), cause: d.cause.trim(), fix: d.fix.trim() };
163
+ });
164
+ }
165
+
166
+ /** One cover look round: the eight cover questions, the defects, and round 1's change (no stills-only round). */
167
+ function recordCoverLook({ outDir, round, body, stills, look }) {
168
+ const name = (file) => String(file ?? "").replace(/^stills\//u, "");
169
+ const viewed = Array.isArray(body.viewed) ? body.viewed.map(name) : [];
170
+ if (!viewed.length) refuse("viewed must list every stills file you opened with view_image this round");
171
+ if (!Array.isArray(body.answers)) refuse("answers must be an array of { q, verdict, frame, observed }");
172
+ const byQ = new Map();
173
+ for (const answer of body.answers) {
174
+ const q = Number(answer?.q);
175
+ if (!Number.isInteger(q) || q < 1 || q > COVER_QUESTIONS.length) refuse(`unknown question ${answer?.q} (a cover round answers ${COVER_QUESTIONS.length})`);
176
+ if (byQ.has(q)) refuse(`question ${q} answered twice`);
177
+ if (answer.verdict !== "yes" && answer.verdict !== "no") refuse(`question ${q}: verdict must be "yes" or "no"`);
178
+ if (!sentence(answer.observed)) refuse(`question ${q}: observed must be a sentence naming a concrete visible detail, not a bare yes/no`);
179
+ byQ.set(q, { q, verdict: answer.verdict, frame: name(answer.frame), observed: answer.observed.trim() });
180
+ }
181
+ for (let q = 1; q <= COVER_QUESTIONS.length; q++) if (!byQ.has(q)) refuse(`question ${q} is not answered (${COVER_QUESTIONS[q - 1]})`);
182
+ const answers = [...byQ.values()].sort((a, b) => a.q - b.q);
183
+ const defects = coverDefects(body.defects, stills);
184
+ const frames = stampFrames(outDir, stills, [...viewed, ...answers.map((a) => a.frame), ...defects.map((d) => d.frame)]);
185
+ if (round === 1 && (typeof body.change !== "string" || body.change.trim().split(/\s+/u).length < 3)) refuse("round 1 must state the change you made (change)");
186
+ const openItems = answers.filter((a) => a.verdict === COVER_REVISE_ON[a.q]).map((a) => `Q${a.q}: ${a.observed}`);
187
+ const entry = { round, at: new Date().toISOString(), kind: "cover", mode: "cover", manifestSha256: stills.sha, frames, viewed: [...new Set(viewed)], answers, defects, ...(typeof body.change === "string" ? { change: body.change.trim() } : {}), needsAnotherRound: openItems.length > 0, openItems };
188
+ look.rounds.push(entry);
189
+ writeFileSync(join(outDir, "look.json"), `${JSON.stringify(look, null, 2)}\n`);
190
+ return entry;
191
+ }
192
+
110
193
  /** Frames viewed for the render whose stills manifest hash is `manifestSha`, from look.json only. */
111
194
  export function viewedFor(outDir, manifestSha) {
112
195
  if (!manifestSha) return null;
@@ -138,6 +221,12 @@ const PREVIEWS = ["preview.webp", "preview.gif"];
138
221
  */
139
222
  export function evaluateDone(outDir) {
140
223
  const notDone = (reason) => ({ status: "not complete", reason, downgraded: [], openItems: [] });
224
+ try {
225
+ const raw = JSON.parse(readFileSync(join(outDir, "treatment.json"), "utf8"));
226
+ if (raw?.mode === "cover") return evaluateCoverDone(outDir, raw);
227
+ } catch {
228
+ // A missing or unreadable treatment is reported by the film checks below.
229
+ }
141
230
  const manifestPath = join(outDir, "manifest.json");
142
231
  const reportPath = join(outDir, "gate-report.txt");
143
232
  if (!existsSync(manifestPath) || !existsSync(reportPath)) return notDone("no manifest and gate report: nothing verified was rendered (a started, stills-only or BLOCKED run)");
@@ -180,3 +269,40 @@ export function evaluateDone(outDir) {
180
269
  if (last.needsAnotherRound && last.round < MAX_ROUNDS) return { ...notDone(`look round ${last.round} found items that need another round: ${last.openItems.map((item) => item.split(":")[0]).join(", ")}`), downgraded };
181
270
  return { status: "complete", reason: `${gateNote}; ${rounds.length} look rounds, the last on the final render with every still viewed${last.openItems.length ? "; deliver with the open items stated" : ""}`, downgraded, openItems: last.openItems ?? [] };
182
271
  }
272
+
273
+ /**
274
+ * The cover done-check (references/cover.md, Rounds and done): a valid cover treatment unchanged since
275
+ * the last cover render, that render's report at PASS+TARGET, at least two look rounds (the first naming
276
+ * its change), and the last round stamped with that render's stills and viewing the sheet, the poster
277
+ * and the seam pair. Generated assets come back as labels the reply has to carry.
278
+ */
279
+ export function evaluateCoverDone(outDir, raw) {
280
+ const labels = generatedLabels(outDir);
281
+ const notDone = (reason) => ({ status: "not complete", reason, downgraded: [], openItems: [], labels, mode: "cover" });
282
+ try {
283
+ validateCoverTreatment(raw);
284
+ } catch (error) {
285
+ if (error instanceof TreatmentError) return notDone(`the cover treatment is not valid (${error.message})`);
286
+ throw error;
287
+ }
288
+ const manifestPath = join(outDir, "manifest.json");
289
+ const reportPath = join(outDir, "gate-report.txt");
290
+ if (!existsSync(manifestPath) || !existsSync(reportPath)) return notDone("no finished cover render: manifest.json or gate-report.txt is missing");
291
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
292
+ if (manifest.mode !== "cover") return notDone("the last render was not a cover render; run `render.mjs cover`");
293
+ if (manifest.treatmentSha256 !== sha256(readFileSync(join(outDir, "treatment.json")))) return notDone("treatment.json changed after the last cover render; render again");
294
+ if (!/^COVER gate --strict: PASS\+TARGET$/mu.test(readFileSync(reportPath, "utf8"))) return notDone("the decoded cover did not reach every TARGET gate on the last render (gate-report.txt)");
295
+ const rounds = readLook(outDir).rounds;
296
+ const last = rounds.at(-1);
297
+ if (last?.blocked) return { status: "DONE_UNVIEWED", reason: "every TARGET gate passed, but no image tool was reachable: nobody viewed the sheet. Say so plainly in the reply.", downgraded: [], openItems: [], labels, mode: "cover" };
298
+ if (rounds.length < 2) return notDone("needs at least 2 look rounds: view the sheet, poster and seam pair with view_image, record the round, make its change, render, look again");
299
+ if (!rounds[0].change) return notDone("the first look round must name the change made after it");
300
+ if (last.manifestSha256 !== manifest.stillsManifestSha256) return notDone("the last look round viewed an older stills set than the final cover render; view the final stills and record another round");
301
+ const stills = latestStills(outDir);
302
+ const required = stills ? [...stills.files.values()].filter((f) => COVER_VIEWS.has(f.kind)).map((f) => f.file) : [];
303
+ const seen = new Set([...(last.viewed ?? []), ...Object.keys(last.frames ?? {})]);
304
+ const unseen = required.filter((file) => !seen.has(file));
305
+ if (unseen.length) return notDone(`the last look round did not view ${unseen.join(", ")} (the sheet, the poster and the seam pair)`);
306
+ if (last.needsAnotherRound && last.round < MAX_ROUNDS) return notDone(`look round ${last.round} found items that need another round: ${last.openItems.map((item) => item.split(":")[0]).join(", ")}`);
307
+ return { status: "complete", reason: `every TARGET gate passed on the decoded cover; ${rounds.length} look rounds, the last on the final render with the sheet, poster and seam pair viewed${last.openItems.length ? "; deliver with the open items stated" : ""}`, downgraded: [], openItems: last.openItems ?? [], labels, mode: "cover" };
308
+ }
@@ -0,0 +1,104 @@
1
+ // LitLoop kit, served to cover pages at /lit/loop-kit.js. A cover page draws every frame from one
2
+ // loop time t in [0, 1) through window.renderFrame(t); the renderer seeks t = i / N in any order and
3
+ // in fresh browsers. So every helper here is either pure or periodic in t: the value at t = 1 is the
4
+ // value at t = 0, and nothing remembers the frame drawn before. Layout randomness comes from rng(seed);
5
+ // per-frame variation comes only from t (the cover init script makes every clock throw).
6
+ (function litLoopKit(global) {
7
+ "use strict";
8
+
9
+ const TAU = Math.PI * 2;
10
+ const clamp = (x, lo = 0, hi = 1) => (x < lo ? lo : x > hi ? hi : x);
11
+ const fract = (x) => x - Math.floor(x);
12
+ const mix = (a, b, k) => a + (b - a) * k;
13
+
14
+ /** mulberry32: a seeded generator for layout only (positions, sizes, which copy is the accent). */
15
+ function rng(seed) {
16
+ let state = seed >>> 0;
17
+ return () => {
18
+ state = (state + 0x6d2b79f5) >>> 0;
19
+ let x = Math.imul(state ^ (state >>> 15), 1 | state);
20
+ x = (x + Math.imul(x ^ (x >>> 7), 61 | x)) ^ x;
21
+ return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
22
+ };
23
+ }
24
+
25
+ /**
26
+ * Seeded 3D value noise. loopNoise walks it around a circle, so one loop of t returns to its start;
27
+ * `offset` separates the elements that share the field and `radius` sets how far one loop wanders.
28
+ */
29
+ function makeNoise(seed) {
30
+ const next = rng(seed);
31
+ const perm = new Uint8Array(512);
32
+ const lattice = new Float32Array(256);
33
+ for (let i = 0; i < 256; i++) {
34
+ perm[i] = i;
35
+ lattice[i] = next() * 2 - 1;
36
+ }
37
+ for (let i = 255; i > 0; i--) {
38
+ const j = Math.floor(next() * (i + 1));
39
+ const swap = perm[i];
40
+ perm[i] = perm[j];
41
+ perm[j] = swap;
42
+ }
43
+ for (let i = 0; i < 256; i++) perm[i + 256] = perm[i];
44
+ const fade = (x) => x * x * (3 - 2 * x);
45
+ const corner = (x, y, z) => lattice[perm[perm[perm[x & 255] + (y & 255)] + (z & 255)]];
46
+ return (x, y, z) => {
47
+ const x0 = Math.floor(x);
48
+ const y0 = Math.floor(y);
49
+ const z0 = Math.floor(z);
50
+ const u = fade(x - x0);
51
+ const v = fade(y - y0);
52
+ const w = fade(z - z0);
53
+ const edge = (yy, zz) => mix(corner(x0, yy, zz), corner(x0 + 1, yy, zz), u);
54
+ const face = (zz) => mix(edge(y0, zz), edge(y0 + 1, zz), v);
55
+ return mix(face(z0), face(z0 + 1), w);
56
+ };
57
+ }
58
+ const loopNoise = (noise, t, offset = 0, radius = 1.3) => noise(offset + radius * Math.cos(TAU * t), radius * Math.sin(TAU * t), offset * 0.37);
59
+
60
+ // Shapes for events. Linear time is only for motion that never stops (drift, laps, rising motes).
61
+ const ease = Object.freeze({
62
+ smooth: (p) => p * p * (3 - 2 * p),
63
+ outCubic: (p) => 1 - (1 - p) ** 3,
64
+ inCubic: (p) => p ** 3,
65
+ outExpo: (p) => (p >= 1 ? 1 : 1 - 2 ** (-10 * p)),
66
+ outBack: (p, s = 1.6) => 1 + (s + 1) * (p - 1) ** 3 + s * (p - 1) ** 2,
67
+ gain: (p, k) => (p < 0.5 ? 0.5 * (2 * p) ** k : 1 - 0.5 * (2 * (1 - p)) ** k),
68
+ });
69
+
70
+ /**
71
+ * A symmetric bump of half-width w around c, 0 outside. Prefer it for micro events: an exponential
72
+ * tail is a slow fade, and a lossy animation encoder drops changes that small.
73
+ */
74
+ function cubicPulse(c, w, x) {
75
+ const d = Math.abs(x - c);
76
+ if (d > w) return 0;
77
+ const k = d / w;
78
+ return 1 - k * k * (3 - 2 * k);
79
+ }
80
+ const expImpulse = (x, k) => k * x * Math.exp(1 - k * x);
81
+
82
+ /** Loop position of one copy of a rule: the same rule at another offset is the whole system. */
83
+ const phase = (t, offset = 0, cycles = 1) => fract(t * cycles - offset);
84
+ /** Distance from p to c around the loop (0..0.5), for an event that straddles t = 0. */
85
+ const cdist = (p, c) => {
86
+ const d = fract(p - c);
87
+ return Math.min(d, 1 - d);
88
+ };
89
+ /** A one-shot event inside the loop: 0..1 across [start, start + dur) (wrapping), -1 outside. */
90
+ const span = (p, start, dur) => {
91
+ const q = fract(p - start);
92
+ return q < dur ? q / dur : -1;
93
+ };
94
+ /** Hold and move: dwell at `stops` poses per cycle, travelling during the last `travel` of each slot. */
95
+ const steps = (p, stops, travel = 0.35, shape = ease.smooth) => {
96
+ const x = p * stops;
97
+ const slot = Math.floor(x);
98
+ return (slot + shape(clamp((x - slot - (1 - travel)) / travel))) / stops;
99
+ };
100
+ /** A cosine swell 0..1..0 over one cycle that dwells at both ends. */
101
+ const swell = (p) => 0.5 - 0.5 * Math.cos(TAU * p);
102
+
103
+ global.LitLoop = Object.freeze({ TAU, clamp, fract, mix, rng, makeNoise, loopNoise, ease, cubicPulse, expImpulse, phase, cdist, window: span, steps, swell });
104
+ })(typeof window !== "undefined" ? window : globalThis);
@@ -1,7 +1,8 @@
1
1
  // Motion runtime: a product-owned cache under ${XDG_CACHE_HOME:-~/.cache}/litcodex/motion-runtime,
2
2
  // filled only by `litcodex motion-runtime install` (or the installer/postinstall pre-warm) from the
3
3
  // pinned lockfile, pinned font URLs and a hash-pinned audio requirements file. Renders only read it
4
- // (MO-A-42/43). This module also carries the five doctor/status probes (MO-A-44/55).
4
+ // (MO-A-42/43). This module also carries the six doctor/status probes (MO-A-44/55): the five film
5
+ // probes and the cover encoder that cover mode needs.
5
6
  import { spawnSync } from "node:child_process";
6
7
  import { createHash } from "node:crypto";
7
8
  import { closeSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
@@ -119,9 +120,22 @@ function withLock(root, action) {
119
120
  const INHERITED_NPM_MODE = /^npm_config_(global|location|prefix|dry[-_]run)$/iu;
120
121
  const npmChildEnv = (env) => Object.fromEntries(Object.entries(env).filter(([key]) => !INHERITED_NPM_MODE.test(key)));
121
122
 
122
- function npmCommand(env) {
123
- if (env.npm_execpath && existsSync(env.npm_execpath)) return [process.execPath, [env.npm_execpath]];
124
- return [process.platform === "win32" ? "npm.cmd" : "npm", []];
123
+ /**
124
+ * How to run npm: node + npm's own entry script when one exists. Node refuses to spawn a .cmd/.bat
125
+ * shim without a shell (CVE-2024-27980), so on Windows the last resort is a quoted cmd.exe line.
126
+ */
127
+ export function npmCommand(args, env = process.env, platform = process.platform, exists = existsSync) {
128
+ if (env.npm_execpath && exists(env.npm_execpath)) return { command: process.execPath, args: [env.npm_execpath, ...args] };
129
+ if (platform !== "win32") return { command: "npm", args };
130
+ const bundled = join(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
131
+ if (exists(bundled)) return { command: process.execPath, args: [bundled, ...args] };
132
+ return { command: ["npm.cmd", ...args].map(cmdArgument).join(" "), args: [], shell: true };
133
+ }
134
+
135
+ /** One argument for a cmd.exe line: quoted when it holds spaces; refused when cmd would interpret it. */
136
+ export function cmdArgument(value) {
137
+ if (/["%^&|<>!\r\n]/u.test(value)) throw new Error(`refusing to pass ${JSON.stringify(value)} through cmd.exe`);
138
+ return /[\s()]/u.test(value) ? `"${value}"` : value;
125
139
  }
126
140
 
127
141
  /**
@@ -139,12 +153,12 @@ export async function install({ env = process.env, audio = false, wordTiming = f
139
153
  mkdirSync(dir, { recursive: true });
140
154
  if (!depsState(dir).missing.every((m) => m === "pre-warm receipt missing")) {
141
155
  for (const name of ["package.json", "package-lock.json"]) copyFileSync(join(RUNTIME_SOURCES, name), join(dir, name));
142
- const [command, prefix] = npmCommand(env);
143
- const args = [...prefix, "ci", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"];
144
- if (env.LITCODEX_MOTION_NPM_CACHE) args.push("--offline", "--cache", env.LITCODEX_MOTION_NPM_CACHE);
156
+ const ci = ["ci", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"];
157
+ if (env.LITCODEX_MOTION_NPM_CACHE) ci.push("--offline", "--cache", env.LITCODEX_MOTION_NPM_CACHE);
158
+ const npm = npmCommand(ci, env);
145
159
  log(`installing pinned engine dependencies into ${dir}`);
146
- const result = spawnSync(command, args, { cwd: dir, encoding: "utf8", env: { ...npmChildEnv(env), PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" }, timeout: 300000 });
147
- if (result.status !== 0) throw new Error(`npm ci failed: ${(result.error?.message || result.stderr || "").trim().split("\n").slice(-2).join(" ")}`);
160
+ const result = spawnSync(npm.command, npm.args, { cwd: dir, encoding: "utf8", env: { ...npmChildEnv(env), PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: "1" }, timeout: 300000, ...(npm.shell ? { shell: true } : {}) });
161
+ if (result.status !== 0) throw new Error(`npm ci failed (exit ${result.status ?? result.signal}): ${(result.error?.message || result.stderr || "").trim().split(/\r?\n/u).slice(-2).join(" ")}`);
148
162
  }
149
163
  for (const item of FETCHED) {
150
164
  const target = join(dir, item.path);
@@ -163,15 +177,48 @@ export async function install({ env = process.env, audio = false, wordTiming = f
163
177
  return { ready: deps.ready && fonts.ready, dir, missing: [...deps.missing, ...fonts.missing] };
164
178
  }
165
179
 
180
+ // The audio requirements are compiled for CPython 3.10 and up, but --only-binary needs a wheel for
181
+ // every pin, and those stop at MAX_PYTHON: a newer host python3 (3.15 on some Macs) fails pip on the
182
+ // first package without one. So the venv is built from the newest python3.X inside the range.
183
+ const MIN_PYTHON = [3, 10];
184
+ const MAX_PYTHON = [3, 14];
185
+ const PYTHON_RANGE = `${MIN_PYTHON.join(".")} to ${MAX_PYTHON.join(".")}`;
186
+
187
+ export function probePython(command, env = process.env) {
188
+ const probe = spawnSync(command, ["-c", "import sys; print('%d.%d.%d' % sys.version_info[:3])"], { encoding: "utf8", env, timeout: 30000 });
189
+ if (probe.error || probe.status !== 0) return { ok: false, command, detail: probe.error?.code === "ENOENT" || !probe.stderr ? "not found" : probe.stderr.trim().split(/\r?\n/u).pop() };
190
+ const version = probe.stdout.trim();
191
+ const [major, minor] = version.split(".").map(Number);
192
+ if (major < MIN_PYTHON[0] || (major === MIN_PYTHON[0] && minor < MIN_PYTHON[1])) return { ok: false, command, version, detail: `${version} is older than ${MIN_PYTHON.join(".")}` };
193
+ if (major > MAX_PYTHON[0] || (major === MAX_PYTHON[0] && minor > MAX_PYTHON[1])) return { ok: false, command, version, detail: `${version} is newer than ${MAX_PYTHON.join(".")}` };
194
+ return { ok: true, command, version, detail: version };
195
+ }
196
+
197
+ /** $LITCODEX_MOTION_PYTHON alone when set; otherwise python3.14 down to python3.10, then python3 and python. */
198
+ export function pickPython(env = process.env, probe = (command) => probePython(command, env)) {
199
+ if (env.LITCODEX_MOTION_PYTHON) return probe(env.LITCODEX_MOTION_PYTHON);
200
+ const candidates = [];
201
+ for (let minor = MAX_PYTHON[1]; minor >= MIN_PYTHON[1]; minor -= 1) candidates.push(`python3.${minor}`);
202
+ const tried = [];
203
+ for (const command of [...candidates, "python3", "python"]) {
204
+ const found = probe(command);
205
+ if (found.ok) return found;
206
+ if (found.detail !== "not found") tried.push(`${command}: ${found.detail}`);
207
+ }
208
+ return { ok: false, command: "python3", detail: `no supported Python (${PYTHON_RANGE}) on PATH${tried.length ? `; tried ${tried.join(", ")}` : ""}` };
209
+ }
210
+
166
211
  function installAudio(dir, env, log) {
167
212
  const venv = join(dir, "audio-venv");
168
- const python = env.LITCODEX_MOTION_PYTHON || "python3";
169
- log(`creating the librosa venv with ${python}`);
213
+ const picked = pickPython(env);
214
+ if (!picked.ok) throw new Error(`audio venv needs Python ${PYTHON_RANGE}: ${picked.detail}; set LITCODEX_MOTION_PYTHON to one`);
215
+ const python = picked.command;
216
+ log(`creating the librosa venv with ${python} ${picked.version}`);
170
217
  rmSync(venv, { recursive: true, force: true });
171
218
  const made = spawnSync(python, ["-m", "venv", venv], { encoding: "utf8", env, timeout: 120000 });
172
219
  if (made.status !== 0) throw new Error(`python venv failed: ${(made.error?.message || made.stderr || "").trim()}`);
173
220
  const pip = spawnSync(venvPython(dir), ["-m", "pip", "install", "--disable-pip-version-check", "--no-input", "--require-hashes", "--only-binary=:all:", "-r", AUDIO_REQUIREMENTS], { encoding: "utf8", env, timeout: 900000 });
174
- if (pip.status !== 0) throw new Error(`pip install --require-hashes failed: ${(pip.stderr || "").trim().split("\n").slice(-2).join(" ")}`);
221
+ if (pip.status !== 0) throw new Error(`pip install --require-hashes failed (exit ${pip.status ?? pip.signal}): ${(pip.error?.message || pip.stderr || "").trim().split(/\r?\n/u).slice(-2).join(" ")}`);
175
222
  writeFileSync(join(venv, "litcodex-audio.json"), `${JSON.stringify({ requirementsSha256: requirementsDigest() })}\n`);
176
223
  }
177
224
 
@@ -206,12 +253,26 @@ export function stageFlags(width, height, platform = process.platform) {
206
253
  return [...chromeLadder(platform)[1], ...CHROME_STAGE_FLAGS, `--window-size=${width},${height}`];
207
254
  }
208
255
 
256
+ /**
257
+ * Cover mode's launch: the stage rung at the cover's device scale, with raster kept off the GPU path
258
+ * and never partial: at 2x, glyph edges rastered in GPU tiles came out one level apart between fresh
259
+ * browsers.
260
+ */
261
+ export function coverFlags(width, height, scale, platform = process.platform) {
262
+ return [...stageFlags(width, height, platform).map((flag) => (flag === "--force-device-scale-factor=1" ? `--force-device-scale-factor=${scale}` : flag)), "--disable-gpu-rasterization", "--disable-partial-raster"];
263
+ }
264
+
209
265
  export const isSoftware = (renderer) => SOFTWARE_GL.some((needle) => String(renderer).toLowerCase().includes(needle));
210
266
 
211
- function which(command, env) {
212
- for (const dir of (env.PATH || "").split(delimiter)) {
213
- const path = join(dir, command);
214
- if (dir && existsSync(path)) return path;
267
+ /** A PATH lookup; on Windows it tries each PATHEXT extension, so ffmpeg.exe answers for ffmpeg. */
268
+ export function which(command, env = process.env, platform = process.platform, exists = existsSync) {
269
+ const extensions = platform === "win32" ? (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
270
+ for (const dir of (env.PATH ?? env.Path ?? "").split(platform === "win32" ? ";" : delimiter)) {
271
+ if (!dir) continue;
272
+ for (const extension of extensions) {
273
+ const path = join(dir, `${command}${extension}`);
274
+ if (exists(path)) return path;
275
+ }
215
276
  }
216
277
  return null;
217
278
  }
@@ -220,7 +281,7 @@ export function ffmpegProbe(env = process.env) {
220
281
  const path = which("ffmpeg", env);
221
282
  if (!path) return { ok: false, line: "not found on PATH", previewEncoder: null };
222
283
  const version = spawnSync(path, ["-hide_banner", "-version"], { encoding: "utf8", env });
223
- const first = (version.stdout || "").split("\n")[0].trim();
284
+ const first = (version.stdout || "").split(/\r?\n/u)[0].trim();
224
285
  const encoders = spawnSync(path, ["-hide_banner", "-encoders"], { encoding: "utf8", env }).stdout || "";
225
286
  const img2webp = which("img2webp", env);
226
287
  const previewEncoder = /\blibwebp_anim\b/u.test(encoders) ? "libwebp_anim" : img2webp ? "img2webp" : "gif";
@@ -250,7 +311,18 @@ export function webglProbe(chrome, env = process.env) {
250
311
 
251
312
  export const firstLine = (text) => String(text).trim().split("\n").find((line) => line.trim())?.trim() ?? String(text);
252
313
 
253
- /** The five MO-A-44 probes, plus audio and word-timing state, every time. */
314
+ /** Cover mode's encoder: img2webp with dwebp (encode, then decode for the gate), else the gifski fallback. */
315
+ export function coverEncoderProbe(env = process.env) {
316
+ const img2webp = which("img2webp", env);
317
+ const dwebp = which("dwebp", env);
318
+ const version = (tool) => /\d+\.\d+(?:\.\d+)?/u.exec(`${spawnSync(tool, ["-version"], { encoding: "utf8", env }).stdout ?? ""}`)?.[0] ?? "version unknown";
319
+ if (img2webp && dwebp) return { ok: true, line: `img2webp ${version(img2webp)} and dwebp ${version(dwebp)}: README covers encode as animated WebP and the gate reads the decoded file` };
320
+ const gifski = which("gifski", env);
321
+ if (gifski) return { ok: true, line: `gifski at ${gifski}: covers fall back to GIF (${[img2webp ? null : "img2webp", dwebp ? null : "dwebp"].filter(Boolean).join(" and ")} missing)` };
322
+ return { ok: false, line: "BLOCKED_NO_COVER_ENCODER: install libwebp (img2webp, dwebp) or gifski; cover renders stop with exit 21" };
323
+ }
324
+
325
+ /** The six MO-A-44 probes, plus audio and word-timing state, every time. */
254
326
  export function status({ env = process.env, browser = true } = {}) {
255
327
  const chrome = findChrome(env);
256
328
  const version = chrome ? spawnSync(chrome, ["--version"], { encoding: "utf8", env, timeout: 15000 }) : null;
@@ -267,6 +339,7 @@ export function status({ env = process.env, browser = true } = {}) {
267
339
  webgl2: gl.ok ? gl.renderer : gl.detail,
268
340
  rendererWarning: warning,
269
341
  prewarm: missing.length ? `missing: ${missing.join("; ")}; fix: ${INSTALL_COMMAND}` : `ready (${dir})`,
342
+ coverEncoder: coverEncoderProbe(env).line,
270
343
  ready: missing.length === 0,
271
344
  missing,
272
345
  cache: dir,
@@ -285,6 +358,7 @@ export function renderStatus(report) {
285
358
  `WebGL2 renderer: ${report.webgl2}`,
286
359
  `Renderer warning: ${report.rendererWarning}`,
287
360
  `Pre-warm: ${report.prewarm}`,
361
+ `Cover encoder: ${report.coverEncoder}`,
288
362
  `Audio tier: ${report.audio}`,
289
363
  `Word timing: ${report.wordTiming}`,
290
364
  ].join("\n");
@@ -174,6 +174,7 @@ export function stageFontFaults(faults) {
174
174
  */
175
175
  export function stageRouter({ root, fonts, record }) {
176
176
  const kit = readFileSync(join(SKILL_ROOT, "engine", "stage-kit.js"));
177
+ const loopKit = readFileSync(join(SKILL_ROOT, "engine", "loop-kit.js"));
177
178
  return async (route) => {
178
179
  const url = route.request().url();
179
180
  if (!url.startsWith(`${STAGE_ORIGIN}/`)) {
@@ -189,6 +190,7 @@ export function stageRouter({ root, fonts, record }) {
189
190
  return route.fulfill({ status: 400, body: "" });
190
191
  }
191
192
  if (path === "/lit/stage-kit.js") return route.fulfill({ status: 200, contentType: CONTENT_TYPES[".js"], body: kit });
193
+ if (path === "/lit/loop-kit.js") return route.fulfill({ status: 200, contentType: CONTENT_TYPES[".js"], body: loopKit });
192
194
  if (path === "/lit/fonts.css") return route.fulfill({ status: 200, contentType: CONTENT_TYPES[".css"], body: fonts.css });
193
195
  const font = fonts.routes.get(path);
194
196
  if (font) return route.fulfill({ status: 200, contentType: font.type, body: readFileSync(font.file) });
@@ -48,7 +48,7 @@ export function typeLedCue(request) {
48
48
  }
49
49
 
50
50
  /** True when `candidate` shares a normalized substring of `limit` characters with `against`. */
51
- function sharesRun(candidate, against, limit) {
51
+ export function sharesRun(candidate, against, limit) {
52
52
  if (limit < 1) return false;
53
53
  const a = Array.from(normalizeText(candidate));
54
54
  const b = normalizeText(against);
@@ -66,7 +66,7 @@ function requireText(t, field, value = t[field]) {
66
66
  }
67
67
 
68
68
  /** Every string leaf that still holds an example placeholder such as "<one sentence>". */
69
- function findPlaceholder(value, path) {
69
+ export function findPlaceholder(value, path) {
70
70
  if (typeof value === "string") return PLACEHOLDER.test(value) ? path : null;
71
71
  if (Array.isArray(value)) {
72
72
  for (let i = 0; i < value.length; i++) {
@@ -148,6 +148,7 @@ function beatCoverage(beats, indices) {
148
148
  */
149
149
  export function validateTreatment(t, { examples = shippedExamples() } = {}) {
150
150
  if (!t || typeof t !== "object" || Array.isArray(t)) throw new TreatmentError("treatment", "must be a JSON object");
151
+ if (t.mode === "cover") throw new TreatmentError("mode", "this is a cover treatment: render it with `render.mjs cover --out <dir>` (references/cover.md)");
151
152
  const placeholder = findPlaceholder(t, "");
152
153
  if (placeholder) throw new TreatmentError(placeholder, "still holds an example placeholder (<...>); write the real value");
153
154
  if (examples.length && copiedFrom(t, examples)) throw new TreatmentError("copiedExample", "half or more of the free-text fields equal a shipped example; write this film's own treatment");
@@ -0,0 +1,140 @@
1
+ // Animated WebP, decoded the way a browser shows it, with no npm dependency: the RIFF container is
2
+ // parsed here (canvas size, loop count, and every ANMF frame's rectangle, duration, blend and dispose
3
+ // flags), each frame's own bitstream is wrapped as a standalone still and decoded by the host's
4
+ // `dwebp` (libwebp ships it with img2webp), and the stills are composited onto one canvas in order.
5
+ // The cover gate reads the encoded file through this, because a lossy animation encoder skips small
6
+ // changes and only the decoded file shows what it skipped.
7
+ import { spawnSync } from "node:child_process";
8
+ import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { which } from "./runtime.mjs";
12
+
13
+ export const findImg2webp = (env = process.env) => which("img2webp", env);
14
+ export const findDwebp = (env = process.env) => which("dwebp", env);
15
+
16
+ const u24 = (bytes, o) => bytes[o] | (bytes[o + 1] << 8) | (bytes[o + 2] << 16);
17
+
18
+ /** The container: { width, height, loop, animated, frames: [{ x, y, w, h, durationMs, blend, dispose, data, still }] }. */
19
+ export function parseWebp(bytes) {
20
+ if (bytes.length < 16 || bytes.toString("latin1", 0, 4) !== "RIFF" || bytes.toString("latin1", 8, 12) !== "WEBP") throw new Error("not a WebP file");
21
+ const out = { width: 0, height: 0, loop: null, animated: false, frames: [] };
22
+ const end = Math.min(bytes.length, 8 + bytes.readUInt32LE(4));
23
+ for (let o = 12; o + 8 <= end; ) {
24
+ const type = bytes.toString("latin1", o, o + 4);
25
+ const size = bytes.readUInt32LE(o + 4);
26
+ const body = bytes.subarray(o + 8, o + 8 + size);
27
+ if (type === "VP8X") {
28
+ out.animated = (body[0] & 0x02) !== 0;
29
+ out.width = 1 + u24(body, 4);
30
+ out.height = 1 + u24(body, 7);
31
+ } else if (type === "ANIM") out.loop = body.readUInt16LE(4);
32
+ else if (type === "ANMF")
33
+ out.frames.push({ x: 2 * u24(body, 0), y: 2 * u24(body, 3), w: 1 + u24(body, 6), h: 1 + u24(body, 9), durationMs: u24(body, 12), blend: (body[15] & 0x02) === 0, dispose: (body[15] & 0x01) !== 0, data: body.subarray(16), still: false });
34
+ else if ((type === "VP8 " || type === "VP8L") && out.frames.length === 0) out.frames.push({ x: 0, y: 0, w: 0, h: 0, durationMs: 0, blend: false, dispose: false, data: bytes.subarray(o, o + 8 + size + (size & 1)), still: true });
35
+ o += 8 + size + (size & 1);
36
+ }
37
+ if (!out.animated && out.frames.length === 1 && out.loop === null) out.loop = 0;
38
+ return out;
39
+ }
40
+
41
+ /** One ANMF payload (an optional ALPH chunk, then VP8 or VP8L) as a standalone still WebP. */
42
+ function asStill(frame, header) {
43
+ if (frame.still) return Buffer.concat([header, frame.data]);
44
+ const alpha = frame.data.toString("latin1", 0, 4) === "ALPH";
45
+ const chunks = [frame.data];
46
+ if (alpha) {
47
+ const vp8x = Buffer.alloc(18);
48
+ vp8x.write("VP8X", 0, "latin1");
49
+ vp8x.writeUInt32LE(10, 4);
50
+ vp8x[8] = 0x10;
51
+ vp8x.writeUIntLE(frame.w - 1, 12, 3);
52
+ vp8x.writeUIntLE(frame.h - 1, 15, 3);
53
+ chunks.unshift(vp8x);
54
+ }
55
+ const riff = Buffer.alloc(12);
56
+ riff.write("RIFF", 0, "latin1");
57
+ riff.writeUInt32LE(4 + chunks.reduce((n, c) => n + c.length, 0), 4);
58
+ riff.write("WEBP", 8, "latin1");
59
+ return Buffer.concat([riff, ...chunks]);
60
+ }
61
+
62
+ /** A PAM image (P7) as dwebp writes it: { width, height, rgba }. */
63
+ export function readPam(buffer) {
64
+ const end = buffer.indexOf("ENDHDR\n");
65
+ if (buffer.toString("latin1", 0, 2) !== "P7" || end < 0) throw new Error("not a PAM image");
66
+ const head = buffer.toString("latin1", 0, end);
67
+ const field = (name) => Number(new RegExp(`${name} (\\d+)`, "u").exec(head)?.[1]);
68
+ const width = field("WIDTH");
69
+ const height = field("HEIGHT");
70
+ const depth = field("DEPTH");
71
+ const data = buffer.subarray(end + 7);
72
+ if (depth === 4) return { width, height, rgba: data };
73
+ const rgba = Buffer.alloc(width * height * 4, 255);
74
+ for (let i = 0; i < width * height; i++) for (let c = 0; c < 3; c++) rgba[i * 4 + c] = data[i * depth + c];
75
+ return { width, height, rgba };
76
+ }
77
+
78
+ /** Composite one decoded frame: non-premultiplied alpha blend (as libwebp's demuxer) or a plain copy. */
79
+ function composite(canvas, canvasWidth, frame, rgba) {
80
+ for (let y = 0; y < frame.h; y++)
81
+ for (let x = 0; x < frame.w; x++) {
82
+ const s = (y * frame.w + x) * 4;
83
+ const d = ((frame.y + y) * canvasWidth + frame.x + x) * 4;
84
+ const sa = rgba[s + 3];
85
+ if (!frame.blend || sa === 255) {
86
+ canvas[d] = rgba[s];
87
+ canvas[d + 1] = rgba[s + 1];
88
+ canvas[d + 2] = rgba[s + 2];
89
+ canvas[d + 3] = sa;
90
+ } else if (sa > 0) {
91
+ const under = (canvas[d + 3] * (255 - sa)) / 255;
92
+ const alpha = sa + under;
93
+ for (let c = 0; c < 3; c++) canvas[d + c] = Math.round((rgba[s + c] * sa + canvas[d + c] * under) / alpha);
94
+ canvas[d + 3] = Math.round(alpha);
95
+ }
96
+ }
97
+ }
98
+
99
+ /**
100
+ * Decode every frame of `file`. `onFrame(index, rgba, durationMs, width, height)` sees the composited
101
+ * canvas, which is reused between calls (copy what you keep). Returns { width, height, loop, durations,
102
+ * bytes, frames }.
103
+ */
104
+ export function decodeWebp(file, { env = process.env, onFrame = () => {} } = {}) {
105
+ const dwebp = findDwebp(env);
106
+ if (!dwebp) throw new Error("dwebp not found on PATH (libwebp ships it with img2webp)");
107
+ const bytes = readFileSync(file);
108
+ const info = parseWebp(bytes);
109
+ if (!info.frames.length) throw new Error(`${file} holds no frames`);
110
+ const work = mkdtempSync(join(tmpdir(), "litcodex-webp-"));
111
+ try {
112
+ let width = info.width;
113
+ let height = info.height;
114
+ let canvas = null;
115
+ let previous = null;
116
+ const durations = [];
117
+ info.frames.forEach((frame, i) => {
118
+ const src = join(work, "frame.webp");
119
+ const pam = join(work, "frame.pam");
120
+ writeFileSync(src, asStill(frame, bytes.subarray(0, 12)));
121
+ const run = spawnSync(dwebp, [src, "-pam", "-quiet", "-o", pam], { encoding: "utf8", env });
122
+ if (run.status !== 0) throw new Error(`dwebp failed on frame ${i}: ${(run.stderr || run.error?.message || "").trim().split("\n")[0]}`);
123
+ const decoded = readPam(readFileSync(pam));
124
+ if (frame.still) {
125
+ width = decoded.width;
126
+ height = decoded.height;
127
+ Object.assign(frame, { w: width, h: height });
128
+ }
129
+ canvas ??= Buffer.alloc(width * height * 4);
130
+ if (previous?.dispose) for (let y = previous.y; y < previous.y + previous.h; y++) canvas.fill(0, (y * width + previous.x) * 4, (y * width + previous.x + previous.w) * 4);
131
+ composite(canvas, width, frame, decoded.rgba);
132
+ durations.push(frame.durationMs);
133
+ onFrame(i, canvas, frame.durationMs, width, height);
134
+ previous = frame;
135
+ });
136
+ return { width, height, loop: info.loop, durations, bytes: statSync(file).size, frames: info.frames.length };
137
+ } finally {
138
+ rmSync(work, { recursive: true, force: true });
139
+ }
140
+ }