@kriya-ai/harness 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/README.md +379 -2
  2. package/SAFETY.md +162 -0
  3. package/THIRD_PARTY_NOTICES.md +7911 -0
  4. package/bin/kriya.js +577 -0
  5. package/bundle/cordis.patch.yml +397 -0
  6. package/contract/SOURCE.md +15 -0
  7. package/contract/contract.json +1355 -0
  8. package/package.json +57 -4
  9. package/plugins/anchor/index.js +56 -0
  10. package/plugins/anchor/package.json +13 -0
  11. package/plugins/approvals/index.js +183 -0
  12. package/plugins/approvals/package.json +13 -0
  13. package/plugins/brand/DESIGN.md +112 -0
  14. package/plugins/brand/client.js +826 -0
  15. package/plugins/brand/index.js +15 -0
  16. package/plugins/brand/package.json +25 -0
  17. package/plugins/brand/src/client.js +823 -0
  18. package/plugins/browser/index.js +218 -0
  19. package/plugins/browser/package.json +13 -0
  20. package/plugins/budget/index.js +108 -0
  21. package/plugins/budget/package.json +13 -0
  22. package/plugins/changes/client.js +245 -0
  23. package/plugins/changes/index.js +75 -0
  24. package/plugins/changes/package.json +22 -0
  25. package/plugins/edit/client.js +113 -0
  26. package/plugins/edit/index.js +58 -0
  27. package/plugins/edit/package.json +23 -0
  28. package/plugins/fs-freshness/index.js +28 -0
  29. package/plugins/fs-freshness/package.json +13 -0
  30. package/plugins/graph/client.js +178 -0
  31. package/plugins/graph/index.js +4 -0
  32. package/plugins/graph/package.json +22 -0
  33. package/plugins/kriya-handoff/index.js +194 -0
  34. package/plugins/kriya-handoff/package.json +13 -0
  35. package/plugins/kriya-tools/index.js +189 -0
  36. package/plugins/kriya-tools/package.json +13 -0
  37. package/plugins/loop/index.js +743 -0
  38. package/plugins/loop/package.json +13 -0
  39. package/plugins/mirror/index.js +235 -0
  40. package/plugins/mirror/package.json +13 -0
  41. package/plugins/overview/client.js +276 -0
  42. package/plugins/overview/index.js +95 -0
  43. package/plugins/overview/package.json +22 -0
  44. package/plugins/preview/client.js +337 -0
  45. package/plugins/preview/index.js +4 -0
  46. package/plugins/preview/package.json +22 -0
  47. package/plugins/progress/client.js +290 -0
  48. package/plugins/progress/index.js +100 -0
  49. package/plugins/progress/package.json +22 -0
  50. package/plugins/projects/client.js +249 -0
  51. package/plugins/projects/index.js +30 -0
  52. package/plugins/projects/package.json +24 -0
  53. package/plugins/rea/index.js +256 -0
  54. package/plugins/rea/package.json +10 -0
  55. package/plugins/rea/skill/LICENSE +21 -0
  56. package/plugins/rea/skill/SKILL.md +360 -0
  57. package/plugins/rea/skill/references/android-applications.md +36 -0
  58. package/plugins/rea/skill/references/connection-and-recovery.md +127 -0
  59. package/plugins/rea/skill/references/evidence-workflows.md +71 -0
  60. package/plugins/rea/skill/references/javascript-applications.md +218 -0
  61. package/plugins/rea/skill/references/native-and-artifacts.md +297 -0
  62. package/plugins/rea/skill/references/runtime-observation.md +78 -0
  63. package/plugins/remote/index.js +297 -0
  64. package/plugins/remote/package.json +10 -0
  65. package/plugins/router/index.js +84 -0
  66. package/plugins/router/package.json +13 -0
  67. package/plugins/sessions/client.js +68 -0
  68. package/plugins/sessions/index.js +79 -0
  69. package/plugins/sessions/package.json +20 -0
  70. package/plugins/skills/client.js +504 -0
  71. package/plugins/skills/index.js +166 -0
  72. package/plugins/skills/package.json +23 -0
  73. package/src/api.js +97 -0
  74. package/src/browser.js +286 -0
  75. package/src/changes.js +191 -0
  76. package/src/checkpoints.js +313 -0
  77. package/src/daemon.js +503 -0
  78. package/src/doctor.js +137 -0
  79. package/src/edit/core/anchors.js +102 -0
  80. package/src/edit/core/audio.js +158 -0
  81. package/src/edit/core/faces.js +99 -0
  82. package/src/edit/core/ffmpeg.js +258 -0
  83. package/src/edit/core/handoff.js +220 -0
  84. package/src/edit/core/history.js +90 -0
  85. package/src/edit/core/layout.js +92 -0
  86. package/src/edit/core/mix.js +115 -0
  87. package/src/edit/core/ops.js +602 -0
  88. package/src/edit/core/plan.js +266 -0
  89. package/src/edit/core/project.d.ts +134 -0
  90. package/src/edit/core/project.js +307 -0
  91. package/src/edit/core/reframe.js +125 -0
  92. package/src/edit/core/solver.js +416 -0
  93. package/src/edit/core/time.js +110 -0
  94. package/src/edit/core/tonemap.js +57 -0
  95. package/src/edit/director/ask.js +120 -0
  96. package/src/edit/director/gateway.js +16 -0
  97. package/src/edit/director/revise.js +186 -0
  98. package/src/edit/engine/capabilities.js +33 -0
  99. package/src/edit/engine/captions.js +154 -0
  100. package/src/edit/engine/color.js +269 -0
  101. package/src/edit/engine/confine.js +67 -0
  102. package/src/edit/engine/dna.js +148 -0
  103. package/src/edit/engine/index.js +473 -0
  104. package/src/edit/engine/loudness.js +43 -0
  105. package/src/edit/engine/media.js +57 -0
  106. package/src/edit/engine/motion.js +281 -0
  107. package/src/edit/engine/packs.js +87 -0
  108. package/src/edit/engine/probe.js +101 -0
  109. package/src/edit/engine/receipt.js +123 -0
  110. package/src/edit/engine/tool.js +101 -0
  111. package/src/edit/gates/copy.js +113 -0
  112. package/src/edit/gates/index.js +430 -0
  113. package/src/edit/gates/picture.js +130 -0
  114. package/src/edit/gates/sound.js +58 -0
  115. package/src/edit/gates/speech.js +127 -0
  116. package/src/edit/gates/text.js +196 -0
  117. package/src/edit/gates/text.swift +22 -0
  118. package/src/edit/graph/index.js +139 -0
  119. package/src/edit/graph/journal.js +69 -0
  120. package/src/edit/graph/scheduler.js +79 -0
  121. package/src/edit/host/client.js +58 -0
  122. package/src/edit/host/deliver.js +119 -0
  123. package/src/edit/host/jobs.js +84 -0
  124. package/src/edit/host/main.js +135 -0
  125. package/src/edit/host/paths.js +11 -0
  126. package/src/edit/host/projects.js +415 -0
  127. package/src/edit/host/server.js +391 -0
  128. package/src/edit/host/taste.js +135 -0
  129. package/src/edit/host/tavi.js +417 -0
  130. package/src/edit/host/watch.js +141 -0
  131. package/src/edit/index/db.js +109 -0
  132. package/src/edit/index/index.js +236 -0
  133. package/src/edit/index/layers/faces.js +78 -0
  134. package/src/edit/index/layers/faces.swift +18 -0
  135. package/src/edit/index/layers/meta.js +35 -0
  136. package/src/edit/index/layers/music.js +146 -0
  137. package/src/edit/index/layers/quality.js +120 -0
  138. package/src/edit/index/layers/retakes.js +132 -0
  139. package/src/edit/index/layers/screen.js +99 -0
  140. package/src/edit/index/layers/shots.js +29 -0
  141. package/src/edit/index/layers/sound.js +42 -0
  142. package/src/edit/index/layers/words.js +64 -0
  143. package/src/edit/index/story.js +248 -0
  144. package/src/edit/index/views.js +71 -0
  145. package/src/edit/loop/governor.js +112 -0
  146. package/src/edit/loop/loop.js +69 -0
  147. package/src/edit/loop/make.js +115 -0
  148. package/src/edit/loop/repair.js +97 -0
  149. package/src/edit/loop/replay.js +32 -0
  150. package/src/edit/recipes/multicam.js +461 -0
  151. package/src/edit/recipes/reel.js +202 -0
  152. package/src/edit/recipes/short-from-long.js +237 -0
  153. package/src/edit/recipes/tutorial.js +137 -0
  154. package/src/edit/recipes/youtube.js +155 -0
  155. package/src/edit/runtime/cli.js +126 -0
  156. package/src/edit/runtime/doctor.js +122 -0
  157. package/src/edit/runtime/fetch.js +15 -0
  158. package/src/edit/runtime/licences.js +88 -0
  159. package/src/edit/runtime/manifest.js +73 -0
  160. package/src/edit/runtime/setup.js +252 -0
  161. package/src/failure.js +69 -0
  162. package/src/gateway-proxy.js +213 -0
  163. package/src/intent.js +130 -0
  164. package/src/launch.js +315 -0
  165. package/src/live.js +81 -0
  166. package/src/local-skills.js +284 -0
  167. package/src/login.js +82 -0
  168. package/src/loop.js +428 -0
  169. package/src/modes.js +128 -0
  170. package/src/overview.js +71 -0
  171. package/src/paths.js +30 -0
  172. package/src/profiles.js +92 -0
  173. package/src/projects.js +104 -0
  174. package/src/recon.js +244 -0
  175. package/src/rules.js +139 -0
  176. package/src/runner.bundle.js +21172 -0
  177. package/src/sentinel.js +248 -0
  178. package/src/skill-switches.js +130 -0
  179. package/src/store.js +58 -0
  180. package/src/strict.js +124 -0
  181. package/src/verify.js +659 -0
  182. package/src/world.js +268 -0
  183. package/studio/dist/index.html +14 -0
  184. package/studio/dist/studio.css +163 -0
  185. package/studio/dist/studio.js +1 -0
@@ -0,0 +1,130 @@
1
+ // QG-03 Sync, QG-07 Picture health and QG-11 Motion (QUALITY_GATES §2, ED10), read
2
+ // from the rendered file and its tiles by FFmpeg. Each returns its numbers and every
3
+ // failure with its time; the runner turns them into a verdict.
4
+
5
+ import { metadataFrames } from "../index/layers/meta.js"
6
+
7
+ const FLICKS = 705_600_000
8
+ const toFlicks = (seconds) => Math.round(Number(seconds) * FLICKS)
9
+ const round = (n, places = 3) => Math.round(n * 10 ** places) / 10 ** places
10
+
11
+ /* ─────────────────────────────── QG-03 ─────────────────────────────── */
12
+
13
+ /**
14
+ * Where each stream starts and ends, from the container's own timestamps.
15
+ * shortcut: streams only; speech onsets against lip activity need a mouth track (L8 landmarks), not built
16
+ */
17
+ export async function streamTimes(file, run) {
18
+ const data = JSON.parse(await run("ffprobe", ["-v", "error", "-print_format", "json", "-show_entries", "stream=codec_type,codec_name,start_time,duration,initial_padding,sample_rate", file], { timeoutMs: 120_000 }))
19
+ const of = (type) => {
20
+ const s = data.streams.find((stream) => stream.codec_type === type)
21
+ if (!s) return null
22
+ // AAC that lost its padding note plays its priming samples first, so the sound proper starts later
23
+ // (found by EG-4's seeds). shortcut: FFmpeg's AAC delay, 1024 samples; other encoders' delays differ
24
+ const primed = type === "audio" && s.codec_name === "aac" && Number(s.initial_padding ?? 0) === 0 && Number(s.sample_rate) > 0 ? 1024 / Number(s.sample_rate) : 0
25
+ const start = Number(s.start_time ?? 0) + primed
26
+ return { start, end: Number(s.start_time ?? 0) + Number(s.duration ?? 0), ...(primed ? { primed: Math.round(primed * 10000) / 10 } : {}) }
27
+ }
28
+ return { video: of("video"), audio: of("audio") }
29
+ }
30
+
31
+ export function judgeSync({ video, audio }, { maxDriftMs }) {
32
+ if (!video || !audio) return { failures: [], numbers: { streams: [video ? "video" : null, audio ? "audio" : null].filter(Boolean) }, applicable: false }
33
+ const startMs = Math.abs(video.start - audio.start) * 1000
34
+ const endMs = Math.abs(video.end - audio.end) * 1000
35
+ const failures = []
36
+ if (startMs > maxDriftMs) failures.push({ kind: "offset", ms: round(startMs, 1), t: 0 })
37
+ // AAC ends on its own frame (21 ms at 48 kHz), so the end allows one more
38
+ if (endMs > maxDriftMs + 21.4) failures.push({ kind: "drift", ms: round(endMs, 1), t: toFlicks(Math.min(video.end, audio.end)) })
39
+ return { failures, numbers: { startMs: round(startMs, 1), endMs: round(endMs, 1), allowedMs: maxDriftMs, ...(audio.primed ? { primingMs: audio.primed } : {}), lipSync: "not built" } }
40
+ }
41
+
42
+ /* ─────────────────────────────── QG-07 ─────────────────────────────── */
43
+
44
+ export const healthArgs = (file) => ["-hide_banner", "-nostdin", "-loglevel", "error", "-i", file, "-an", "-vf", "scale=320:-2,blackdetect=d=0.1:pix_th=0.1,freezedetect=n=-55dB:d=1,signalstats,metadata=mode=print:file=-", "-f", "null", "-"]
45
+
46
+ /** Black and frozen spans and the picture's mean brightness per frame, from one pass. */
47
+ export function readHealth(text) {
48
+ const frames = metadataFrames(text)
49
+ const black = []
50
+ const frozen = []
51
+ const luma = []
52
+ let open = null
53
+ for (const { pts, values } of frames) {
54
+ luma.push(Number(values["lavfi.signalstats.YAVG"]))
55
+ if (values["lavfi.black_start"] !== undefined) open = { start: toFlicks(values["lavfi.black_start"]) }
56
+ if (values["lavfi.black_end"] !== undefined && open) {
57
+ black.push({ ...open, end: toFlicks(values["lavfi.black_end"]) })
58
+ open = null
59
+ }
60
+ if (values["lavfi.freezedetect.freeze_start"] !== undefined) frozen.push({ start: toFlicks(values["lavfi.freezedetect.freeze_start"]), end: null })
61
+ if (values["lavfi.freezedetect.freeze_end"] !== undefined && frozen.at(-1)?.end === null) frozen.at(-1).end = toFlicks(values["lavfi.freezedetect.freeze_end"])
62
+ void pts
63
+ }
64
+ if (open) black.push({ ...open, end: null })
65
+ return { black, frozen, luma }
66
+ }
67
+
68
+ /**
69
+ * @param {{ black: object[], frozen: object[], luma: number[] }} health
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
+ */
72
+ export function judgeHealth({ black, frozen, luma }, { duration, fps, holds, cuts }, { exposureJump }) {
73
+ const failures = []
74
+ const close = (span) => ({ ...span, end: span.end ?? duration })
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) })
77
+ 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
+ const frameAt = (t) => Math.min(luma.length - 1, Math.max(0, Math.floor((t * fps.n) / (FLICKS * fps.d))))
79
+ let worst = 0
80
+ for (const cut of cuts) {
81
+ if (!cut.same) continue
82
+ const before = luma[frameAt(cut.t) - 1]
83
+ const after = luma[frameAt(cut.t)]
84
+ if (!Number.isFinite(before) || !Number.isFinite(after)) continue
85
+ const jump = Math.abs(after - before)
86
+ worst = Math.max(worst, jump)
87
+ if (jump > exposureJump) failures.push({ kind: "exposure_jump", severity: "note", t: cut.t, jump: round(jump, 1), allowed: exposureJump })
88
+ }
89
+ return { failures, numbers: { black: black.length, frozen: frozen.length, worstJump: round(worst, 1), banding: "not built" } }
90
+ }
91
+
92
+ /* ─────────────────────────────── QG-11 ─────────────────────────────── */
93
+
94
+ const SMALL = { w: 96, h: 96 }
95
+
96
+ /** A tile's frames, small, as alpha: is there motion at all, and how many frames are there. */
97
+ export async function tileFrames(file, run) {
98
+ const chunks = []
99
+ await run("ffmpeg", ["-hide_banner", "-nostdin", "-loglevel", "error", "-i", file, "-vf", `alphaextract,scale=${SMALL.w}:${SMALL.h},format=gray`, "-f", "rawvideo", "pipe:1"], { timeoutMs: 120_000, onStdout: (chunk) => chunks.push(chunk) })
100
+ const data = Buffer.concat(chunks)
101
+ const size = SMALL.w * SMALL.h
102
+ const frames = []
103
+ for (let i = 0; (i + 1) * size <= data.length; i++) frames.push(data.subarray(i * size, (i + 1) * size))
104
+ return frames
105
+ }
106
+
107
+ const meanDiff = (a, b) => {
108
+ let sum = 0
109
+ for (let i = 0; i < a.length; i++) sum += Math.abs(a[i] - b[i])
110
+ return sum / a.length
111
+ }
112
+
113
+ /**
114
+ * @param {{ tile: object, frames: Buffer[], expected: number }[]} tiles expected: frames the window holds
115
+ */
116
+ export function judgeMotion(tiles, { minMotion }) {
117
+ const failures = []
118
+ let still = 0
119
+ for (const { tile, frames, expected } of tiles) {
120
+ if (frames.length < expected) failures.push({ kind: "clipped_overlay", t: tile.at, frames: frames.length, expected })
121
+ // The entrance: how far the first second moves from the first frame
122
+ let moved = 0
123
+ for (let i = 1; i < Math.min(frames.length, 30); i++) moved = Math.max(moved, meanDiff(frames[0], frames[i]))
124
+ if (moved < minMotion) {
125
+ still++
126
+ failures.push({ kind: "no_motion", t: tile.at, change: round(moved, 2), needed: minMotion })
127
+ }
128
+ }
129
+ return { failures, numbers: { tiles: tiles.length, still } }
130
+ }
@@ -0,0 +1,58 @@
1
+ // QG-06's mix checks (QUALITY_GATES §2, ED9), on the stems the Engine rendered:
2
+ // speech over music in every stretch of speech, sound effects against the voice, and
3
+ // the loudness range of the whole. Loudness is EBU R128 momentary, at 100 ms.
4
+
5
+ import { readSound, soundArgs, STEP } from "../index/layers/sound.js"
6
+
7
+ const FLICKS = 705_600_000
8
+
9
+ /** Momentary loudness every 100 ms, null where silent (below R128's gate). */
10
+ export async function curveOf(file, { run, duration }) {
11
+ return readSound(await run("ffmpeg", soundArgs(file), { timeoutMs: 600_000 }), duration).data.loudness
12
+ }
13
+
14
+ /** Energy mean of LUFS values, ignoring silence; null when all silent. */
15
+ export function energyMean(values) {
16
+ const live = values.filter((v) => v !== null && v !== undefined)
17
+ if (!live.length) return null
18
+ return 10 * Math.log10(live.reduce((sum, v) => sum + 10 ** (v / 10), 0) / live.length)
19
+ }
20
+
21
+ const slice = (curve, at, end) => curve.slice(Math.floor(at / STEP), Math.ceil(end / STEP))
22
+
23
+ /**
24
+ * @param {{ speech: { at: number, end: number }[], dialogue: (number|null)[], music?: (number|null)[], sfx?: (number|null)[], voice: number | null, thresholds: { speechOverMusic: number, sfxOverVoice: number } }} input
25
+ * voice: the dialogue stem's integrated loudness
26
+ * @returns {{ failures: object[], numbers: object }}
27
+ */
28
+ export function judgeMix({ speech, dialogue, music, sfx, voice, thresholds }) {
29
+ const failures = []
30
+ let worst = null
31
+ if (music) {
32
+ for (const span of speech) {
33
+ if (span.end - span.at < FLICKS) continue // too short to read loudness from
34
+ const d = energyMean(slice(dialogue, span.at, span.end))
35
+ const m = energyMean(slice(music, span.at, span.end))
36
+ if (d === null || m === null) continue
37
+ const margin = d - m
38
+ worst = worst === null ? margin : Math.min(worst, margin)
39
+ if (margin < thresholds.speechOverMusic) failures.push({ kind: "music_masks_speech", seconds: Math.round((span.at / FLICKS) * 10) / 10, margin: Math.round(margin * 10) / 10, needed: thresholds.speechOverMusic })
40
+ }
41
+ }
42
+ let loudestEffect = null
43
+ if (sfx && voice !== null) {
44
+ const top = Math.max(...sfx.filter((v) => v !== null), -Infinity)
45
+ if (top > -Infinity) {
46
+ loudestEffect = Math.round((top - voice) * 10) / 10
47
+ if (top - voice > thresholds.sfxOverVoice) failures.push({ kind: "effect_over_voice", over: loudestEffect, allowed: thresholds.sfxOverVoice, seconds: Math.round(((sfx.indexOf(top) * STEP) / FLICKS) * 10) / 10 })
48
+ }
49
+ }
50
+ return { failures, numbers: { speechOverMusic: worst === null ? null : Math.round(worst * 10) / 10, effectOverVoice: loudestEffect, sections: speech.filter((s) => s.end - s.at >= FLICKS).length } }
51
+ }
52
+
53
+ /** The loudness range (LRA, LU) from FFmpeg's ebur128 summary. */
54
+ export async function rangeOf(file, run) {
55
+ const text = await run("ffmpeg", ["-hide_banner", "-nostdin", "-protocol_whitelist", "file,pipe", "-i", file, "-vn", "-af", "ebur128=metadata=1,ametadata=mode=print:key=lavfi.r128.LRA:file=-", "-f", "null", "-"], { timeoutMs: 600_000 })
56
+ const values = [...text.matchAll(/lavfi\.r128\.LRA=([\d.]+)/g)].map((m) => Number(m[1]))
57
+ return values.length ? Math.round(values.at(-1) * 10) / 10 : null
58
+ }
@@ -0,0 +1,127 @@
1
+ // QG-04 Round-trip speech and QG-14 Blind reviewer (QUALITY_GATES §2, EDD-20, ED10).
2
+ // QG-04 listens to its own output and aligns what it heard with the words the plan
3
+ // keeps and the words it removed. QG-14 lets a model hear only what a viewer gets and
4
+ // say what the video is about; code compares that with the brief, and it can only add
5
+ // a note: a model's text never changes a verdict (ET-QG-20).
6
+
7
+ import { busOf } from "../core/audio.js"
8
+ import { scaleFlicks } from "../core/time.js"
9
+ import { normalise } from "./copy.js"
10
+
11
+ const FLICKS = 705_600_000
12
+
13
+ /** The words the plan keeps, in output order, and the ones it removed, from the index. */
14
+ export function expectedWords(plan, words) {
15
+ const kept = []
16
+ const keptIds = new Set()
17
+ for (const item of plan.audio.items) {
18
+ if (busOf(item.role) !== "dialogue") continue
19
+ const rate = { n: item.speed?.d ?? 1, d: item.speed?.n ?? 1 }
20
+ for (const w of words) {
21
+ if (w.asset !== item.asset || w.start < item.in || w.end > item.out) continue
22
+ kept.push({ ...w, at: item.at + scaleFlicks(w.start - item.in, rate) })
23
+ keptIds.add(w.id)
24
+ }
25
+ }
26
+ kept.sort((a, b) => a.at - b.at)
27
+ const assets = new Set(plan.audio.items.filter((i) => busOf(i.role) === "dialogue").map((i) => i.asset))
28
+ const removed = words.filter((w) => assets.has(w.asset) && !keptIds.has(w.id))
29
+ return { kept, removed }
30
+ }
31
+
32
+ const token = (text) => normalise(text).replace(/ /g, "")
33
+ const STOP = new Set("the a an and or but of to in on for with is are was were it this that we you i our they them at as by be so if from".split(" "))
34
+ // Recognisers differ on small words and on a letter here and there: a word of 4 or more letters matches within one edit
35
+ function same(a, b) {
36
+ if (a === b) return true
37
+ if (a.length < 4 || b.length < 4 || Math.abs(a.length - b.length) > 1) return false
38
+ let i = 0
39
+ let j = 0
40
+ let edits = 0
41
+ while (i < a.length && j < b.length) {
42
+ if (a[i] === b[j]) {
43
+ i++
44
+ j++
45
+ continue
46
+ }
47
+ if (++edits > 1) return false
48
+ if (a.length > b.length) i++
49
+ else if (b.length > a.length) j++
50
+ else {
51
+ i++
52
+ j++
53
+ }
54
+ }
55
+ return edits + (a.length - i) + (b.length - j) <= 1
56
+ }
57
+
58
+ /** Longest common subsequence of two token lists: which of `a` were heard, in order. */
59
+ function align(a, b) {
60
+ const n = a.length
61
+ const m = b.length
62
+ const L = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1))
63
+ for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i][j] = same(a[i], b[j]) ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1])
64
+ const matchedA = new Set()
65
+ const matchedB = new Set()
66
+ let i = 0
67
+ let j = 0
68
+ while (i < n && j < m) {
69
+ if (same(a[i], b[j])) {
70
+ matchedA.add(i++)
71
+ matchedB.add(j++)
72
+ } else if (L[i + 1][j] >= L[i][j + 1]) i++
73
+ else j++
74
+ }
75
+ return { matchedA, matchedB }
76
+ }
77
+
78
+ /**
79
+ * @param {{ kept: object[], removed: object[] }} expected
80
+ * @param {{ text: string, start: number }[]} heard the recogniser's words on the output
81
+ */
82
+ export function judgeSpeech(expected, heard) {
83
+ const keptTokens = expected.kept.map((w) => token(w.text))
84
+ const heardTokens = heard.map((w) => token(w.text))
85
+ const { matchedA, matchedB } = align(keptTokens, heardTokens)
86
+ const failures = []
87
+ // A kept word missing: ignore short words and function words, which recognisers drop or swap
88
+ // shortcut: an untuned list, English only; EX-11's real-speech check sets it per language
89
+ expected.kept.forEach((w, i) => {
90
+ if (!matchedA.has(i) && keptTokens[i].length > 2 && !STOP.has(keptTokens[i])) failures.push({ kind: "kept_word_missing", t: w.at, seconds: Math.round((w.at / FLICKS) * 100) / 100, word: w.text })
91
+ })
92
+ // A removed word audible: heard, matched to nothing kept, and it is one of the removed words
93
+ const keptSet = new Set(keptTokens)
94
+ heard.forEach((w, j) => {
95
+ if (matchedB.has(j)) return
96
+ const t = heardTokens[j]
97
+ if (t.length < 3 || keptSet.has(t)) return
98
+ if (expected.removed.some((r) => same(token(r.text), t))) failures.push({ kind: "removed_word_audible", t: w.start, seconds: Math.round((w.start / FLICKS) * 100) / 100, word: w.text })
99
+ })
100
+ // Order: words that are all there, but heard in another order, align short
101
+ const bag = new Map()
102
+ for (const t of heardTokens) bag.set(t, (bag.get(t) ?? 0) + 1)
103
+ let present = 0
104
+ for (const t of keptTokens) if ((bag.get(t) ?? 0) > 0) {
105
+ present++
106
+ bag.set(t, bag.get(t) - 1)
107
+ }
108
+ if (present - matchedA.size >= 2) failures.push({ kind: "order_wrong", t: 0, seconds: 0, present, inOrder: matchedA.size })
109
+ return { failures, numbers: { kept: expected.kept.length, heard: heard.length, matched: matchedA.size } }
110
+ }
111
+
112
+ /* ─────────────────────────────── QG-14 ─────────────────────────────── */
113
+
114
+ export const REVIEWER_SCHEMA = { type: "object", properties: { about: { type: "string", maxLength: 300 } }, required: ["about"], additionalProperties: false }
115
+
116
+ const contentWords = (text) => new Set(normalise(text).split(" ").filter((w) => w.length > 2 && !STOP.has(w)))
117
+
118
+ /**
119
+ * Code's comparison: does the reviewer's one sentence share any content word with the
120
+ * lines the brief names (must-keeps, or the opening line)? Never a failure, only a note.
121
+ */
122
+ export function judgeReview(about, keyLines) {
123
+ const said = contentWords(about)
124
+ const key = new Set(keyLines.flatMap((line) => [...contentWords(line)]))
125
+ const shared = [...key].filter((w) => said.has(w))
126
+ return { note: key.size > 0 && shared.length === 0, numbers: { shared: shared.length, keyWords: key.size } }
127
+ }
@@ -0,0 +1,196 @@
1
+ // QG-08 Layout and QG-09 Legibility (QUALITY_GATES §2, ED8). Both read what was
2
+ // actually drawn: text boxes measured in the tile's own DOM at each beat, face boxes
3
+ // mapped onto the output, and the composited pixels behind each text box.
4
+
5
+ import { mkdirSync, mkdtempSync, rmSync } from "node:fs"
6
+ import { join } from "node:path"
7
+
8
+ import { outputFaces } from "../core/faces.js"
9
+ import { segmentArgs } from "../core/ffmpeg.js"
10
+ import { safeZoneFor } from "../core/layout.js"
11
+ import { wholeSegment } from "../core/plan.js"
12
+ import { captionComposition, READING_LIMITS, scriptOf } from "../engine/captions.js"
13
+ import { compositionFor, measureText } from "../engine/motion.js"
14
+
15
+ const FLICKS = 705_600_000
16
+ const SETTLE_MS = { caption: 350, block: 950 } // the entrances' lengths, so a beat sees text at rest
17
+
18
+ const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h
19
+ const frameMs = (fps) => (1000 * fps.d) / fps.n
20
+ const rounded = (box) => ({ x: Math.round(box.x), y: Math.round(box.y), w: Math.round(box.w), h: Math.round(box.h) })
21
+
22
+ /** The times worth looking at in a tile, in ms from its start: at rest, each word, the last frame. */
23
+ export function beatsOf(tile, fps) {
24
+ const length = Math.max(0, (tile.end - tile.at) / FLICKS) * 1000
25
+ const last = Math.max(0, length - frameMs(fps))
26
+ const times = [Math.min(last, SETTLE_MS[tile.kind] ?? 0), last]
27
+ if (tile.kind === "caption") for (const word of tile.node.words) times.push((((word.at + word.end) / 2) / FLICKS) * 1000)
28
+ return [...new Set(times.filter((t) => t >= Math.min(last, SETTLE_MS[tile.kind] ?? 0) && t <= last).map((t) => Math.round(t)))].sort((a, b) => a - b)
29
+ }
30
+
31
+ const textTiles = (plan) => plan.tiles.filter((tile) => tile.kind === "caption" || tile.kind === "block")
32
+
33
+ /**
34
+ * Every text tile measured at every beat of every tile it shares the screen with.
35
+ * @returns {Promise<{ t: number, tile: object, box: object }[]>} t: output flicks
36
+ */
37
+ export async function measurePlan(plan, { motion, work, measure = measureText }) {
38
+ const tiles = textTiles(plan)
39
+ const beats = [...new Set(tiles.flatMap((tile) => beatsOf(tile, plan.output.fps).map((ms) => tile.at + Math.round((ms / 1000) * FLICKS))))].sort((a, b) => a - b)
40
+ const frame = { output: plan.output, canvas: plan.canvas }
41
+ const items = tiles.map((tile) => ({
42
+ id: tile.key,
43
+ html: compositionFor(tile, frame, captionComposition),
44
+ times: beats.filter((t) => t >= tile.at && t < tile.end).map((t) => ((t - tile.at) / FLICKS) * 1000),
45
+ }))
46
+ mkdirSync(work, { recursive: true })
47
+ const dir = mkdtempSync(join(work, "m-"))
48
+ let measured
49
+ try {
50
+ measured = await measure({ items: items.filter((item) => item.times.length), work: dir, runtime: motion })
51
+ } finally {
52
+ rmSync(dir, { recursive: true, force: true })
53
+ }
54
+ const out = []
55
+ for (const [i, tile] of tiles.entries()) {
56
+ const sets = measured.get(tile.key) ?? []
57
+ sets.forEach((boxes, k) => {
58
+ const t = tile.at + Math.round((items[i].times[k] / 1000) * FLICKS)
59
+ for (const box of boxes) out.push({ t, tile, box })
60
+ })
61
+ }
62
+ return out
63
+ }
64
+
65
+ /* ─────────────────────────────── QG-08 ─────────────────────────────── */
66
+
67
+ /**
68
+ * @param {{ plan: object, project: object, index: object, measured: Awaited<ReturnType<typeof measurePlan>> }} input
69
+ * @returns {{ status: "passed" | "failed", numbers: object, failures: object[] }}
70
+ */
71
+ export function judgeLayout({ plan, project, index, measured }) {
72
+ const { width, height } = plan.output
73
+ const sx = width / plan.canvas.width
74
+ const sy = height / plan.canvas.height
75
+ const zone = safeZoneFor(project)
76
+ const safe = { top: (zone.top ?? 0) * sy, right: (zone.right ?? 0) * sx, bottom: (zone.bottom ?? 0) * sy, left: (zone.left ?? 0) * sx }
77
+ const sizeOf = (id) => project.assets.find((asset) => asset.id === id)?.facts
78
+ const faces = outputFaces(wholeSegment(plan).node.picture, index.faces ?? [], sizeOf, { canvas: plan.canvas, output: plan.output })
79
+ const failures = []
80
+ const fail = (kind, item, extra = {}) => failures.push({ kind, t: item.t, seconds: Math.round((item.t / FLICKS) * 100) / 100, tile: item.tile.key, box: rounded(item.box), ...extra })
81
+ for (const item of measured) {
82
+ const { box } = item
83
+ if (box.x < -0.5 || box.y < -0.5 || box.x + box.w > width + 0.5 || box.y + box.h > height + 0.5) fail("outside_frame", item)
84
+ 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) fail("outside_safe_zone", item, { safe: rounded({ x: safe.left, y: safe.top, w: width - safe.left - safe.right, h: height - safe.top - safe.bottom }) })
85
+ if (box.clipped) fail("clipped", item)
86
+ // Behind-the-speaker text may cross the face: the matte draws the speaker over it
87
+ const behind = item.tile.node.behind === true && !item.tile.front
88
+ if (!behind) {
89
+ const face = faces.find((f) => Math.abs(f.t - item.t) <= FLICKS * 0.6 && overlaps(box, f.box))
90
+ if (face) fail("on_face", item, { face: face.box })
91
+ }
92
+ }
93
+ const byTime = new Map()
94
+ for (const item of measured) byTime.set(item.t, [...(byTime.get(item.t) ?? []), item])
95
+ for (const items of byTime.values()) {
96
+ for (let i = 0; i < items.length; i++) for (let k = i + 1; k < items.length; k++) if (items[i].tile.key !== items[k].tile.key && overlaps(items[i].box, items[k].box)) fail("overlap", items[i], { with: items[k].tile.key })
97
+ }
98
+ const numbers = { beats: byTime.size, boxes: measured.length, faces: faces.length, failures: failures.length, safe: zone }
99
+ return { status: failures.length ? "failed" : "passed", numbers, failures }
100
+ }
101
+
102
+ /* ─────────────────────────────── QG-09 ─────────────────────────────── */
103
+
104
+ /** WCAG relative luminance of an sRGB colour, 0 to 255 a channel. */
105
+ export function luminance([r, g, b]) {
106
+ const lin = (c) => {
107
+ const v = c / 255
108
+ return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4
109
+ }
110
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
111
+ }
112
+ export const contrast = (a, b) => (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)
113
+
114
+ export function parseColour(text) {
115
+ const m = /rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:[,\s/]+([\d.]+))?\s*\)/.exec(text ?? "")
116
+ return m ? { rgb: [Number(m[1]), Number(m[2]), Number(m[3])], alpha: m[4] === undefined ? 1 : Number(m[4]) } : null
117
+ }
118
+
119
+ /**
120
+ * The contrast text keeps against the pixels behind its box: each pixel under the
121
+ * plate (if any) blended, the worst `share` of them. @param {Buffer} rgb a whole frame
122
+ */
123
+ export function boxContrast(rgb, width, height, box, { colours, plate }, share = 0.1) {
124
+ const x0 = Math.max(0, Math.floor(box.x))
125
+ const y0 = Math.max(0, Math.floor(box.y))
126
+ const x1 = Math.min(width, Math.ceil(box.x + box.w))
127
+ const y1 = Math.min(height, Math.ceil(box.y + box.h))
128
+ const texts = colours.map(parseColour).filter(Boolean).map((c) => luminance(c.rgb))
129
+ const back = parseColour(plate)
130
+ const a = back?.alpha ?? 0
131
+ const values = []
132
+ for (let y = y0; y < y1; y += 2) {
133
+ for (let x = x0; x < x1; x += 2) {
134
+ const i = (y * width + x) * 3
135
+ const px = [rgb[i], rgb[i + 1], rgb[i + 2]]
136
+ const seen = a > 0 ? px.map((c, k) => back.rgb[k] * a + c * (1 - a)) : px
137
+ const l = luminance(seen)
138
+ values.push(Math.min(...texts.map((t) => contrast(t, l))))
139
+ }
140
+ }
141
+ values.sort((p, q) => p - q)
142
+ return values.length ? values[Math.floor(values.length * share)] : null
143
+ }
144
+
145
+ /** Raw RGB frames of the plan, without the tiles `without` names, at frame numbers. */
146
+ async function stills(plan, frames, { inputPath, tilePath, run, without }) {
147
+ const { width, height } = plan.output
148
+ const size = width * height * 3
149
+ const chunks = []
150
+ const args = segmentArgs(plan, wholeSegment(plan), { input: inputPath, tile: tilePath, output: "pipe:1", encoder: [], frames, without })
151
+ await run("ffmpeg", args, { timeoutMs: 600_000, onStdout: (chunk) => chunks.push(chunk) })
152
+ const data = Buffer.concat(chunks)
153
+ return frames.map((_, i) => data.subarray(i * size, (i + 1) * size)).filter((frame) => frame.length === size)
154
+ }
155
+
156
+ /**
157
+ * @param {{ plan: object, measured: object[], inputPath: (asset: string) => string, tilePath: (key: string) => string, run: Function, thresholds: object }} input
158
+ */
159
+ export async function judgeLegibility({ plan, measured, inputPath, tilePath, run, thresholds }) {
160
+ const { width, height } = plan.output
161
+ const fps = plan.output.fps
162
+ const total = Math.floor((plan.duration * fps.n) / (FLICKS * fps.d))
163
+ const failures = []
164
+ const fail = (kind, item, extra) => failures.push({ kind, seconds: Math.round((item.t / FLICKS) * 100) / 100, tile: item.tile.key, box: rounded(item.box), ...extra })
165
+ // One look per tile, at rest: the first beat measured
166
+ const first = new Map()
167
+ for (const item of measured) if (!first.has(item.tile.key) || first.get(item.tile.key).t > item.t) first.set(item.tile.key, item)
168
+ const items = [...first.values()]
169
+ const frameOf = (t) => Math.min(Math.max(0, total - 1), Math.floor((t * fps.n) / (FLICKS * fps.d)))
170
+ let worst = Infinity
171
+ // Captions over cards: a caption's background keeps the cards; a card's keeps neither
172
+ for (const [kind, without] of [["caption", (part) => part.kind === "caption"], ["block", () => true]]) {
173
+ const own = items.filter((item) => item.tile.kind === kind)
174
+ if (!own.length) continue
175
+ const frames = [...new Set(own.map((item) => frameOf(item.t)))].sort((a, b) => a - b)
176
+ const pictures = await stills(plan, frames, { inputPath, tilePath, run, without })
177
+ if (pictures.length !== frames.length) throw new Error("the frames behind the text couldn't be read")
178
+ for (const item of own) {
179
+ const value = boxContrast(pictures[frames.indexOf(frameOf(item.t))], width, height, item.box, item.box)
180
+ if (value === null) continue
181
+ worst = Math.min(worst, value)
182
+ if (value < thresholds.contrast) fail("low_contrast", item, { contrast: Math.round(value * 100) / 100, needed: thresholds.contrast })
183
+ }
184
+ }
185
+ for (const item of items) {
186
+ if (item.box.size / height < thresholds.minTextShare) fail("too_small", item, { px: item.box.size, minimum: Math.ceil(thresholds.minTextShare * height) })
187
+ if (item.tile.kind !== "caption") continue
188
+ const seconds = (item.tile.end - item.tile.at) / FLICKS
189
+ const words = item.tile.node.words.length
190
+ const script = scriptOf(item.tile.node.text)
191
+ const rate = words / Math.max(seconds, 1e-3)
192
+ if (rate > READING_LIMITS[script]) fail("too_fast", item, { wordsPerSecond: Math.round(rate * 100) / 100, limit: READING_LIMITS[script], script })
193
+ }
194
+ const numbers = { texts: items.length, worstContrast: worst === Infinity ? null : Math.round(worst * 100) / 100, needed: thresholds.contrast, failures: failures.length }
195
+ return { status: failures.length ? "failed" : "passed", numbers, failures }
196
+ }
@@ -0,0 +1,22 @@
1
+ // QG-10's reader: Apple's Vision text recognition, accurate mode, on this machine;
2
+ // no model download, nothing leaves it. Reads every .png in one folder and prints one
3
+ // JSON line per image: its recognised lines, top to bottom, with confidences.
4
+ import Foundation
5
+ import Vision
6
+
7
+ let folder = URL(fileURLWithPath: CommandLine.arguments[1])
8
+ let languages = CommandLine.arguments.count > 2 ? CommandLine.arguments[2].split(separator: ",").map(String.init) : ["en-US"]
9
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []
10
+ for name in names.filter({ $0.hasSuffix(".png") }).sorted() {
11
+ let request = VNRecognizeTextRequest()
12
+ request.recognitionLevel = .accurate
13
+ request.usesLanguageCorrection = false
14
+ request.recognitionLanguages = languages
15
+ try? VNImageRequestHandler(url: folder.appendingPathComponent(name)).perform([request])
16
+ let lines = (request.results ?? [])
17
+ .sorted { $0.boundingBox.maxY > $1.boundingBox.maxY }
18
+ .compactMap { $0.topCandidates(1).first }
19
+ .map { ["text": $0.string, "c": Double($0.confidence)] as [String: Any] }
20
+ let data = try! JSONSerialization.data(withJSONObject: ["image": name, "lines": lines])
21
+ print(String(data: data, encoding: .utf8)!)
22
+ }