@litfamily/litcodex 1.0.28 → 1.0.30

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 (170) 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 +59 -31
  6. package/dist/install/generated-skill-payload-hashes.js +59 -31
  7. package/dist/install/index.js +1 -1
  8. package/dist/install/marketplace.js +10 -1
  9. package/dist/install/motion-runtime.d.ts +4 -1
  10. package/dist/install/motion-runtime.js +15 -4
  11. package/dist/install/office-runtime.d.ts +10 -11
  12. package/dist/install/office-runtime.js +8 -3
  13. package/dist/install/skill-catalog.d.ts +1 -1
  14. package/dist/install/skill-catalog.js +1 -0
  15. package/dist/postinstall.js +4 -2
  16. package/marketplace/.agents/plugins/marketplace.json +4 -1
  17. package/marketplace/plugins/litcodex/.codex-plugin/plugin.json +14 -2
  18. package/marketplace/plugins/litcodex/assets/screenshot-lit-ignited.png +0 -0
  19. package/marketplace/plugins/litcodex/components/auto-update/dist/auto-update.d.ts +12 -0
  20. package/marketplace/plugins/litcodex/components/auto-update/dist/auto-update.js +31 -2
  21. package/marketplace/plugins/litcodex/components/auto-update/package.json +1 -1
  22. package/marketplace/plugins/litcodex/components/comment-checker/package.json +1 -1
  23. package/marketplace/plugins/litcodex/components/git-bash/package.json +1 -1
  24. package/marketplace/plugins/litcodex/components/lit-loop/directive.md +2 -1
  25. package/marketplace/plugins/litcodex/components/lit-loop/directives/deep-interview.md +2 -0
  26. package/marketplace/plugins/litcodex/components/lit-loop/directives/lit-brainstorm.md +216 -0
  27. package/marketplace/plugins/litcodex/components/lit-loop/directives/litgoal.md +8 -1
  28. package/marketplace/plugins/litcodex/components/lit-loop/directives/review-work.md +12 -4
  29. package/marketplace/plugins/litcodex/components/lit-loop/dist/codex-hook.d.ts +6 -1
  30. package/marketplace/plugins/litcodex/components/lit-loop/dist/codex-hook.js +16 -5
  31. package/marketplace/plugins/litcodex/components/lit-loop/dist/guards.d.ts +3 -1
  32. package/marketplace/plugins/litcodex/components/lit-loop/dist/guards.js +5 -2
  33. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.d.ts +2 -0
  34. package/marketplace/plugins/litcodex/components/lit-loop/dist/hook-cli.js +26 -8
  35. package/marketplace/plugins/litcodex/components/lit-loop/dist/markers.d.ts +2 -0
  36. package/marketplace/plugins/litcodex/components/lit-loop/dist/markers.js +2 -0
  37. package/marketplace/plugins/litcodex/components/lit-loop/dist/modes.d.ts +1 -1
  38. package/marketplace/plugins/litcodex/components/lit-loop/dist/modes.js +9 -1
  39. package/marketplace/plugins/litcodex/components/lit-loop/dist/motion-route.js +2 -0
  40. package/marketplace/plugins/litcodex/components/lit-loop/dist/plan-persistence.d.ts +2 -0
  41. package/marketplace/plugins/litcodex/components/lit-loop/dist/plan-persistence.js +8 -0
  42. package/marketplace/plugins/litcodex/components/lit-loop/dist/reentry.d.ts +56 -0
  43. package/marketplace/plugins/litcodex/components/lit-loop/dist/reentry.js +171 -0
  44. package/marketplace/plugins/litcodex/components/lit-loop/dist/route-context.js +5 -2
  45. package/marketplace/plugins/litcodex/components/lit-loop/dist/route-heads.js +35 -15
  46. package/marketplace/plugins/litcodex/components/lit-loop/dist/skill-mention-scope.js +2 -0
  47. package/marketplace/plugins/litcodex/components/lit-loop/dist/trigger.d.ts +2 -2
  48. package/marketplace/plugins/litcodex/components/lit-loop/dist/trigger.js +17 -6
  49. package/marketplace/plugins/litcodex/components/lit-loop/dist/workflow-map.js +1 -0
  50. package/marketplace/plugins/litcodex/components/lit-loop/package.json +1 -1
  51. package/marketplace/plugins/litcodex/components/lsp/package.json +1 -1
  52. package/marketplace/plugins/litcodex/components/rules/dist/model-metadata.d.ts +16 -0
  53. package/marketplace/plugins/litcodex/components/rules/dist/model-metadata.js +37 -1
  54. package/marketplace/plugins/litcodex/components/rules/node_modules/picomatch/README.md +15 -21
  55. package/marketplace/plugins/litcodex/components/rules/node_modules/picomatch/lib/parse.js +49 -10
  56. package/marketplace/plugins/litcodex/components/rules/node_modules/picomatch/lib/picomatch.js +14 -2
  57. package/marketplace/plugins/litcodex/components/rules/node_modules/picomatch/lib/scan.js +30 -18
  58. package/marketplace/plugins/litcodex/components/rules/node_modules/picomatch/package.json +3 -2
  59. package/marketplace/plugins/litcodex/components/rules/package.json +1 -1
  60. package/marketplace/plugins/litcodex/components/start-work-continuation/package.json +1 -1
  61. package/marketplace/plugins/litcodex/components/telemetry/package.json +1 -1
  62. package/marketplace/plugins/litcodex/components/wikify-knowledge/package.json +1 -1
  63. package/marketplace/plugins/litcodex/skills/browser-drive/scripts/capability-probe.mjs +24 -4
  64. package/marketplace/plugins/litcodex/skills/deep-interview/SKILL.md +3 -1
  65. package/marketplace/plugins/litcodex/skills/lit-brainstorm/SKILL.md +271 -0
  66. package/marketplace/plugins/litcodex/skills/lit-brainstorm/agents/openai.yaml +6 -0
  67. package/marketplace/plugins/litcodex/skills/lit-diagram-drawer/scripts/doctor.mjs +4 -3
  68. package/marketplace/plugins/litcodex/skills/lit-diagram-drawer/scripts/export.mjs +6 -5
  69. package/marketplace/plugins/litcodex/skills/lit-diagram-drawer/scripts/runtime-probes.mjs +25 -0
  70. package/marketplace/plugins/litcodex/skills/lit-docx/scripts/convert_md_to_pdf.py +31 -1
  71. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/acs/template.tex +2 -0
  72. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/elsevier/template.tex +2 -0
  73. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/ieee/template.tex +2 -0
  74. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/korean-generic/template.tex +2 -0
  75. package/marketplace/plugins/litcodex/skills/lit-docx/templates/latex/nature/template.tex +2 -0
  76. package/marketplace/plugins/litcodex/skills/lit-loop/SKILL.md +8 -1
  77. package/marketplace/plugins/litcodex/skills/lit-pptx/scripts/office-run.mjs +42 -10
  78. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/SKILL.md +11 -9
  79. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/agents/openai.yaml +3 -0
  80. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/THIRD_PARTY_NOTICES +4 -0
  81. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/constants.mjs +38 -0
  82. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-assets.mjs +113 -0
  83. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-capture.mjs +161 -0
  84. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-gate.mjs +327 -0
  85. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-image.mjs +136 -0
  86. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-init.js +43 -0
  87. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-sheet.mjs +69 -0
  88. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-treatment.mjs +102 -0
  89. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover-worker.mjs +21 -0
  90. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/cover.mjs +352 -0
  91. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/driver.mjs +19 -1
  92. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/fonts.mjs +11 -0
  93. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/look.mjs +128 -2
  94. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/loop-kit.js +104 -0
  95. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/runtime.mjs +92 -18
  96. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/stage.mjs +2 -0
  97. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/treatment.mjs +3 -2
  98. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/engine/webp.mjs +140 -0
  99. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/fonts/jetbrains-mono/JetBrainsMono-wght-latin.woff2 +0 -0
  100. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/fonts/jetbrains-mono/OFL.txt +93 -0
  101. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/card-scenes/expected.json +16 -0
  102. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/card-scenes/index.html +42 -0
  103. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/reset-sweep/expected.json +16 -0
  104. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/reset-sweep/index.html +27 -0
  105. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/still-glow/expected.json +17 -0
  106. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/still-glow/index.html +29 -0
  107. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/title-slam/expected.json +17 -0
  108. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/negatives/title-slam/index.html +44 -0
  109. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/orbit-loop/expected.json +67 -0
  110. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/orbit-loop/index.html +182 -0
  111. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/painted-light/expected.json +95 -0
  112. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/painted-light/index.html +231 -0
  113. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/weight-tide/expected.json +67 -0
  114. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/recipes/weight-tide/index.html +103 -0
  115. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/cover.md +389 -0
  116. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/quality-gate.md +4 -0
  117. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/runtime.md +7 -6
  118. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/stage.md +3 -1
  119. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/references/treatment.md +2 -0
  120. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/runtime/requirements-audio.txt +3 -3
  121. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/scripts/render.mjs +37 -5
  122. package/marketplace/plugins/litcodex/skills/lit-typographic-motion/scripts/runtime.mjs +1 -1
  123. package/marketplace/plugins/litcodex/skills/litgoal/SKILL.md +8 -3
  124. package/marketplace/plugins/litcodex/skills/lsp-setup/SKILL.md +2 -1
  125. package/marketplace/plugins/litcodex/skills/lsp-setup/scripts/verify-lsp.ts +43 -7
  126. package/marketplace/plugins/litcodex/skills/readme-studio/templates/hyperframes-cover/package-lock.json +3 -3
  127. package/marketplace/plugins/litcodex/skills/readme-studio/templates/remotion-cover/package-lock.json +3 -3
  128. package/marketplace/plugins/litcodex/skills/review-work/SKILL.md +21 -4
  129. package/node_modules/@litcodex/lit-loop/CHANGELOG.md +7 -0
  130. package/node_modules/@litcodex/lit-loop/README.md +6 -0
  131. package/node_modules/@litcodex/lit-loop/directive.md +2 -1
  132. package/node_modules/@litcodex/lit-loop/directives/deep-interview.md +2 -0
  133. package/node_modules/@litcodex/lit-loop/directives/lit-brainstorm.md +216 -0
  134. package/node_modules/@litcodex/lit-loop/directives/litgoal.md +8 -1
  135. package/node_modules/@litcodex/lit-loop/directives/review-work.md +12 -4
  136. package/node_modules/@litcodex/lit-loop/dist/codex-hook.d.ts +6 -1
  137. package/node_modules/@litcodex/lit-loop/dist/codex-hook.js +16 -5
  138. package/node_modules/@litcodex/lit-loop/dist/guards.d.ts +3 -1
  139. package/node_modules/@litcodex/lit-loop/dist/guards.js +5 -2
  140. package/node_modules/@litcodex/lit-loop/dist/hook-cli.d.ts +2 -0
  141. package/node_modules/@litcodex/lit-loop/dist/hook-cli.js +26 -8
  142. package/node_modules/@litcodex/lit-loop/dist/markers.d.ts +2 -0
  143. package/node_modules/@litcodex/lit-loop/dist/markers.js +2 -0
  144. package/node_modules/@litcodex/lit-loop/dist/modes.d.ts +1 -1
  145. package/node_modules/@litcodex/lit-loop/dist/modes.js +9 -1
  146. package/node_modules/@litcodex/lit-loop/dist/motion-route.js +2 -0
  147. package/node_modules/@litcodex/lit-loop/dist/plan-persistence.d.ts +2 -0
  148. package/node_modules/@litcodex/lit-loop/dist/plan-persistence.js +8 -0
  149. package/node_modules/@litcodex/lit-loop/dist/reentry.d.ts +56 -0
  150. package/node_modules/@litcodex/lit-loop/dist/reentry.js +171 -0
  151. package/node_modules/@litcodex/lit-loop/dist/route-context.js +5 -2
  152. package/node_modules/@litcodex/lit-loop/dist/route-heads.js +35 -15
  153. package/node_modules/@litcodex/lit-loop/dist/skill-mention-scope.js +2 -0
  154. package/node_modules/@litcodex/lit-loop/dist/trigger.d.ts +2 -2
  155. package/node_modules/@litcodex/lit-loop/dist/trigger.js +17 -6
  156. package/node_modules/@litcodex/lit-loop/dist/workflow-map.js +1 -0
  157. package/node_modules/@litcodex/lit-loop/package.json +1 -1
  158. package/node_modules/@litcodex/lit-loop/skills/browser-drive/scripts/capability-probe.mjs +24 -4
  159. package/node_modules/@litcodex/lit-loop/skills/deep-interview/SKILL.md +3 -1
  160. package/node_modules/@litcodex/lit-loop/skills/lit-brainstorm/SKILL.md +271 -0
  161. package/node_modules/@litcodex/lit-loop/skills/lit-loop/SKILL.md +8 -1
  162. package/node_modules/@litcodex/lit-loop/skills/litgoal/SKILL.md +8 -3
  163. package/node_modules/@litcodex/lit-loop/skills/review-work/SKILL.md +21 -4
  164. package/package.json +2 -2
  165. package/readme-assets/badge-version.svg +1 -1
  166. package/readme-assets/cover-motion-still.webp +0 -0
  167. package/readme-assets/cover-motion.webp +0 -0
  168. package/readme-assets/cover.webp +0 -0
  169. package/readme-assets/litfamily-machines.png +0 -0
  170. package/readme-assets/skills/lit-brainstorm.webp +0 -0
@@ -0,0 +1,69 @@
1
+ // The cover's review sheet: twelve decoded frames above a frame-difference plot of the whole loop (one
2
+ // point per grid step, with the still threshold and the median drawn in). The plot shows what single
3
+ // stills cannot: holds lie flat on the still line, encoder pops are regular spikes, a reset is a spike
4
+ // at the right end. `marks` shades spans on the plot (a logged defect's window). The sheet is laid out
5
+ // as an HTML page and captured by headless Chrome, so its captions are real type; it is a review
6
+ // artifact and never feeds a gate.
7
+ import { mkdirSync, rmSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { COVER } from "./constants.mjs";
10
+ import { launchCover } from "./driver.mjs";
11
+ import { downscale, encodePng } from "./image.mjs";
12
+
13
+ const esc = (s) => String(s).replace(/[&<>"]/gu, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
14
+ const TILE_W = 400;
15
+ const COLUMNS = 4;
16
+
17
+ /** The sheet as one HTML page: tiles [{ png, caption }] four to a row, then the plot of `diffs`. */
18
+ export function sheetPage({ tiles, tileHeight, diffs, medianD, label, status, marks = [], durationSec }) {
19
+ const pad = 8;
20
+ const caption = 22;
21
+ const rows = Math.ceil(tiles.length / COLUMNS);
22
+ const width = COLUMNS * TILE_W + (COLUMNS + 1) * pad;
23
+ const plotTop = rows * (tileHeight + caption + pad) + pad + 10;
24
+ const plotH = 170;
25
+ const height = plotTop + plotH + 44;
26
+ const plotW = width - 2 * pad;
27
+ const top = Math.max(0.01, ...diffs) * 1.05;
28
+ const x = (i) => pad + (i / Math.max(1, diffs.length - 1)) * plotW;
29
+ const y = (v) => plotTop + plotH - (v / top) * plotH;
30
+ const at = (sec) => pad + (sec / durationSec) * plotW;
31
+ const cells = tiles
32
+ .map((tile, k) => {
33
+ const left = pad + (k % COLUMNS) * (TILE_W + pad);
34
+ const head = pad + Math.floor(k / COLUMNS) * (tileHeight + caption + pad);
35
+ return `<div class="cap" style="left:${left}px;top:${head}px">${esc(tile.caption)}</div><img src="data:image/png;base64,${tile.png.toString("base64")}" style="left:${left}px;top:${head + caption}px;width:${TILE_W}px;height:${tileHeight}px">`;
36
+ })
37
+ .join("\n");
38
+ const shaded = marks.map((m) => `<rect x="${at(m.t0).toFixed(1)}" y="${plotTop}" width="${Math.max(2, at(m.t1) - at(m.t0)).toFixed(1)}" height="${plotH}" fill="#ffb02e" opacity="0.18"/>`).join("");
39
+ const line = diffs.map((v, i) => `${x(i).toFixed(1)},${y(v).toFixed(1)}`).join(" ");
40
+ const html = `<!doctype html><meta charset="utf-8"><style>html,body{margin:0;width:${width}px;height:${height}px;overflow:hidden;background:#080b10}
41
+ img{position:absolute;display:block}.cap{position:absolute;font:13px ui-monospace,Menlo,monospace;color:#9aa}
42
+ .foot{position:absolute;left:${pad}px;top:${plotTop + plotH + 12}px;font:14px ui-monospace,Menlo,monospace;color:#ccd;white-space:nowrap}</style>
43
+ <body>${cells}<svg width="${width}" height="${height}" style="position:absolute;left:0;top:0"><rect x="${pad}" y="${plotTop}" width="${plotW}" height="${plotH}" fill="#11161d"/>${shaded}
44
+ <line x1="${pad}" x2="${pad + plotW}" y1="${y(COVER.stillEps)}" y2="${y(COVER.stillEps)}" stroke="#a33" stroke-dasharray="4 4"/>
45
+ <line x1="${pad}" x2="${pad + plotW}" y1="${y(medianD)}" y2="${y(medianD)}" stroke="#5a8" stroke-dasharray="2 3"/>
46
+ <polyline points="${line}" fill="none" stroke="#ff7a46" stroke-width="1.5"/></svg><div class="foot">${esc(label)} | ${esc(status)}</div></body>`;
47
+ return { html, width, height };
48
+ }
49
+
50
+ /**
51
+ * Render the sheet to `file`. `tiles` are [{ rgba, width, height, caption }] at the cover size; each is
52
+ * box-downscaled to 400 px wide before it goes into the page.
53
+ */
54
+ export async function renderSheet({ file, tiles, diffs, medianD, label, status, marks, durationSec, runtime, workDir, env }) {
55
+ const tileHeight = Math.round((TILE_W * tiles[0].height) / tiles[0].width);
56
+ const small = tiles.map((t) => ({ caption: t.caption, png: encodePng(TILE_W, tileHeight, downscale(t.rgba, t.width, t.height, TILE_W, tileHeight), 4, 3) }));
57
+ const { html, width, height } = sheetPage({ tiles: small, tileHeight, diffs, medianD, label, status, marks, durationSec });
58
+ mkdirSync(workDir, { recursive: true });
59
+ const { context, page } = await launchCover({ runtime, width, height, scale: 1, profileDir: join(workDir, "chrome"), env });
60
+ try {
61
+ await page.setContent(html, { waitUntil: "load" });
62
+ await page.evaluate(() => Promise.all([...document.images].map((img) => img.decode())));
63
+ writeFileSync(file, await page.screenshot({ clip: { x: 0, y: 0, width, height }, type: "png" }));
64
+ } finally {
65
+ await context.close().catch(() => {});
66
+ rmSync(workDir, { recursive: true, force: true });
67
+ }
68
+ return file;
69
+ }
@@ -0,0 +1,102 @@
1
+ // The cover treatment: `treatment.json` with `"mode": "cover"`, written before the first cover render
2
+ // and validated by every one (exit 16 names the first bad field). A cover is not a film: no beats, no
3
+ // arc, no ending, no copy lines, no sound. It names one recipe, one rule and its copies, the three speed
4
+ // layers, the brand word set once (plus at most one motto the user or the project already uses), the
5
+ // aspect and loop length, and the title box the contrast and cap-height gates measure. Every string in
6
+ // it is the user's content or the director's plan, never an instruction.
7
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { COVER } from "./constants.mjs";
10
+ import { findPlaceholder, normalizeText, sharesRun, stripQuoted, TreatmentError } from "./treatment.mjs";
11
+
12
+ export const RECIPES = Object.freeze(["painted-light", "weight-tide", "orbit-loop", "own"]);
13
+ export const LAYERS = Object.freeze(["slow", "mid", "beat"]);
14
+
15
+ const fault = (field, message) => {
16
+ throw new TreatmentError(field, message);
17
+ };
18
+ const isText = (value) => typeof value === "string" && value.trim().length > 0;
19
+ const sentences = (text) => String(text).trim().split(/(?<=[.!?。])\s+(?=\S)/u).filter(Boolean).length;
20
+ const words = (text) => String(text).trim().split(/\s+/u).filter(Boolean).length;
21
+ const isBox = (b) => Array.isArray(b) && b.length === 4 && b.every((v) => typeof v === "number" && v >= 0 && v <= 1);
22
+
23
+ function text(t, path, { maxSentences } = {}) {
24
+ const value = path.split(".").reduce((node, key) => (node && typeof node === "object" ? node[key] : undefined), t);
25
+ if (value === undefined || value === null) fault(path, "missing");
26
+ if (!isText(value)) fault(path, "must be a non-empty string");
27
+ if (maxSentences && sentences(value) > maxSentences) fault(path, `at most ${maxSentences} sentence${maxSentences > 1 ? "s" : ""}`);
28
+ return value;
29
+ }
30
+
31
+ /** Validate a cover treatment. Returns it with the page and cover sizes, frame count, encode and seed filled in. */
32
+ export function validateCoverTreatment(t) {
33
+ if (!t || typeof t !== "object" || Array.isArray(t)) fault("treatment", "must be a JSON object");
34
+ if (t.mode !== "cover") fault("mode", 'must be "cover" for a cover render');
35
+ const placeholder = findPlaceholder(t, "");
36
+ if (placeholder) fault(placeholder, "still holds an example placeholder (<...>); write the real value");
37
+ const request = text(t, "request");
38
+ const idea = text(t, "idea", { maxSentences: 1 });
39
+ const unquoted = normalizeText(stripQuoted(request));
40
+ const limit = Math.min(10, Math.floor(Array.from(unquoted).length / 2));
41
+ if (sharesRun(idea, stripQuoted(request), limit)) fault("idea", `restates the request (shares ${limit}+ normalized characters with it); say what the loop does`);
42
+ if (!RECIPES.includes(t.recipe)) fault("recipe", t.recipe === undefined ? "missing" : `must be one of ${RECIPES.join(", ")}`);
43
+ text(t, "recipeReason", { maxSentences: 2 });
44
+ const brand = text(t, "brandWord");
45
+ if (words(brand) > 3) fault("brandWord", "is the name set once: at most three words");
46
+ if ("motto" in t) {
47
+ if (!t.motto || typeof t.motto !== "object") fault("motto", "must be { text, source, from? }");
48
+ const motto = text(t, "motto.text");
49
+ if (words(motto) > 6) fault("motto.text", "at most six words");
50
+ if (!["user", "project"].includes(t.motto.source)) fault("motto.source", "must be user (it is in the request) or project (the project already uses it; name where in from)");
51
+ if (t.motto.source === "user" && !normalizeText(request).includes(normalizeText(motto))) fault("motto.text", "a user motto must appear in the request; a cover never invents a tagline");
52
+ if (t.motto.source === "project") text(t, "motto.from");
53
+ }
54
+ for (const key of ["copy", "beats", "lines"]) if (key in t) fault(key, "a cover has no copy lines and no beats: the brand word is set once and never swapped (references/cover.md)");
55
+ if ("sound" in t && t.sound !== "none") fault("sound", 'a cover is silent: leave sound out or set it to "none"');
56
+ if (!(t.aspect in COVER.aspects)) fault("aspect", `must be ${Object.keys(COVER.aspects).join(" or ")}`);
57
+ if (typeof t.loopSec !== "number" || !(t.loopSec >= COVER.minSec && t.loopSec <= COVER.maxSec)) fault("loopSec", `must be ${COVER.minSec} to ${COVER.maxSec} seconds`);
58
+ if (!COVER.fps.includes(t.fps)) fault("fps", `must be one of ${COVER.fps.join(", ")}`);
59
+ if (!t.layers || typeof t.layers !== "object") fault("layers", "missing: name what moves on the slow, mid and beat layers");
60
+ for (const layer of LAYERS) text(t, `layers.${layer}`, { maxSentences: 2 });
61
+ if (!t.system || typeof t.system !== "object") fault("system", "missing: the one rule, its copies and where their offsets come from");
62
+ for (const key of ["rule", "copies", "offset"]) text(t, `system.${key}`, { maxSentences: 2 });
63
+ if (!t.title || typeof t.title !== "object") fault("title", "missing: { box: [x, y, w, h] as fractions of the cover, kind: live or painted }");
64
+ const box = t.title.box;
65
+ if (!isBox(box)) fault("title.box", "must be [x, y, w, h], each a fraction 0..1 of the cover");
66
+ if (box[2] <= 0 || box[3] <= 0 || box[0] + box[2] > 1 + 1e-9 || box[1] + box[3] > 1 + 1e-9) fault("title.box", "must lie inside the cover");
67
+ if (!["live", "painted"].includes(t.title.kind)) fault("title.kind", "must be live (set as text on the page) or painted (part of the base art)");
68
+ if ("palette" in t) {
69
+ if (!Array.isArray(t.palette) || t.palette.length < 2 || t.palette.length > 6) fault("palette", "2 to 6 { color, role } entries");
70
+ t.palette.forEach((entry, i) => {
71
+ if (!/^#[0-9a-f]{6}$/iu.test(entry?.color ?? "")) fault(`palette[${i}].color`, "must be #rrggbb");
72
+ if (!isText(entry?.role)) fault(`palette[${i}].role`, "must say the colour's job");
73
+ });
74
+ }
75
+ if ("encode" in t) {
76
+ if (!t.encode || typeof t.encode !== "object") fault("encode", "must be { q, edgeQ, edgeFrames }");
77
+ for (const [key, lo, hi] of [["q", 50, 100], ["edgeQ", 50, 100], ["edgeFrames", 0, 60]]) if (key in t.encode && !(Number.isInteger(t.encode[key]) && t.encode[key] >= lo && t.encode[key] <= hi)) fault(`encode.${key}`, `an integer ${lo} to ${hi}`);
78
+ }
79
+ text(t, "ambition", { maxSentences: 2 });
80
+ const { page, size } = COVER.aspects[t.aspect];
81
+ return { ...t, page: [...page], size: [...size], frames: Math.round(t.loopSec * t.fps), encode: { ...COVER.encode, ...(t.encode ?? {}) }, seed: Number.isInteger(t.seed) ? t.seed >>> 0 : 20261020 };
82
+ }
83
+
84
+ /** Read and validate `<outDir>/treatment.json` as a cover; the first valid one is kept for the record. */
85
+ export function loadCoverTreatment(outDir) {
86
+ const file = join(outDir, "treatment.json");
87
+ if (!existsSync(file)) fault("treatment", `no treatment.json at ${file}; write it before any cover render (references/cover.md)`);
88
+ let raw;
89
+ try {
90
+ raw = JSON.parse(readFileSync(file, "utf8"));
91
+ } catch (error) {
92
+ fault("treatment", `not valid JSON (${error.message})`);
93
+ }
94
+ if (raw?.mode !== "cover") fault("mode", "this treatment is a film: render it with stage or film (references/treatment.md); a cover sets \"mode\": \"cover\"");
95
+ const treatment = validateCoverTreatment(raw);
96
+ const first = join(outDir, ".run", "treatment-first.json");
97
+ if (!existsSync(first)) {
98
+ mkdirSync(join(outDir, ".run"), { recursive: true });
99
+ writeFileSync(first, `${JSON.stringify(raw, null, 2)}\n`);
100
+ }
101
+ return treatment;
102
+ }
@@ -0,0 +1,21 @@
1
+ // Cover frame worker: decode one 2x capture, Lanczos-downsample it to the cover size, write it as an
2
+ // RGB PNG (the encoder's input, and what G0 and the seek-order check hash) and return that PNG's
3
+ // SHA-256 with the captured size, so the capture thread only steps the page.
4
+ import { createHash } from "node:crypto";
5
+ import { writeFileSync } from "node:fs";
6
+ import { parentPort } from "node:worker_threads";
7
+ import { lanczosResize } from "./cover-image.mjs";
8
+ import { decodePng, encodePng } from "./image.mjs";
9
+
10
+ parentPort.on("message", ({ id, png, width, height, file }) => {
11
+ try {
12
+ const shot = decodePng(Buffer.from(png));
13
+ if (shot.channels !== 4) throw new Error(`capture has ${shot.channels} channel(s); expected RGB or RGBA`);
14
+ const small = lanczosResize(shot.pixels, shot.width, shot.height, width, height);
15
+ const bytes = encodePng(width, height, small, 4, 1);
16
+ if (file) writeFileSync(file, bytes);
17
+ parentPort.postMessage({ id, sha256: createHash("sha256").update(bytes).digest("hex"), captured: `${shot.width}x${shot.height}` });
18
+ } catch (error) {
19
+ parentPort.postMessage({ id, error: String(error?.message ?? error) });
20
+ }
21
+ });
@@ -0,0 +1,352 @@
1
+ // Cover mode orchestration (references/cover.md). One round: the cover treatment -> the static scan of
2
+ // cover/ -> assets.json (exit 22 for a missing asset, before any capture) -> fonts -> a master Chrome
3
+ // seeks t = i / N for every frame at 2x, the pool downsamples each to the cover size, and the same
4
+ // page draws the title mask -> a fresh Chrome repeats every frame (G0) -> another fresh Chrome renders
5
+ // a seeded shuffle of frames, which must match the master (a page that keeps state between frames
6
+ // fails here, exit 18) -> the flash audit on the frames, looped -> img2webp with frame 0 and the
7
+ // frames before the seam at a higher quality, or gifski when libwebp is missing -> the cover gate on
8
+ // the DECODED file with the cap-height floor and frame 0's base art -> stills (decoded sheet frames,
9
+ // poster, seam pair) and the review sheet -> manifest and report. A flash FAIL withholds the cover.
10
+ // `--window t0,t1` captures and sheets only the frames around a logged defect; it never counts as done.
11
+ import { spawnSync } from "node:child_process";
12
+ import { createHash } from "node:crypto";
13
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
14
+ import { basename, join } from "node:path";
15
+ import { COVER, EXIT, Exit, INSTALL_COMMAND } from "./constants.mjs";
16
+ import { artCheck, checkAssets, readRaster } from "./cover-assets.mjs";
17
+ import { CoverPool, CoverSession, capturePass } from "./cover-capture.mjs";
18
+ import { coverGate, formatCoverReport, frameFiles, readPngRgba, verdictOf } from "./cover-gate.mjs";
19
+ import { lumaGrid } from "./cover-image.mjs";
20
+ import { renderSheet } from "./cover-sheet.mjs";
21
+ import { loadCoverTreatment } from "./cover-treatment.mjs";
22
+ import { countFlashes, detectLoopingStream } from "./flash.mjs";
23
+ import { FONTS, verifyFonts } from "./fonts.mjs";
24
+ import { encodePng } from "./image.mjs";
25
+ import { resolveRuntime, which } from "./runtime.mjs";
26
+ import { fontRoutes, scanStage, stageFontFaults } from "./stage.mjs";
27
+ import { TreatmentError } from "./treatment.mjs";
28
+ import { findDwebp, findImg2webp } from "./webp.mjs";
29
+
30
+ export const COVER_DIR = "cover";
31
+ export const COVER_OUTPUTS = Object.freeze(["cover.webp", "cover.gif", "poster.png", "manifest.json", "gate-report.txt"]);
32
+
33
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
34
+ const pad4 = (n) => String(n).padStart(4, "0");
35
+ const writeJson = (file, value) => writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);
36
+
37
+ /** Display time of one frame in whole milliseconds, as img2webp stores it. */
38
+ export const frameMs = (fps) => Math.round(1000 / fps);
39
+
40
+ /** Loop times on the master grid: frame i shows t = i / N, so t = 1 (a copy of frame 0) is never drawn. */
41
+ export const loopTimes = (frames) => Array.from({ length: frames }, (_, i) => [i, i / frames]);
42
+
43
+ /** The decoded frame on screen at `ms`, given per-frame durations. */
44
+ export function frameAt(durations, ms) {
45
+ let end = 0;
46
+ for (let i = 0; i < durations.length; i++) {
47
+ end += durations[i];
48
+ if (ms < end) return i;
49
+ }
50
+ return durations.length - 1;
51
+ }
52
+
53
+ /** img2webp arguments: lossy, loop forever, default keyframes, frame 0 and the last `edgeFrames` at `edgeQ`. */
54
+ export function img2webpArgs({ files, fps, encode, out }) {
55
+ const args = ["-loop", "0", "-lossy", "-q", String(encode.q), "-m", String(encode.method)];
56
+ files.forEach((file, i) => args.push("-d", String(frameMs(fps)), "-q", String(i === 0 || i >= files.length - encode.edgeFrames ? encode.edgeQ : encode.q), file));
57
+ return [...args, "-o", out];
58
+ }
59
+
60
+ /** The encoder this host offers: img2webp with dwebp (the gate decodes with it), else gifski, else exit 21. */
61
+ export function coverEncoder(env = process.env) {
62
+ const img2webp = findImg2webp(env);
63
+ const dwebp = findDwebp(env);
64
+ if (img2webp && dwebp) return { kind: "img2webp", path: img2webp };
65
+ const gifski = which("gifski", env);
66
+ if (gifski) return { kind: "gifski", path: gifski };
67
+ throw new Exit(EXIT.BLOCKED_NO_COVER_ENCODER, "BLOCKED_NO_COVER_ENCODER: install libwebp (img2webp and dwebp) or gifski; a cover is never an MP4, because a README does not autoplay video");
68
+ }
69
+
70
+ /** Encode the frames into `<outDir>/cover.webp` (or cover.gif). */
71
+ export function encodeCover({ files, fps, encode, outDir, env = process.env }) {
72
+ const encoder = coverEncoder(env);
73
+ const file = join(outDir, encoder.kind === "img2webp" ? "cover.webp" : "cover.gif");
74
+ const args = encoder.kind === "img2webp" ? img2webpArgs({ files, fps, encode, out: file }) : ["--fps", String(fps), "--quality", "90", "--repeat", "0", "-o", file, ...files];
75
+ const run = spawnSync(encoder.path, args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024, env });
76
+ if (run.status !== 0) throw new Error(`${encoder.kind} failed: ${(run.stderr || run.error?.message || `exit ${run.status}`).trim().split("\n").pop()}`);
77
+ return { file, encoder: encoder.kind };
78
+ }
79
+
80
+ /** A seeded shuffle (mulberry32, as the loop kit's rng) of `count` distinct frame indices. */
81
+ export function seekOrder(frames, seed, count = COVER.seekFrames) {
82
+ let state = seed >>> 0;
83
+ const next = () => {
84
+ state = (state + 0x6d2b79f5) >>> 0;
85
+ let x = Math.imul(state ^ (state >>> 15), 1 | state);
86
+ x = (x + Math.imul(x ^ (x >>> 7), 61 | x)) ^ x;
87
+ return ((x ^ (x >>> 14)) >>> 0) / 4294967296;
88
+ };
89
+ const order = Array.from({ length: frames }, (_, i) => i);
90
+ for (let i = frames - 1; i > 0; i--) {
91
+ const j = Math.floor(next() * (i + 1));
92
+ [order[i], order[j]] = [order[j], order[i]];
93
+ }
94
+ return order.slice(0, Math.min(count, frames));
95
+ }
96
+
97
+ /** The largest per-channel difference between two same-size PNG frames (255 when the sizes differ). */
98
+ export function maxLevelDiff(fileA, fileB) {
99
+ const a = readPngRgba(fileA);
100
+ const b = readPngRgba(fileB);
101
+ if (a.width !== b.width || a.height !== b.height) return 255;
102
+ let max = 0;
103
+ for (let i = 0; i < a.rgba.length; i++) max = Math.max(max, Math.abs(a.rgba[i] - b.rgba[i]));
104
+ return max;
105
+ }
106
+
107
+ /** Everything a cover round checks before the first capture: treatment, page, assets, runtime, fonts. */
108
+ function prepare(outDir) {
109
+ let treatment;
110
+ try {
111
+ treatment = loadCoverTreatment(outDir);
112
+ } catch (error) {
113
+ if (error instanceof TreatmentError) throw new Exit(EXIT.BLOCKED_TREATMENT_INVALID, `BLOCKED_TREATMENT_INVALID: ${error.message}`);
114
+ throw error;
115
+ }
116
+ const coverDir = join(outDir, COVER_DIR);
117
+ if (!existsSync(join(coverDir, "index.html"))) throw new Exit(EXIT.STAGE_CONTRACT_ERROR, `STAGE_CONTRACT_ERROR: no cover/index.html in ${outDir}; write the cover page first (references/cover.md)`);
118
+ const scan = scanStage(coverDir);
119
+ const { assets } = checkAssets({ outDir, treatment, files: scan.files, coverDir: COVER_DIR });
120
+ const runtime = resolveRuntime();
121
+ if (!runtime.deps.ready) throw new Exit(EXIT.BLOCKED_DEPS_NOT_PREWARMED, `BLOCKED_DEPS_NOT_PREWARMED: ${runtime.deps.missing.join("; ")}. Run \`${INSTALL_COMMAND}\` outside the sandboxed session, then rerun.`);
122
+ stageFontFaults(verifyFonts(FONTS.map((f) => f.key), runtime.dir));
123
+ return { treatment, scan, assets, runtime, fonts: fontRoutes(runtime.dir) };
124
+ }
125
+
126
+ /** The cover stills (frames decoded from the encoded file): twelve sheet frames, the poster and the seam pair. */
127
+ function writeCoverStills({ outDir, durations, kept, width, height }) {
128
+ const dir = join(outDir, "stills");
129
+ rmSync(dir, { recursive: true, force: true });
130
+ mkdirSync(dir, { recursive: true });
131
+ const total = durations.reduce((a, b) => a + b, 0);
132
+ const files = [];
133
+ const put = (name, bytes, entry) => {
134
+ writeFileSync(join(dir, name), bytes);
135
+ files.push({ file: name, sha256: sha256(bytes), ...entry });
136
+ };
137
+ const tiles = [];
138
+ for (let k = 0; k < COVER.sheetTiles; k++) {
139
+ const t = k / COVER.sheetTiles;
140
+ const frame = frameAt(durations, t * total);
141
+ put(`frame-${String(k).padStart(2, "0")}.png`, encodePng(width, height, kept.get(frame), 4, 6), { kind: "frame", t: Number(t.toFixed(4)), frame });
142
+ tiles.push({ rgba: kept.get(frame), width, height, caption: `t=${t.toFixed(3)} frame ${frame}` });
143
+ }
144
+ const last = durations.length - 1;
145
+ put("poster.png", encodePng(width, height, kept.get(0), 4, 6), { kind: "poster", frame: 0 });
146
+ const pair = Buffer.alloc(width * 2 * height * 4);
147
+ for (let y = 0; y < height; y++) {
148
+ pair.set(kept.get(last).subarray(y * width * 4, (y + 1) * width * 4), y * width * 8);
149
+ pair.set(kept.get(0).subarray(y * width * 4, (y + 1) * width * 4), y * width * 8 + width * 4);
150
+ }
151
+ put("seam.png", encodePng(width * 2, height, pair, 4, 6), { kind: "seam", frames: [last, 0] });
152
+ return { dir, files, tiles };
153
+ }
154
+
155
+ /**
156
+ * Render one cover round. Returns the exit code: 0 when the decoded cover reaches every TARGET gate,
157
+ * 13 when a gate misses TARGET or FLOOR or the flash audit fails (the cover is then withheld).
158
+ */
159
+ export async function renderCover({ outDir, round, log = () => {}, env = process.env }) {
160
+ if (!Number.isInteger(round) || round < 1 || round > 3) throw new Exit(EXIT.USAGE, "--round must be 1..3");
161
+ const { treatment, scan, assets, runtime, fonts } = prepare(outDir);
162
+ coverEncoder(env);
163
+ for (const name of COVER_OUTPUTS) rmSync(join(outDir, name), { force: true });
164
+ rmSync(join(outDir, "withheld"), { recursive: true, force: true });
165
+ const [pw, ph] = treatment.page;
166
+ const size = treatment.size;
167
+ const runDir = join(outDir, ".run", "cover");
168
+ rmSync(runDir, { recursive: true, force: true });
169
+ const dirs = { frames: join(runDir, "frames"), masks: join(runDir, "masks"), replay: join(runDir, "replay"), seek: join(runDir, "seek") };
170
+ for (const dir of Object.values(dirs)) mkdirSync(dir, { recursive: true });
171
+ const times = loopTimes(treatment.frames);
172
+ const order = seekOrder(times.length, treatment.seed);
173
+ const started = Date.now();
174
+ const pool = new CoverPool();
175
+ let master;
176
+ let replay;
177
+ let sought;
178
+ try {
179
+ const pass = async (label, work) => {
180
+ const session = await CoverSession.open({ runtime, scan, fonts, width: pw, height: ph, scale: COVER.captureScale, profileDir: join(runDir, `chrome-${label}`), env });
181
+ try {
182
+ return await work(session);
183
+ } finally {
184
+ await session.close();
185
+ }
186
+ };
187
+ master = await pass("master", async (session) => {
188
+ const hashes = await capturePass({ session, pool, times, dir: dirs.frames, size });
189
+ log(`cover: ${times.length} frames captured at ${pw * COVER.captureScale}x${ph * COVER.captureScale} and downsampled to ${size.join("x")}`);
190
+ await capturePass({ session, pool, times, dir: dirs.masks, prefix: "m", mask: true, size });
191
+ return hashes;
192
+ });
193
+ replay = await pass("replay", (session) => capturePass({ session, pool, times, dir: dirs.replay, size }));
194
+ sought = await pass("seek", (session) => capturePass({ session, pool, times: order.map((i) => times[i]), dir: dirs.seek, prefix: "s", size }));
195
+ } finally {
196
+ await pool.close();
197
+ }
198
+ const captureSec = (Date.now() - started) / 1000;
199
+ const ms = frameMs(treatment.fps);
200
+ const differing = times.filter(([i]) => master.get(i) !== replay.get(i)).map(([i, t]) => `frame ${i} (t = ${t.toFixed(4)})`);
201
+ if (differing.length) throw new Exit(EXIT.STAGE_NONDETERMINISTIC, `STAGE_NONDETERMINISTIC: a fresh capture differs at ${differing.slice(0, 4).join(", ")}${differing.length > 4 ? ` (+${differing.length - 4})` : ""}; draw every pixel from t and LitLoop.rng(seed)`);
202
+ // A sought frame within one level per channel of the master is the software rasterizer's own
203
+ // rounding (opacity and transform changing together depend on what was painted before); state kept
204
+ // between frames differs by far more.
205
+ let oneLevel = 0;
206
+ for (const [k, i] of order.entries()) {
207
+ if (sought.get(i) === master.get(i)) continue;
208
+ const levels = maxLevelDiff(join(dirs.frames, `f${pad4(i)}.png`), join(dirs.seek, `s${pad4(i)}.png`));
209
+ if (levels <= COVER.seekLevels) {
210
+ oneLevel++;
211
+ continue;
212
+ }
213
+ throw new Exit(EXIT.STAGE_NONDETERMINISTIC, `STAGE_NONDETERMINISTIC: frame ${i} (t = ${((i * ms) / 1000).toFixed(3)} s) differs by up to ${levels} levels when sought out of order (a fresh page drew it ${k ? `after frame ${order[k - 1]}` : "first"}); the page keeps state between frames: clear every canvas and draw each frame from t alone`);
214
+ }
215
+
216
+ const files = frameFiles(dirs.frames, "f");
217
+ const [cw, ch] = size;
218
+ const flash = countFlashes(await detectLoopingStream(files.length, cw, ch, async (i) => readPngRgba(files[i]).rgba), treatment.fps, true);
219
+ const encoded = encodeCover({ files, fps: treatment.fps, encode: treatment.encode, outDir, env });
220
+ const planned = times.length * ms;
221
+ const wanted = Array.from({ length: COVER.sheetTiles }, (_, k) => (k / COVER.sheetTiles) * planned);
222
+ let elapsed = 0;
223
+ const keep = (i, dur) => {
224
+ const start = elapsed;
225
+ elapsed += dur;
226
+ return i === 0 || start + dur >= planned || wanted.some((x) => x >= start && x < start + dur);
227
+ };
228
+ const painted = treatment.title.kind === "painted" ? assets.find((a) => a.role === "base-art" && a.title) : null;
229
+ const gate = coverGate(encoded.file, { frames: dirs.frames, frames2: dirs.replay, masks: dirs.masks, title: treatment.title.box, glyph: { exempt: painted ? `painted into the base art ${painted.path}` : null }, fps: treatment.fps, keep, env });
230
+ gate.gates.SEEK = { pass: true, sampled: order.length, identical: order.length - oneLevel, oneLevel };
231
+ for (const asset of assets.filter((a) => a.role === "base-art")) {
232
+ const art = readRaster(join(outDir, asset.path), env);
233
+ const check = art ? artCheck({ frame0: gate.kept.get(0), width: gate.width, height: gate.height, art, box: asset.box, checkBox: asset.checkBox }) : null;
234
+ gate.gates.ART = check ? { pass: check.pass, ssim: check.ssim, checked: check.checked.join(",") } : { pass: false, reason: `${asset.path} could not be decoded to compare with frame 0` };
235
+ }
236
+ gate.gates.FLASH = { pass: flash.pass, generalFlashes: flash.general.flashes, redFlashes: flash.red.flashes, worstStartFrame: flash.general.startFrame };
237
+ gate.pass = Object.values(gate.gates).every((g) => g.pass !== false);
238
+ gate.target = gate.pass && Object.values(gate.gates).every((g) => g.target !== false);
239
+
240
+ const stills = writeCoverStills({ outDir, durations: gate.durations, kept: gate.kept, width: gate.width, height: gate.height });
241
+ const status = Object.entries(gate.gates).map(([k, g]) => `${k}:${g.pass === false ? "FAIL" : g.target === false ? "floor" : "ok"}`).join(" ");
242
+ const sheetFile = join(stills.dir, "sheet.png");
243
+ await renderSheet({
244
+ file: sheetFile,
245
+ tiles: stills.tiles,
246
+ diffs: gate.diffs,
247
+ medianD: gate.medianD,
248
+ durationSec: gate.durationSec,
249
+ label: `median d ${gate.medianD.toFixed(5)} | moving ${(100 * gate.movingFrac).toFixed(0)}% | longest still ${gate.longestStillSec.toFixed(2)} s | spike ${gate.spike.toFixed(1)} | seam ${gate.seamLocal.toFixed(2)}x local | ${(gate.bytes / 1048576).toFixed(2)} MiB`,
250
+ status,
251
+ runtime,
252
+ workDir: join(runDir, "sheet"),
253
+ env,
254
+ });
255
+ const sheetBytes = readFileSync(sheetFile);
256
+ stills.files.push({ file: "sheet.png", sha256: sha256(sheetBytes), kind: "sheet" });
257
+ const stillsManifest = `${JSON.stringify({ schema: 1, kind: "cover", mode: "cover", round, width: gate.width, height: gate.height, fps: treatment.fps, durationSec: gate.sourceDurationSec, files: stills.files }, null, 2)}\n`;
258
+ writeFileSync(join(stills.dir, "manifest.json"), stillsManifest);
259
+ writeFileSync(join(outDir, "poster.png"), readFileSync(join(stills.dir, "poster.png")));
260
+ const report = formatCoverReport(gate, { strict: true });
261
+ writeFileSync(join(outDir, "gate-report.txt"), report);
262
+ const manifest = {
263
+ schemaVersion: 1,
264
+ path: "cover",
265
+ mode: "cover",
266
+ round,
267
+ recipe: treatment.recipe,
268
+ treatmentSha256: sha256(readFileSync(join(outDir, "treatment.json"))),
269
+ stillsManifestSha256: sha256(stillsManifest),
270
+ page: treatment.page,
271
+ size,
272
+ scale: COVER.captureScale,
273
+ fps: treatment.fps,
274
+ frames: times.length,
275
+ frameMs: ms,
276
+ encoder: encoded.encoder,
277
+ encode: treatment.encode,
278
+ file: basename(encoded.file),
279
+ bytes: statSync(encoded.file).size,
280
+ captureSec: Math.round(captureSec * 10) / 10,
281
+ gate: { verdict: verdictOf(gate), pass: gate.pass, target: gate.target, medianD: gate.medianD, movingFrac: gate.movingFrac, longestStillSec: gate.longestStillSec, spike: gate.spike, seamLocal: gate.seamLocal, gates: gate.gates },
282
+ generatedAt: new Date().toISOString(),
283
+ };
284
+ writeJson(join(outDir, "manifest.json"), manifest);
285
+ if (!flash.pass) {
286
+ mkdirSync(join(outDir, "withheld"), { recursive: true });
287
+ renameSync(encoded.file, join(outDir, "withheld", basename(encoded.file)));
288
+ rmSync(join(outDir, "poster.png"), { force: true });
289
+ }
290
+ log(report.trimEnd());
291
+ log(`cover: ${manifest.file} ${manifest.bytes} bytes, ${times.length} frames at ${treatment.fps} fps, ${size.join("x")}, captured in ${captureSec.toFixed(0)} s; stills and sheet in ${stills.dir}`);
292
+ if (gate.target) return EXIT.OK;
293
+ const missed = Object.entries(gate.gates).filter(([, g]) => g.pass === false || g.target === false).map(([k]) => k);
294
+ throw new Exit(EXIT.GATE_FAIL_QA, `GATE_FAIL_QA: ${missed.join(", ")} ${gate.pass ? "miss the cover TARGET" : "fail"}${flash.pass ? "" : "; the flash audit failed, so the cover is withheld in withheld/"}. Fix the cause and render round ${Math.min(3, round + 1)}; never raise a number, shorten the loop or drop a layer to pass. Report: ${join(outDir, "gate-report.txt")}`);
295
+ }
296
+
297
+ /**
298
+ * `--window t0,t1` (seconds into the loop): capture only the frames from t0 - 0.5 s to t1 + 0.5 s
299
+ * (wrapping at the seam) in a fresh page and sheet them with the span shaded. It reads the same
300
+ * treatment, page and asset list as a full render and writes only under windows/round-N/; stills,
301
+ * cover file, report and manifest stay untouched, so a window render never counts as done.
302
+ */
303
+ export async function renderCoverWindow({ outDir, round, window: [t0, t1], log = () => {}, env = process.env }) {
304
+ const { treatment, scan, runtime, fonts } = prepare(outDir);
305
+ const ms = frameMs(treatment.fps);
306
+ const total = (treatment.frames * ms) / 1000;
307
+ if (!(Number.isFinite(t0) && Number.isFinite(t1) && t0 >= 0 && t1 >= t0 && t1 <= total)) throw new Exit(EXIT.USAGE, `--window takes t0,t1 in seconds with 0 <= t0 <= t1 <= ${total.toFixed(3)}`);
308
+ const lo = t0 - COVER.windowPadSec;
309
+ const hi = t1 + COVER.windowPadSec;
310
+ const picks = [];
311
+ for (let i = 0; i < treatment.frames; i++)
312
+ for (const lap of [-1, 0, 1]) {
313
+ const t = (i * ms) / 1000 + lap * total;
314
+ if (t >= lo - 1e-9 && t <= hi + 1e-9) picks.push({ index: i, t: Number(t.toFixed(3)) });
315
+ }
316
+ picks.sort((a, b) => a.t - b.t);
317
+ const dir = join(outDir, "windows", `round-${round}`, `${t0.toFixed(3)}-${t1.toFixed(3)}`);
318
+ rmSync(dir, { recursive: true, force: true });
319
+ mkdirSync(dir, { recursive: true });
320
+ const size = treatment.size;
321
+ const pool = new CoverPool();
322
+ const session = await CoverSession.open({ runtime, scan, fonts, width: treatment.page[0], height: treatment.page[1], scale: COVER.captureScale, profileDir: join(outDir, ".run", "cover-window-chrome"), env });
323
+ try {
324
+ await capturePass({ session, pool, times: [...new Set(picks.map((p) => p.index))].map((i) => [i, i / treatment.frames]), dir, size });
325
+ } finally {
326
+ await session.close();
327
+ await pool.close();
328
+ }
329
+ const frames = picks.map((p) => readPngRgba(join(dir, `f${pad4(p.index)}.png`)));
330
+ const lumas = frames.map((f) => lumaGrid(f.rgba, f.width, f.height).luma);
331
+ const diffs = lumas.slice(1).map((l, k) => l.reduce((sum, v, i) => sum + Math.abs(v - lumas[k][i]), 0) / l.length / 255);
332
+ const sorted = [...diffs].sort((a, b) => a - b);
333
+ const count = Math.min(COVER.sheetTiles, picks.length);
334
+ const tiles = Array.from({ length: count }, (_, k) => Math.round((k * (picks.length - 1)) / Math.max(1, count - 1))).map((p) => ({ ...frames[p], caption: `t=${picks[p].t.toFixed(3)} s frame ${picks[p].index}` }));
335
+ await renderSheet({
336
+ file: join(dir, "sheet.png"),
337
+ tiles,
338
+ diffs,
339
+ medianD: sorted.length ? sorted[sorted.length >> 1] : 0,
340
+ durationSec: hi - lo,
341
+ marks: [{ t0: t0 - lo, t1: t1 - lo }],
342
+ label: `window ${t0.toFixed(3)}-${t1.toFixed(3)} s (shaded) with ${COVER.windowPadSec} s on each side | ${picks.length} frames before encoding`,
343
+ status: "a window render never counts as done",
344
+ runtime,
345
+ workDir: join(outDir, ".run", "cover-window-sheet"),
346
+ env,
347
+ });
348
+ writeJson(join(dir, "window.json"), { schema: 1, round, t0, t1, padSec: COVER.windowPadSec, frames: picks, note: "frames before encoding; a window render never counts as done" });
349
+ log(`window round ${round}: ${picks.length} frames from ${lo.toFixed(3)} to ${hi.toFixed(3)} s; sheet: ${join(dir, "sheet.png")}`);
350
+ log("a window render never counts as done: fix the cause, then render the full cover");
351
+ return EXIT.OK;
352
+ }
@@ -8,7 +8,7 @@ import { join } from "node:path";
8
8
  import { pathToFileURL } from "node:url";
9
9
  import { EXIT } from "./constants.mjs";
10
10
  import { SKILL_ROOT } from "./fonts.mjs";
11
- import { chromeLadder, findChrome, firstLine, stageFlags } from "./runtime.mjs";
11
+ import { chromeLadder, coverFlags, findChrome, firstLine, stageFlags } from "./runtime.mjs";
12
12
 
13
13
  export class Blocked extends Error {
14
14
  constructor(exit, name, message) {
@@ -100,6 +100,24 @@ export async function launchStage({ runtime, outDir, width, height, env = proces
100
100
  return { context, page, chrome, flags, profileRoot };
101
101
  }
102
102
 
103
+ /**
104
+ * Launch a cover pass's Chrome (or the review sheet's): the stage rung at device scale `scale`, the
105
+ * viewport the cover page's CSS size, a profile at `profileDir`, service workers blocked. The caller
106
+ * installs routes before the first navigation and removes the profile after closing.
107
+ */
108
+ export async function launchCover({ runtime, width, height, scale, profileDir, env = process.env }) {
109
+ const chrome = findChrome(env);
110
+ if (!chrome) throw new Blocked(EXIT.BLOCKED_NO_CHROME, "BLOCKED_NO_CHROME", "Chrome/Chromium not found: install Google Chrome or set CHROME_PATH");
111
+ const { chromium } = await import(pathToFileURL(runtime.playwright).href);
112
+ try {
113
+ const context = await chromium.launchPersistentContext(profileDir, { executablePath: chrome, headless: true, args: coverFlags(width, height, scale), viewport: { width, height }, deviceScaleFactor: scale, serviceWorkers: "block", timeout: 45000 });
114
+ return { context, page: context.pages()[0] ?? (await context.newPage()) };
115
+ } catch (error) {
116
+ rmSync(profileDir, { recursive: true, force: true });
117
+ throw new Blocked(EXIT.BLOCKED_NO_CHROME, "BLOCKED_NO_CHROME", `Chrome failed to launch headless: ${firstLine(error.message.replace(/^browserType\.launchPersistentContext:\s*/u, ""))}`);
118
+ }
119
+ }
120
+
103
121
  /** Open the frame socket; on a refused listen, return the CDP-pull fallback with the real error. */
104
122
  export async function openEgress({ runtime, page, env = process.env }) {
105
123
  let listenError = null;
@@ -62,6 +62,17 @@ export const FONTS = Object.freeze([
62
62
  sha256: "cf4de751ada78ceac033dbe16a687742939995b77bc2a052ae17a4957958594d",
63
63
  licence: ["fonts/vt323/OFL.txt"],
64
64
  },
65
+ {
66
+ // A variable face with a real wght axis (100-800) and a fixed advance: cover-mode weight motion
67
+ // never reflows a line. Unmodified latin subset; no Reserved Font Name.
68
+ key: "jetbrains-mono",
69
+ family: "JetBrains Mono",
70
+ weight: "100 800",
71
+ source: "bundled",
72
+ path: "fonts/jetbrains-mono/JetBrainsMono-wght-latin.woff2",
73
+ sha256: "18be452724bfdc236c074ca94a249a7f41a86752c7d04ab258ce9ed5651f6a7e",
74
+ licence: ["fonts/jetbrains-mono/OFL.txt"],
75
+ },
65
76
  {
66
77
  key: "galmuri9",
67
78
  family: "Galmuri9",