@kriya-ai/harness 0.2.4 → 2.0.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 (134) hide show
  1. package/RELEASE_NOTES.md +121 -0
  2. package/SAFETY.md +181 -0
  3. package/THIRD_PARTY_NOTICES.md +113 -0
  4. package/bin/kriya.js +188 -2
  5. package/bundle/cordis.patch.yml +49 -0
  6. package/contract/SOURCE.md +3 -3
  7. package/contract/contract.json +504 -3
  8. package/contract/schemas/api.json +64 -0
  9. package/contract/schemas/auth_matrix.json +44 -0
  10. package/contract/schemas/component_states.json +33 -0
  11. package/contract/schemas/design_tokens.json +34 -0
  12. package/contract/schemas/scene_direction.json +82 -0
  13. package/contract/schemas/threat_model.json +44 -0
  14. package/package.json +2 -1
  15. package/plugins/changes/client.js +5 -3
  16. package/plugins/deploy/index.js +215 -0
  17. package/plugins/deploy/package.json +13 -0
  18. package/plugins/grounding/index.js +81 -0
  19. package/plugins/grounding/lookup.js +373 -0
  20. package/plugins/grounding/package.json +13 -0
  21. package/plugins/kriya-tools/index.js +2 -1
  22. package/plugins/loop/index.js +376 -10
  23. package/plugins/mcp/index.js +79 -0
  24. package/plugins/mcp/package.json +13 -0
  25. package/plugins/mirror/index.js +17 -0
  26. package/plugins/overview/client.js +5 -2
  27. package/plugins/preview/client.js +12 -6
  28. package/plugins/progress/client.js +7 -4
  29. package/plugins/repo/index.js +230 -0
  30. package/plugins/repo/package.json +13 -0
  31. package/plugins/repo/repo.js +348 -0
  32. package/plugins/runstrip/client.js +426 -0
  33. package/plugins/runstrip/index.js +301 -0
  34. package/plugins/runstrip/package.json +23 -0
  35. package/src/cartridges.js +133 -0
  36. package/src/contracts.js +130 -0
  37. package/src/critic.js +78 -0
  38. package/src/daemon.js +7 -1
  39. package/src/doctor.js +67 -0
  40. package/src/edit/core/effects.js +185 -0
  41. package/src/edit/core/ffmpeg.js +82 -5
  42. package/src/edit/core/layout.js +46 -1
  43. package/src/edit/core/ops.js +175 -3
  44. package/src/edit/core/plan.js +95 -9
  45. package/src/edit/core/project.d.ts +24 -0
  46. package/src/edit/core/project.js +64 -0
  47. package/src/edit/core/solver.js +34 -6
  48. package/src/edit/core/style-brief.js +211 -0
  49. package/src/edit/core/style-packs.js +57 -0
  50. package/src/edit/core/transitions.js +17 -0
  51. package/src/edit/core/type-kit.js +173 -0
  52. package/src/edit/director/ask.js +37 -3
  53. package/src/edit/director/assembly.js +829 -0
  54. package/src/edit/director/continuity.js +137 -0
  55. package/src/edit/director/custom-motion.js +88 -0
  56. package/src/edit/director/graphics.js +186 -0
  57. package/src/edit/director/intent.js +125 -0
  58. package/src/edit/director/mentions.js +52 -0
  59. package/src/edit/director/plan.js +89 -12
  60. package/src/edit/director/revise.js +172 -7
  61. package/src/edit/director/viewer.js +136 -0
  62. package/src/edit/director/watch-fix.js +119 -0
  63. package/src/edit/engine/captions.js +110 -5
  64. package/src/edit/engine/confine.js +81 -4
  65. package/src/edit/engine/custom.js +243 -0
  66. package/src/edit/engine/dna2.js +893 -0
  67. package/src/edit/engine/fonts.js +218 -0
  68. package/src/edit/engine/graphics.js +439 -0
  69. package/src/edit/engine/index.js +14 -5
  70. package/src/edit/engine/motion.js +153 -14
  71. package/src/edit/engine/music-bed.js +59 -1
  72. package/src/edit/engine/packs.js +11 -0
  73. package/src/edit/engine/reference2.js +26 -0
  74. package/src/edit/engine/sfx.js +56 -1
  75. package/src/edit/engine/tool.js +21 -5
  76. package/src/edit/gates/assembly.js +194 -0
  77. package/src/edit/gates/copy.js +7 -4
  78. package/src/edit/gates/index.js +76 -8
  79. package/src/edit/gates/picture.js +6 -3
  80. package/src/edit/gates/reference.js +115 -0
  81. package/src/edit/gates/tile.js +96 -0
  82. package/src/edit/host/client.js +4 -3
  83. package/src/edit/host/clips.js +33 -0
  84. package/src/edit/host/jobs.js +9 -3
  85. package/src/edit/host/layers.js +134 -0
  86. package/src/edit/host/main.js +17 -7
  87. package/src/edit/host/paths.js +34 -3
  88. package/src/edit/host/preview.js +108 -0
  89. package/src/edit/host/projects.js +494 -29
  90. package/src/edit/host/server.js +263 -19
  91. package/src/edit/host/tavi.js +77 -0
  92. package/src/edit/loop/make.js +44 -3
  93. package/src/edit/recipes/assembly.js +352 -0
  94. package/src/edit/recipes/graphic-clips.js +59 -0
  95. package/src/edit/recipes/openings.js +36 -0
  96. package/src/edit/recipes/reel.js +138 -17
  97. package/src/edit/recipes/reference-look.js +29 -0
  98. package/src/edit/recipes/short-from-long.js +3 -3
  99. package/src/edit/recipes/sound.js +71 -0
  100. package/src/edit/runtime/cli.js +26 -5
  101. package/src/edit/runtime/fetch.js +4 -3
  102. package/src/edit/runtime/licences.js +7 -1
  103. package/src/explore.js +103 -0
  104. package/src/failure.js +1 -1
  105. package/src/gate-commands.js +114 -0
  106. package/src/gates/api.js +127 -0
  107. package/src/gates/commands.js +111 -0
  108. package/src/gates/detectors.js +370 -0
  109. package/src/gates/http.js +62 -0
  110. package/src/gates/index.js +196 -0
  111. package/src/gates/page.js +264 -0
  112. package/src/gates/sast.js +64 -0
  113. package/src/gates/stack.js +110 -0
  114. package/src/gates/tenant.js +162 -0
  115. package/src/gates/three.js +407 -0
  116. package/src/gates/ui.js +111 -0
  117. package/src/launch.js +15 -3
  118. package/src/loop.js +199 -7
  119. package/src/mcp.js +126 -0
  120. package/src/milestones.js +188 -0
  121. package/src/modes.js +32 -0
  122. package/src/orchestra.js +43 -0
  123. package/src/outcomes.js +88 -0
  124. package/src/profiles.js +5 -0
  125. package/src/receipts.js +238 -0
  126. package/src/release.js +356 -0
  127. package/src/runstrip.js +122 -0
  128. package/src/stack.js +120 -0
  129. package/src/verify.js +67 -20
  130. package/studio/dist/fonts/fraunces.woff2 +0 -0
  131. package/studio/dist/fonts/geist.woff2 +0 -0
  132. package/studio/dist/fonts/jetbrains-mono.woff2 +0 -0
  133. package/studio/dist/studio.css +452 -3
  134. package/studio/dist/studio.js +3 -3
@@ -0,0 +1,194 @@
1
+ // QG-15 Assembly (TP2, ASSEMBLY_AND_INTENT §6.3): does the film have the files it was asked
2
+ // for, in the order asked? Two readings. From the cut as solved: the parts play in the
3
+ // assembly's order, each inside its own stretch, each `over` part inside its host. From the
4
+ // rendered file: half a second after each join, the frame matches the expected file at the
5
+ // expected source time (the same region of both, small and grey, compared by how its light and
6
+ // dark fall: a look or an encode moves that little, another file or moment moves it a lot). It runs on
7
+ // assembly makes only, and it is a note until its threshold is measured (TPX-04, EQ-22) and
8
+ // its seeded run passes 10 of 10 with no false alarm (EH-70). It can't tell two takes of the
9
+ // same shot apart; checking a join by its source sound isn't built.
10
+
11
+ import { edgeTime } from "../director/assembly.js"
12
+
13
+ const FLICKS = 705_600_000
14
+ const SPINE = ["story", "whole"]
15
+ export const THUMB = { w: 32, h: 18 }
16
+ // shortcut: not measured on natural footage (EQ-22, TPX-04). On barcoded synthetic files a frame either side
17
+ // reads about 0.17 and another file or a moment a second away reads 0.5 or more
18
+ export const ASSEMBLY_THRESHOLDS = { distance: 0.25, afterJoin: FLICKS / 2, stretchSlack: FLICKS / 2 }
19
+
20
+ const seconds = (flicks) => (flicks / FLICKS).toFixed(6)
21
+ const round = (n) => Math.round(n * 1000) / 1000
22
+
23
+ /**
24
+ * How unlike two small grey pictures are, 0 (the same) to 2 (the negative): one minus the
25
+ * correlation of their light and dark, so a brighter, flatter or tinted copy is still the same.
26
+ * A picture with no light and dark at all (a black frame) is unlike everything but its like.
27
+ */
28
+ export function thumbDistance(a, b) {
29
+ if (!a || !b || a.length !== b.length || !a.length) return 2
30
+ const mean = (x) => x.reduce((sum, v) => sum + v, 0) / x.length
31
+ const [ma, mb] = [mean(a), mean(b)]
32
+ let [ab, aa, bb] = [0, 0, 0]
33
+ for (let i = 0; i < a.length; i++) {
34
+ ab += (a[i] - ma) * (b[i] - mb)
35
+ aa += (a[i] - ma) ** 2
36
+ bb += (b[i] - mb) ** 2
37
+ }
38
+ // Flat pictures: alike only when both are flat and as bright as each other
39
+ if (aa < a.length || bb < a.length) return aa < a.length && bb < a.length && Math.abs(ma - mb) < 16 ? 0 : 1
40
+ return 1 - ab / Math.sqrt(aa * bb)
41
+ }
42
+
43
+ /**
44
+ * Where the same picture is in the source and in the output, under the plan's own geometry:
45
+ * fill shows the source's middle over the whole frame; fit and blur show the whole source in
46
+ * the frame's middle; a reframe shows the crop the plan chose at that moment.
47
+ * @returns {{ source: { x: number, y: number, w: number, h: number }, output: { x: number, y: number, w: number, h: number } }}
48
+ */
49
+ export function sameRegion({ source, output, mode = "fill", cropX }) {
50
+ const even = (n) => Math.max(2, Math.floor(n / 2) * 2)
51
+ if (mode === "fit" || mode === "blur") {
52
+ const scale = Math.min(output.width / source.width, output.height / source.height)
53
+ const [w, h] = [even(source.width * scale), even(source.height * scale)]
54
+ return { source: { x: 0, y: 0, w: source.width, h: source.height }, output: { x: Math.floor((output.width - w) / 2), y: Math.floor((output.height - h) / 2), w, h } }
55
+ }
56
+ const frame = output.width / output.height
57
+ const w = even(Math.min(source.width, source.height * frame))
58
+ const h = even(Math.min(source.height, source.width / frame))
59
+ return { source: { x: cropX === undefined ? Math.floor((source.width - w) / 2) : Math.max(0, Math.min(source.width - w, cropX)), y: Math.floor((source.height - h) / 2), w, h }, output: { x: 0, y: 0, w: output.width, h: output.height } }
60
+ }
61
+
62
+ async function thumbAt(file, t, region, run) {
63
+ const chunks = []
64
+ await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-ss", seconds(Math.max(0, t)), "-protocol_whitelist", "file,pipe", "-i", file, "-frames:v", "1", "-vf", `crop=${region.w}:${region.h}:${region.x}:${region.y},scale=${THUMB.w}:${THUMB.h}:flags=area,format=gray`, "-f", "rawvideo", "pipe:1"], { timeoutMs: 120_000, onStdout: (chunk) => chunks.push(chunk) })
65
+ const data = Buffer.concat(chunks)
66
+ return data.length >= THUMB.w * THUMB.h ? data.subarray(0, THUMB.w * THUMB.h) : null
67
+ }
68
+
69
+ /** The picture as it plays, one run per stretch of one file: [{ asset, at, end, in, out, pieces }]. */
70
+ export function runsOf(picture) {
71
+ const runs = []
72
+ for (const piece of [...picture].sort((a, b) => a.at - b.at)) {
73
+ if (piece.echo) continue
74
+ const last = runs.at(-1)
75
+ if (last && last.asset === piece.asset) Object.assign(last, { end: piece.end, in: Math.min(last.in, piece.in), out: Math.max(last.out, piece.out), pieces: [...last.pieces, piece] })
76
+ else runs.push({ asset: piece.asset, at: piece.at, end: piece.end, in: piece.in, out: piece.out, pieces: [piece] })
77
+ }
78
+ return runs
79
+ }
80
+
81
+ /**
82
+ * The cut against the assembly, with no file read: order, stretches, hosts.
83
+ * @param {{ assembly: { parts: object[] }, timeline: object, project: object, index?: object, left?: string[] }} input left: part ids the make left out with a note (a file gone)
84
+ * @returns {{ failures: object[], expected: { asset: string, at: number, end: number, in: number, out: number, pieces: object[] }[] }}
85
+ */
86
+ export function judgeOrder({ assembly, timeline, project, index = {}, left = [] }) {
87
+ const failures = []
88
+ const parts = assembly.parts.filter((p) => !left.includes(p.id))
89
+ const lengthOf = (asset) => project.assets.find((a) => a.id === asset)?.facts?.duration ?? Number.MAX_SAFE_INTEGER
90
+ // Parts of one file that follow each other play as one run
91
+ const asked = []
92
+ for (const part of parts.filter((p) => SPINE.includes(p.use))) {
93
+ const stretch = { from: edgeTime(part.from, index, "start") ?? 0, to: edgeTime(part.to, index, "end") ?? lengthOf(part.asset) }
94
+ const last = asked.at(-1)
95
+ if (last && last.asset === part.asset) last.stretches.push(stretch)
96
+ else asked.push({ asset: part.asset, ids: [part.id], stretches: [stretch] })
97
+ if (last && last.asset === part.asset) last.ids.push(part.id)
98
+ }
99
+ const runs = runsOf(timeline.picture)
100
+ const played = runs.map((r) => r.asset)
101
+ const wanted = asked.map((a) => a.asset)
102
+ if (JSON.stringify(played) !== JSON.stringify(wanted)) {
103
+ const missing = wanted.filter((asset) => !played.includes(asset))
104
+ failures.push(missing.length ? { kind: "missing_part", assets: missing, asked: wanted, played } : { kind: "order", asked: wanted, played })
105
+ } else {
106
+ const slack = ASSEMBLY_THRESHOLDS.stretchSlack
107
+ runs.forEach((run, i) => {
108
+ for (const piece of run.pieces) {
109
+ if (piece.hold) continue
110
+ if (!asked[i].stretches.some((s) => piece.in >= s.from - slack && piece.out <= s.to + slack)) failures.push({ kind: "outside_stretch", part: asked[i].ids[0], asset: run.asset, seconds: round(piece.at / FLICKS), plays: [round(piece.in / FLICKS), round(piece.out / FLICKS)] })
111
+ }
112
+ })
113
+ }
114
+ // Each `over` part lies inside its host
115
+ const overlays = timeline.overlays.filter((o) => !o.block)
116
+ for (const part of parts.filter((p) => p.use === "over")) {
117
+ const shown = overlays.filter((o) => o.asset === part.asset)
118
+ const host = parts.find((p) => p.id === part.at?.part)
119
+ const hostRuns = runs.filter((r) => r.asset === host?.asset)
120
+ if (!shown.length) failures.push({ kind: "missing_part", assets: [part.asset], over: true })
121
+ for (const o of shown) if (!hostRuns.some((r) => o.at >= r.at && o.end <= r.end)) failures.push({ kind: "over_outside_host", part: part.id, asset: part.asset, seconds: round(o.at / FLICKS) })
122
+ }
123
+ return { failures, expected: runs }
124
+ }
125
+
126
+ /**
127
+ * QG-15, as the runner calls it.
128
+ * @param {{ file: string, plan: object, project: object, index: object, sourcePath: (asset: string) => string, run: Function, assembly: { parts: object[], left?: string[] }, timeline: object }} input
129
+ */
130
+ export async function judgeAssembly({ file, plan, project, index, sourcePath, run, assembly, timeline }) {
131
+ const { failures, expected } = judgeOrder({ assembly, timeline, project, index, left: assembly.left })
132
+ const factsOf = (asset) => project.assets.find((a) => a.id === asset)?.facts ?? {}
133
+ const output = plan.output
134
+ // What to look at: half a second into each run (the first too), its middle and near its end, and the middle
135
+ // of each cutaway. One moment can look like another by chance; three rarely all do
136
+ const frame = Math.round((FLICKS * output.fps.d) / output.fps.n)
137
+ const overlays = timeline.overlays.filter((o) => !o.block)
138
+ const within = (r, t) => Math.max(r.at, Math.min(r.end - 2 * frame, t))
139
+ // Under a cutaway the part's own picture can't be seen, so it is read where it can be
140
+ const covered = (t) => overlays.some((o) => o.at - frame <= t && t <= o.end + frame)
141
+ const points = [
142
+ ...expected.flatMap((r) => [...new Set([within(r, r.at + ASSEMBLY_THRESHOLDS.afterJoin), within(r, Math.floor((r.at + r.end) / 2)), within(r, r.end - ASSEMBLY_THRESHOLDS.afterJoin)])].filter((t) => !covered(t)).map((t) => ({ t, piece: r.pieces.find((p) => p.at <= t && t < p.end) ?? r.pieces[0], what: "join" }))),
143
+ // A cutaway is read a few frames in: the Engine shows an overlay a frame after its start
144
+ ...overlays.map((o) => ({ t: Math.floor((o.at + o.end) / 2), piece: o, what: "over" })),
145
+ ]
146
+ let worst = 0
147
+ let checked = 0
148
+ let unread = 0
149
+ for (const { t, piece, what } of points) {
150
+ const facts = factsOf(piece.asset)
151
+ if (!facts.width || !facts.height || piece.hold) continue
152
+ const rate = piece.speed ?? { n: 1, d: 1 }
153
+ const sourceT = piece.in + Math.round(((t - piece.at) * rate.n) / rate.d)
154
+ const framed = piece.effects?.find((e) => e.type === "frame")
155
+ const reframe = piece.effects?.find((e) => e.type === "reframe")
156
+ // shortcut: a reframe that follows a face is read at the centre crop; a moving crop can read a little off
157
+ const region = sameRegion({ source: { width: facts.width, height: facts.height }, output, mode: framed?.mode ?? "fill", ...(reframe?.mode === "fixed" ? { cropX: reframe.x ?? 0 } : {}) })
158
+ const wanted = await thumbAt(sourcePath(piece.asset), sourceT, region.source, run)
159
+ if (!wanted) {
160
+ unread++
161
+ continue
162
+ }
163
+ const seen = await thumbAt(file, t, region.output, run)
164
+ checked++
165
+ // The film has no frame where this part should be playing: it is shorter than the order asked for
166
+ if (!seen) {
167
+ failures.push({ kind: "frame_missing", what, asset: piece.asset, seconds: round(t / FLICKS) })
168
+ continue
169
+ }
170
+ const distance = thumbDistance(seen, wanted)
171
+ worst = Math.max(worst, distance)
172
+ if (distance > ASSEMBLY_THRESHOLDS.distance) failures.push({ kind: "frame_mismatch", what, asset: piece.asset, seconds: round(t / FLICKS), distance: round(distance), allowed: ASSEMBLY_THRESHOLDS.distance })
173
+ }
174
+ const numbers = { parts: assembly.parts.length, joins: Math.max(0, expected.length - 1), framesChecked: checked, framesUnread: unread, worstDistance: round(worst), allowed: ASSEMBLY_THRESHOLDS.distance, threshold: "not measured on natural footage (EQ-22)" }
175
+ return { failures, numbers }
176
+ }
177
+
178
+ /** A failure in plain words. */
179
+ export function sayFailure(f, numberOf = (asset) => asset) {
180
+ switch (f.kind) {
181
+ case "missing_part":
182
+ return `${f.assets.map(numberOf).join(" and ")} ${f.over ? "was to play over the voice and doesn't" : "was asked for and isn't in the film"}.`
183
+ case "order":
184
+ return `The parts play as ${f.played.map(numberOf).join(", ")}; the order asked for was ${f.asked.map(numberOf).join(", ")}.`
185
+ case "outside_stretch":
186
+ return `${numberOf(f.asset)} plays ${f.plays[0]} to ${f.plays[1]} s of its file at ${f.seconds} s, outside the stretch asked for.`
187
+ case "over_outside_host":
188
+ return `${numberOf(f.asset)} plays over a part it wasn't asked to, at ${f.seconds} s.`
189
+ case "frame_missing":
190
+ return `The film has no picture at ${f.seconds} s, where ${numberOf(f.asset)} should be playing.`
191
+ default:
192
+ return `At ${f.seconds} s the picture doesn't look like ${numberOf(f.asset)} at that moment (unlike by ${f.distance}; ${f.allowed} allowed).`
193
+ }
194
+ }
@@ -52,7 +52,8 @@ function nearly(a, b) {
52
52
  }
53
53
 
54
54
  /** Letters and digits, lower case, one space between words: what both sides are compared as. */
55
- export const normalise = (text) => String(text).normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()
55
+ // Combining marks stay with their letter (TP7): Devanagari's vowel signs are marks, and a misread one is a misread word
56
+ export const normalise = (text) => String(text).normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{M}\p{N}]+/gu, " ").trim()
56
57
 
57
58
  export function similarity(a, b) {
58
59
  const x = normalise(a)
@@ -75,8 +76,9 @@ export function similarity(a, b) {
75
76
  export function intendedText(tile) {
76
77
  if (tile.kind === "caption") return tile.node.text ?? tile.node.words.map((w) => w.text).join(" ")
77
78
  if (isSceneBlock(tile.node)) return sceneText(tile.node.variables)
79
+ if (tile.node.blockId === "custom") return (tile.node.variables?.texts ?? []).join(" ")
78
80
  if (tile.node.blockId === "term") return [tile.node.variables?.text, tile.node.variables?.quote, tile.node.variables?.source].filter(Boolean).join(" ")
79
- return [tile.node.variables?.text, tile.node.variables?.subtitle].filter(Boolean).join(" ")
81
+ return [tile.node.variables?.text, ...(tile.node.variables?.steps ?? []), tile.node.variables?.subtitle].filter(Boolean).join(" ")
80
82
  }
81
83
 
82
84
  // A name or a number: capitalised after the first word, or with a digit in it
@@ -90,12 +92,13 @@ export function judgeCopy(read, { copySimilarity }) {
90
92
  const failures = []
91
93
  const unread = []
92
94
  let worst = 1
93
- for (const { tile, seen: reading, unsure = [] } of read) {
95
+ for (const { tile, seen: reading, unsure = [], reads = ["latin"] } of read) {
94
96
  const meant = intendedText(tile)
95
97
  // A reader's stray space ("O kay") isn't on the screen
96
98
  const squeezed = (text) => normalise(text).replace(/ /g, "")
97
99
  const seen = squeezed(meant) === squeezed(reading ?? "") ? meant : reading
98
- if (scriptOf(meant) !== "latin") {
100
+ // TP7: a typed tile in Devanagari is read with hi-IN (SPIKES §6); every other script is unread here
101
+ if (!reads.includes(scriptOf(meant))) {
99
102
  unread.push({ tile: tile.key, script: scriptOf(meant) })
100
103
  continue
101
104
  }
@@ -10,10 +10,18 @@ import { join } from "node:path"
10
10
  import { busOf, speechSpans } from "../core/audio.js"
11
11
  import { isSceneBlock } from "../core/layout.js"
12
12
  import { wholeSegment } from "../core/plan.js"
13
+ import { clipNumbers } from "../core/project.js"
13
14
  import { solve } from "../core/solver.js"
14
15
  import { measureLoudness } from "../engine/loudness.js"
15
16
  import { runTool } from "../engine/tool.js"
17
+ import { extractDna2 } from "../engine/dna2.js"
18
+ import { referenceFit, sayFit } from "./reference.js"
19
+ import { judgeAssembly, sayFailure } from "./assembly.js"
16
20
  import { judgeCopy, ocrHelper, readOcr } from "./copy.js"
21
+ import { captionAtRest, captionComposition } from "../engine/captions.js"
22
+ import { glyphProblems, OCR_READS, scriptsIn } from "../engine/fonts.js"
23
+ import { checkGlyphs, compositionFor } from "../engine/motion.js"
24
+ import { intendedText } from "./copy.js"
17
25
  import { healthArgs, judgeHealth, judgeMotion, judgeSync, readHealth, streamTimes, tileFrames } from "./picture.js"
18
26
  import { curveOf, judgeMix, rangeOf } from "./sound.js"
19
27
  import { expectedWords, judgeReview, judgeSpeech, REVIEWER_SCHEMA } from "./speech.js"
@@ -52,7 +60,9 @@ const ratio = (text) => {
52
60
  return n > 0 && d > 0 ? { n, d } : null
53
61
  }
54
62
  const seconds = (flicks) => (flicks / FLICKS).toFixed(6)
55
- const SEVERITY = { "QG-13": "note", "QG-14": "note" }
63
+ // QG-15 is a note until its threshold is measured and its seeded run passes (EH-70)
64
+ // QG-16 (TP6) is a note by design: the film is the person's, not the reference's
65
+ const SEVERITY = { "QG-13": "note", "QG-14": "note", "QG-15": "note", "QG-16": "note" }
56
66
  const result = (id, status, numbers = {}, message = "", at = null, severity = SEVERITY[id] ?? "block") => ({ id, status, severity, numbers, message, ...(at === null ? {} : { at }) })
57
67
 
58
68
  async function probeFile(file, run) {
@@ -309,13 +319,16 @@ async function qg07({ file, plan, run, thresholds }) {
309
319
  const picture = wholeSegment(plan).node.picture.sort((a, b) => a.at - b.at)
310
320
  // A freeze the plan asks for; and a scene may rest on a finished diagram while the voice explains it
311
321
  const holds = [...picture.filter((p) => p.hold), ...plan.tiles.filter((tile) => isSceneBlock(tile.node))].map(({ at, end }) => ({ at, end }))
322
+ // A transition the plan asks for holds the last frame under the next clip, and a dip passes through black
323
+ const transitions = picture.filter((p) => p.enter).map((p) => ({ at: p.at, end: p.at + p.enter.duration }))
324
+ holds.push(...transitions)
312
325
  const cuts = picture.slice(1).map((p, i) => ({ t: p.at, same: p.asset === picture[i].asset && !p.hold && !picture[i].hold }))
313
- return outcome("QG-07", judgeHealth(health, { duration: plan.duration, fps: plan.output.fps, holds, cuts }, thresholds))
326
+ return outcome("QG-07", judgeHealth(health, { duration: plan.duration, fps: plan.output.fps, holds, cuts, transitions }, thresholds))
314
327
  }
315
328
 
316
329
  const textTiles = (plan) => plan.tiles.filter((t) => t.kind === "caption" || t.kind === "block")
317
330
 
318
- async function qg10({ plan, run, thresholds, tilePath, binDir, work }) {
331
+ async function qg10({ plan, run, thresholds, tilePath, binDir, work, motion, glyphs = checkGlyphs }) {
319
332
  const tiles = textTiles(plan)
320
333
  if (!tiles.length) return result("QG-10", "not_applicable", {}, "No text on screen.")
321
334
  if (!tilePath || !binDir || !work) return result("QG-10", "not_checked", {}, "The gate has no tiles or helper folder to read text from.")
@@ -323,23 +336,46 @@ async function qg10({ plan, run, thresholds, tilePath, binDir, work }) {
323
336
  if (helper.missing) return result("QG-10", "not_checked", {}, helper.missing)
324
337
  mkdirSync(work, { recursive: true })
325
338
  const dir = mkdtempSync(join(work, "ocr-"))
339
+ // TP7 (EQ-17, SPIKES §6): a tile drawn with a type kit is read in Devanagari too (hi-IN), and the
340
+ // scripts no reader reads are checked glyph by glyph. A tile without a kit is read as before
341
+ const scriptsOf = (tile) => scriptsIn(intendedText(tile))
342
+ const devanagari = (tile) => !!tile.node.type && scriptsOf(tile).includes("devanagari") && scriptsOf(tile).every((script) => Object.hasOwn(OCR_READS, script))
343
+ const unreadable = (tile) => !!tile.node.type && scriptsOf(tile).some((script) => !Object.hasOwn(OCR_READS, script))
326
344
  try {
345
+ mkdirSync(join(dir, "hi"))
346
+ const fileOf = (tile, i) => join(dir, devanagari(tile) ? "hi" : "", `t${String(i).padStart(4, "0")}.png`)
327
347
  // Each tile at rest, over mid grey, as the reader sees it
328
348
  for (const [i, tile] of tiles.entries()) {
329
349
  const length = (tile.end - tile.at) / FLICKS
330
- // A scene's labels come in as they're said, so it's read when they're all in, before it fades
331
- const at = isSceneBlock(tile.node) ? Math.max(0, length - 0.5) : Math.min(length * 0.9, tile.kind === "caption" ? 0.4 : 1)
350
+ // A scene's labels come in as they're said, so it's read when they're all in, before it fades;
351
+ // a TP7 look whose words arrive as said is read once its last word is in
352
+ const rest = tile.kind === "caption" ? captionAtRest(tile.node) : null
353
+ const at = isSceneBlock(tile.node) ? Math.max(0, length - 0.5) : rest !== null ? Math.min(length * 0.9, rest / 1000) : Math.min(length * 0.9, tile.kind === "caption" ? 0.4 : 1)
332
354
  // The tile from zero: a seek rounded to just before a frame made the overlay's first output plain grey, an empty read (found on real footage)
333
- await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-ss", at.toFixed(3), "-i", tilePath(tile.key), "-f", "lavfi", "-i", `color=c=0x808080:s=${plan.output.width}x${plan.output.height}`, "-filter_complex", "[0:v]setpts=PTS-STARTPTS[tile];[1:v][tile]overlay=shortest=1", "-frames:v", "1", "-y", join(dir, `t${String(i).padStart(4, "0")}.png`)], { timeoutMs: 60_000 })
355
+ await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-ss", at.toFixed(3), "-i", tilePath(tile.key), "-f", "lavfi", "-i", `color=c=0x808080:s=${plan.output.width}x${plan.output.height}`, "-filter_complex", "[0:v]setpts=PTS-STARTPTS[tile];[1:v][tile]overlay=shortest=1", "-frames:v", "1", "-y", fileOf(tile, i)], { timeoutMs: 60_000 })
334
356
  }
335
357
  let seen = readOcr(await run(helper.path, [dir], { timeoutMs: 300_000 }))
336
358
  // The reader swallows its own errors: every tile blank at once is the reader, not the screen (found under load).
337
359
  // One more read; a render that's really blank still fails
338
360
  if (tiles.length > 1 && tiles.every((_, i) => !seen.get(`t${String(i).padStart(4, "0")}.png`)?.text)) seen = readOcr(await run(helper.path, [dir], { timeoutMs: 300_000 }))
361
+ if (tiles.some(devanagari)) for (const [name, read] of readOcr(await run(helper.path, [join(dir, "hi"), OCR_READS.devanagari], { timeoutMs: 300_000 }))) seen.set(name, read)
339
362
  const judged = judgeCopy(tiles.map((tile, i) => {
340
363
  const read = seen.get(`t${String(i).padStart(4, "0")}.png`)
341
- return { tile, seen: read?.text ?? "", unsure: read?.unsure ?? [] }
364
+ return { tile, seen: read?.text ?? "", unsure: read?.unsure ?? [], reads: devanagari(tile) ? ["latin", "devanagari"] : ["latin"] }
342
365
  }), thresholds)
366
+ // The glyph check, in the runtime's Chrome: no missing glyph, the shipped fonts drew it, every cluster drawn
367
+ const checked = tiles.filter(unreadable)
368
+ if (checked.length && motion && !motion.missing) {
369
+ const frame = { output: plan.output, canvas: plan.canvas }
370
+ const items = checked.map((tile) => ({ id: tile.key, html: compositionFor(tile, frame, captionComposition), at: tile.kind === "caption" ? (captionAtRest(tile.node) ?? 400) : Math.min(((tile.end - tile.at) / FLICKS) * 900, 1000) }))
371
+ const reports = await glyphs({ items, work: mkdtempSync(join(work, "glyphs-")), runtime: motion })
372
+ for (const tile of checked) {
373
+ const problems = (reports.get(tile.key) ?? []).flatMap((report) => glyphProblems(report, { shipped: tile.node.type.shipped }))
374
+ for (const problem of problems) judged.failures.push({ kind: "missing_glyph", t: tile.at, seconds: Math.round((tile.at / FLICKS) * 100) / 100, problem })
375
+ }
376
+ judged.unread = judged.unread.filter((u) => !checked.some((tile) => tile.key === u.tile))
377
+ judged.numbers = { ...judged.numbers, glyphChecked: checked.length, unread: judged.unread.length }
378
+ }
343
379
  if (judged.unread.length === tiles.length) return result("QG-10", "not_checked", judged.numbers, `No reader for ${judged.unread[0].script} script here, so its shaping wasn't checked.`)
344
380
  return outcome("QG-10", judged)
345
381
  } finally {
@@ -417,7 +453,7 @@ export function verdictOf(results) {
417
453
  * tilePath, motion, work: the Engine's tiles, the runtime's Chrome and a scratch folder, for QG-08 and QG-09; stems: the Engine's, for QG-06's mix;
418
454
  * recognise: a verified recogniser (file → words), for QG-04 and QG-14; ask: the Director, for QG-14 only; binDir: where helpers are built (QG-10)
419
455
  */
420
- export async function runGates({ file, plan, project, index, sourcePath, run = runTool, only = [...BUILT], thresholds = {}, tilePath, motion, work, inputPath, stems, recognise, ask, binDir }) {
456
+ export async function runGates({ file, plan, project, index, sourcePath, run = runTool, only = [...BUILT], thresholds = {}, tilePath, motion, work, inputPath, stems, recognise, ask, binDir, assembly, referenceFit: fit }) {
421
457
  // Frozen: no gate, fix or model can loosen what the recipe set (QUALITY_GATES §4)
422
458
  const limits = Object.freeze({ ...THRESHOLDS, ...thresholds })
423
459
  const shared = { file, plan, project, index, sourcePath, run, thresholds: limits, tilePath, motion, work, inputPath, stems, recognise, ask, binDir }
@@ -434,5 +470,37 @@ export async function runGates({ file, plan, project, index, sourcePath, run = r
434
470
  results.push(result(id, "not_checked", {}, `The gate couldn't run: ${error.message}`))
435
471
  }
436
472
  }
473
+ // QG-15 (TP2): only for a make that followed an assembly, so every other film has the gates it had
474
+ if (assembly?.parts?.length && (only.includes("QG-15") || only.length === BUILT.size)) {
475
+ try {
476
+ results.push(await qg15({ ...shared, assembly }))
477
+ } catch (error) {
478
+ results.push(result("QG-15", "not_checked", {}, `The gate couldn't run: ${error.message}`))
479
+ }
480
+ }
481
+ // QG-16 (TP6): only for a make that followed a reference's style brief, so every other film has the gates it had
482
+ if (fit?.kept?.length && (only.includes("QG-16") || only.length === BUILT.size)) {
483
+ try {
484
+ results.push(await qg16({ ...shared, kept: fit.kept }))
485
+ } catch (error) {
486
+ results.push(result("QG-16", "not_checked", {}, `The gate couldn't run: ${error.message}`))
487
+ }
488
+ }
437
489
  return { gates: results, ...verdictOf(results) }
438
490
  }
491
+
492
+ // The made cut, measured by the same code that measured the reference, against the lines the person kept
493
+ async function qg16({ file, run, kept }) {
494
+ const judged = referenceFit(kept, await extractDna2(file, { run }))
495
+ const numbers = { followed: judged.followed, of: judged.of, unread: judged.unread }
496
+ if (!judged.missed.length) return result("QG-16", judged.of ? "passed" : "not_checked", numbers, sayFit(judged))
497
+ return { ...result("QG-16", "failed", numbers, sayFit(judged)), failures: judged.missed.map((m) => ({ kind: "reference_trait", trait: m.id, hint: m.hint })) }
498
+ }
499
+
500
+ async function qg15(input) {
501
+ const judged = await judgeAssembly({ ...input, timeline: solve(input.project, input.index) })
502
+ const numbers = clipNumbers(input.project)
503
+ const first = judged.failures[0]
504
+ if (!first) return result("QG-15", "passed", judged.numbers)
505
+ return { ...result("QG-15", "failed", { ...judged.numbers, first }, sayFailure(first, (asset) => `clip ${numbers.get(asset) ?? "?"}`), first.seconds === undefined ? null : Math.round(first.seconds * FLICKS)), failures: judged.failures }
506
+ }
@@ -69,16 +69,19 @@ export function readHealth(text) {
69
69
  * @param {{ black: object[], frozen: object[], luma: number[] }} health
70
70
  * @param {{ duration: number, fps: { n: number, d: number }, holds: { at: number, end: number }[], cuts: { t: number, same: boolean }[] }} plan holds: freezes the plan asks for; cuts: where pieces of one source meet
71
71
  */
72
- export function judgeHealth({ black, frozen, luma }, { duration, fps, holds, cuts }, { exposureJump }) {
72
+ export function judgeHealth({ black, frozen, luma }, { duration, fps, holds, cuts, transitions = [] }, { exposureJump }) {
73
73
  const failures = []
74
74
  const close = (span) => ({ ...span, end: span.end ?? duration })
75
75
  const planned = (span) => holds.some((h) => h.at <= span.start + FLICKS / 10 && span.end - FLICKS / 10 <= h.end)
76
- for (const span of black.map(close)) failures.push({ kind: "black", severity: "block", t: span.start, seconds: round((span.end - span.start) / FLICKS, 2) })
76
+ // Black is a fault except inside a transition the plan asked for (a dip to black)
77
+ const dipped = (span) => transitions.some((t) => t.at <= span.start + FLICKS / 10 && span.end - FLICKS / 10 <= t.end)
78
+ for (const span of black.map(close).filter((span) => !dipped(span))) failures.push({ kind: "black", severity: "block", t: span.start, seconds: round((span.end - span.start) / FLICKS, 2) })
77
79
  for (const span of frozen.map(close)) if (!planned(span)) failures.push({ kind: "frozen", severity: "block", t: span.start, seconds: round((span.end - span.start) / FLICKS, 2) })
78
80
  const frameAt = (t) => Math.min(luma.length - 1, Math.max(0, Math.floor((t * fps.n) / (FLICKS * fps.d))))
79
81
  let worst = 0
80
82
  for (const cut of cuts) {
81
- if (!cut.same) continue
83
+ // A cut dressed with a transition isn't a hard cut: its brightness is meant to move
84
+ if (!cut.same || transitions.some((t) => t.at === cut.t)) continue
82
85
  const before = luma[frameAt(cut.t) - 1]
83
86
  const after = luma[frameAt(cut.t)]
84
87
  if (!Number.isFinite(before) || !Number.isFinite(after)) continue
@@ -0,0 +1,115 @@
1
+ // QG-16, reference fit (TP6, CRAFT_UPGRADE §4.4, EDD-65): after a make that followed a reference's
2
+ // style brief, the same code measures the made cut's Edit DNA 2 and compares it, trait by trait,
3
+ // with the lines the person kept ticked, each within a tolerance. It is a note and never blocks:
4
+ // the film is the person's, not the reference's (audit §6 rule 8). A missed trait carries a typed
5
+ // repair hint: a rung and a direction, never free text from a model.
6
+
7
+ import { PRESENT } from "../core/style-brief.js"
8
+
9
+ // How near is near enough, per trait. Untuned on real references (EQ-19): a note only
10
+ export const TOLERANCE = {
11
+ pace: 0.3, // share of the reference's seconds between picture changes
12
+ joinShare: 0.25,
13
+ zoomScale: 0.08, // a punch-in's scale
14
+ captionHeight: 0.35, // share
15
+ graphics: 0.5, // share, or 1.5 a minute
16
+ lightness: 0.08, // OKLab L
17
+ chroma: 0.04, // OKLab a, b
18
+ bars: 0.03, // share of the height
19
+ bpm: 4,
20
+ }
21
+
22
+ const near = (made, wanted, part, floor = 0) => Math.abs(made - wanted) <= Math.max(floor, Math.abs(wanted) * part)
23
+ const hint = (rung, change, extra = {}) => ({ rung, change, ...extra })
24
+
25
+ /**
26
+ * One kept line against the made cut's DNA.
27
+ * @returns {{ ok: boolean, hint?: object } | null} null when the made cut's trait couldn't be read, so it isn't counted either way
28
+ */
29
+ function judge(line, dna) {
30
+ const t = line.target
31
+ const read = (name) => dna[name]?.read === "yes"
32
+ switch (line.id) {
33
+ case "pace": {
34
+ if (!read("rhythm")) return null
35
+ // The rate of visual change, as the brief counted it: every join and punch-in over the running time
36
+ const every = dna.rhythm.cutsPerMinute > 0 ? 60 / dna.rhythm.cutsPerMinute : Infinity
37
+ return near(every, t.every, TOLERANCE.pace) ? { ok: true } : { ok: false, hint: hint("punches", every > t.every ? "more" : "fewer") }
38
+ }
39
+ case "joins": {
40
+ if (!read("transitions")) return null
41
+ const per = dna.transitions.perMinute
42
+ const total = Object.values(per).reduce((sum, v) => sum + (v ?? 0), 0) + (dna.transitions.unread ?? 0)
43
+ if (!total) return null
44
+ if (t.kind === "cut") return per.cut / total >= 1 - TOLERANCE.joinShare ? { ok: true } : { ok: false, hint: hint("transition", "fewer", { kind: "cut" }) }
45
+ const part = (per[t.kind] ?? 0) / total
46
+ // Kriya dresses the joins where the story changes moment, so "some" is followed by any; "most" needs most
47
+ const enough = t.share >= 0.6 ? part >= t.share - TOLERANCE.joinShare : part > 0
48
+ return enough ? { ok: true } : { ok: false, hint: hint("transition", "more", { kind: t.kind }) }
49
+ }
50
+ case "zooms": {
51
+ if (!read("moves")) return null
52
+ if (!(dna.moves.zoomsPerMinute > 0)) return { ok: false, hint: hint("punches", "more") }
53
+ return Math.abs(dna.moves.scale - t.scale) <= TOLERANCE.zoomScale ? { ok: true } : { ok: false, hint: hint("zoom_scale", dna.moves.scale < t.scale ? "larger" : "smaller") }
54
+ }
55
+ case "captions": {
56
+ if (!read("captions")) return null
57
+ if (!dna.captions.present) return { ok: false, hint: hint("captions", "more") }
58
+ // Where they sit is the safe zones' call, not the reference's: only size and plate are compared
59
+ if (t.height !== null && dna.captions.height !== null && !near(dna.captions.height, t.height, TOLERANCE.captionHeight)) return { ok: false, hint: hint("caption_size", dna.captions.height < t.height ? "larger" : "smaller") }
60
+ if (t.plate !== null && dna.captions.plate !== null && dna.captions.plate !== t.plate) return { ok: false, hint: hint("caption_look", t.plate === "box" ? "more" : "fewer") }
61
+ return { ok: true }
62
+ }
63
+ case "graphics": {
64
+ if (!read("graphics")) return null
65
+ return near(dna.graphics.perMinute, t.perMinute, TOLERANCE.graphics, 1.5) ? { ok: true } : { ok: false, hint: hint("graphics", dna.graphics.perMinute < t.perMinute ? "more" : "fewer") }
66
+ }
67
+ case "colour": {
68
+ if (!read("colour")) return null
69
+ const [l, a, b] = dna.colour.mean.map((v, i) => v - t.mean[i])
70
+ return Math.abs(l) <= TOLERANCE.lightness && Math.hypot(a, b) <= TOLERANCE.chroma ? { ok: true } : { ok: false, hint: hint("colour_match", "more") }
71
+ }
72
+ case "grain":
73
+ return !read("colour") || dna.colour.grain === null ? null : dna.colour.grain > PRESENT.grain ? { ok: true } : { ok: false, hint: hint("grain", "more") }
74
+ case "corners":
75
+ return !read("colour") || dna.colour.vignette === null ? null : dna.colour.vignette > PRESENT.corners ? { ok: true } : { ok: false, hint: hint("vignette", "more") }
76
+ case "bars":
77
+ return !read("colour") || dna.colour.letterbox === null ? null : Math.abs(dna.colour.letterbox - t.letterbox) <= TOLERANCE.bars ? { ok: true } : { ok: false, hint: hint("letterbox", dna.colour.letterbox < t.letterbox ? "more" : "fewer") }
78
+ case "music": {
79
+ if (!read("sound") || dna.sound.bed === null) return null
80
+ if (dna.sound.bed <= PRESENT.bed) return { ok: false, hint: hint("music", "more") }
81
+ return t.bpm === null || dna.sound.bpm === null || Math.abs(dna.sound.bpm - t.bpm) <= TOLERANCE.bpm ? { ok: true } : { ok: false, hint: hint("music_tempo", dna.sound.bpm < t.bpm ? "more" : "fewer") }
82
+ }
83
+ case "opening":
84
+ return !read("opening") || dna.opening.textEarly === null ? null : dna.opening.textEarly === true ? { ok: true } : { ok: false, hint: hint("titles", "more") }
85
+ case "format":
86
+ return !read("format") ? null : dna.format.shape === t.shape ? { ok: true } : { ok: false, hint: hint("format", "more") }
87
+ default:
88
+ return null
89
+ }
90
+ }
91
+
92
+ /**
93
+ * @param {{ id: string, text: string, target?: object }[]} kept the style brief's lines the person left ticked
94
+ * @param {object} dna the made cut's Edit DNA 2
95
+ * @returns {{ followed: number, of: number, unread: number, missed: { id: string, text: string, hint: object }[] }}
96
+ */
97
+ export function referenceFit(kept, dna) {
98
+ let [followed, unread] = [0, 0]
99
+ const missed = []
100
+ for (const line of kept) {
101
+ if (!line.target) continue
102
+ const judged = judge(line, dna)
103
+ if (!judged) unread++
104
+ else if (judged.ok) followed++
105
+ else missed.push({ id: line.id, text: line.text, hint: judged.hint })
106
+ }
107
+ return { followed, of: followed + missed.length, unread, missed }
108
+ }
109
+
110
+ /** The note, in plain words. */
111
+ export function sayFit({ followed, of, unread, missed }) {
112
+ if (!of) return "Nothing from your reference could be compared in this cut."
113
+ const lower = (text) => `${text.charAt(0).toLowerCase()}${text.slice(1)}`
114
+ return `Followed ${followed} of ${of} things from your reference${missed.length ? `; not: ${missed.map((m) => lower(m.text)).join("; ")}` : ""}${unread ? `. ${unread} couldn't be read back from the cut` : ""}.`
115
+ }
@@ -0,0 +1,96 @@
1
+ // QG-08…QG-11 on one custom tile, before the person sees it (MG2, TP9; DIRECTOR_AND_AGENT §11 step 4).
2
+ // The tile is rendered in the runtime's Chrome inside the OS sandbox, exactly as the film will draw it,
3
+ // and judged by the gates' own measures: where its words land (QG-08), whether they read on their own
4
+ // plate (QG-09: the footage behind is unknown here, so a word must carry its own plate or outline),
5
+ // what an OCR reads back (QG-10, where the helper exists) and whether it moves at all (QG-11). The
6
+ // film's own gates run again on the rendered cut; this is the check before a proposal is offered.
7
+
8
+ import { mkdirSync, rmSync } from "node:fs"
9
+ import { join } from "node:path"
10
+
11
+ import { confinement } from "../engine/confine.js"
12
+ import { customDocument, measureText, renderTile, tileSeconds } from "../engine/motion.js"
13
+ import { runTool } from "../engine/tool.js"
14
+ import { judgeCopy, ocrHelper, readOcr } from "./copy.js"
15
+ import { THRESHOLDS } from "./index.js"
16
+ import { judgeMotion, tileFrames } from "./picture.js"
17
+ import { contrast, luminance, parseColour, strokeContrast } from "./text.js"
18
+
19
+ const FLICKS = 705_600_000
20
+ const round = (n) => Math.round(n * 100) / 100
21
+
22
+ /** QG-08 and QG-09 from measured boxes (pure, so the rules are tested without Chrome). @param {object[][]} sets boxes per time */
23
+ export function judgeTileText(sets, { output, safe, thresholds = THRESHOLDS }) {
24
+ const { width, height } = output
25
+ const layout = []
26
+ const legibility = []
27
+ for (const boxes of sets) {
28
+ for (const [i, box] of boxes.entries()) {
29
+ if (box.x < -0.5 || box.y < -0.5 || box.x + box.w > width + 0.5 || box.y + box.h > height + 0.5) layout.push({ kind: "outside_frame", text: box.text })
30
+ else if (box.y < safe.top - 0.5 || box.x < safe.left - 0.5 || box.x + box.w > width - safe.right + 0.5 || box.y + box.h > height - safe.bottom + 0.5) layout.push({ kind: "outside_safe_zone", text: box.text })
31
+ if (box.clipped) layout.push({ kind: "clipped", text: box.text })
32
+ for (const other of boxes.slice(i + 1)) if (box.x < other.x + other.w && other.x < box.x + box.w && box.y < other.y + other.h && other.y < box.y + box.h) layout.push({ kind: "overlap", text: box.text })
33
+ }
34
+ }
35
+ // Legibility at rest (the first set): text against its own plate, or its own outline
36
+ for (const box of sets[0] ?? []) {
37
+ const plate = parseColour(box.plate)
38
+ const texts = (box.colours ?? []).map(parseColour).filter(Boolean)
39
+ const onPlate = plate && plate.alpha >= 0.9 && texts.length ? Math.min(...texts.map((t) => contrast(luminance(t.rgb), luminance(plate.rgb)))) : null
40
+ const value = Math.max(onPlate ?? 0, strokeContrast(box) ?? 0)
41
+ if (!value) legibility.push({ kind: "no_plate", text: box.text })
42
+ else if (value < thresholds.contrast) legibility.push({ kind: "low_contrast", text: box.text, contrast: round(value), needed: thresholds.contrast })
43
+ if (box.size / height < thresholds.minTextShare) legibility.push({ kind: "too_small", text: box.text, px: box.size, minimum: Math.ceil(thresholds.minTextShare * height) })
44
+ }
45
+ const status = (failures, any) => (!any ? "not_applicable" : failures.length ? "failed" : "passed")
46
+ const any = sets.some((boxes) => boxes.length)
47
+ return [
48
+ { id: "QG-08", status: status(layout, any), failures: layout },
49
+ { id: "QG-09", status: status(legibility, any), failures: legibility },
50
+ ]
51
+ }
52
+
53
+ /**
54
+ * @param {{ node: object, output: { width: number, height: number, fps: object }, canvas: object, safe: object, runtime: object, work: string, run?: Function, which?: object, binDir?: string, launch?: Function, ocr?: boolean }} input
55
+ * safe: the safe zone in output pixels; binDir: where the OCR helper is built (QG-10 is not checked without it)
56
+ * @returns {Promise<{ passed: boolean, results: { id: string, status: string, failures?: object[] }[] }>}
57
+ */
58
+ export async function gateCustomTile({ node, output, canvas, safe, runtime, work, run = runTool, which = confinement(), binDir, launch, thresholds = THRESHOLDS }) {
59
+ const html = customDocument(node, { output, canvas }, { allowed: true, which })
60
+ mkdirSync(work, { recursive: true })
61
+ const file = join(work, "tile.mov")
62
+ const seconds = tileSeconds(node.duration, output.fps)
63
+ try {
64
+ await renderTile({ html, work: join(work, "render"), output: file, fps: output.fps, runtime, run, which, seconds, launch })
65
+ const results = []
66
+ // QG-11: it moves, and every frame of its window is there
67
+ const frames = await tileFrames(file, run)
68
+ const expected = Math.ceil((node.duration * output.fps.n) / (FLICKS * output.fps.d) - 1e-9)
69
+ const motion = judgeMotion([{ tile: { at: 0 }, frames, expected }], thresholds)
70
+ results.push({ id: "QG-11", status: motion.failures.length ? "failed" : "passed", failures: motion.failures })
71
+ // QG-08, QG-09: the words' boxes at rest and on the last frame
72
+ const frameMs = (1000 * output.fps.d) / output.fps.n
73
+ const last = Math.max(0, (node.duration / FLICKS) * 1000 - frameMs)
74
+ const times = [...new Set([Math.min(last, 950), Math.round(last)])]
75
+ const measured = await measureText({ items: [{ id: "t", html, times }], work: join(work, "measure"), runtime, which, launch })
76
+ results.push(...judgeTileText(measured.get("t") ?? [], { output, safe, thresholds }))
77
+ // QG-10: what a reader sees at rest, over mid grey, against the words meant
78
+ const texts = node.variables.texts ?? []
79
+ if (!texts.length) results.push({ id: "QG-10", status: "not_applicable" })
80
+ else {
81
+ const helper = binDir ? await ocrHelper(binDir, run) : { missing: "no helper folder" }
82
+ if (helper.missing) results.push({ id: "QG-10", status: "not_checked", message: helper.missing })
83
+ else {
84
+ const dir = join(work, "ocr")
85
+ mkdirSync(dir, { recursive: true })
86
+ await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-ss", (Math.min(last, 1000) / 1000).toFixed(3), "-i", file, "-f", "lavfi", "-i", `color=c=0x808080:s=${output.width}x${output.height}`, "-filter_complex", "[0:v]setpts=PTS-STARTPTS[tile];[1:v][tile]overlay=shortest=1", "-frames:v", "1", "-y", join(dir, "t0000.png")], { timeoutMs: 60_000 })
87
+ const seen = readOcr(await run(helper.path, [dir], { timeoutMs: 120_000 })).get("t0000.png")
88
+ const judged = judgeCopy([{ tile: { kind: "block", node, at: 0 }, seen: seen?.text ?? "", unsure: seen?.unsure ?? [] }], thresholds)
89
+ results.push({ id: "QG-10", status: judged.failures.length ? "failed" : judged.unread?.length ? "not_checked" : "passed", failures: judged.failures })
90
+ }
91
+ }
92
+ return { passed: results.every((r) => r.status !== "failed"), results }
93
+ } finally {
94
+ rmSync(join(work, "render"), { recursive: true, force: true })
95
+ }
96
+ }