@kriya-ai/harness 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
@@ -0,0 +1,281 @@
1
+ // The motion layer (EDIT_ENGINE §6, EDD-07, EDD-17): blocks and captions become
2
+ // short HyperFrames compositions, each rendered on a transparent background to a
3
+ // ProRes 4444 tile, inside the OS sandbox (ES-05, EDD-44). Springs are computed here
4
+ // and baked into Web Animations keyframes (EX-01): no GSAP (EDD-09), no Remotion
5
+ // (EDD-08), no clock, no network, so one definition drives preview and render.
6
+
7
+ import { existsSync, mkdirSync, realpathSync, writeFileSync } from "node:fs"
8
+ import { join } from "node:path"
9
+
10
+ import { childEnv } from "../runtime/setup.js"
11
+ import { confine, confinement, installOf } from "./confine.js"
12
+ import { EngineFailure, runTool } from "./tool.js"
13
+
14
+ const FLICKS = 705_600_000
15
+
16
+ /* ─────────────────────────────── springs ─────────────────────────────── */
17
+
18
+ /**
19
+ * A damped spring's progress, 0 to 1 (it may overshoot), sampled evenly.
20
+ * @param {{ damping: number, frequency: number, ms: number, steps?: number }} spring damping ratio, angular frequency in rad/s
21
+ */
22
+ export function springCurve({ damping, frequency, ms, steps = 24 }) {
23
+ if (!(damping > 0 && damping < 1)) throw new RangeError("a spring's damping ratio is between 0 and 1")
24
+ const wd = frequency * Math.sqrt(1 - damping * damping)
25
+ const out = []
26
+ for (let i = 0; i <= steps; i++) {
27
+ const t = ((i / steps) * ms) / 1000
28
+ out.push(1 - Math.exp(-damping * frequency * t) * (Math.cos(wd * t) + ((damping * frequency) / wd) * Math.sin(wd * t)))
29
+ }
30
+ out[steps] = 1 // settled by the end, so the last frame is exact
31
+ return out
32
+ }
33
+
34
+ /** Keyframes moving from `from` to `to` (y in px, opacity, scale) along a spring. */
35
+ export function springKeyframes({ from, to, ...spring }) {
36
+ const curve = springCurve(spring)
37
+ const at = (key, u) => (from[key] ?? to[key]) + ((to[key] ?? from[key]) - (from[key] ?? to[key])) * u
38
+ return curve.map((u, i) => {
39
+ const frame = { offset: i / (curve.length - 1) }
40
+ const transform = []
41
+ if ("y" in from || "y" in to) transform.push(`translateY(${at("y", u).toFixed(2)}px)`)
42
+ if ("scale" in from || "scale" in to) transform.push(`scale(${at("scale", u).toFixed(4)})`)
43
+ if (transform.length) frame.transform = transform.join(" ")
44
+ if ("opacity" in from || "opacity" in to) frame.opacity = Math.min(1, Math.max(0, at("opacity", u))).toFixed(4)
45
+ return frame
46
+ })
47
+ }
48
+
49
+ /* ─────────────────────────────── documents ─────────────────────────────── */
50
+
51
+ // No network, no outside script; fonts and images only from the composition itself
52
+ const CSP = "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; font-src 'self' data:; img-src 'self' data:; connect-src 'none'"
53
+ const CSP_META = `<meta http-equiv="Content-Security-Policy" content="${CSP}">`
54
+ // A script's data as JSON that can't close the script element
55
+ const scriptJson = (value) => JSON.stringify(value).replace(/</g, "\\u003c").replace(/[\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16)}`)
56
+
57
+ /** Seconds a tile lasts, as a whole number of frames at fps, so its last frame is covered. */
58
+ export function tileSeconds(flicks, fps) {
59
+ const frames = Math.max(1, Math.ceil((flicks * fps.n) / (FLICKS * fps.d) - 1e-9))
60
+ return (frames * fps.d) / fps.n
61
+ }
62
+
63
+ /**
64
+ * One tile as a HyperFrames composition: a transparent stage, one clip for the whole
65
+ * tile, Kriya's own animations. Non-GSAP, so `data-no-timeline` (EX-01).
66
+ * @param {{ width: number, height: number, duration: number, css: string, body: string, animations: { id: string, keyframes: object[], options: object }[], fit?: { id: string, within: string, min: number } }} parts duration in flicks;
67
+ * fit: shrink an element's font, a pixel at a time, until it fits its box (no clock, so every render agrees)
68
+ */
69
+ export function tileDocument({ width, height, duration, css, body, animations, fit }) {
70
+ const fitting = fit ? `{const t=document.getElementById(${scriptJson(fit.id)}),a=document.getElementById(${scriptJson(fit.within)});let s=parseFloat(getComputedStyle(t).fontSize);while((t.offsetHeight>a.clientHeight||t.scrollWidth>a.clientWidth)&&s>${Number(fit.min)}){s-=1;t.style.fontSize=s+"px"}}` : ""
71
+ const seconds = (duration / FLICKS).toFixed(6)
72
+ return [
73
+ "<!doctype html>",
74
+ `<html><head><meta charset="utf-8">${CSP_META}`,
75
+ `<style>html,body{margin:0;background:transparent;overflow:hidden}#stage{position:relative;width:${width}px;height:${height}px;overflow:hidden}${css}</style></head>`,
76
+ `<body><div id="stage" data-composition-id="kriya" data-no-timeline data-start="0" data-duration="${seconds}" data-width="${width}" data-height="${height}">`,
77
+ `<div id="clip" class="clip" data-start="0" data-duration="${seconds}" data-track-index="0">${body}</div></div>`,
78
+ `<script>${fitting}for (const a of ${scriptJson(animations)}) document.getElementById(a.id).animate(a.keyframes, a.options)</script>`,
79
+ "</body></html>",
80
+ ].join("")
81
+ }
82
+
83
+ /* ─────────────────────────────── blocks ─────────────────────────────── */
84
+
85
+ const escapeText = (text) => String(text).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c])
86
+ const textVar = (variables, key, max = 120) => {
87
+ const value = variables?.[key]
88
+ if (value === undefined) return ""
89
+ if (typeof value !== "string" || value.length > max) throw new EngineFailure("plan", "bad_variable", `The "${key}" of this card must be text of up to ${max} characters.`)
90
+ return value
91
+ }
92
+
93
+ const RISE = { damping: 0.55, frequency: 11, ms: 900 }
94
+
95
+ /** Kriya's blocks (SKILLS_AND_OPEN_SOURCE §6): typed variables, escaped, WAAPI only. */
96
+ export const BLOCKS = {
97
+ title: {
98
+ version: 1,
99
+ build: ({ variables, area, size }) => ({
100
+ css: `#a{position:absolute;left:${area.x}px;top:${area.y}px;width:${area.w}px;height:${area.h}px;display:flex;align-items:center;justify-content:center}#t{font:800 ${Math.round(size * 1.6)}px/1.1 'Helvetica Neue',Helvetica,Arial,sans-serif;color:#f2eadf;background:#13292bea;padding:${Math.round(size * 0.4)}px ${Math.round(size * 0.7)}px;border-radius:${Math.round(size * 0.5)}px;text-align:center}`,
101
+ body: `<div id="a"><div id="t" data-text>${escapeText(textVar(variables, "text"))}</div></div>`,
102
+ animations: [{ id: "t", keyframes: springKeyframes({ ...RISE, from: { y: Math.round(size * 4), scale: 0.8, opacity: 0 }, to: { y: 0, scale: 1, opacity: 1 } }), options: { duration: RISE.ms, fill: "both" } }],
103
+ }),
104
+ },
105
+ "lower-third": {
106
+ version: 1,
107
+ build: ({ variables, area, size }) => ({
108
+ css: `#a{position:absolute;left:${area.x}px;top:${area.y}px;width:${area.w}px;height:${area.h}px;display:flex;align-items:flex-end}#t{font:800 ${Math.round(size * 1.1)}px/1.15 'Helvetica Neue',Helvetica,Arial,sans-serif;color:#ffffff;background:#13292bf0;padding:${Math.round(size * 0.3)}px ${Math.round(size * 0.5)}px;border-left:${Math.round(size * 0.18)}px solid #ffb347}#t small{display:block;font-weight:500;font-size:${Math.round(size * 0.7)}px;color:#f2eadf}`,
109
+ body: `<div id="a"><div id="t" data-text>${escapeText(textVar(variables, "text"))}${variables?.subtitle ? `<small>${escapeText(textVar(variables, "subtitle"))}</small>` : ""}</div></div>`,
110
+ animations: [{ id: "t", keyframes: springKeyframes({ ...RISE, from: { y: Math.round(size * 2), opacity: 0 }, to: { y: 0, opacity: 1 } }), options: { duration: RISE.ms, fill: "both" } }],
111
+ }),
112
+ },
113
+ card: {
114
+ version: 1,
115
+ build: ({ variables, area, size }) => ({
116
+ css: `#a{position:absolute;left:${area.x}px;top:${area.y}px;width:${area.w}px;height:${area.h}px}#t{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font:700 ${Math.round(size * 1.2)}px/1.2 'Helvetica Neue',Helvetica,Arial,sans-serif;color:#f2eadf;background:#13292b;border-radius:${Math.round(size * 0.6)}px;text-align:center}`,
117
+ body: `<div id="a"><div id="t" data-text>${escapeText(textVar(variables, "text"))}</div></div>`,
118
+ animations: [{ id: "t", keyframes: springKeyframes({ ...RISE, from: { y: Math.round(size * 6), scale: 0.8, opacity: 0 }, to: { y: 0, scale: 1, opacity: 1 } }), options: { duration: RISE.ms, fill: "both" } }],
119
+ }),
120
+ },
121
+ }
122
+
123
+ /** A block tile's composition. An unknown block or version is refused, never drawn as something else. */
124
+ export function blockComposition(node, { output, canvas }) {
125
+ const block = BLOCKS[node.blockId]
126
+ if (!block || block.version !== node.version) throw new EngineFailure("plan", "unknown_block", `There is no motion block "${node.blockId}" version ${node.version}.`)
127
+ const sx = output.width / canvas.width
128
+ const sy = output.height / canvas.height
129
+ const box = node.placement ?? { x: Math.round(canvas.width * 0.1), y: Math.round(canvas.height * 0.4), w: Math.round(canvas.width * 0.8), h: Math.round(canvas.height * 0.12) }
130
+ const area = { x: Math.round(box.x * sx), y: Math.round(box.y * sy), w: Math.round(box.w * sx), h: Math.round(box.h * sy) }
131
+ const size = Math.round(output.height * 0.03)
132
+ return tileDocument({ width: output.width, height: output.height, duration: node.duration, ...block.build({ variables: node.variables, area, size }) })
133
+ }
134
+
135
+ /* ─────────────────────────────── model-written code ─────────────────────────────── */
136
+
137
+ // Anything that reaches out, reads the clock or loads code (SKILLS §6, ET-SEC-04)
138
+ const REFUSED = [
139
+ [/\b(?:fetch|XMLHttpRequest|WebSocket|EventSource|sendBeacon|RTCPeerConnection|importScripts|Worker|SharedWorker)\b/, "it reaches the network"],
140
+ [/\bimport\s*\(|<script[^>]*\bsrc\s*=|<link\b|<iframe\b|<object\b|<embed\b|<base\b|@import\b/i, "it loads code or pages from outside"],
141
+ [/\b(?:https?|wss?|ftp|file|blob):|(?:src|href|action|poster|srcset)\s*=\s*["']?\s*\/\/|url\(\s*["']?\s*\/\//i, "it names an address"],
142
+ [/\bDate\b|\bperformance\s*\.\s*now\b|\bsetTimeout\b|\bsetInterval\b|\brequestAnimationFrame\b|\brequestIdleCallback\b/, "it reads the clock, so it wouldn't seek"],
143
+ [/\bMath\s*\.\s*random\b|\bcrypto\b/, "it is random, so two renders differ"],
144
+ [/\beval\b|\bFunction\s*\(|\bnew\s+Function\b|\bdocument\s*\.\s*write\b/, "it builds code from text"],
145
+ [/\b(?:localStorage|sessionStorage|indexedDB|caches|navigator\s*\.\s*(?:clipboard|serviceWorker|geolocation|mediaDevices))\b/, "it reaches the browser's storage or devices"],
146
+ [/\bgsap\b|\bTweenMax\b|\bTimelineMax\b|\bremotion\b/i, "it uses GSAP or Remotion (EDD-08, EDD-09)"],
147
+ ]
148
+
149
+ /** @returns {string[]} why the composition is refused; empty when it may render */
150
+ export function lintComposition(html) {
151
+ return REFUSED.filter(([pattern]) => pattern.test(html)).map(([, reason]) => reason)
152
+ }
153
+
154
+ /**
155
+ * A composition a model wrote (`edit_motion`, EDD-44): off unless `editing.customMotion`
156
+ * is on, refused where the OS can't confine Chrome, and linted before it renders.
157
+ * @param {string} html
158
+ * @param {{ allowed: boolean, which?: ReturnType<typeof confinement> }} gate allowed: the server's editing.customMotion
159
+ */
160
+ export function customComposition(html, { allowed, which = confinement() }) {
161
+ if (allowed !== true) throw new EngineFailure("plan", "custom_motion_off", "Model-written motion is switched off.")
162
+ if (!which.kind) throw new EngineFailure("environment", "no_confinement", which.missing)
163
+ if (typeof html !== "string" || html.length > 200_000) throw new EngineFailure("plan", "bad_composition", "A composition is text of up to 200 kB.")
164
+ const reasons = lintComposition(html)
165
+ if (reasons.length) throw new EngineFailure("plan", "lint_refused", `This composition was refused: ${reasons.join("; ")}.`)
166
+ // Kriya's policy first in the document: a second, looser one in the model's text can't widen it
167
+ const head = /<head[^>]*>/i.exec(html)
168
+ if (!head) throw new EngineFailure("plan", "bad_composition", "A composition needs a <head>.")
169
+ return `${html.slice(0, head.index + head[0].length)}${CSP_META}${html.slice(head.index + head[0].length)}`
170
+ }
171
+
172
+ /** The composition for any tile in a plan. */
173
+ export function compositionFor(tile, frame, captions) {
174
+ if (tile.kind === "caption") return captions(tile.node, frame)
175
+ if (tile.kind === "block") return blockComposition(tile.node, frame)
176
+ throw new EngineFailure("plan", "unknown_tile", `This render can't draw a ${tile.kind} tile.`)
177
+ }
178
+
179
+ /* ─────────────────────────────── the runtime ─────────────────────────────── */
180
+
181
+ const CLI = ["hyperframes", "node_modules", "hyperframes", "bin", "hyperframes.mjs"]
182
+
183
+ /**
184
+ * HyperFrames and Chrome from the Media Runtime: `<runtime>/hyperframes/` and the
185
+ * manifest's `chrome-headless-shell` artifact.
186
+ * @param {{ dir: string, manifest: object } | null} runtime from activeRuntime()
187
+ * @returns {{ cli: string, chrome: string, dir: string, reads: string[] } | { missing: string }}
188
+ */
189
+ export function motionRuntime(runtime, platform = `${process.platform}-${process.arch}`) {
190
+ if (!runtime) return { missing: "The motion layer needs the Media Runtime. Run kriya edit setup." }
191
+ const cli = join(runtime.dir, ...CLI)
192
+ const chrome = runtime.manifest?.platforms?.[platform]?.artifacts?.find((a) => a.id === "chrome-headless-shell")
193
+ const chromePath = chrome ? join(runtime.dir, chrome.id, chrome.entry) : null
194
+ if (!existsSync(cli)) return { missing: "This Media Runtime has no HyperFrames, so captions and motion can't render. A newer runtime brings it." }
195
+ if (!chromePath || !existsSync(chromePath)) return { missing: "This Media Runtime has no Chrome for the motion layer." }
196
+ // The runtime's own folders, after links: all a confined render may read of it
197
+ return { cli, chrome: chromePath, dir: runtime.dir, reads: [runtime.dir, realpathSync(join(runtime.dir, "hyperframes")), realpathSync(join(runtime.dir, chrome.id))] }
198
+ }
199
+
200
+ /** The environment for a confined render: built from scratch, telemetry off (EH-43), home in the work folder. */
201
+ export function motionEnv(work, runtime, env = process.env) {
202
+ return { ...childEnv(undefined, env), HOME: work, TMPDIR: join(work, "tmp"), HYPERFRAMES_NO_TELEMETRY: "1", DO_NOT_TRACK: "1", HYPERFRAMES_HISTORY_ROOT: join(work, "history"), PRODUCER_HEADLESS_SHELL_PATH: runtime.chrome }
203
+ }
204
+
205
+ /**
206
+ * Renders one composition to a transparent ProRes 4444 tile, confined.
207
+ * @param {{ html: string, work: string, output: string, fps: { n: number, d: number }, runtime: ReturnType<typeof motionRuntime>, run?: typeof runTool, signal?: AbortSignal, which?: ReturnType<typeof confinement>, seconds?: number }} input
208
+ * work: a folder of this tile's own; output: where the tile goes
209
+ */
210
+ export async function renderTile({ html, work, output, fps, runtime, run = runTool, signal, which = confinement(), seconds = 10 }) {
211
+ if (runtime.missing) throw new EngineFailure("environment", "missing_feature", runtime.missing)
212
+ const comp = join(work, "comp")
213
+ mkdirSync(join(work, "tmp"), { recursive: true })
214
+ mkdirSync(comp, { recursive: true })
215
+ writeFileSync(join(comp, "index.html"), html)
216
+ const outDir = output.slice(0, output.lastIndexOf("/"))
217
+ const args = [runtime.cli, "render", comp, "--format", "mov", "--prores-profile", "4444", "--fps", `${fps.n}/${fps.d}`, "--workers", "1", "--quiet", "--no-wait", "--no-browser-gpu", "-o", output]
218
+ const { command, args: wrapped } = confine(process.execPath, args, { read: [installOf(process.execPath), ...runtime.reads, ...ffmpegHome()], write: [work, outDir] }, which)
219
+ await run(command, wrapped, { env: motionEnv(work, runtime), cwd: work, signal, timeoutMs: 60_000 + seconds * 10_000, stallMs: 120_000 })
220
+ if (!existsSync(output)) throw new EngineFailure("render", "failed", "The motion renderer finished without writing its tile.")
221
+ }
222
+
223
+ // HyperFrames encodes with the FFmpeg on PATH; Homebrew's lives outside the runtime (EDD-06)
224
+ function ffmpegHome() {
225
+ return ["/opt/homebrew", "/usr/local/Cellar", "/usr/local/opt", "/usr/local/bin"].filter((path) => existsSync(path))
226
+ }
227
+
228
+ /* ─────────────────────────────── measuring ─────────────────────────────── */
229
+
230
+ // Run in the page by Kriya, never by the composition: every animation paused at t, then the text's boxes
231
+ function readBoxes(times) {
232
+ return times.map((t) => {
233
+ for (const animation of document.getAnimations()) {
234
+ animation.pause()
235
+ animation.currentTime = t
236
+ }
237
+ return [...document.querySelectorAll("[data-text]")].map((el) => {
238
+ const r = el.getBoundingClientRect()
239
+ const style = getComputedStyle(el)
240
+ const colours = new Set([style.color, ...[...el.querySelectorAll("span")].map((span) => getComputedStyle(span).color)])
241
+ return { x: r.x, y: r.y, w: r.width, h: r.height, text: el.textContent, size: parseFloat(style.fontSize), colours: [...colours], plate: style.backgroundColor, clipped: el.scrollWidth > el.clientWidth + 1 || el.scrollHeight > el.clientHeight + 1 }
242
+ })
243
+ })
244
+ }
245
+
246
+ /**
247
+ * The rendered text boxes of compositions at given times (QG-08's "boxes from the
248
+ * DOM at each beat"), read in the runtime's Chrome inside the same sandbox.
249
+ * @param {{ items: { id: string, html: string, times: number[] }[], work: string, runtime: object, which?: object, launch?: Function }} input times in ms
250
+ * @returns {Promise<Map<string, object[][]>>} per item, per time, its text boxes
251
+ */
252
+ export async function measureText({ items, work, runtime, which = confinement(), launch }) {
253
+ if (runtime.missing) throw new EngineFailure("environment", "missing_feature", runtime.missing)
254
+ const { chromium } = launch ? {} : await import("playwright-core")
255
+ const open = launch ?? ((dir, options) => chromium.launchPersistentContext(dir, options))
256
+ if ([work, runtime.chrome].some((path) => path.includes("'"))) throw new EngineFailure("environment", "bad_path", "A folder name with a quote can't hold the motion layer's work.")
257
+ mkdirSync(join(work, "tmp"), { recursive: true })
258
+ const files = items.map((item, i) => {
259
+ const dir = join(work, `c${i}`)
260
+ mkdirSync(dir, { recursive: true })
261
+ writeFileSync(join(dir, "index.html"), item.html)
262
+ return join(dir, "index.html")
263
+ })
264
+ // Playwright starts this script; the script starts Chrome inside the sandbox
265
+ const { args } = confine(runtime.chrome, [], { read: [...runtime.reads, work], write: [work] }, which)
266
+ writeFileSync(join(work, "chrome.sb"), args[1])
267
+ const wrapper = join(work, "chrome.sh")
268
+ writeFileSync(wrapper, `#!/bin/sh\nexec /usr/bin/sandbox-exec -f '${join(work, "chrome.sb")}' '${runtime.chrome}' "$@"\n`, { mode: 0o755 })
269
+ const context = await open(join(work, "profile"), { executablePath: wrapper, headless: true, offline: true, env: { HOME: work, TMPDIR: join(work, "tmp") } })
270
+ try {
271
+ const page = context.pages()[0] ?? (await context.newPage())
272
+ const out = new Map()
273
+ for (const [i, item] of items.entries()) {
274
+ await page.goto(`file://${files[i]}`)
275
+ out.set(item.id, await page.evaluate(readBoxes, item.times))
276
+ }
277
+ return out
278
+ } finally {
279
+ await context.close()
280
+ }
281
+ }
@@ -0,0 +1,87 @@
1
+ // Capability packs (CAPABILITY_PACKS, EDD-43): optional, local, typed. A pack is
2
+ // reached only by the operations it lists; nothing in the core depends on one. Its
3
+ // files come from the signed Media Runtime manifest (`platforms.<id>.packs`), placed
4
+ // beside the core by `kriya edit setup --pack <name>` and removed the same way, never
5
+ // touching the core. When a pack is missing, the operation that needs it fails with a
6
+ // plain reason before anything renders, and everything else keeps working.
7
+
8
+ import { existsSync } from "node:fs"
9
+ import { join } from "node:path"
10
+
11
+ import { platformId } from "../runtime/setup.js"
12
+ import { EngineFailure } from "./tool.js"
13
+
14
+ /**
15
+ * The packs this client knows. `filters` are FFmpeg's; `artifacts` are ids the
16
+ * runtime manifest must ship for the pack; `ops` are the operations that need it.
17
+ * Data only: no command, path, URL or price.
18
+ */
19
+ export const PACKS = {
20
+ "pack-color": {
21
+ title: "Colour",
22
+ does: "colour matching between shots, and LUTs",
23
+ ops: ["match_color", "apply_lut"],
24
+ filters: ["lut3d"],
25
+ artifacts: [],
26
+ licences: [{ item: "FFmpeg lut3d", licence: "LGPL-2.1-or-later (FFmpeg, EQ-02)" }],
27
+ },
28
+ "pack-voice-clean": {
29
+ title: "Clean voice",
30
+ does: "noise and room removal with DeepFilterNet; without it, FFmpeg's own filters clean the voice",
31
+ ops: [],
32
+ filters: [],
33
+ artifacts: ["deepfilternet3"],
34
+ licences: [{ item: "DeepFilterNet", licence: "MIT or Apache-2.0" }],
35
+ },
36
+ "pack-depth": {
37
+ title: "Depth motion",
38
+ does: "stills that move with parallax, from Depth Anything V2's permissively licensed sizes",
39
+ ops: ["parallax"],
40
+ filters: [],
41
+ artifacts: ["depth-anything-v2-small"],
42
+ licences: [{ item: "Depth Anything V2 Small", licence: "Apache-2.0" }],
43
+ },
44
+ }
45
+
46
+ export const packName = (id) => id.replace(/^pack-/, "")
47
+
48
+ /** Where a pack's files sit in a runtime version. */
49
+ export const packDir = (runtime, id) => join(runtime.dir, "packs", id)
50
+
51
+ /**
52
+ * Each pack's state on this computer: installed, or why not, in plain words.
53
+ * @param {{ runtime: { dir: string, manifest: object } | null, capabilities: { filters: Set<string> }, platform?: string }} where
54
+ * @returns {Record<string, { title: string, installed: boolean, missing: string | null }>}
55
+ */
56
+ export function packStatus({ runtime, capabilities, platform = platformId() }) {
57
+ const status = {}
58
+ for (const [id, pack] of Object.entries(PACKS)) {
59
+ const filter = pack.filters.find((name) => !capabilities.filters.has(name))
60
+ let missing = null
61
+ if (filter) missing = `This FFmpeg has no ${filter} filter, which ${pack.title.toLowerCase()} needs. Install an FFmpeg with it (kriya edit doctor says which).`
62
+ else if (pack.artifacts.length) {
63
+ const offered = runtime?.manifest?.platforms?.[platform]?.packs?.[id]
64
+ if (!runtime) missing = `The ${pack.title} pack needs the Media Runtime, which isn't installed.`
65
+ else if (!offered) missing = `This Media Runtime (${runtime.version}) doesn't offer the ${pack.title} pack yet.`
66
+ else if (!existsSync(join(packDir(runtime, id), ".complete"))) missing = `The ${pack.title} pack isn't installed. Run kriya edit setup --pack ${packName(id)}.`
67
+ }
68
+ status[id] = { title: pack.title, installed: missing === null, missing }
69
+ }
70
+ return status
71
+ }
72
+
73
+ /** The pack an operation needs, if any. */
74
+ export const packFor = (op) => Object.keys(PACKS).find((id) => PACKS[id].ops.includes(op)) ?? null
75
+
76
+ /** Throws the plain reason when `id` isn't installed. */
77
+ export function requirePack(id, status) {
78
+ const state = status[id]
79
+ if (!state) throw new EngineFailure("environment", "missing_pack", `There is no pack called ${id}.`)
80
+ if (!state.installed) throw new EngineFailure("environment", "missing_pack", state.missing)
81
+ }
82
+
83
+ /** The packs a compiled plan needs: colour for a LUT or a colour match. */
84
+ export function packsForPlan(plan) {
85
+ const effects = plan.segments.flatMap((s) => s.node.picture.flatMap((item) => item.effects))
86
+ return effects.some((e) => e.type === "lut" || (e.type === "grade" && e.match)) ? ["pack-color"] : []
87
+ }
@@ -0,0 +1,101 @@
1
+ // L0 Probe: what a file really is. Times arrive as FFprobe's own integers and
2
+ // rationals and stay exact; no float seconds cross this boundary.
3
+
4
+ import { EngineFailure, runTool } from "./tool.js"
5
+
6
+ const FLICKS = 705_600_000n
7
+ const HDR = new Set(["smpte2084", "arib-std-b67"])
8
+ // A container's timebase can jitter CFR timestamps by a tick: more than this is real
9
+ const VFR_SLACK = 1_411_200
10
+
11
+ const ceilDiv = (a, b) => (a + b - 1n) / b
12
+
13
+ /** pts × "1/90000" as flicks, exactly. */
14
+ function ticks(value, timeBase) {
15
+ const [n, d] = timeBase.split("/").map(BigInt)
16
+ return Number(ceilDiv(BigInt(value) * n * FLICKS, d))
17
+ }
18
+
19
+ /** "12.345678" as flicks, from the digits. */
20
+ function decimal(text) {
21
+ const [whole, fraction = ""] = text.split(".")
22
+ const digits = fraction.padEnd(9, "0").slice(0, 9)
23
+ return Number(ceilDiv((BigInt(whole) * 1_000_000_000n + BigInt(digits)) * FLICKS, 1_000_000_000n))
24
+ }
25
+
26
+ function rate(text) {
27
+ const [n, d] = (text ?? "").split("/").map(Number)
28
+ return n > 0 && d > 0 ? { n, d } : null
29
+ }
30
+
31
+ // ES-03, ES-07: files only (no playlist reaching the network), a time limit, and only
32
+ // container formats Kriya edits. HLS, concat lists, tee and the rest are refused after probing.
33
+ const LOCAL = ["-protocol_whitelist", "file,pipe"]
34
+ const FORMATS = new Set(["mov", "matroska", "avi", "mpegts", "mxf", "wav", "w64", "aiff", "caf", "mp3", "aac", "flac", "ogg", "image2", "png_pipe", "jpeg_pipe", "webp_pipe"])
35
+
36
+ const known = (value) => (value && value !== "unknown" ? value : null)
37
+
38
+ function rotationOf(stream) {
39
+ const matrix = stream.side_data_list?.find((data) => data.rotation !== undefined)
40
+ return matrix ? (((Math.round(matrix.rotation) % 360) + 360) % 360) : 0
41
+ }
42
+
43
+ function colourOf(stream) {
44
+ const primaries = known(stream.color_primaries)
45
+ const transfer = known(stream.color_transfer)
46
+ return { primaries: primaries ?? "unknown", transfer: transfer ?? "unknown", range: known(stream.color_range) ?? "unknown", tagged: !!primaries && !!transfer, hdr: HDR.has(transfer) }
47
+ }
48
+
49
+ async function frameTimes(file, stream, run) {
50
+ const text = await run("ffprobe", ["-v", "error", ...LOCAL, "-select_streams", String(stream.index), "-show_entries", "packet=pts", "-of", "csv=p=0", file], { timeoutMs: 900_000, stallMs: 120_000 })
51
+ return text
52
+ .split("\n")
53
+ .map((line) => line.trim().replace(/,+$/, ""))
54
+ .filter((line) => /^-?\d+$/.test(line))
55
+ .map((pts) => ticks(pts, stream.time_base))
56
+ .sort((a, b) => a - b)
57
+ }
58
+
59
+ /**
60
+ * @param {string} file
61
+ * @param {{ run?: typeof runTool }} [options]
62
+ * @returns {Promise<{ facts: object, timestamps?: number[] }>} timestamps only for a VFR file
63
+ */
64
+ export async function probe(file, { run = runTool } = {}) {
65
+ let data
66
+ try {
67
+ data = JSON.parse(await run("ffprobe", ["-v", "error", ...LOCAL, "-print_format", "json", "-show_streams", "-show_format", file], { timeoutMs: 120_000 }))
68
+ } catch (error) {
69
+ if (error instanceof SyntaxError) throw new EngineFailure("input", "unreadable", "This file can't be read.")
70
+ throw error
71
+ }
72
+ if (!FORMATS.has(String(data.format?.format_name ?? "").split(",")[0])) throw new EngineFailure("input", "refused", "Kriya doesn't open this kind of file.")
73
+ const video = data.streams?.find((stream) => stream.codec_type === "video" && stream.disposition?.attached_pic !== 1)
74
+ const audio = data.streams?.find((stream) => stream.codec_type === "audio")
75
+ if (!video && !audio) throw new EngineFailure("input", "unreadable", "This file has no picture or sound.")
76
+
77
+ const facts = { hasAudio: !!audio }
78
+ if (audio) Object.assign(facts, { sampleRate: Number(audio.sample_rate), channels: audio.channels })
79
+ const lead = video ?? audio
80
+ if (lead.duration_ts && lead.time_base) facts.duration = ticks(lead.duration_ts, lead.time_base)
81
+ else if (data.format?.duration) facts.duration = decimal(data.format.duration)
82
+ if (!video) return { facts: { ...facts, vfr: false } }
83
+
84
+ const rotation = rotationOf(video)
85
+ const sideways = rotation % 180 !== 0
86
+ Object.assign(facts, { width: sideways ? video.height : video.width, height: sideways ? video.width : video.height, rotation, color: colourOf(video) })
87
+
88
+ const times = await frameTimes(file, video, run)
89
+ // A loop, not Math.max(...gaps): a 2-hour take has 216,000 gaps, past the call stack (found in ED17's soak)
90
+ let low = Infinity
91
+ let high = -Infinity
92
+ for (let i = 1; i < times.length; i++) {
93
+ const gap = times[i] - times[i - 1]
94
+ if (gap < low) low = gap
95
+ if (gap > high) high = gap
96
+ }
97
+ const vfr = times.length > 2 && high - low > VFR_SLACK
98
+ facts.vfr = vfr
99
+ facts.fps = vfr ? null : (rate(video.avg_frame_rate) ?? rate(video.r_frame_rate))
100
+ return vfr ? { facts, timestamps: times } : { facts }
101
+ }
@@ -0,0 +1,123 @@
1
+ // Receipts, reports and `kriya edit verify` (EDIT_ENGINE §12, QUALITY_GATES §6, ED10).
2
+ // The receipt is proof of what was done: hashes of every input and of the output,
3
+ // tool versions, the plan's hash, every gate's numbers and the verdict, tokens and
4
+ // money as the gateway reported them. `verify` re-measures a file against it.
5
+
6
+ import { readFileSync, statSync, writeFileSync } from "node:fs"
7
+ import { basename } from "node:path"
8
+
9
+ import { canonical, hashProject, sha256 } from "../core/project.js"
10
+ import { fileSha256 } from "../runtime/manifest.js"
11
+ import { measureLoudness } from "./loudness.js"
12
+ import { runTool } from "./tool.js"
13
+
14
+ export const RECEIPT_SCHEMA = 1
15
+ const FLICKS = 705_600_000
16
+
17
+ export const receiptPath = (file) => file.replace(/\.[^./]+$/, ".receipt.json")
18
+ export const reportPath = (file) => file.replace(/\.[^./]+$/, ".report.html")
19
+
20
+ /** The facts verify compares: what the file is, read from the file. */
21
+ export async function factsOf(file, run = runTool) {
22
+ const data = JSON.parse(await run("ffprobe", ["-v", "error", "-print_format", "json", "-show_streams", "-show_format", file], { timeoutMs: 120_000 }))
23
+ const video = data.streams.find((s) => s.codec_type === "video")
24
+ const audio = data.streams.find((s) => s.codec_type === "audio")
25
+ const { integrated, truePeak } = audio ? await measureLoudness(file, { run }) : { integrated: null, truePeak: null }
26
+ return {
27
+ video: video ? { codec: video.codec_name, width: video.width, height: video.height, fps: video.avg_frame_rate, pixFmt: video.pix_fmt } : null,
28
+ audio: audio ? { codec: audio.codec_name, rate: Number(audio.sample_rate), channels: audio.channels } : null,
29
+ seconds: Math.round(Number(data.format.duration) * 1000) / 1000,
30
+ loudness: { integrated: integrated === null ? null : Math.round(integrated * 10) / 10, truePeak: truePeak === null ? null : Math.round(truePeak * 10) / 10 },
31
+ }
32
+ }
33
+
34
+ /**
35
+ * @param {{ file: string, project: object, parent: string | null, plan: object, sources: Record<string, string>, tools: object, gates: object[], verdict: string, calls: object[], exportedAnyway?: boolean, run?: typeof runTool }} input
36
+ * sources: asset id → path; calls: the journal's Director calls for the job
37
+ */
38
+ export async function makeReceipt({ file, project, parent, plan, sources, tools, gates, verdict, calls, exportedAnyway = false, run = runTool }) {
39
+ const inputs = {}
40
+ for (const [id, path] of Object.entries(sources)) inputs[id] = { sha256: await fileSha256(path), bytes: statSync(path).size }
41
+ const tokens = calls.reduce((sum, c) => ({ input: sum.input + (c.input_tokens ?? 0), cached: sum.cached + (c.cached_tokens ?? 0), output: sum.output + (c.output_tokens ?? 0) }), { input: 0, cached: 0, output: 0 })
42
+ return {
43
+ schema: RECEIPT_SCHEMA,
44
+ file: { name: basename(file), sha256: await fileSha256(file), bytes: statSync(file).size },
45
+ facts: await factsOf(file, run),
46
+ project: { hash: hashProject(project), parent },
47
+ plan: { hash: sha256(canonical(plan)), quality: plan.quality, seconds: Math.round((plan.duration / FLICKS) * 1000) / 1000 },
48
+ inputs,
49
+ tools,
50
+ gates: gates.map((g) => ({ id: g.id, status: g.status, severity: g.severity, numbers: g.numbers, ...(g.message ? { message: g.message } : {}) })),
51
+ verdict,
52
+ ...(exportedAnyway ? { exportedAnyway: true } : {}),
53
+ // Money only as the gateway reports it: Kriya never prices a call itself
54
+ model: { calls: calls.length, tokens, money: calls.some((c) => c.cost !== undefined && c.cost !== null) ? calls.reduce((sum, c) => sum + (c.cost ?? 0), 0) : "not reported by the gateway" },
55
+ }
56
+ }
57
+
58
+ export function writeReceipt(file, receipt) {
59
+ const path = receiptPath(file)
60
+ writeFileSync(path, `${JSON.stringify(receipt, null, 2)}\n`)
61
+ return path
62
+ }
63
+
64
+ /**
65
+ * Re-measures a file against its receipt (ET-QG-21). The same bytes match outright;
66
+ * different bytes are re-measured and every difference is listed.
67
+ * @returns {Promise<{ ok: boolean, identical: boolean, differences: string[] }>}
68
+ */
69
+ export async function verifyFile(file, receipt, run = runTool) {
70
+ if (receipt?.schema !== RECEIPT_SCHEMA) return { ok: false, identical: false, differences: ["this isn't a receipt this version can read"] }
71
+ if ((await fileSha256(file)) === receipt.file.sha256) return { ok: true, identical: true, differences: [] }
72
+ const now = await factsOf(file, run)
73
+ const was = receipt.facts
74
+ const differences = []
75
+ for (const key of ["codec", "width", "height", "fps", "pixFmt"]) if (now.video?.[key] !== was.video?.[key]) differences.push(`video ${key}: ${was.video?.[key]} → ${now.video?.[key]}`)
76
+ for (const key of ["codec", "rate", "channels"]) if (now.audio?.[key] !== was.audio?.[key]) differences.push(`audio ${key}: ${was.audio?.[key]} → ${now.audio?.[key]}`)
77
+ if (Math.abs(now.seconds - was.seconds) > 0.034) differences.push(`length: ${was.seconds} s → ${now.seconds} s`)
78
+ if (was.loudness.integrated !== null && (now.loudness.integrated === null || Math.abs(now.loudness.integrated - was.loudness.integrated) > 0.2)) differences.push(`loudness: ${was.loudness.integrated} → ${now.loudness.integrated} LUFS`)
79
+ if (was.loudness.truePeak !== null && now.loudness.truePeak !== null && now.loudness.truePeak - was.loudness.truePeak > 0.3) differences.push(`true peak: ${was.loudness.truePeak} → ${now.loudness.truePeak} dBTP`)
80
+ // Same measurements, other bytes: not the file the receipt describes
81
+ return { ok: false, identical: false, differences: differences.length ? differences : ["the bytes differ from the receipt's, though it measures the same"] }
82
+ }
83
+
84
+ export const readReceipt = (path) => JSON.parse(readFileSync(path, "utf8"))
85
+
86
+ /* ─────────────────────────────── the report ─────────────────────────────── */
87
+
88
+ const esc = (text) => String(text ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c])
89
+ const WORDS = { delivered: "Checked", delivered_with_notes: "Checked, with notes", blocked: "Needs you", not_checked: "Not checked" }
90
+
91
+ /**
92
+ * One page beside the export (QUALITY_GATES §6): verdict, facts, each gate with its
93
+ * numbers, before and after contact sheets, the changes, notes, rights, tokens and money.
94
+ * @param {{ receipt: object, title: string, before?: Buffer | null, after?: Buffer | null, changes: string[], notes: string[], rights: { id: string, rights: string, role: string }[], repairs?: object[] }} input jpgs as Buffers
95
+ */
96
+ export function reportHtml({ receipt, title, before = null, after = null, changes, notes, rights, repairs = [] }) {
97
+ const img = (jpg, alt) => (jpg ? `<img alt="${esc(alt)}" src="data:image/jpeg;base64,${jpg.toString("base64")}">` : `<p class="muted">No ${esc(alt)}.</p>`)
98
+ const facts = receipt.facts
99
+ const rows = receipt.gates.map((g) => `<tr><td>${esc(g.id)}</td><td class="s-${esc(g.status)}">${esc(g.status.replaceAll("_", " "))}${g.severity === "note" && g.status === "failed" ? " (note)" : ""}</td><td>${esc(g.message ?? "")}</td><td><code>${esc(JSON.stringify(g.numbers ?? {}))}</code></td></tr>`).join("")
100
+ const list = (items) => (items.length ? `<ul>${items.map((i) => `<li>${esc(i)}</li>`).join("")}</ul>` : `<p class="muted">None.</p>`)
101
+ const money = typeof receipt.model.money === "number" ? `${receipt.model.money}` : receipt.model.money
102
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(title)}: report</title><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'"><style>
103
+ :root{color-scheme:light dark;--bg:#fbfaf7;--fg:#1d1b18;--muted:#6b665e;--line:#e3ded5;--ok:#1f7a4d;--bad:#b3261e;--note:#8a5a00}
104
+ @media (prefers-color-scheme:dark){:root{--bg:#161513;--fg:#ece8e1;--muted:#a49e94;--line:#34312c;--ok:#5fcf97;--bad:#ff8a80;--note:#f2c46d}}
105
+ body{margin:0 auto;max-width:960px;padding:24px 16px;background:var(--bg);color:var(--fg);font:15px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
106
+ h1{font-size:22px;margin:0 0 4px}h2{font-size:16px;margin:28px 0 8px}.muted{color:var(--muted)}
107
+ .verdict{font-size:18px;font-weight:600}.v-delivered{color:var(--ok)}.v-blocked{color:var(--bad)}.v-delivered_with_notes,.v-not_checked{color:var(--note)}
108
+ table{width:100%;border-collapse:collapse;font-size:13px}td{border-top:1px solid var(--line);padding:6px 8px;vertical-align:top}code{font-size:12px;word-break:break-all}
109
+ .s-passed{color:var(--ok)}.s-failed{color:var(--bad)}.s-not_checked,.s-not_applicable{color:var(--muted)}
110
+ .sheets{display:grid;grid-template-columns:1fr 1fr;gap:12px}.sheets img{width:100%;border:1px solid var(--line)}@media (max-width:640px){.sheets{grid-template-columns:1fr}}
111
+ </style></head><body>
112
+ <h1>${esc(title)}</h1><p class="verdict v-${esc(receipt.verdict)}">${esc(WORDS[receipt.verdict] ?? receipt.verdict)}${receipt.exportedAnyway ? " (exported anyway)" : ""}</p>
113
+ <p class="muted">${esc(receipt.file.name)} · ${esc(facts.video ? `${facts.video.width}×${facts.video.height} ${facts.video.codec} ${facts.video.fps}` : "no picture")} · ${esc(facts.seconds)} s · ${esc(facts.loudness.integrated)} LUFS · ${esc(facts.loudness.truePeak)} dBTP · sha256 <code>${esc(receipt.file.sha256.slice(0, 16))}…</code></p>
114
+ <h2>Gates</h2><table>${rows}</table>
115
+ <h2>Before and after</h2><div class="sheets"><div><p class="muted">Source</p>${img(before, "source contact sheet")}</div><div><p class="muted">Delivered</p>${img(after, "delivered contact sheet")}</div></div>
116
+ <h2>What changed</h2>${list(changes)}
117
+ ${repairs.length ? `<h2>Repairs</h2>${list(repairs.map((r) => `Round ${r.round}: ${r.fixes.map((f) => f.why).join(" ")} ${r.accepted ? "Kept." : `Set aside${r.reason ? `: ${r.reason}` : ", it wasn't better"}.`}`))}` : ""}
118
+ <h2>Notes</h2>${list(notes)}
119
+ <h2>Rights</h2>${list(rights.map((r) => `${r.id} (${r.role}): ${r.rights}`))}
120
+ <h2>Model use</h2><p>${esc(receipt.model.calls)} calls · ${esc(receipt.model.tokens.input)} input tokens (${esc(receipt.model.tokens.cached)} cached) · ${esc(receipt.model.tokens.output)} output tokens · money: ${esc(money)}</p>
121
+ </body></html>
122
+ `
123
+ }