@kriya-ai/harness 0.2.2 → 0.2.4

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 (45) hide show
  1. package/contract/SOURCE.md +3 -3
  2. package/contract/contract.json +188 -0
  3. package/package.json +1 -1
  4. package/src/edit/core/ffmpeg.js +5 -1
  5. package/src/edit/core/layout.js +26 -1
  6. package/src/edit/core/ops.js +74 -6
  7. package/src/edit/core/plan.js +2 -1
  8. package/src/edit/core/project.js +6 -1
  9. package/src/edit/core/solver.js +66 -15
  10. package/src/edit/director/ask.js +42 -27
  11. package/src/edit/director/beats.js +335 -0
  12. package/src/edit/director/lookups.js +133 -0
  13. package/src/edit/director/plan.js +365 -0
  14. package/src/edit/director/playbooks.js +131 -0
  15. package/src/edit/director/revise.js +171 -12
  16. package/src/edit/engine/captions.js +32 -0
  17. package/src/edit/engine/found-media.js +64 -0
  18. package/src/edit/engine/motion.js +78 -18
  19. package/src/edit/engine/music-bed.js +110 -0
  20. package/src/edit/engine/reference.js +134 -0
  21. package/src/edit/engine/scenes.js +480 -0
  22. package/src/edit/engine/sfx.js +63 -0
  23. package/src/edit/gates/copy.js +25 -5
  24. package/src/edit/gates/index.js +12 -4
  25. package/src/edit/gates/picture.js +5 -0
  26. package/src/edit/gates/text.js +20 -4
  27. package/src/edit/graph/scheduler.js +1 -1
  28. package/src/edit/host/client.js +28 -4
  29. package/src/edit/host/deliver.js +8 -1
  30. package/src/edit/host/jobs.js +43 -0
  31. package/src/edit/host/main.js +4 -2
  32. package/src/edit/host/paths.js +25 -0
  33. package/src/edit/host/projects.js +328 -38
  34. package/src/edit/host/server.js +106 -8
  35. package/src/edit/index/db.js +5 -0
  36. package/src/edit/index/layers/retakes.js +7 -1
  37. package/src/edit/index/views.js +9 -0
  38. package/src/edit/loop/make.js +9 -6
  39. package/src/edit/recipes/montage.js +74 -0
  40. package/src/edit/recipes/programme.js +24 -0
  41. package/src/edit/recipes/reel.js +149 -20
  42. package/src/edit/recipes/scene-clips.js +127 -0
  43. package/src/edit/runtime/fetch.js +32 -0
  44. package/studio/dist/studio.css +62 -4
  45. package/studio/dist/studio.js +4 -2
@@ -0,0 +1,480 @@
1
+ // Explainer scenes (VISUAL_SCENES.md, EDD-51): the Director's cutaways, drawn by Kriya's own
2
+ // code from typed variables. A scene is an opaque tile, Web Animations only, so it seeks
3
+ // and renders like any other (EX-01): no model-written code, no clock, no randomness, no
4
+ // network. Layout is computed here, so a scene is the same in the preview and the render.
5
+
6
+ import { EngineFailure } from "./tool.js"
7
+
8
+ const FLICKS = 705_600_000
9
+
10
+ export const SCENE_BLOCK = "scene"
11
+ export const SCENE_VERSION = 1
12
+
13
+ /** Colours chosen so ink on plate holds WCAG 4.5:1 (tested). `band` backs a caption row on a light theme. */
14
+ export const SCENE_THEMES = {
15
+ lab: { label: "Lab", bg: "#0b1f2a", plate: "#143545", ink: "#eaf6fb", accent: "#4fd1c5", hot: "#ffb347", line: "#2c5a6d" },
16
+ blueprint: { label: "Blueprint", bg: "#0d2b52", plate: "#143c70", ink: "#f1f7ff", accent: "#7cc4ff", hot: "#ffd166", line: "#3a689f" },
17
+ chalk: { label: "Chalkboard", bg: "#1b2a25", plate: "#273b33", ink: "#f5f1e6", accent: "#f4d35e", hot: "#ee964b", line: "#4c6358" },
18
+ paper: { label: "Paper", bg: "#f6f1e7", plate: "#ffffff", ink: "#1c2530", accent: "#2a5cb3", hot: "#c8431f", line: "#c9c0ad", band: "#16232c" },
19
+ }
20
+
21
+ /** The kinds, what each needs, and what the Director and the Plan Card call it. */
22
+ export const SCENE_KINDS = {
23
+ process: { label: "Steps", min: 2, max: 5, when: "steps that happen in order, or a chain of causes" },
24
+ cycle: { label: "Cycle", min: 3, max: 5, when: "something that repeats and comes back to the start" },
25
+ hub: { label: "Parts of an idea", min: 3, max: 6, when: "one term in the centre (the first item) and its parts or effects" },
26
+ flow: { label: "Moving through", min: 2, max: 3, when: "something moving from one place to another; mode flows, blocked (stopped at the middle item or before the end) or floods (more and more of it arrives)" },
27
+ compare: { label: "Side by side", min: 2, max: 2, when: "two things against each other, with their numbers if the speaker said them" },
28
+ stat: { label: "Big number", min: 1, max: 1, values: true, when: "one number the speaker said; the item's value is that number" },
29
+ bars: { label: "Number bars", min: 2, max: 6, values: true, when: "several numbers the speaker said, compared" },
30
+ }
31
+ export const FLOW_MODES = ["flows", "blocked", "floods"]
32
+ const TEXT_MAX = 32
33
+ const TITLE_MAX = 60
34
+ const UNIT_MAX = 8
35
+ const VALUE = /^\d{1,7}(?:[.,]\d{1,3})?$/
36
+
37
+ const cleanText = (value, max) => (typeof value === "string" ? value.replace(/[\u0000-\u001f\u007f<>]/g, " ").replace(/\s+/g, " ").trim().slice(0, max).trim() : "")
38
+
39
+ /**
40
+ * A scene's shape, at every trust boundary (a model's answer, a browser's request). Unknown
41
+ * fields go; text is cleaned. Whether its words were spoken is `groundProblems`' job.
42
+ * @returns {object | null} null when it can't be a scene
43
+ */
44
+ export function cleanScene(raw) {
45
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null
46
+ const kind = Object.hasOwn(SCENE_KINDS, raw.kind ?? "") ? raw.kind : null
47
+ if (!kind) return null
48
+ const shape = SCENE_KINDS[kind]
49
+ const items = (Array.isArray(raw.items) ? raw.items : []).slice(0, 6).map((item) => {
50
+ const text = cleanText(item?.text, TEXT_MAX)
51
+ const value = typeof item?.value === "string" && VALUE.test(item.value.trim()) ? item.value.trim() : undefined
52
+ const unit = value !== undefined ? cleanText(item?.unit, UNIT_MAX) : ""
53
+ return { text, ...(value !== undefined ? { value } : {}), ...(unit ? { unit } : {}) }
54
+ })
55
+ if (items.length < shape.min || items.length > shape.max || items.some((i) => !i.text)) return null
56
+ if (shape.values && items.some((i) => i.value === undefined)) return null
57
+ const id = (value) => (typeof value === "string" && /^[A-Za-z0-9:_-]{1,64}$/.test(value) ? value : null)
58
+ return {
59
+ kind,
60
+ title: cleanText(raw.title, TITLE_MAX),
61
+ items,
62
+ theme: Object.hasOwn(SCENE_THEMES, raw.theme ?? "") ? raw.theme : "lab",
63
+ ...(kind === "flow" ? { mode: FLOW_MODES.includes(raw.mode) ? raw.mode : "flows" } : {}),
64
+ ...(id(raw.from) ? { from: id(raw.from) } : {}),
65
+ ...(id(raw.to) ? { to: id(raw.to) } : {}),
66
+ }
67
+ }
68
+
69
+ /** The kinds this scene's items can also be drawn as, its own first: what the Plan Card offers. */
70
+ export function swapsFor(scene) {
71
+ const count = scene.items.length
72
+ const valued = scene.items.every((i) => i.value !== undefined)
73
+ const fits = Object.entries(SCENE_KINDS).filter(([, kind]) => count >= kind.min && count <= kind.max && (!kind.values || valued)).map(([id]) => id)
74
+ return [scene.kind, ...fits.filter((id) => id !== scene.kind)]
75
+ }
76
+
77
+ /** Every word shown, for the copy gate and the timeline. */
78
+ export function sceneText(variables) {
79
+ return [variables?.title, ...(variables?.items ?? []).flatMap((i) => [i.text, i.value !== undefined ? `${i.value}${i.unit ?? ""}` : ""])].filter(Boolean).join(" ")
80
+ }
81
+
82
+ /* ─────────────────────────────── geometry ─────────────────────────────── */
83
+
84
+ const escapeText = (text) => String(text).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c])
85
+ const round = (n) => Math.round(n * 100) / 100
86
+ const clampNumber = (n, a, b) => Math.max(a, Math.min(b, n))
87
+ // Spreads particles without randomness, so two renders are the same frame for frame
88
+ const seeded = (n) => {
89
+ const x = Math.sin(n * 127.1 + 311.7) * 43758.5453
90
+ return x - Math.floor(x)
91
+ }
92
+
93
+ // Average glyph width in em, a little wide on purpose so a line never overflows its plate
94
+ const GLYPH = 0.6
95
+
96
+ /** Lines greedy wrap makes, long words broken. */
97
+ function linesAt(text, size, width) {
98
+ const perLine = Math.max(1, Math.floor(width / (size * GLYPH)))
99
+ let lines = 1
100
+ let used = 0
101
+ for (const word of String(text).split(" ")) {
102
+ const length = word.length
103
+ if (length > perLine) {
104
+ lines += used ? 1 : 0
105
+ lines += Math.ceil(length / perLine) - 1
106
+ used = length % perLine
107
+ } else if (used + (used ? 1 : 0) + length > perLine) {
108
+ lines++
109
+ used = length
110
+ } else used += (used ? 1 : 0) + length
111
+ }
112
+ return lines
113
+ }
114
+
115
+ /** The biggest font that fits a box, never under the floor the legibility gate needs. */
116
+ export function fitFont(text, width, height, biggest, floor) {
117
+ const longest = Math.max(...String(text).split(" ").map((word) => word.length))
118
+ for (let size = Math.round(biggest); size > floor; size--) if (longest * size * GLYPH <= width && linesAt(text, size, width) * size * 1.2 <= height) return size
119
+ return floor
120
+ }
121
+
122
+ const collide = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
123
+
124
+ /**
125
+ * Where each kind puts its boxes, inside `d`, the diagram's region. Plain data, tested for
126
+ * overlap in every format. `tall`: the frame is portrait, so things stack.
127
+ */
128
+ export function layoutKind(kind, count, d, base, tall = d.h > d.w) {
129
+ const gap = Math.round(base * 0.9)
130
+ const middle = { x: d.x + d.w / 2, y: d.y + d.h / 2 }
131
+ if (kind === "process") {
132
+ if (tall) {
133
+ const h = Math.min((d.h - gap * (count - 1)) / count, base * 3.4)
134
+ const total = h * count + gap * (count - 1)
135
+ return Array.from({ length: count }, (_, i) => ({ x: d.x, y: d.y + (d.h - total) / 2 + i * (h + gap), w: d.w, h }))
136
+ }
137
+ const w = (d.w - gap * (count - 1)) / count
138
+ const h = Math.min(d.h * 0.7, base * 6)
139
+ return Array.from({ length: count }, (_, i) => ({ x: d.x + i * (w + gap), y: middle.y - h / 2, w, h }))
140
+ }
141
+ if (kind === "cycle") {
142
+ let w = Math.min(d.w * (tall ? 0.5 : 0.28), base * 9.5)
143
+ const h = Math.min(d.h * (tall ? 0.17 : 0.26), base * 3.2)
144
+ for (;;) {
145
+ const rx = (d.w - w) / 2
146
+ const ry = (d.h - h) / 2
147
+ const boxes = Array.from({ length: count }, (_, i) => {
148
+ const a = -Math.PI / 2 + (i * 2 * Math.PI) / count
149
+ return { x: middle.x + Math.cos(a) * rx - w / 2, y: middle.y + Math.sin(a) * ry - h / 2, w, h }
150
+ })
151
+ if (w <= base * 4 || !boxes.some((a, i) => boxes.some((b, k) => k > i && collide(a, b)))) return boxes
152
+ w *= 0.94
153
+ }
154
+ }
155
+ if (kind === "hub") {
156
+ // The centre, with its parts in a row above and a row below: holds in every frame
157
+ const spokes = count - 1
158
+ const above = Math.ceil(spokes / 2)
159
+ const rowH = Math.min((d.h - gap * 2) * 0.3, base * 3.3)
160
+ const row = (n, y, from) => {
161
+ const w = Math.min((d.w - gap * (n - 1)) / n, base * 9.5)
162
+ const total = w * n + gap * (n - 1)
163
+ return Array.from({ length: n }, (_, i) => ({ x: middle.x - total / 2 + i * (w + gap), y, w, h: rowH, from }))
164
+ }
165
+ const ch = Math.min(d.h - (rowH + gap * 1.6) * 2, base * 3.6)
166
+ const cw = Math.min(d.w * 0.62, base * 11)
167
+ const top = middle.y - ch / 2 - gap * 1.6 - rowH
168
+ const bottom = middle.y + ch / 2 + gap * 1.6
169
+ return [{ x: middle.x - cw / 2, y: middle.y - ch / 2, w: cw, h: ch }, ...row(above, top), ...row(spokes - above, bottom)]
170
+ }
171
+ if (kind === "flow") {
172
+ const along = tall ? d.h : d.w
173
+ const size = tall ? Math.min(along * 0.2, base * 3.4) : Math.min(along * (count === 3 ? 0.2 : 0.24), base * 7.5)
174
+ const across = tall ? d.w : Math.min(d.h * 0.46, base * 4.8)
175
+ const place = (u) => (tall ? { x: d.x, y: d.y + u * (d.h - size), w: across, h: size } : { x: d.x + u * (d.w - size), y: middle.y - across / 2, w: size, h: across })
176
+ return count === 3 ? [place(0), place(0.5), place(1)] : [place(0), place(1)]
177
+ }
178
+ if (kind === "compare") {
179
+ if (tall) {
180
+ const h = (d.h - gap) / 2
181
+ return [{ x: d.x, y: d.y, w: d.w, h }, { x: d.x, y: d.y + h + gap, w: d.w, h }]
182
+ }
183
+ const w = (d.w - gap) / 2
184
+ return [{ x: d.x, y: d.y, w, h: d.h }, { x: d.x + w + gap, y: d.y, w, h: d.h }]
185
+ }
186
+ if (kind === "stat") return [{ x: d.x, y: d.y, w: d.w, h: d.h }]
187
+ // bars: one row each
188
+ const rowGap = Math.round(base * 0.45)
189
+ const h = Math.min((d.h - rowGap * (count - 1)) / count, tall ? base * 3.6 : base * 2.6)
190
+ const total = h * count + rowGap * (count - 1)
191
+ return Array.from({ length: count }, (_, i) => ({ x: d.x, y: d.y + (d.h - total) / 2 + i * (h + rowGap), w: d.w, h }))
192
+ }
193
+
194
+ /* ─────────────────────────────── the composition ─────────────────────────────── */
195
+
196
+ const POP = { damping: 0.62, frequency: 13, ms: 560 }
197
+
198
+ /**
199
+ * @param {{ variables: object, area: { x: number, y: number, w: number, h: number }, output: { width: number, height: number }, duration: number }} input
200
+ * @param {(spring: object) => object[]} springKeyframes motion.js's, handed in so the two files don't import each other
201
+ * @returns {{ css: string, body: string, animations: object[] }}
202
+ */
203
+ export function buildScene({ variables, area, output, duration }, springKeyframes) {
204
+ const scene = cleanScene(variables)
205
+ if (!scene) throw new EngineFailure("plan", "bad_scene", "This scene's variables don't describe a scene.")
206
+ const { kind, title, items } = scene
207
+ const theme = SCENE_THEMES[scene.theme]
208
+ const ms = (duration / FLICKS) * 1000
209
+ const { width: W, height: H } = output
210
+ const base = Math.round(Math.min(W, H) * 0.05)
211
+ const tall = H > W
212
+ const floor = Math.ceil(H * 0.0205)
213
+ const titleSize = fitFont(title || " ", area.w, base * 3.4, base * 1.3, floor)
214
+ const titleLines = title ? linesAt(title, titleSize, area.w) : 0
215
+ const titleH = title ? Math.ceil(titleLines * titleSize * 1.2) : 0
216
+ const room = titleH ? titleH + Math.round(base * 0.9) : 0
217
+ const d = { x: area.x, y: area.y + room, w: area.w, h: area.h - room }
218
+ const boxes = layoutKind(kind, items.length, d, base, tall).map((b) => ({ x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.w), h: Math.round(b.h) }))
219
+
220
+ // Each label when its word is spoken: code's times, or evenly through the first two thirds
221
+ const start = Math.min(450, ms * 0.15)
222
+ const last = Math.max(start, ms * 0.68)
223
+ const reveals = items.map((item, i) => {
224
+ const even = items.length === 1 ? start : start + ((last - start) * i) / (items.length - 1)
225
+ return Math.round(clampNumber(variables.items?.[i]?.reveal ?? even, start, last))
226
+ })
227
+
228
+ const animations = []
229
+ const animate = (id, keyframes, options) => animations.push({ id, keyframes, options: { fill: "both", ...options } })
230
+ // The whole scene comes in and goes out, so the voice carries across
231
+ const inMs = Math.min(240, ms * 0.1)
232
+ const outMs = Math.min(200, ms * 0.08)
233
+ animate("s", [{ opacity: 0, offset: 0 }, { opacity: 1, offset: round(inMs / ms) }, { opacity: 1, offset: round(1 - outMs / ms) }, { opacity: 0, offset: 1 }], { duration: ms })
234
+ animate("w", [{ transform: "scale(1) translate(0,0)" }, { transform: "scale(1.04) translate(-0.6%,-0.4%)" }], { duration: ms, easing: "linear" })
235
+
236
+ const pop = (id, at, from = { y: Math.round(base * 0.9), scale: 0.88, opacity: 0 }) => animate(id, springKeyframes({ ...POP, from, to: { y: 0, scale: 1, opacity: 1 } }), { duration: POP.ms, delay: at })
237
+ const draw = (id, at, length = 420) => animate(id, [{ strokeDashoffset: 1 }, { strokeDashoffset: 0 }], { duration: length, delay: Math.max(0, at), easing: "cubic-bezier(.3,0,.2,1)" })
238
+
239
+ const parts = []
240
+ const svg = []
241
+ const label = (i, box, text, { size, plate = theme.plate, color = theme.ink, extra = "", align = "center", transparent = false } = {}) => {
242
+ const pad = Math.round(base * 0.45)
243
+ const font = size ?? fitFont(text, box.w - pad * 2, box.h - pad, base * 1.1, floor)
244
+ const seen = plate === theme.bg
245
+ parts.push(`<div id="l${i}" class="l" style="left:${box.x}px;top:${box.y}px;width:${box.w}px;height:${box.h}px;background:${transparent ? "transparent" : plate};justify-content:${align};${seen || transparent ? "border-color:transparent;" : ""}${extra}"><span data-text style="font-size:${font}px;background:${plate};color:${color};text-align:${align === "center" ? "center" : "left"}">${escapeText(text)}</span></div>`)
246
+ pop(`l${i}`, reveals[i] ?? start)
247
+ // A ring leaves the card as it lands, so the eye goes to what was just said
248
+ if (!seen) animate(`l${i}`, [{ boxShadow: `0 0 0 0 ${theme.accent}cc` }, { boxShadow: `0 0 0 ${Math.round(base * 0.5)}px ${theme.accent}00` }], { duration: 620, delay: (reveals[i] ?? start) + 90, easing: "ease-out" })
249
+ }
250
+ const dash = `pathLength="1" stroke-dasharray="1" stroke-dashoffset="1"`
251
+ const stroke = Math.max(4, Math.round(base * 0.14))
252
+ const centerOf = (b) => ({ x: b.x + b.w / 2, y: b.y + b.h / 2 })
253
+ // A point on a box's edge on the way to another point, so lines start at the plate, not inside it
254
+ const edgeToward = (b, to) => {
255
+ const c = centerOf(b)
256
+ const dx = to.x - c.x
257
+ const dy = to.y - c.y
258
+ const scale = Math.min(dx ? b.w / 2 / Math.abs(dx) : Infinity, dy ? b.h / 2 / Math.abs(dy) : Infinity)
259
+ return { x: Math.round(c.x + dx * scale), y: Math.round(c.y + dy * scale) }
260
+ }
261
+ const arrow = (id, a, b, at, colour = theme.accent) => {
262
+ const from = edgeToward(a, centerOf(b))
263
+ const to = edgeToward(b, centerOf(a))
264
+ const angle = Math.atan2(to.y - from.y, to.x - from.x)
265
+ const head = Math.round(base * 0.42)
266
+ const tip = (t) => `${Math.round(to.x - head * Math.cos(angle + t))},${Math.round(to.y - head * Math.sin(angle + t))}`
267
+ svg.push(`<path id="${id}" d="M${from.x} ${from.y}L${to.x} ${to.y}" fill="none" stroke="${colour}" stroke-width="${stroke}" stroke-linecap="round" ${dash}/>`)
268
+ svg.push(`<polygon id="${id}h" points="${to.x},${to.y} ${tip(0.45)} ${tip(-0.45)}" fill="${colour}"/>`)
269
+ draw(id, at - 380, 380)
270
+ animate(`${id}h`, [{ opacity: 0 }, { opacity: 1 }], { duration: 120, delay: Math.max(0, at - 60) })
271
+ return { from, to }
272
+ }
273
+ // A small light travelling a path for the rest of the scene, so a finished diagram still lives
274
+ const pulses = []
275
+ const runner = (id, path, at, loop, size = Math.round(base * 0.34), colour = theme.hot, offset = 0) => {
276
+ pulses.push(`<i id="${id}" class="p" style="width:${size}px;height:${size}px;margin:${-size / 2}px 0 0 ${-size / 2}px;background:${colour};box-shadow:0 0 ${size}px ${colour};offset-path:path('${path}')"></i>`)
277
+ const remaining = Math.max(1, ms - at)
278
+ animate(id, [{ offsetDistance: "0%", opacity: 0, offset: 0 }, { opacity: 1, offset: 0.08 }, { opacity: 1, offset: 0.92 }, { offsetDistance: "100%", opacity: 0, offset: 1 }], { duration: loop, delay: at + offset, iterations: Math.max(1, Math.ceil(remaining / loop)), easing: "linear" })
279
+ }
280
+
281
+ if (kind === "process") {
282
+ items.forEach((item, i) => {
283
+ label(i, boxes[i], item.text)
284
+ if (i) arrow(`a${i}`, boxes[i - 1], boxes[i], reveals[i])
285
+ })
286
+ const allIn = reveals.at(-1) + POP.ms
287
+ items.slice(1).forEach((_, i) => {
288
+ const from = edgeToward(boxes[i], centerOf(boxes[i + 1]))
289
+ const to = edgeToward(boxes[i + 1], centerOf(boxes[i]))
290
+ runner(`r${i}`, `M${from.x} ${from.y}L${to.x} ${to.y}`, allIn, 1400, undefined, undefined, i * 280)
291
+ })
292
+ } else if (kind === "cycle") {
293
+ const c = { x: d.x + d.w / 2, y: d.y + d.h / 2 }
294
+ const rx = Math.round((d.w - boxes[0].w) / 2)
295
+ const ry = Math.round((d.h - boxes[0].h) / 2)
296
+ const ring = `M${c.x} ${c.y - ry}A${rx} ${ry} 0 1 1 ${c.x} ${c.y + ry}A${rx} ${ry} 0 1 1 ${c.x} ${c.y - ry}`
297
+ svg.push(`<path id="ring" d="${ring}" fill="none" stroke="${theme.line}" stroke-width="${stroke}" ${dash}/>`)
298
+ draw("ring", start, Math.max(600, last - start))
299
+ items.forEach((item, i) => label(i, boxes[i], item.text))
300
+ const allIn = reveals.at(-1) + 200
301
+ for (let i = 0; i < 3; i++) runner(`r${i}`, ring, allIn, 3200, undefined, i === 0 ? theme.hot : theme.accent, i * 1066)
302
+ } else if (kind === "hub") {
303
+ label(0, boxes[0], items[0].text, { plate: theme.accent, color: theme.bg })
304
+ items.slice(1).forEach((item, i) => {
305
+ const box = boxes[i + 1]
306
+ const from = edgeToward(boxes[0], centerOf(box))
307
+ const to = edgeToward(box, centerOf(boxes[0]))
308
+ svg.push(`<path id="a${i}" d="M${from.x} ${from.y}L${to.x} ${to.y}" fill="none" stroke="${theme.accent}" stroke-width="${stroke}" stroke-linecap="round" ${dash}/>`)
309
+ draw(`a${i}`, reveals[i + 1] - 320, 320)
310
+ label(i + 1, box, item.text)
311
+ runner(`r${i}`, `M${from.x} ${from.y}L${to.x} ${to.y}`, reveals[i + 1] + POP.ms, 1500, undefined, undefined, i * 220)
312
+ })
313
+ } else if (kind === "flow") {
314
+ const first = boxes[0]
315
+ const lastBox = boxes.at(-1)
316
+ const a = edgeToward(first, centerOf(lastBox))
317
+ const b = edgeToward(lastBox, centerOf(first))
318
+ const mode = scene.mode
319
+ const width = Math.round(base * (tall ? 3.4 : 2.6))
320
+ // The vessel: a wide soft channel with its two walls drawn in
321
+ const tube = `M${a.x} ${a.y}L${b.x} ${b.y}`
322
+ svg.push(`<path d="${tube}" fill="none" stroke="${theme.plate}" stroke-width="${width}"/>`)
323
+ const nx = tall ? width / 2 : 0
324
+ const ny = tall ? 0 : width / 2
325
+ for (const [n, sign] of [[0, 1], [1, -1]]) {
326
+ svg.push(`<path id="wall${n}" d="M${a.x + sign * nx} ${a.y + sign * ny}L${b.x + sign * nx} ${b.y + sign * ny}" fill="none" stroke="${theme.line}" stroke-width="${Math.max(3, stroke - 2)}" ${dash}/>`)
327
+ draw(`wall${n}`, start, 520)
328
+ }
329
+ // Stops short of the end when blocked: at the middle item if there is one, else a barrier
330
+ const stopAt = items.length === 3 ? edgeToward(boxes[1], centerOf(first)) : { x: Math.round(a.x + (b.x - a.x) * 0.55), y: Math.round(a.y + (b.y - a.y) * 0.55) }
331
+ const span = Math.hypot(b.x - a.x, b.y - a.y)
332
+ const count = mode === "floods" ? 36 : 22
333
+ const size = Math.round(base * 0.5)
334
+ const window = Math.max(600, ms - start - 400)
335
+ for (let i = 0; i < count; i++) {
336
+ const lane = (seeded(i) - 0.5) * (width - size * 1.6)
337
+ const ox = tall ? lane : 0
338
+ const oy = tall ? 0 : lane
339
+ const colour = seeded(i + 40) > 0.75 ? theme.accent : theme.hot
340
+ const end = mode === "blocked" ? stopAt : b
341
+ // Blocked: they pile up behind the stop, each a little further back than the last
342
+ const pile = mode === "blocked" ? 1 - (seeded(i + 7) * 0.32 + (i / count) * 0.2) : 1
343
+ const path = `M${a.x + ox} ${a.y + oy}L${Math.round(a.x + (end.x - a.x) * pile + ox)} ${Math.round(a.y + (end.y - a.y) * pile + oy)}`
344
+ const u = (i + seeded(i + 20) * 0.6) / count
345
+ // Floods: few at first, then more and more
346
+ const when = start + 200 + window * 0.82 * (mode === "floods" ? Math.sqrt(u) : u)
347
+ const travel = Math.max(450, (span / (base * 18)) * 1000) * (0.85 + seeded(i + 3) * 0.3)
348
+ pulses.push(`<i id="q${i}" class="p" style="width:${size}px;height:${size}px;margin:${-size / 2}px 0 0 ${-size / 2}px;background:${colour};offset-path:path('${path}')"></i>`)
349
+ if (mode === "blocked") animate(`q${i}`, [{ offsetDistance: "0%", opacity: 0, offset: 0 }, { opacity: 1, offset: 0.1 }, { offsetDistance: "100%", opacity: 1, offset: 1 }], { duration: travel, delay: when * 0.6, easing: "cubic-bezier(.2,.7,.3,1)" })
350
+ else animate(`q${i}`, [{ offsetDistance: "0%", opacity: 0, offset: 0 }, { opacity: 1, offset: 0.1 }, { opacity: 1, offset: 0.9 }, { offsetDistance: "100%", opacity: 0, offset: 1 }], { duration: travel, delay: when, iterations: Math.max(1, Math.ceil((ms - when) / travel)), easing: "linear" })
351
+ }
352
+ if (mode === "blocked" && items.length === 2) {
353
+ const bar = Math.round(width * 0.62)
354
+ const gx = stopAt.x
355
+ const gy = stopAt.y
356
+ svg.push(`<path id="stop" d="${tall ? `M${gx - bar} ${gy}L${gx + bar} ${gy}` : `M${gx} ${gy - bar}L${gx} ${gy + bar}`}" fill="none" stroke="${theme.hot}" stroke-width="${stroke * 2}" stroke-linecap="round" ${dash}/>`)
357
+ draw("stop", start + 260, 260)
358
+ }
359
+ if (mode === "floods") {
360
+ // The far end fills up
361
+ parts.push(`<div class="c" style="left:${lastBox.x}px;top:${lastBox.y}px;width:${lastBox.w}px;height:${lastBox.h}px;background:${theme.plate}"></div><div id="fill" class="c" style="left:${lastBox.x}px;top:${lastBox.y}px;width:${lastBox.w}px;height:${lastBox.h}px;background:${theme.hot};transform-origin:50% 100%"></div>`)
362
+ animate("fill", [{ transform: "scaleY(0)", opacity: 0.9 }, { transform: "scaleY(1)", opacity: 0.9 }], { duration: Math.max(400, ms - start - 300), delay: start + 200, easing: "cubic-bezier(.5,0,.8,.6)" })
363
+ }
364
+ items.forEach((item, i) => label(i, boxes[i], item.text, mode === "floods" && i === items.length - 1 ? { transparent: true } : {}))
365
+ } else if (kind === "compare") {
366
+ const numbers = items.map((i) => Number(String(i.value ?? "").replace(",", ".")))
367
+ const bothNumbers = numbers.every((n) => Number.isFinite(n) && n >= 0) && items.every((i) => i.value !== undefined)
368
+ const largest = Math.max(1e-9, ...numbers.filter(Number.isFinite))
369
+ items.forEach((item, i) => {
370
+ const box = boxes[i]
371
+ const colour = i ? theme.hot : theme.accent
372
+ const pad = Math.round(base * 0.7)
373
+ parts.push(`<div id="c${i}" class="c" style="left:${box.x}px;top:${box.y}px;width:${box.w}px;height:${box.h}px;background:${theme.plate}"></div>`)
374
+ pop(`c${i}`, reveals[i])
375
+ const textBox = { x: box.x + pad, y: box.y + pad, w: box.w - pad * 2, h: Math.round((box.h - pad * 2) * (item.value !== undefined ? 0.42 : 1)) }
376
+ label(i, textBox, item.text, { size: fitFont(item.text, textBox.w - base, textBox.h - base * 0.4, base * 1.3, floor), extra: "border-color:transparent;" })
377
+ if (item.value !== undefined) {
378
+ const numberBox = { x: box.x + pad, y: textBox.y + textBox.h + Math.round(base * 0.2), w: box.w - pad * 2, h: Math.round((box.h - pad * 2) * 0.34) }
379
+ const text = `${item.value}${item.unit ?? ""}`
380
+ const size = Math.max(floor, Math.min(Math.round(numberBox.h * 0.8), Math.floor((numberBox.w - base) / (text.length * 0.66))))
381
+ parts.push(`<div id="n${i}" class="l" style="left:${numberBox.x}px;top:${numberBox.y}px;width:${numberBox.w}px;height:${numberBox.h}px;background:${theme.plate};border-color:transparent"><span class="n" data-text style="font-size:${size}px;background:${theme.plate};color:${colour};text-align:center">${escapeText(text)}</span></div>`)
382
+ pop(`n${i}`, reveals[i] + 140)
383
+ if (bothNumbers) {
384
+ const track = { x: box.x + pad, y: numberBox.y + numberBox.h + Math.round(base * 0.2), w: box.w - pad * 2, h: Math.round(base * 0.55) }
385
+ parts.push(`<div class="c" style="left:${track.x}px;top:${track.y}px;width:${track.w}px;height:${track.h}px;background:${theme.bg}"></div><div id="b${i}" class="c" style="left:${track.x}px;top:${track.y}px;width:${Math.max(track.h, Math.round((track.w * numbers[i]) / largest))}px;height:${track.h}px;background:${colour};transform-origin:0 50%"></div>`)
386
+ animate(`b${i}`, [{ transform: "scaleX(0)" }, { transform: "scaleX(1)" }], { duration: 700, delay: reveals[i] + 200, easing: "cubic-bezier(.2,.8,.2,1)" })
387
+ }
388
+ }
389
+ })
390
+ } else if (kind === "stat") {
391
+ const item = items[0]
392
+ const box = boxes[0]
393
+ const value = String(item.value)
394
+ const unit = item.unit ?? ""
395
+ const numberH = Math.round(box.h * 0.46)
396
+ const size = Math.round(Math.min(numberH * 0.86, (box.w * 0.92) / (value.length * 0.62 + unit.length * 1.05)))
397
+ const top = box.y + Math.round(box.h * 0.1)
398
+ const cellW = Math.round(size * 0.62)
399
+ const unitW = Math.ceil(size * 1.05 * unit.length)
400
+ const totalW = cellW * value.length + unitW
401
+ let x = box.x + Math.round((box.w - totalW) / 2)
402
+ const cellH = Math.round(size * 1.16)
403
+ const rail = Array.from({ length: 10 }, (_, n) => `<b style="height:${cellH}px;line-height:${cellH}px">${n}</b>`).join("")
404
+ let column = 0
405
+ for (const ch of value) {
406
+ if (/\d/.test(ch)) {
407
+ const id = `d${column}`
408
+ parts.push(`<div class="o" style="left:${x}px;top:${top}px;width:${cellW}px;height:${cellH}px;font-size:${size}px;color:${theme.hot}"><div id="${id}" style="position:absolute;left:0;top:0;width:100%;text-align:center">${rail}</div></div>`)
409
+ // Rolls through the digits and settles on the spoken one
410
+ const target = -Number(ch) * cellH
411
+ animate(id, [{ transform: `translateY(${cellH * 0}px)` }, { transform: `translateY(${target}px)` }], { duration: 760 + column * 90, delay: reveals[0], easing: "cubic-bezier(.16,.9,.28,1)" })
412
+ column++
413
+ } else parts.push(`<div class="o" style="left:${x}px;top:${top}px;width:${cellW}px;height:${cellH}px;font-size:${size}px;line-height:${cellH}px;color:${theme.hot};text-align:center">${escapeText(ch)}</div>`)
414
+ x += cellW
415
+ }
416
+ if (unit) parts.push(`<div id="u" class="o" style="left:${x}px;top:${top}px;width:${unitW}px;height:${cellH}px;font-size:${size}px;line-height:${cellH}px;color:${theme.accent};text-align:left;white-space:nowrap">${escapeText(unit)}</div>`)
417
+ if (unit) pop("u", reveals[0] + 500)
418
+ // A share of 100 fills a line under the number
419
+ const whole = Number(value.replace(",", "."))
420
+ const barY = top + cellH + Math.round(base * 0.6)
421
+ if (unit === "%" && whole >= 0 && whole <= 100) {
422
+ const barH = Math.round(base * 0.5)
423
+ const barX = box.x + Math.round(box.w * 0.08)
424
+ const barW = Math.round(box.w * 0.84)
425
+ parts.push(`<div class="c" style="left:${barX}px;top:${barY}px;width:${barW}px;height:${barH}px;background:${theme.plate}"></div><div id="fillbar" class="c" style="left:${barX}px;top:${barY}px;width:${Math.max(barH, Math.round((barW * whole) / 100))}px;height:${barH}px;background:${theme.hot};transform-origin:0 50%"></div>`)
426
+ animate("fillbar", [{ transform: "scaleX(0)" }, { transform: "scaleX(1)" }], { duration: 800, delay: reveals[0] + 200, easing: "cubic-bezier(.2,.8,.2,1)" })
427
+ }
428
+ const labelY = barY + Math.round(base * 1.4)
429
+ label(0, { x: box.x, y: labelY, w: box.w, h: Math.max(Math.round(base * 2.4), box.y + box.h - labelY) }, item.text, { size: fitFont(item.text, box.w - base, Math.max(Math.round(base * 2.4), box.y + box.h - labelY) - base * 0.4, base * 1.3, floor) })
430
+ } else {
431
+ const numbers = items.map((i) => Number(String(i.value).replace(",", ".")))
432
+ const largest = Math.max(1e-9, ...numbers)
433
+ items.forEach((item, i) => {
434
+ const box = boxes[i]
435
+ const stacked = tall
436
+ const labelW = stacked ? box.w : Math.round(box.w * 0.36)
437
+ const labelH = stacked ? Math.round(box.h * 0.52) : box.h
438
+ const trackY = stacked ? box.y + labelH : box.y + Math.round(box.h * 0.2)
439
+ const trackX = stacked ? box.x : box.x + labelW + Math.round(base * 0.4)
440
+ const trackH = stacked ? box.h - labelH : Math.round(box.h * 0.6)
441
+ const valueText = `${item.value}${item.unit ?? ""}`
442
+ const valueW = Math.round(Math.max(base * 2.4, (valueText.length * base * 0.72) + base * 0.9))
443
+ const trackW = box.x + box.w - trackX - valueW - Math.round(base * 0.3)
444
+ const size = fitFont(item.text, labelW - base, labelH - base * 0.2, base, floor)
445
+ label(i, { x: box.x, y: box.y, w: labelW, h: labelH }, item.text, { size, align: "flex-start" })
446
+ const barW = Math.max(trackH, Math.round((trackW * numbers[i]) / largest))
447
+ const colour = numbers[i] === largest ? theme.hot : theme.accent
448
+ parts.push(`<div class="c" style="left:${trackX}px;top:${trackY}px;width:${trackW}px;height:${trackH}px;background:${theme.plate}"></div><div id="b${i}" class="c" style="left:${trackX}px;top:${trackY}px;width:${barW}px;height:${trackH}px;background:${colour};transform-origin:0 50%"></div>`)
449
+ animate(`b${i}`, [{ transform: "scaleX(0)" }, { transform: "scaleX(1)" }], { duration: 760, delay: reveals[i] + 60, easing: "cubic-bezier(.2,.8,.2,1)" })
450
+ const numberSize = Math.max(floor, Math.min(base, Math.floor((valueW - base * 0.9) / (valueText.length * 0.66)), Math.floor(trackH / 1.2)))
451
+ parts.push(`<div id="n${i}" class="l" style="left:${trackX + trackW + Math.round(base * 0.3)}px;top:${trackY}px;width:${valueW}px;height:${trackH}px;background:${theme.plate};justify-content:center"><span class="n" data-text style="font-size:${numberSize}px;background:${theme.plate};color:${colour};text-align:center">${escapeText(valueText)}</span></div>`)
452
+ pop(`n${i}`, reveals[i] + 260)
453
+ })
454
+ }
455
+
456
+ // A few slow motes behind everything, so a finished diagram still lives
457
+ const motes = []
458
+ for (let i = 0; i < 14; i++) {
459
+ const size = Math.round(base * (0.14 + seeded(i + 60) * 0.2))
460
+ const x = Math.round(seeded(i + 80) * W)
461
+ const y = Math.round(seeded(i + 100) * H)
462
+ const drift = Math.round(base * (2 + seeded(i + 120) * 3))
463
+ motes.push(`<i id="m${i}" class="p" style="left:${x}px;top:${y}px;width:${size}px;height:${size}px;background:${i % 3 ? theme.accent : theme.hot};opacity:.22"></i>`)
464
+ animate(`m${i}`, [{ transform: "translate(0,0)" }, { transform: `translate(${Math.round((seeded(i + 140) - 0.5) * drift)}px,${-drift}px)` }], { duration: ms, easing: "linear" })
465
+ }
466
+
467
+ // The caption row on a light theme keeps its own dark band, so white captions read
468
+ const bandTop = area.y + area.h
469
+ const band = variables.band && theme.band ? `<div class="c" style="left:0;top:${bandTop}px;width:${W}px;height:${H - bandTop}px;background:${theme.band};border-radius:0"></div>` : ""
470
+ const titleHtml = title ? `<div id="t" class="t" style="left:${area.x}px;top:${area.y}px;width:${area.w}px"><span data-text style="font-size:${titleSize}px;background:${theme.bg}">${escapeText(title)}</span></div>` : ""
471
+ if (title) pop("t", Math.min(120, ms * 0.04), { y: Math.round(base * 0.6), opacity: 0 })
472
+ const dots = Math.round(base * 1.1)
473
+ const pattern = scene.theme === "blueprint" || scene.theme === "paper" ? `background-image:linear-gradient(${theme.line}33 1px,transparent 1px),linear-gradient(90deg,${theme.line}33 1px,transparent 1px);background-size:${dots * 2}px ${dots * 2}px` : `background-image:radial-gradient(${theme.line}66 ${Math.max(1, Math.round(base * 0.05))}px,transparent 0);background-size:${dots}px ${dots}px`
474
+
475
+ return {
476
+ css: `#s{position:absolute;inset:0;background:${theme.bg};overflow:hidden;font-family:'Helvetica Neue',Helvetica,Arial,'Noto Sans','Noto Sans Devanagari','Noto Sans Telugu',sans-serif;color:${theme.ink}}#w{position:absolute;inset:-4%;${pattern}}#v{position:absolute;inset:0;background:radial-gradient(ellipse at 50% 45%,${theme.accent}26,transparent 68%)}#g{position:absolute;left:0;top:0;width:${W}px;height:${H}px;overflow:visible}.l,.c,.o,.t,.p{position:absolute}.l{display:flex;align-items:center;border-radius:${Math.round(base * 0.4)}px;box-sizing:border-box;padding:0 ${Math.round(base * 0.4)}px;border:${Math.max(2, Math.round(base * 0.05))}px solid ${theme.line}}.l span{display:block;width:100%;font-weight:700;line-height:1.2;overflow-wrap:anywhere;border-radius:.2em}.l span.n{white-space:nowrap;overflow-wrap:normal;font-weight:800}.c{border-radius:${Math.round(base * 0.4)}px}.o{overflow:hidden;font-weight:800;font-variant-numeric:tabular-nums}.o b{display:block;font-weight:800}.t{text-align:center}.t span{font-weight:800;line-height:1.2;display:inline-block;max-width:100%}.p{left:0;top:0;border-radius:50%;offset-rotate:0deg}`,
477
+ body: `<div id="s"><div id="w"></div><div id="v"></div>${motes.join("")}${band}<svg id="g" viewBox="0 0 ${W} ${H}">${svg.join("")}</svg>${pulses.join("")}${titleHtml}${parts.join("")}</div>`,
478
+ animations,
479
+ }
480
+ }
@@ -0,0 +1,63 @@
1
+ // Sound effects made by code (2026-11-09): a whoosh or a pop for cuts, a riser into the
2
+ // intro, a hit for a cold open's end. Written sample by sample, so no one else's sound is
3
+ // in them, and each knows where its peak is: add_sfx lands that peak on the cut.
4
+
5
+ import { writeWav } from "./music-bed.js"
6
+
7
+ const RATE = 48_000
8
+ const FLICKS = 705_600_000
9
+
10
+ /** Each effect: its length and where its loudest moment falls, in seconds. */
11
+ export const SFX = {
12
+ whoosh: { seconds: 0.7, peak: 0.42 },
13
+ pop: { seconds: 0.14, peak: 0.01 },
14
+ riser: { seconds: 1.6, peak: 1.55 },
15
+ hit: { seconds: 0.9, peak: 0.02 },
16
+ }
17
+
18
+ /**
19
+ * Writes one effect as a stereo WAV.
20
+ * @returns {{ file: string, peak: number }} peak in flicks from the file's start
21
+ */
22
+ export function writeSfx(file, kind) {
23
+ const spec = SFX[kind]
24
+ if (!spec) throw new RangeError(`There is no "${kind}" sound.`)
25
+ const total = Math.round(spec.seconds * RATE)
26
+ const left = new Float32Array(total)
27
+ const right = new Float32Array(total)
28
+ let seed = 0x2545f491
29
+ const noise = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32) * 2 - 1
30
+ let lowL = 0
31
+ let lowR = 0
32
+ for (let i = 0; i < total; i++) {
33
+ const t = i / RATE
34
+ const x = t / spec.seconds // 0 to 1 through the effect
35
+ let l = 0
36
+ let r = 0
37
+ if (kind === "whoosh" || kind === "riser") {
38
+ // Noise through a one-pole low-pass that opens and closes: the sweep you hear
39
+ const open = kind === "whoosh" ? Math.sin(Math.PI * Math.min(1, t / spec.peak / 2 + (t > spec.peak ? 0.5 * ((t - spec.peak) / (spec.seconds - spec.peak)) : 0))) : x * x
40
+ const k = 0.02 + 0.5 * open
41
+ lowL += k * (noise() - lowL)
42
+ lowR += k * (noise() - lowR)
43
+ const env = kind === "whoosh" ? Math.exp(-(((t - spec.peak) / 0.16) ** 2)) : x ** 2.2 * (t < spec.peak ? 1 : Math.max(0, 1 - (t - spec.peak) / 0.05))
44
+ // A riser also climbs in pitch
45
+ const tone = kind === "riser" ? 0.35 * Math.sin(2 * Math.PI * (200 + 900 * x * x) * t) : 0
46
+ // The whoosh moves from left to right as it passes
47
+ const pan = kind === "whoosh" ? x : 0.5
48
+ l = (lowL + tone) * env * (1 - pan * 0.6)
49
+ r = (lowR + tone) * env * (0.4 + pan * 0.6)
50
+ } else if (kind === "pop") {
51
+ const env = Math.exp(-t * 60)
52
+ l = r = Math.sin(2 * Math.PI * (900 - 600 * x) * t) * env
53
+ } else {
54
+ // Hit: a deep falling thump with a short noisy attack
55
+ const env = Math.exp(-t * 6)
56
+ l = r = Math.sin(2 * Math.PI * (40 + 90 * Math.exp(-t * 25)) * t) * env + noise() * Math.exp(-t * 80) * 0.4
57
+ }
58
+ left[i] = l
59
+ right[i] = r
60
+ }
61
+ writeWav(file, left, right)
62
+ return { file, peak: Math.round(spec.peak * FLICKS) }
63
+ }
@@ -7,7 +7,9 @@ import { existsSync, mkdirSync, readFileSync, renameSync } from "node:fs"
7
7
  import { dirname, join } from "node:path"
8
8
  import { fileURLToPath } from "node:url"
9
9
 
10
+ import { isSceneBlock } from "../core/layout.js"
10
11
  import { scriptOf } from "../engine/captions.js"
12
+ import { sceneText } from "../engine/scenes.js"
11
13
 
12
14
  const HELPER = join(dirname(fileURLToPath(import.meta.url)), "text.swift")
13
15
  const FLICKS = 705_600_000
@@ -72,6 +74,8 @@ export function similarity(a, b) {
72
74
  /** What a tile meant to show. */
73
75
  export function intendedText(tile) {
74
76
  if (tile.kind === "caption") return tile.node.text ?? tile.node.words.map((w) => w.text).join(" ")
77
+ if (isSceneBlock(tile.node)) return sceneText(tile.node.variables)
78
+ if (tile.node.blockId === "term") return [tile.node.variables?.text, tile.node.variables?.quote, tile.node.variables?.source].filter(Boolean).join(" ")
75
79
  return [tile.node.variables?.text, tile.node.variables?.subtitle].filter(Boolean).join(" ")
76
80
  }
77
81
 
@@ -86,19 +90,35 @@ export function judgeCopy(read, { copySimilarity }) {
86
90
  const failures = []
87
91
  const unread = []
88
92
  let worst = 1
89
- for (const { tile, seen, unsure = [] } of read) {
93
+ for (const { tile, seen: reading, unsure = [] } of read) {
90
94
  const meant = intendedText(tile)
95
+ // A reader's stray space ("O kay") isn't on the screen
96
+ const squeezed = (text) => normalise(text).replace(/ /g, "")
97
+ const seen = squeezed(meant) === squeezed(reading ?? "") ? meant : reading
91
98
  if (scriptOf(meant) !== "latin") {
92
99
  unread.push({ tile: tile.key, script: scriptOf(meant) })
93
100
  continue
94
101
  }
95
- const score = similarity(meant, seen ?? "")
96
- worst = Math.min(worst, score)
97
102
  // Every word meant must be on screen as itself: a one-letter change in a name passes a similarity (found in ED10)
98
103
  const shownWords = new Set(normalise(seen ?? "").split(" "))
99
104
  // Where the reader wasn't sure, one letter off is the reader's slip; where it was sure, it is the screen
100
- const lost = normalise(meant).split(" ").filter((w) => w && !shownWords.has(w) && !unsure.some((u) => nearly(u, w)))
101
- if (score < copySimilarity || lost.length) failures.push({ kind: "copy_mismatch", t: tile.at, seconds: Math.round((tile.at / FLICKS) * 100) / 100, meant, seen: seen ?? "", similarity: Math.round(score * 100) / 100, ...(lost.length ? { missing: lost } : {}) })
105
+ const expected = normalise(meant).split(" ").filter(Boolean)
106
+ const isScene = isSceneBlock(tile.node)
107
+ // A scene's unit sits apart from its number and a reader runs them together ("50000₹" read as "50000k"): the digits must still be exact
108
+ const shownNumber = (w) => isScene && /^\d/.test(w) && [...shownWords].some((seenWord) => new RegExp(`^${w}(?:\\D|$)`).test(seenWord))
109
+ // A caption's text comes from code, so one letter misread in an ordinary word, the same length, is the reader's slip ("back" read as "Dack", found on real footage).
110
+ // A name or a number must still match exactly
111
+ const ordinary = new Set(tile.kind === "caption" ? meant.split(/\s+/).filter((w, i) => !isNameOrNumber(w, i)).map(normalise) : [])
112
+ // Thin strokes (l, i, 1) and doubled letters are what a reader drops ("all" read as "a", "mellitus" as "melitus")
113
+ const thin = (w) => w.replace(/[li1|]/g, "").replace(/(.)\1+/g, "$1")
114
+ const slip = (w) => ordinary.has(w) && [...shownWords].some((seenWord) => (seenWord.length === w.length && nearly(seenWord, w)) || (thin(seenWord) === thin(w) && thin(w).length > 0))
115
+ const lost = expected.filter((w) => !shownWords.has(w) && !shownNumber(w) && !slip(w) && !unsure.some((u) => nearly(u, w)))
116
+ // A diagram has no reading order, so a scene is judged by its words alone
117
+ const score = isScene ? 1 - lost.length / Math.max(1, expected.length) : similarity(meant, seen ?? "")
118
+ worst = Math.min(worst, score)
119
+ // Nothing meant is missing and the reading only adds a stray letter ("week.s"): the screen is right
120
+ const strays = tile.kind === "caption" && !lost.length && [...shownWords].filter((w) => !expected.includes(w)).every((w) => w.length === 1)
121
+ if ((score < copySimilarity && !strays) || lost.length) failures.push({ kind: "copy_mismatch", t: tile.at, seconds: Math.round((tile.at / FLICKS) * 100) / 100, meant, seen: seen ?? "", similarity: Math.round(score * 100) / 100, ...(lost.length ? { missing: lost } : {}) })
102
122
  // What was said: a caption's names and numbers must be on screen as they were spoken
103
123
  if (tile.kind === "caption") {
104
124
  const shown = ` ${normalise(seen ?? "")} `