// quoteCheck.mjs (lane one-clock): the plan finds what the render would play, // the run judges each clip from the words the editor heard and the cues, the // gate refuses a moved or missing quote unless ruled, and --align snaps the cut // to the words. The words and cues are the 6 Nov c43 window's // (report-to-video/fixtures/rev9-a3-rumble-words.json): heard 13 s late. // // Run with: pnpm test:scripts import assert from "node:assert/strict"; import test from "node:test"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { alignPatch, judgeClip, planQuoteCheck, quoteCheckCommand, quoteGate, readQuoteCheck, rowIsCurrent, runQuoteCheck } from "./quoteCheck.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const FIX = JSON.parse(await readFile(path.join(HERE, "..", "..", "report-to-video", "fixtures", "rev9-a3-rumble-words.json"), "utf8")); const C43 = FIX.clips.find((c) => c.id === "c43"); const C44 = FIX.clips.find((c) => c.id === "c44"); async function project() { const root = await mkdtemp(path.join(os.tmpdir(), "quote-check-")); const dir = path.join(root, "diet"); const raw = path.join(dir, "out", "clips-raw"); await mkdir(raw, { recursive: true }); const channels = path.join(root, "channels"); await mkdir(channels, { recursive: true }); // The windows the render would play: the project's raw cache, named for the cue clock. for (const c of [C43, C44]) await writeFile(path.join(raw, `${c.video}_${c.window[0].toFixed(2)}-${c.window[1].toFixed(2)}.mp4`), "mp4"); const manifest = { provenance: { channelSlug: "the-quartering-rumble", channelsDir: channels, channelsFallback: false }, timeline: [ { type: "clip", id: "c43", channel: C43.channel, video: C43.video, start: 2119.34, end: 2127.44, quote: C43.quote }, { type: "clip", id: "c44", channel: C44.channel, video: C44.video, start: 633.42, end: 644.16, quote: C44.quote }, { type: "clip", id: "c99", channel: C44.channel, video: C44.video, start: 10, end: 20 }, ], }; await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(manifest)); return { root, dir, channels, manifest }; } // The editor, stood in for: the fixture's words between start and end, on the file's clock. const fakeTranscribe = async (req) => { const clip = [C43, C44].find((c) => req.path.includes(c.video)); return clip.words.filter((w) => w.start >= req.start - 0.01 && w.end <= req.end + 0.01); }; const fakeCues = async (_slug, video) => [C43, C44].find((c) => c.video === video)?.cues ?? null; test("plan, run, gate, align: c43 is heard 13 s late; c44 where its cues say", async () => { const p = await project(); try { const plan = await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] }); const c43 = plan.find((r) => r.id === "c43"); assert.equal(c43.source.kind, "raw-cache"); assert.equal(c43.source.windowStart, C43.window[0]); // The cut ±15 s, inside the window the render would cut from. assert.deepEqual(c43.span, { from: 2104.34, to: 2142.44 }); assert.deepEqual(c43.file, { start: 0, end: 38.1 }); assert.equal(plan.find((r) => r.id === "c99").skip, "no-quote"); const lines = []; const { doc } = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: fakeTranscribe, cuesOf: fakeCues, log: (l) => lines.push(l) }); assert.equal(doc.clips.c43.status, "moved"); assert.ok(Math.abs(doc.clips.c43.offset - 13.1) < 0.15, String(doc.clips.c43.offset)); assert.equal(doc.clips.c43.against, "cues"); assert.equal(doc.clips.c44.status, "ok"); assert.equal(doc.clips.c99.status, "no-quote"); assert.match(lines.join("\n"), /c43 +moved +\+13\.\d\d s heard 2132\.\d\d/); assert.deepEqual(await readQuoteCheck(p.dir), doc); // The gate: c43 refused, c44 not; ruled, c43 renders; a changed cut is stale and says nothing. assert.deepEqual(quoteGate(p.manifest.timeline, doc).map((g) => [g.id, g.status]), [["c43", "moved"]]); const ruled = p.manifest.timeline.map((e) => (e.id === "c43" ? { ...e, quoteRuled: true } : e)); assert.deepEqual(quoteGate(ruled, doc), []); const moved = p.manifest.timeline.map((e) => (e.id === "c43" ? { ...e, cutStart: 2120, cutEnd: 2127 } : e)); assert.equal(rowIsCurrent(doc.clips.c43, moved[0]), false); assert.deepEqual(quoteGate(moved, doc), []); // --align: the cut on the words as heard, the extent widened to hold it. const patch = alignPatch(p.manifest.timeline[0], doc.clips.c43); assert.equal(patch.lockCut, true); assert.ok(Math.abs(patch.cutStart - (doc.clips.c43.heard.from - 0.15)) < 0.011); assert.ok(patch.cutStart > 2132 && patch.cutEnd > 2140, JSON.stringify(patch)); assert.equal(patch.start, undefined); assert.equal(patch.end, patch.cutEnd); assert.throws(() => alignPatch(moved[0], doc.clips.c43), /stale/); assert.throws(() => alignPatch(p.manifest.timeline[0], null), /no quote check/); } finally { await rm(p.root, { recursive: true, force: true }); } }); test("judge: not heard is not-found; with no cues the cut is what the offset is measured from", () => { const row = { quote: C43.quote, cut: { from: 2119.34, to: 2127.44 }, span: { from: 2104.34, to: 2142.44 } }; const words = C43.words.map((w) => ({ ...w, start: w.start + C43.window[0], end: w.end + C43.window[0] })); const noCues = judgeClip(row, words, null); assert.equal(noCues.against, "cut"); // Against the cut only: moved when the words are heard outside the cut (the cut does not play them). assert.equal(noCues.status, "moved"); const inside = judgeClip({ ...row, cut: { from: 2130, to: 2142 } }, words, null); assert.equal(inside.status, "ok"); const elsewhere = judgeClip({ ...row, quote: "I promise you by this time next year I will be down 100 pounds" }, words, C43.cues); assert.equal(elsewhere.status, "not-found"); }); test("the CLI: a project's clips checked through the injected editor, --status after", async () => { const p = await project(); try { const out = []; const code = await quoteCheckCommand(["diet", "--clips", "c43"], { reportsRoot: p.root, log: (l) => out.push(l), err: (l) => out.push(`ERR ${l}`), transcribe: fakeTranscribe, cuesOf: fakeCues, }); assert.equal(code, 0, out.join("\n")); assert.match(out.join("\n"), /0 ok, 1 moved, 0 not found/); const st = []; assert.equal(await quoteCheckCommand(["diet", "--status"], { reportsRoot: p.root, log: (l) => st.push(l), err: (l) => st.push(l) }), 0); assert.match(st.join("\n"), /c43 +moved/); assert.match(st.join("\n"), /c44 +unchecked/); } finally { await rm(p.root, { recursive: true, force: true }); } }); test("umtool check: a moved quote and a missing one are blocking, with the fix; ruled or stale, nothing", async () => { const { decisionsFor } = await import("../projects/core.mjs"); const { walkProjects } = await import("../projects/walk.mjs"); const root = await mkdtemp(path.join(os.tmpdir(), "quote-decisions-")); try { const channelsDir = path.join(root, "channels"); const vdir = path.join(channelsDir, "chan", "data", "vid"); await mkdir(vdir, { recursive: true }); await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ cues: Array.from({ length: 200 }, (_, i) => ({ start: i, end: i + 1, text: `Line ${i}.` })) })); const dir = path.join(root, "reports", "cut"); await mkdir(dir, { recursive: true }); const clip = (id, start, extra = {}) => ({ type: "clip", id, video: "vid", start, end: start + 5, cite: start, lock: true, quote: `Line ${start}`, ...extra }); await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: "cut", title: "Cut", provenance: { channelSlug: "chan", channelsDir: path.relative(dir, channelsDir), siteOrigin: "https://example.test" }, render: { width: 1920, height: 1080, fps: 30 }, timeline: [clip("a", 10), clip("b", 20), clip("c", 30, { quoteRuled: true }), clip("d", 40)], })); const row = (start, status, extra = {}) => ({ status, cut: { from: start, to: start + 5 }, quote: `Line ${start}`, match: 0.3, ...extra }); await writeFile(path.join(dir, "quote-check.json"), JSON.stringify({ version: 1, clips: { a: row(10, "moved", { offset: 13.06, match: 1, heard: { from: 23.06, to: 25 } }), b: row(20, "not-found"), c: row(30, "not-found"), d: { ...row(40, "not-found"), cut: { from: 41, to: 45 } }, }, })); const [ref] = (await walkProjects(path.join(root, "reports"))).filter((p) => p.id === "cut"); const ds = (await decisionsFor(ref, path.join(root, "reports"))).filter((d) => d.kind.startsWith("clip-quote")); assert.deepEqual(ds.map((d) => [d.kind, d.target, d.severity]), [ ["clip-quote-moved", "a", "blocking"], ["clip-quote-missing", "b", "blocking"], ]); assert.match(ds[0].why, /a: its quote is heard \+13\.06 s from its cut — umtool window cut a --align/); assert.equal(ds[0].fix, "umtool window cut a --align # or --quote-ruled, having heard it"); assert.match(ds[1].fix, /umtool fetch cut --refetch b/); // The one press (L4): a moved quote's cut snapped to the words as heard (alignPatch); a missing one checked again. assert.deepEqual(ds[0].settle, { kind: "patch", clip: "a", patch: alignPatch({ ...clip("a", 10), type: "clip" }, { ...row(10, "moved", { heard: { from: 23.06, to: 25 } }) }), label: "Snap the cut to the words" }); assert.equal(ds[0].settle.patch.lockCut, true); assert.deepEqual(ds[1].settle, { kind: "quote-check", clips: ["b"], label: "Run quote-check" }); } finally { await rm(root, { recursive: true, force: true }); } }); test("prep --status says the quote check's verdicts on the clips as they are now", async () => { const { quoteLine } = await import("./prepCli.mjs"); const p = await project(); try { assert.equal(await quoteLine(p.dir), null); const plan = await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] }); await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: fakeTranscribe, cuesOf: fakeCues }); const q = await quoteLine(p.dir); assert.equal(q.line, " quotes: 1 ok, 1 moved (c43) — umtool window

--align"); assert.deepEqual(q.counts, { moved: 1, ok: 1, "no-quote": 1 }); } finally { await rm(p.root, { recursive: true, force: true }); } }); test("the editor's work files are never under out/: /.quote-check by its real path, and the next dir when the editor refuses one as inside the corpus", async () => { const { quoteCheckWorkDirs } = await import("./quoteCheck.mjs"); const { realpath, symlink, stat } = await import("node:fs/promises"); const p = await project(); try { const root = await realpath(p.root); // out/ linked onto "the media drive" (rev9-a9's project): nothing of the check is written through it. const drive = path.join(root, "drive", "diet-out"); await mkdir(path.dirname(drive), { recursive: true }); const { rename } = await import("node:fs/promises"); await rename(path.join(p.dir, "out"), drive); await symlink(drive, path.join(p.dir, "out")); const dirs = await quoteCheckWorkDirs(p.dir, { reportsRoot: p.root, env: { XDG_CACHE_HOME: path.join(root, "cache") } }); assert.deepEqual(dirs, [ path.join(root, "diet", ".quote-check"), path.join(root, ".umtool", "quote-check", "diet"), path.join(root, "cache", "umtool", "quote-check", "diet"), ]); const plan = await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] }); const outs = []; const seen = async (req) => { outs.push(req.out); return fakeTranscribe(req); }; const first = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: seen, cuesOf: fakeCues, workDirs: dirs }); assert.equal(first.work, dirs[0]); assert.ok(outs.length >= 2 && outs.every((o) => path.dirname(o) === dirs[0]), outs.join("\n")); assert.equal(await stat(path.join(drive, "quote-check")).catch(() => null), null, "nothing under out/"); assert.equal(first.doc.clips.c44.status, "ok"); // The project dir itself inside a location: the editor refuses the first dir, the check moves on and still lands its rows. const lines = []; const refused = []; const picky = async (req) => { if (path.dirname(req.out) === dirs[0]) { refused.push(req.out); throw new Error(`the editor refused it (/api/ops/transcribe, HTTP 400): "out" ${req.out} is inside the corpus (/mnt/media) — this command never writes there; pick a path outside it`); } outs.push(req.out); return fakeTranscribe(req); }; outs.length = 0; const second = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: picky, cuesOf: fakeCues, workDirs: dirs, log: (l) => lines.push(l) }); assert.equal(refused.length, 1, "asked once, not once per clip"); assert.equal(second.work, dirs[1]); assert.ok(outs.length >= 2 && outs.every((o) => path.dirname(o) === dirs[1])); assert.match(lines.join("\n"), /the editor will not write in .*\.quote-check \(inside the corpus\) -- its work files go to .*\.umtool\/quote-check\/diet/); assert.equal(second.doc.clips.c43.status, "moved"); assert.deepEqual(await readQuoteCheck(p.dir), second.doc); // Any other failure is that clip's, as before -- no hopping dirs. const broken = await runQuoteCheck(p.dir, p.manifest, plan, { transcribe: async () => { throw new Error("no engine"); }, cuesOf: fakeCues, workDirs: dirs, log: (l) => lines.push(l) }); assert.equal(broken.work, dirs[0]); assert.match(lines.join("\n"), /c43: the transcription failed: no engine/); } finally { await rm(p.root, { recursive: true, force: true }); } }); test("through the real editor client: the editor's own refusal reaches the fall-through, and the refused work dir is taken back -- no empty .quote-check left in the corpus", async () => { const http = await import("node:http"); const { stat, readdir } = await import("node:fs/promises"); const { OUT_INSIDE_CORPUS, quoteCheckWorkDirs } = await import("./quoteCheck.mjs"); // The controller's sentence, as the editor's source has it: the words the fall-through matches are there. const controller = await readFile(path.join(HERE, "..", "..", "..", "common", "controller", "transcribeFile.ts"), "utf8"); const sentence = /error: `("out" \$\{req\.out\} is inside the corpus \(\$\{root\}\)[^`]*)`/.exec(controller); assert.ok(sentence, "transcribeFile.ts still refuses an out inside the corpus in these words"); const refusalFor = (out, root) => sentence[1].replace("${req.out}", out).replace("${root}", root); assert.match(refusalFor("/mnt/media/x/.quote-check/c43.words.json", "/mnt/media"), OUT_INSIDE_CORPUS); assert.doesNotMatch('"out": the directory /x does not exist', OUT_INSIDE_CORPUS); assert.doesNotMatch("editor job abc failed — out of memory inside the corpus reader", OUT_INSIDE_CORPUS); const p = await project(); const corpus = p.dir; // the project itself sits in a "location": its .quote-check is refused const asked = []; // The editor, stood in for over HTTP: /api/ops/transcribe answers as ops' jobResponse does (400 { ok: false, error } // for a refusal, { ok: true, jobId } and the words written to `out` otherwise), /api/ops/job/ a finished job. const server = http.createServer((req, res) => { let text = ""; req.on("data", (d) => (text += d)); req.on("end", async () => { const send = (status, body) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); }; if (req.method === "POST" && req.url === "/api/ops/transcribe") { const body = JSON.parse(text); asked.push(body.out); if (body.out.startsWith(corpus + path.sep)) return send(400, { ok: false, error: refusalFor(body.out, corpus) }); if (!(await stat(path.dirname(body.out)).catch(() => null))) return send(400, { ok: false, error: `"out": the directory ${path.dirname(body.out)} does not exist` }); const words = await fakeTranscribe(body); await writeFile(body.out, JSON.stringify({ words })); return send(200, { ok: true, jobId: `j${asked.length}` }); } if (req.method === "GET" && req.url.startsWith("/api/ops/job/")) return send(200, { ok: true, job: { status: "done" }, tail: [] }); return send(404, { ok: false, error: "no such route" }); }); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); const env = { url: process.env.ARCHILYZER_EDITOR_URL, token: process.env.WORKER_TOKEN }; process.env.ARCHILYZER_EDITOR_URL = `http://127.0.0.1:${server.address().port}`; process.env.WORKER_TOKEN = "test-token"; try { const dirs = await quoteCheckWorkDirs(p.dir, { reportsRoot: p.root, env: { XDG_CACHE_HOME: path.join(p.root, "cache") } }); const plan = (await planQuoteCheck(p.dir, p.manifest, { channelsDirs: [p.channels] })).filter((r) => r.id !== "c43"); const lines = []; // No `transcribe` given: runQuoteCheck's own editorWords, askEditorOp and all. const r = await runQuoteCheck(p.dir, p.manifest, plan, { cuesOf: fakeCues, workDirs: dirs, log: (l) => lines.push(l) }); assert.equal(asked[0], path.join(dirs[0], "c44.words.json"), "the project's .quote-check is asked first"); assert.equal(asked[1], path.join(dirs[1], "c44.words.json")); assert.equal(r.work, dirs[1]); assert.equal(r.doc.clips.c44.status, "ok", lines.join("\n")); assert.match(lines.join("\n"), /the editor will not write in .* \(inside the corpus\)/); assert.equal(await stat(dirs[0]).catch(() => null), null, "the refused .quote-check is not left behind"); assert.ok((await readdir(dirs[1])).includes("c44.words.json")); // Every dir refused: each one made is taken back, with the parents made for it; the clip's failure says why. await rm(dirs[1], { recursive: true, force: true }); await rm(path.join(p.root, ".umtool"), { recursive: true, force: true }); const inCorpus = [dirs[0], path.join(p.dir, "deep", "er", "work")]; lines.length = 0; const none = await runQuoteCheck(p.dir, p.manifest, plan, { cuesOf: fakeCues, workDirs: inCorpus, log: (l) => lines.push(l) }); assert.match(lines.join("\n"), /c44: the transcription failed: the editor refused it \(\/api\/ops\/transcribe, HTTP 400\): "out" .* is inside the corpus/); assert.equal(await stat(dirs[0]).catch(() => null), null); assert.equal(await stat(path.join(p.dir, "deep")).catch(() => null), null, "the parents made for it too"); assert.equal(none.results.c44, undefined); // A work dir that was already there, with a file in it, is never removed. await mkdir(dirs[0], { recursive: true }); await writeFile(path.join(dirs[0], "kept.txt"), "x"); await runQuoteCheck(p.dir, p.manifest, plan, { cuesOf: fakeCues, workDirs: [dirs[0]], log: () => {} }); assert.ok((await readdir(dirs[0])).includes("kept.txt")); } finally { if (env.url === undefined) delete process.env.ARCHILYZER_EDITOR_URL; else process.env.ARCHILYZER_EDITOR_URL = env.url; if (env.token === undefined) delete process.env.WORKER_TOKEN; else process.env.WORKER_TOKEN = env.token; await new Promise((r) => server.close(r)); await rm(p.root, { recursive: true, force: true }); } });