@kriya-ai/harness 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
@@ -0,0 +1,101 @@
1
+ // Running FFmpeg and friends: `spawn` with an argument array, never a shell, in a
2
+ // built environment. Every way a tool can fail ends as one typed failure.
3
+
4
+ import { spawn } from "node:child_process"
5
+ import { existsSync } from "node:fs"
6
+ import { basename } from "node:path"
7
+
8
+ import { childEnv } from "../runtime/setup.js"
9
+
10
+ const TAIL = 4000
11
+
12
+ // ES-03: FFmpeg and FFprobe get no network at all where the OS can say so (macOS); the
13
+ // protocol whitelist is the other barrier, and the only one elsewhere (EQ-11)
14
+ const SANDBOX_EXEC = "/usr/bin/sandbox-exec"
15
+ const NO_NETWORK = "(version 1)(allow default)(deny network*)"
16
+ const CONFINED = new Set(["ffmpeg", "ffprobe"])
17
+ const canConfine = process.platform === "darwin" && existsSync(SANDBOX_EXEC)
18
+
19
+ /** The command line that actually runs: a media tool wrapped in the no-network profile. */
20
+ export const confined = (command, args) => (canConfine && CONFINED.has(basename(command)) ? [SANDBOX_EXEC, ["-p", NO_NETWORK, command, ...args]] : [command, args])
21
+
22
+ export class EngineFailure extends Error {
23
+ /**
24
+ * @param {"input" | "environment" | "render" | "plan"} kind EDIT_LOOP §11's class
25
+ * @param {string} reason
26
+ * @param {string} message plain enough to show the person
27
+ */
28
+ constructor(kind, reason, message) {
29
+ super(message)
30
+ this.kind = kind
31
+ this.reason = reason
32
+ }
33
+ }
34
+
35
+ const PATTERNS = [
36
+ [/No space left on device/i, "environment", "low_disk", "The disk filled up."],
37
+ [/No such filter|Unknown encoder|Encoder .* not found|Filter not found/i, "environment", "missing_feature", "This FFmpeg can't do that."],
38
+ [/Invalid data found|moov atom not found|does not contain any stream|End of file|No such file or directory|Could not find codec/i, "input", "unreadable", "This file can't be read."],
39
+ ]
40
+
41
+ function classify(tail, code, signal, command) {
42
+ if (/^sandbox-exec: execvp\(\) of '[^']*' failed/m.test(tail)) return new EngineFailure("environment", "missing_tool", `${command} isn't installed.`)
43
+ if (signal) return new EngineFailure("render", "crash", `The tool crashed (${signal}).`)
44
+ for (const [pattern, kind, reason, message] of PATTERNS) if (pattern.test(tail)) return new EngineFailure(kind, reason, message)
45
+ return new EngineFailure("render", "failed", `The tool stopped with code ${code}: ${tail.trim().split("\n").at(-1)?.slice(0, 200) ?? ""}`)
46
+ }
47
+
48
+ /**
49
+ * @param {string} command
50
+ * @param {string[]} args
51
+ * @param {{ timeoutMs?: number, stallMs?: number, signal?: AbortSignal, onStdout?: (chunk: Buffer) => void, env?: object, cwd?: string }} [options]
52
+ * stallMs: a tool that prints nothing for this long is hung
53
+ * @returns {Promise<string>} stdout, unless onStdout takes it
54
+ */
55
+ export function runTool(command, args, { timeoutMs = 0, stallMs = 0, signal, onStdout, env = childEnv(), cwd } = {}) {
56
+ return new Promise((done, fail) => {
57
+ if (signal?.aborted) return fail(signal.reason)
58
+ const [file, argv] = confined(command, args)
59
+ const child = spawn(file, argv, { env, stdio: ["ignore", "pipe", "pipe"], ...(cwd ? { cwd } : {}) })
60
+ let out = ""
61
+ let tail = ""
62
+ let stopped = null
63
+ let stall
64
+ const stop = (failure) => {
65
+ stopped ??= failure
66
+ child.kill("SIGKILL")
67
+ }
68
+ const watch = () => {
69
+ clearTimeout(stall)
70
+ if (stallMs) stall = setTimeout(() => stop(new EngineFailure("render", "hang", "The tool stopped making progress.")), stallMs)
71
+ }
72
+ const limit = timeoutMs ? setTimeout(() => stop(new EngineFailure("render", "timeout", "The tool took too long.")), timeoutMs) : null
73
+ const cancel = () => stop(signal.reason)
74
+ signal?.addEventListener("abort", cancel, { once: true })
75
+ watch()
76
+ child.stdout.on("data", (chunk) => {
77
+ watch()
78
+ if (onStdout) onStdout(chunk)
79
+ else out += chunk
80
+ })
81
+ child.stderr.on("data", (chunk) => {
82
+ watch()
83
+ tail = (tail + chunk).slice(-TAIL)
84
+ })
85
+ const finish = () => {
86
+ clearTimeout(limit)
87
+ clearTimeout(stall)
88
+ signal?.removeEventListener("abort", cancel)
89
+ }
90
+ child.on("error", (error) => {
91
+ finish()
92
+ fail(error.code === "ENOENT" ? new EngineFailure("environment", "missing_tool", `${command} isn't installed.`) : error)
93
+ })
94
+ child.on("close", (code, killed) => {
95
+ finish()
96
+ if (stopped) fail(stopped)
97
+ else if (code === 0) done(out)
98
+ else fail(classify(tail, code, killed, command))
99
+ })
100
+ })
101
+ }
@@ -0,0 +1,113 @@
1
+ // QG-10 Copy (QUALITY_GATES §2, ED10): the text as rendered, read back by OCR, against
2
+ // the text the plan meant, and the names and numbers in it against what was said.
3
+ // macOS uses Vision through a small helper compiled once; other systems say so.
4
+
5
+ import { createHash } from "node:crypto"
6
+ import { existsSync, mkdirSync, readFileSync, renameSync } from "node:fs"
7
+ import { dirname, join } from "node:path"
8
+ import { fileURLToPath } from "node:url"
9
+
10
+ import { scriptOf } from "../engine/captions.js"
11
+
12
+ const HELPER = join(dirname(fileURLToPath(import.meta.url)), "text.swift")
13
+ const FLICKS = 705_600_000
14
+
15
+ /** The compiled reader's path, building it on first use. @returns {Promise<{ path?: string, missing?: string }>} */
16
+ export async function ocrHelper(binDir, run, platform = process.platform) {
17
+ if (platform !== "darwin") return { missing: "Reading rendered text on this system needs the Media Runtime's OCR, which isn't in it yet." }
18
+ const source = readFileSync(HELPER)
19
+ const path = join(binDir, `ocr-${createHash("sha256").update(source).digest("hex").slice(0, 12)}`)
20
+ if (existsSync(path)) return { path }
21
+ mkdirSync(binDir, { recursive: true })
22
+ try {
23
+ await run("swiftc", ["-O", HELPER, "-o", `${path}.${process.pid}.part`], { timeoutMs: 300_000 })
24
+ renameSync(`${path}.${process.pid}.part`, path)
25
+ } catch {
26
+ return { missing: "Reading rendered text needs Apple's command line tools (xcode-select --install)." }
27
+ }
28
+ return { path }
29
+ }
30
+
31
+ // Below this, the reader isn't sure of a line (Vision read a highlighted "and" as "anda" at 0.5, found in ED10)
32
+ export const UNSURE = 0.8
33
+
34
+ /** The reader's lines → per image name, the text and the words it wasn't sure of. */
35
+ export function readOcr(text) {
36
+ const out = new Map()
37
+ for (const line of text.split("\n")) {
38
+ if (!line.trim()) continue
39
+ const { image, lines } = JSON.parse(line)
40
+ out.set(image, { text: lines.map((l) => l.text).join(" "), unsure: lines.filter((l) => l.c < UNSURE).flatMap((l) => normalise(l.text).split(" ")).filter(Boolean) })
41
+ }
42
+ return out
43
+ }
44
+
45
+ /** One edit apart, or the same. */
46
+ function nearly(a, b) {
47
+ if (a === b) return true
48
+ if (Math.abs(a.length - b.length) > 1) return false
49
+ return similarity(a, b) >= 1 - 1 / Math.max(a.length, b.length) - 1e-9
50
+ }
51
+
52
+ /** Letters and digits, lower case, one space between words: what both sides are compared as. */
53
+ export const normalise = (text) => String(text).normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, " ").trim()
54
+
55
+ export function similarity(a, b) {
56
+ const x = normalise(a)
57
+ const y = normalise(b)
58
+ if (!x.length && !y.length) return 1
59
+ const d = Array.from({ length: y.length + 1 }, (_, j) => j)
60
+ for (let i = 1; i <= x.length; i++) {
61
+ let prev = d[0]
62
+ d[0] = i
63
+ for (let j = 1; j <= y.length; j++) {
64
+ const keep = d[j]
65
+ d[j] = Math.min(d[j] + 1, d[j - 1] + 1, prev + (x[i - 1] === y[j - 1] ? 0 : 1))
66
+ prev = keep
67
+ }
68
+ }
69
+ return 1 - d[y.length] / Math.max(x.length, y.length)
70
+ }
71
+
72
+ /** What a tile meant to show. */
73
+ export function intendedText(tile) {
74
+ if (tile.kind === "caption") return tile.node.text ?? tile.node.words.map((w) => w.text).join(" ")
75
+ return [tile.node.variables?.text, tile.node.variables?.subtitle].filter(Boolean).join(" ")
76
+ }
77
+
78
+ // A name or a number: capitalised after the first word, or with a digit in it
79
+ const isNameOrNumber = (text, i) => /\d/.test(text) || (i > 0 && /^\p{Lu}/u.test(text))
80
+
81
+ /**
82
+ * @param {{ tile: object, seen: string, unsure?: string[] }[]} read unsure: words from lines the reader wasn't sure of
83
+ * @returns {{ failures: object[], numbers: object, unread: object[] }}
84
+ */
85
+ export function judgeCopy(read, { copySimilarity }) {
86
+ const failures = []
87
+ const unread = []
88
+ let worst = 1
89
+ for (const { tile, seen, unsure = [] } of read) {
90
+ const meant = intendedText(tile)
91
+ if (scriptOf(meant) !== "latin") {
92
+ unread.push({ tile: tile.key, script: scriptOf(meant) })
93
+ continue
94
+ }
95
+ const score = similarity(meant, seen ?? "")
96
+ worst = Math.min(worst, score)
97
+ // Every word meant must be on screen as itself: a one-letter change in a name passes a similarity (found in ED10)
98
+ const shownWords = new Set(normalise(seen ?? "").split(" "))
99
+ // 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 } : {}) })
102
+ // What was said: a caption's names and numbers must be on screen as they were spoken
103
+ if (tile.kind === "caption") {
104
+ const shown = ` ${normalise(seen ?? "")} `
105
+ for (const [i, word] of tile.node.words.entries()) {
106
+ if (!isNameOrNumber(word.text, i)) continue
107
+ const said = normalise(word.text)
108
+ if (said && !shown.includes(` ${said} `)) failures.push({ kind: "name_mismatch", t: tile.at + word.at, seconds: Math.round(((tile.at + word.at) / FLICKS) * 100) / 100, said: word.text, seen: seen ?? "" })
109
+ }
110
+ }
111
+ }
112
+ return { failures, unread, numbers: { texts: read.length, worstSimilarity: Math.round(worst * 100) / 100, needed: copySimilarity, unread: unread.length } }
113
+ }
@@ -0,0 +1,430 @@
1
+ // Quality gates (QUALITY_GATES.md): verdicts are code, read from the rendered file.
2
+ // Each gate reports its numbers, its threshold and where it failed; a gate that
3
+ // couldn't run is `not_checked`, never `passed`. Thresholds are data (§1 rule 4).
4
+ // Built: QG-01, -02, -05, -06, -12 (ED7); QG-08, -09 (ED8); QG-06 complete (ED9);
5
+ // QG-03, -04, -07, -10, -11, -13, -14 (ED10). A gate whose tool isn't here says `not_checked`.
6
+
7
+ import { mkdirSync, mkdtempSync, rmSync } from "node:fs"
8
+ import { join } from "node:path"
9
+
10
+ import { busOf, speechSpans } from "../core/audio.js"
11
+ import { wholeSegment } from "../core/plan.js"
12
+ import { solve } from "../core/solver.js"
13
+ import { measureLoudness } from "../engine/loudness.js"
14
+ import { runTool } from "../engine/tool.js"
15
+ import { judgeCopy, ocrHelper, readOcr } from "./copy.js"
16
+ import { healthArgs, judgeHealth, judgeMotion, judgeSync, readHealth, streamTimes, tileFrames } from "./picture.js"
17
+ import { curveOf, judgeMix, rangeOf } from "./sound.js"
18
+ import { expectedWords, judgeReview, judgeSpeech, REVIEWER_SCHEMA } from "./speech.js"
19
+ import { judgeLayout, judgeLegibility, measurePlan } from "./text.js"
20
+ import { UNTRUSTED_CLOSE, UNTRUSTED_OPEN } from "../index/views.js"
21
+
22
+ const FLICKS = 705_600_000
23
+ const RATE = 48_000
24
+
25
+ export const THRESHOLDS = {
26
+ frames: 1, // QG-02: off by more than this many frames
27
+ minShotFrames: 3, // QG-05
28
+ voicedRatio: 4, // QG-05: RMS at a cut over the recording's own floor × this is speech
29
+ voicedFloorDb: -50, // and above this, so a silent recording has no "speech"
30
+ clickRatio: 10, // QG-05: a jump this many times the local slope is a pop
31
+ clickMin: 0.05,
32
+ loudnessLU: 0.5, // QG-06
33
+ maxRange: null, // QG-06: a recipe's loudness range limit, in LU; none by default
34
+ speechOverMusic: 8, // QG-06: LU the speech stays over the music in each stretch of speech (untuned)
35
+ sfxOverVoice: 3, // QG-06: LU an effect's loudest moment may pass the voice's integrated loudness (untuned)
36
+ lengthTolerance: 0.15, // QG-12: target length ± this share
37
+ contrast: 4.5, // QG-09: WCAG AA for text, against the pixels behind it
38
+ minTextShare: 0.02, // QG-09: text under this share of the frame's height is too small
39
+ maxDriftMs: 40, // QG-03
40
+ exposureJump: 30, // QG-07: mean luma steps (of 255) at a cut between pieces of one source; a note
41
+ minMotion: 0.5, // QG-11: mean alpha change (of 255) in a tile's first second
42
+ copySimilarity: 0.9, // QG-10: rendered text against the intended text
43
+ }
44
+
45
+ export const GATES = ["QG-01", "QG-02", "QG-03", "QG-04", "QG-05", "QG-06", "QG-07", "QG-08", "QG-09", "QG-10", "QG-11", "QG-12", "QG-13", "QG-14"]
46
+ const BUILT = new Set(GATES)
47
+
48
+ const frameFlicks = (fps) => (FLICKS * fps.d) / fps.n
49
+ const ratio = (text) => {
50
+ const [n, d] = String(text).split("/").map(Number)
51
+ return n > 0 && d > 0 ? { n, d } : null
52
+ }
53
+ const seconds = (flicks) => (flicks / FLICKS).toFixed(6)
54
+ const SEVERITY = { "QG-13": "note", "QG-14": "note" }
55
+ const result = (id, status, numbers = {}, message = "", at = null, severity = SEVERITY[id] ?? "block") => ({ id, status, severity, numbers, message, ...(at === null ? {} : { at }) })
56
+
57
+ async function probeFile(file, run) {
58
+ return JSON.parse(await run("ffprobe", ["-v", "error", "-print_format", "json", "-show_streams", "-show_format", "-count_frames", file], { timeoutMs: 600_000 }))
59
+ }
60
+
61
+ /** Mono samples of a file between two times, as Float32 in [-1, 1]. */
62
+ async function samples(file, from, length, run) {
63
+ const chunks = []
64
+ await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-ss", seconds(Math.max(0, from)), "-t", seconds(length), "-i", file, "-vn", "-ac", "1", "-ar", String(RATE), "-f", "s16le", "pipe:1"], { timeoutMs: 120_000, onStdout: (chunk) => chunks.push(chunk) })
65
+ const data = Buffer.concat(chunks)
66
+ const out = new Float32Array(Math.floor(data.length / 2))
67
+ for (let i = 0; i < out.length; i++) out[i] = data.readInt16LE(i * 2) / 32768
68
+ return out
69
+ }
70
+
71
+ const rms = (x, from = 0, to = x.length) => {
72
+ let sum = 0
73
+ for (let i = from; i < to; i++) sum += x[i] * x[i]
74
+ return to > from ? Math.sqrt(sum / (to - from)) : 0
75
+ }
76
+
77
+ /** A recording's own noise floor: the 10th percentile of its 20 ms RMS. */
78
+ function floorOf(x) {
79
+ const step = RATE / 50
80
+ const levels = []
81
+ for (let i = 0; i + step <= x.length; i += step) levels.push(rms(x, i, i + step))
82
+ levels.sort((a, b) => a - b)
83
+ return levels[Math.floor(levels.length * 0.1)] ?? 0
84
+ }
85
+
86
+ /* ─────────────────────────────── the gates ─────────────────────────────── */
87
+
88
+ async function qg01({ file, plan, run }) {
89
+ try {
90
+ const data = await probeFile(file, run)
91
+ const video = data.streams.find((s) => s.codec_type === "video")
92
+ const audio = data.streams.find((s) => s.codec_type === "audio")
93
+ const fps = ratio(video?.avg_frame_rate)
94
+ const want = plan.output
95
+ const numbers = { codec: video?.codec_name, width: video?.width, height: video?.height, fps: video?.avg_frame_rate, pixFmt: video?.pix_fmt, primaries: video?.color_primaries, audio: audio?.codec_name }
96
+ const wrong = []
97
+ if (video?.codec_name !== "h264") wrong.push("codec")
98
+ if (video?.width !== want.width || video?.height !== want.height) wrong.push("size")
99
+ if (!fps || fps.n * want.fps.d !== want.fps.n * fps.d) wrong.push("fps")
100
+ if (video?.pix_fmt !== "yuv420p") wrong.push("pixel format")
101
+ if (video?.color_primaries !== "bt709" || video?.color_transfer !== "bt709") wrong.push("colour tags")
102
+ if (audio?.codec_name !== "aac") wrong.push("audio codec")
103
+ // A full read: any decode error fails it
104
+ await run("ffmpeg", ["-hide_banner", "-nostdin", "-v", "error", "-xerror", "-i", file, "-f", "null", "-"], { timeoutMs: 600_000 })
105
+ return wrong.length ? result("QG-01", "failed", numbers, `Not to spec: ${wrong.join(", ")}.`) : result("QG-01", "passed", numbers)
106
+ } catch (error) {
107
+ return result("QG-01", "failed", {}, `The file doesn't play: ${error.message}`)
108
+ }
109
+ }
110
+
111
+ async function qg02({ file, plan, run }) {
112
+ const data = await probeFile(file, run)
113
+ const video = data.streams.find((s) => s.codec_type === "video")
114
+ const audio = data.streams.find((s) => s.codec_type === "audio")
115
+ const frame = frameFlicks(plan.output.fps)
116
+ const expected = Math.round(plan.duration / frame)
117
+ const frames = Number(video?.nb_read_frames)
118
+ const base = (stream) => stream.time_base.split("/").map(Number)
119
+ const flicksOf = (stream) => (stream?.duration_ts ? (Number(stream.duration_ts) * base(stream)[0] * FLICKS) / base(stream)[1] : Number(stream?.duration ?? 0) * FLICKS)
120
+ const audioFrames = audio ? flicksOf(audio) / frame : null
121
+ const numbers = { expectedFrames: expected, videoFrames: frames, audioFrames: audioFrames === null ? null : Math.round(audioFrames * 100) / 100, tolerance: THRESHOLDS.frames }
122
+ if (!Number.isFinite(frames)) return result("QG-02", "not_checked", numbers, "The frames couldn't be counted.")
123
+ if (Math.abs(frames - expected) > THRESHOLDS.frames) return result("QG-02", "failed", numbers, `${frames} frames, the plan says ${expected}.`)
124
+ if (audioFrames === null || Math.abs(audioFrames - frames) > THRESHOLDS.frames) return result("QG-02", "failed", numbers, "Sound and picture aren't the same length.")
125
+ return result("QG-02", "passed", numbers)
126
+ }
127
+
128
+ /** Cuts in the base picture: where one piece ends and a non-contiguous one begins. */
129
+ export function cutsOf(picture) {
130
+ const cuts = []
131
+ for (let i = 1; i < picture.length; i++) {
132
+ const [a, b] = [picture[i - 1], picture[i]]
133
+ if (a.asset !== b.asset || a.out !== b.in) cuts.push({ at: b.at, out: { asset: a.asset, t: a.out }, in: { asset: b.asset, t: b.in } })
134
+ }
135
+ return cuts
136
+ }
137
+
138
+ async function qg05({ file, project, index, sourcePath, run }) {
139
+ const timeline = solve(project, index)
140
+ const picture = [...timeline.picture].sort((a, b) => a.at - b.at)
141
+ const fps = project.canvas.fps
142
+ const problems = []
143
+ const short = picture.filter((p) => (p.end - p.at) / frameFlicks(fps) < THRESHOLDS.minShotFrames)
144
+ for (const p of short) problems.push({ at: p.at, kind: "short_shot", frames: Math.round((p.end - p.at) / frameFlicks(fps)) })
145
+ const cuts = cutsOf(picture)
146
+ const words = index.words ?? []
147
+ const inside = (edge) => words.find((w) => w.asset === edge.asset && edge.t > w.start && edge.t < w.end)
148
+ const sources = new Map()
149
+ const sourceOf = async (asset) => {
150
+ if (!sources.has(asset)) {
151
+ const x = await samples(sourcePath(asset), 0, project.assets.find((a) => a.id === asset).facts.duration, run)
152
+ sources.set(asset, { x, floor: floorOf(x) })
153
+ }
154
+ return sources.get(asset)
155
+ }
156
+ let worstClick = 0
157
+ for (const cut of cuts) {
158
+ for (const [side, edge] of [["out", cut.out], ["in", cut.in]]) {
159
+ const word = inside(edge)
160
+ if (word) problems.push({ at: cut.at, kind: "cut_inside_word", side, word: word.id })
161
+ // The source's own sound just inside the kept side of the edge
162
+ const { x, floor } = await sourceOf(edge.asset)
163
+ const at = Math.round((edge.t / FLICKS) * RATE)
164
+ const window = RATE / 100
165
+ const level = side === "out" ? rms(x, Math.max(0, at - window), at) : rms(x, at, Math.min(x.length, at + window))
166
+ const db = 20 * Math.log10(Math.max(level, 1e-9))
167
+ if (level > floor * THRESHOLDS.voicedRatio && db > THRESHOLDS.voicedFloorDb) problems.push({ at: cut.at, kind: "cut_in_voiced_speech", side, db: Math.round(db * 10) / 10 })
168
+ }
169
+ // A pop in the output at the cut: a jump far above the local slope
170
+ const y = await samples(file, cut.at - FLICKS / 50, FLICKS / 25, run)
171
+ let slope = 0
172
+ let jump = 0
173
+ for (let i = 1; i < y.length; i++) {
174
+ const d = Math.abs(y[i] - y[i - 1])
175
+ slope += d
176
+ jump = Math.max(jump, d)
177
+ }
178
+ slope /= Math.max(1, y.length - 1)
179
+ const score = jump / Math.max(slope, 1e-4)
180
+ worstClick = Math.max(worstClick, jump >= THRESHOLDS.clickMin ? score : 0)
181
+ if (jump >= THRESHOLDS.clickMin && score > THRESHOLDS.clickRatio) problems.push({ at: cut.at, kind: "pop", jump: Math.round(jump * 1000) / 1000 })
182
+ }
183
+ const numbers = { cuts: cuts.length, worstClickRatio: Math.round(worstClick * 10) / 10, problems: problems.length }
184
+ return problems.length ? result("QG-05", "failed", { ...numbers, first: problems[0] }, `A cut isn't clean: ${problems[0].kind.replaceAll("_", " ")}.`, problems[0].at) : result("QG-05", "passed", numbers)
185
+ }
186
+
187
+ async function qg06({ file, plan, index, run, thresholds, stems }) {
188
+ const target = plan.audio.loudness
189
+ if (!target) return result("QG-06", "not_applicable", {}, "This render has no loudness target.")
190
+ const { integrated, truePeak } = await measureLoudness(file, { run })
191
+ const range = await rangeOf(file, run)
192
+ const numbers = { integrated, truePeak: truePeak === null ? null : Math.round(truePeak * 100) / 100, target: target.lufs, ceiling: target.tp, tolerance: thresholds.loudnessLU, range }
193
+ if (integrated === null) return result("QG-06", "failed", numbers, "The file is silent.")
194
+ // Every failure is listed, so the report says all of what's wrong
195
+ const failures = []
196
+ if (Math.abs(integrated - target.lufs) > thresholds.loudnessLU) failures.push({ kind: "off_target", message: `Loudness ${integrated.toFixed(1)} LUFS, the target is ${target.lufs}.` })
197
+ if (truePeak !== null && truePeak > target.tp) failures.push({ kind: "over_ceiling", message: `True peak ${truePeak.toFixed(1)} dBTP is over ${target.tp}.` })
198
+ if (thresholds.maxRange !== null && range !== null && range > thresholds.maxRange) failures.push({ kind: "range", message: `The loudness range is ${range} LU, over the recipe's ${thresholds.maxRange}.` })
199
+ // The mix (ED9): speech over music where there is speech, effects against the voice, from the stems
200
+ const buses = new Set(plan.audio.items.map((item) => busOf(item.role)))
201
+ let all = numbers
202
+ let mixed = true
203
+ if (buses.has("music") || buses.has("sfx")) {
204
+ if (!stems) mixed = false
205
+ else {
206
+ const { stems: files, voice } = await stems(plan.audio.key)
207
+ if (files.dialogue) {
208
+ const curve = async (bus) => (files[bus] ? curveOf(files[bus], { run, duration: plan.duration }) : undefined)
209
+ const speech = plan.audio.duck?.speech ?? speechSpans(plan.audio.items, index?.words ?? [])
210
+ const judged = judgeMix({ speech, dialogue: await curve("dialogue"), music: await curve("music"), sfx: await curve("sfx"), voice, thresholds })
211
+ all = { ...numbers, ...judged.numbers, voice }
212
+ for (const f of judged.failures) failures.push({ ...f, message: f.kind === "music_masks_speech" ? (f.margin < 0 ? `The music is ${-f.margin} LU over the speech at ${f.seconds} s.` : `The music is only ${f.margin} LU under the speech at ${f.seconds} s.`) : `A sound effect is ${f.over} LU over the voice at ${f.seconds} s.` })
213
+ }
214
+ }
215
+ }
216
+ if (failures.length) return { ...result("QG-06", "failed", { ...all, first: failures[0] }, failures[0].message), failures }
217
+ if (!mixed) return result("QG-06", "not_checked", all, "Loudness passed; the mix needs the Engine's stems, which this run didn't have.")
218
+ return result("QG-06", "passed", all)
219
+ }
220
+
221
+ /** Sentence ids or phrases the brief names, resolved to their words. */
222
+ function wordsFor(entry, index) {
223
+ const sentence = (index.sentences ?? []).find((s) => s.id === entry)
224
+ const words = index.words ?? []
225
+ if (sentence) {
226
+ const [first, last] = [sentence.firstWord, sentence.lastWord].map((id) => words.findIndex((w) => w.id === id))
227
+ return words.slice(first, last + 1).filter((w) => !w.flags.includes("filler") && !w.flags.includes("stutter"))
228
+ }
229
+ const norm = (t) => t.toLowerCase().replace(/[^\p{L}\p{N} ]+/gu, "").trim()
230
+ const want = norm(entry).split(/\s+/)
231
+ for (let i = 0; i + want.length <= words.length; i++) if (want.every((token, k) => norm(words[i + k].text) === token)) return words.slice(i, i + want.length)
232
+ return null
233
+ }
234
+
235
+ async function qg12({ file, project, index, run, thresholds }) {
236
+ const brief = project.brief
237
+ if (!brief) return result("QG-12", "not_applicable", {}, "This project has no brief.")
238
+ const timeline = solve(project, index)
239
+ const plays = (word) => timeline.picture.some((p) => p.asset === word.asset && word.start >= p.in && word.end <= p.out)
240
+ const misses = []
241
+ for (const entry of brief.mustKeep ?? []) {
242
+ const words = wordsFor(entry, index)
243
+ if (!words?.length) misses.push({ kind: "must_keep_unknown", entry })
244
+ else if (!words.every(plays)) misses.push({ kind: "must_keep_missing", entry })
245
+ }
246
+ for (const entry of brief.mustCut ?? []) {
247
+ const words = wordsFor(entry, index)
248
+ if (words?.some(plays)) misses.push({ kind: "must_cut_present", entry })
249
+ }
250
+ const data = await probeFile(file, run)
251
+ const length = Number(data.format?.duration ?? 0) * FLICKS
252
+ const target = brief.targetDuration
253
+ if (target && Math.abs(length - target) > target * thresholds.lengthTolerance) misses.push({ kind: "length", seconds: Math.round((length / FLICKS) * 10) / 10, target: target / FLICKS })
254
+ const numbers = { mustKeep: brief.mustKeep?.length ?? 0, mustCut: brief.mustCut?.length ?? 0, seconds: Math.round((length / FLICKS) * 10) / 10, targetSeconds: target ? target / FLICKS : null, misses: misses.length }
255
+ return misses.length ? { ...result("QG-12", "failed", { ...numbers, first: misses[0] }, `The brief isn't met: ${misses[0].kind.replaceAll("_", " ")}.`), misses } : result("QG-12", "passed", numbers)
256
+ }
257
+
258
+ // QG-08 and QG-09 share one measurement of the text, made once per run
259
+ const textOf = (input) => (input.text ??= input.motion && !input.motion.missing ? measurePlan(input.plan, { motion: input.motion, work: input.work }) : Promise.resolve(null))
260
+ const noText = (plan) => !plan.tiles.some((tile) => tile.kind === "caption" || tile.kind === "block")
261
+
262
+ async function qg08(input) {
263
+ if (noText(input.plan)) return result("QG-08", "not_applicable", {}, "No text on screen.")
264
+ const measured = await textOf(input)
265
+ if (!measured) return result("QG-08", "not_checked", {}, input.motion?.missing ?? "The gate has no Chrome to measure text in.")
266
+ const judged = judgeLayout({ ...input, measured })
267
+ const first = judged.failures[0]
268
+ return { ...result("QG-08", judged.status, { ...judged.numbers, ...(first ? { first } : {}) }, first ? `Text ${first.kind.replaceAll("_", " ")} at ${first.seconds} s.` : "", first ? first.t : null), failures: judged.failures }
269
+ }
270
+
271
+ async function qg09(input) {
272
+ if (noText(input.plan)) return result("QG-09", "not_applicable", {}, "No text on screen.")
273
+ if (input.plan.input !== "source" && !input.inputPath) return result("QG-09", "not_checked", {}, "Legibility reads a master's pixels.")
274
+ const measured = await textOf(input)
275
+ if (!measured) return result("QG-09", "not_checked", {}, input.motion?.missing ?? "The gate has no Chrome to measure text in.")
276
+ const judged = await judgeLegibility({ ...input, measured, inputPath: input.inputPath ?? input.sourcePath, thresholds: input.thresholds })
277
+ const first = judged.failures[0]
278
+ return { ...result("QG-09", judged.status, { ...judged.numbers, ...(first ? { first } : {}) }, first ? `Text ${first.kind.replaceAll("_", " ")} at ${first.seconds} s.` : ""), failures: judged.failures }
279
+ }
280
+
281
+ /* ─────────────────────────────── ED10 ─────────────────────────────── */
282
+
283
+ const outcome = (id, judged, { at = null, severity } = {}) => {
284
+ const first = judged.failures[0]
285
+ const level = severity ?? (judged.failures.some((f) => (f.severity ?? "block") === "block") ? "block" : "note")
286
+ if (!first) return result(id, "passed", judged.numbers)
287
+ return { ...result(id, "failed", { ...judged.numbers, first }, `${first.kind.replaceAll("_", " ")}${first.seconds !== undefined ? ` at ${first.seconds} s` : ""}.`, at ?? first.t ?? null, level), failures: judged.failures }
288
+ }
289
+
290
+ async function qg03({ file, run, thresholds }) {
291
+ const judged = judgeSync(await streamTimes(file, run), thresholds)
292
+ if (judged.applicable === false) return result("QG-03", "not_applicable", judged.numbers, "This file has no sound, or no picture.")
293
+ return outcome("QG-03", judged)
294
+ }
295
+
296
+ // The recogniser hears the output once; QG-04 and QG-14 share it
297
+ const heardOf = (input) => (input.heard ??= input.recognise(input.file))
298
+
299
+ async function qg04(input) {
300
+ if (!input.recognise) return result("QG-04", "not_checked", {}, "No verified speech recogniser in this Media Runtime (EB-11), so the output wasn't listened to.")
301
+ const expected = expectedWords(input.plan, input.index?.words ?? [])
302
+ if (!expected.kept.length) return result("QG-04", "not_applicable", {}, "No words are kept, so there is nothing to hear.")
303
+ return outcome("QG-04", judgeSpeech(expected, await heardOf(input)))
304
+ }
305
+
306
+ async function qg07({ file, plan, run, thresholds }) {
307
+ const health = readHealth(await run("ffmpeg", healthArgs(file), { timeoutMs: 600_000 }))
308
+ const picture = wholeSegment(plan).node.picture.sort((a, b) => a.at - b.at)
309
+ const holds = picture.filter((p) => p.hold).map(({ at, end }) => ({ at, end }))
310
+ const cuts = picture.slice(1).map((p, i) => ({ t: p.at, same: p.asset === picture[i].asset && !p.hold && !picture[i].hold }))
311
+ return outcome("QG-07", judgeHealth(health, { duration: plan.duration, fps: plan.output.fps, holds, cuts }, thresholds))
312
+ }
313
+
314
+ const textTiles = (plan) => plan.tiles.filter((t) => t.kind === "caption" || t.kind === "block")
315
+
316
+ async function qg10({ plan, run, thresholds, tilePath, binDir, work }) {
317
+ const tiles = textTiles(plan)
318
+ if (!tiles.length) return result("QG-10", "not_applicable", {}, "No text on screen.")
319
+ if (!tilePath || !binDir || !work) return result("QG-10", "not_checked", {}, "The gate has no tiles or helper folder to read text from.")
320
+ const helper = await ocrHelper(binDir, run)
321
+ if (helper.missing) return result("QG-10", "not_checked", {}, helper.missing)
322
+ mkdirSync(work, { recursive: true })
323
+ const dir = mkdtempSync(join(work, "ocr-"))
324
+ try {
325
+ // Each tile at rest, over mid grey, as the reader sees it
326
+ for (const [i, tile] of tiles.entries()) {
327
+ const at = Math.min(((tile.end - tile.at) / FLICKS) * 0.9, tile.kind === "caption" ? 0.4 : 1)
328
+ 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", "[1:v][0:v]overlay=shortest=1", "-frames:v", "1", "-y", join(dir, `t${String(i).padStart(4, "0")}.png`)], { timeoutMs: 60_000 })
329
+ }
330
+ const seen = readOcr(await run(helper.path, [dir], { timeoutMs: 300_000 }))
331
+ const judged = judgeCopy(tiles.map((tile, i) => {
332
+ const read = seen.get(`t${String(i).padStart(4, "0")}.png`)
333
+ return { tile, seen: read?.text ?? "", unsure: read?.unsure ?? [] }
334
+ }), thresholds)
335
+ 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.`)
336
+ return outcome("QG-10", judged)
337
+ } finally {
338
+ rmSync(dir, { recursive: true, force: true })
339
+ }
340
+ }
341
+
342
+ async function qg11({ plan, run, thresholds, tilePath }) {
343
+ const tiles = textTiles(plan)
344
+ if (!tiles.length) return result("QG-11", "not_applicable", {}, "No motion layer in this render.")
345
+ if (!tilePath) return result("QG-11", "not_checked", {}, "The gate has no tiles to look at.")
346
+ const fps = plan.output.fps
347
+ const read = []
348
+ for (const tile of tiles) read.push({ tile, frames: await tileFrames(tilePath(tile.key), run), expected: Math.ceil(((tile.end - tile.at) * fps.n) / (FLICKS * fps.d) - 1e-9) })
349
+ return outcome("QG-11", judgeMotion(read, thresholds))
350
+ }
351
+
352
+ // Third-party material: music, effects and footage on any track but the base
353
+ function qg13({ plan, project }) {
354
+ // EDD-23, ET-SEC-08: a reference gives numbers only; its picture or sound in an output is a failure, however it got there
355
+ const kindOf = (id) => project.assets.find((a) => a.id === id)?.kind
356
+ const references = [...new Set([...plan.segments.flatMap((s) => [...s.node.picture, ...s.node.overlays]), ...plan.audio.items].map((item) => item.asset))].filter((id) => kindOf(id) === "reference")
357
+ if (references.length) return { ...result("QG-13", "failed", { references }, `A reference (${references.join(", ")}) is in this output; a reference gives numbers only, never its picture or sound.`), failures: references.map((asset) => ({ kind: "reference_in_output", asset })) }
358
+ const used = new Map()
359
+ for (const s of plan.segments) {
360
+ for (const item of s.node.overlays) used.set(item.asset, "overlay footage")
361
+ }
362
+ for (const item of plan.audio.items) if (item.role === "music" || item.role === "sfx") used.set(item.asset, item.role)
363
+ const unknown = [...used].map(([id, use]) => ({ id, use, rights: project.assets.find((a) => a.id === id)?.rights ?? "unknown" })).filter((a) => a.rights === "unknown")
364
+ const numbers = { checked: used.size, unknown: unknown.map((a) => a.id) }
365
+ if (!unknown.length) return result("QG-13", used.size ? "passed" : "not_applicable", numbers, used.size ? "" : "No third-party material in this render.")
366
+ return { ...result("QG-13", "failed", numbers, `The rights to ${unknown.map((a) => `${a.id} (${a.use})`).join(", ")} aren't known.`), failures: unknown.map((a) => ({ kind: "rights_unknown", asset: a.id, use: a.use })) }
367
+ }
368
+
369
+ async function qg14(input) {
370
+ if (!input.recognise || !input.ask) return result("QG-14", "not_checked", {}, "The blind reviewer hears the output through the speech recogniser, which isn't verified here (EB-11).")
371
+ const heard = await heardOf(input)
372
+ if (!heard.length) return result("QG-14", "not_checked", {}, "Nothing was heard in the output.")
373
+ // The reviewer gets only what a viewer gets: the words heard, never the plan or the brief
374
+ const review = await input.ask({ task: "reviewer", schema: REVIEWER_SCHEMA, view: `${UNTRUSTED_OPEN}\nwords heard in the video\n${JSON.stringify(heard.map((w) => w.text).join(" ").replace(/[<>]/g, "").slice(0, 6000))}\n${UNTRUSTED_CLOSE}`, request: "In one sentence, what is this video about?", maxOutput: 120, fallback: () => ({ about: "" }) })
375
+ if (!review.value.about) return result("QG-14", "not_checked", {}, review.reason ?? "The reviewer gave no answer.")
376
+ const brief = input.project.brief ?? {}
377
+ const sentences = input.index?.sentences ?? []
378
+ const words = input.index?.words ?? []
379
+ const lineOf = (id) => {
380
+ const s = sentences.find((x) => x.id === id)
381
+ if (!s) return null
382
+ const i = words.findIndex((w) => w.id === s.firstWord)
383
+ const j = words.findIndex((w) => w.id === s.lastWord)
384
+ return words.slice(i, j + 1).map((w) => w.text).join(" ")
385
+ }
386
+ const keyLines = (brief.mustKeep ?? []).map(lineOf).filter(Boolean)
387
+ const judged = judgeReview(review.value.about, keyLines.length ? keyLines : [heard.slice(0, 12).map((w) => w.text).join(" ")])
388
+ const numbers = { ...judged.numbers, about: review.value.about.slice(0, 300) }
389
+ return judged.note ? result("QG-14", "failed", numbers, "The blind reviewer's summary doesn't mention what the brief says the video is for.") : result("QG-14", "passed", numbers)
390
+ }
391
+
392
+ const RUN = { "QG-01": qg01, "QG-02": qg02, "QG-03": qg03, "QG-04": qg04, "QG-05": qg05, "QG-06": qg06, "QG-07": qg07, "QG-08": qg08, "QG-09": qg09, "QG-10": qg10, "QG-11": qg11, "QG-12": qg12, "QG-13": qg13, "QG-14": qg14 }
393
+
394
+ /** Verdict words (QUALITY_GATES §5), from gate results only. */
395
+ export function verdictOf(results) {
396
+ const blocking = results.filter((r) => r.status === "failed" && r.severity === "block").length
397
+ const briefMisses = results.find((r) => r.id === "QG-12")?.misses?.length ?? 0
398
+ const notes = results.filter((r) => r.status === "failed" && r.severity === "note").length
399
+ const ran = results.filter((r) => r.status === "passed" || r.status === "failed")
400
+ const unchecked = results.filter((r) => r.status === "not_checked").length
401
+ const verdict = ran.length === 0 ? "not_checked" : blocking > 0 ? "blocked" : notes > 0 || unchecked > 0 ? "delivered_with_notes" : "delivered"
402
+ return { verdict, blocking: blocking - (briefMisses ? 1 : 0), briefMisses, notes: notes + unchecked }
403
+ }
404
+
405
+ /**
406
+ * Runs the gates on a rendered file.
407
+ * @param {{ file: string, plan: object, project: object, index: object, sourcePath: (asset: string) => string, run?: typeof runTool, only?: string[], thresholds?: Partial<typeof THRESHOLDS>, tilePath?: (key: string) => string, motion?: object, work?: string, inputPath?: (asset: string) => string, stems?: (audioKey: string) => Promise<{ stems: Record<string, string>, voice: number | null }> }} input
408
+ * thresholds: the recipe's values; only tighter or the recipe's own, never loosened by a model.
409
+ * 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;
410
+ * 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)
411
+ */
412
+ export async function runGates({ file, plan, project, index, sourcePath, run = runTool, only = [...BUILT], thresholds = {}, tilePath, motion, work, inputPath, stems, recognise, ask, binDir }) {
413
+ // Frozen: no gate, fix or model can loosen what the recipe set (QUALITY_GATES §4)
414
+ const limits = Object.freeze({ ...THRESHOLDS, ...thresholds })
415
+ const shared = { file, plan, project, index, sourcePath, run, thresholds: limits, tilePath, motion, work, inputPath, stems, recognise, ask, binDir }
416
+ const results = []
417
+ for (const id of GATES) {
418
+ if (!only.includes(id)) continue
419
+ if (!BUILT.has(id)) {
420
+ results.push(result(id, "not_checked", {}, "This gate isn't built yet."))
421
+ continue
422
+ }
423
+ try {
424
+ results.push(await RUN[id](shared))
425
+ } catch (error) {
426
+ results.push(result(id, "not_checked", {}, `The gate couldn't run: ${error.message}`))
427
+ }
428
+ }
429
+ return { gates: results, ...verdictOf(results) }
430
+ }