// The case pipeline's pure half (lib/research/casePipeline.ts): the definition checked, the naming rule in every // reader prompt, rolling captions folded, hits into windows, the noise filters, the batch rule (no line over 200), // a finding checked, the merge, the report, the date checks' sentence, and the browser hash agreeing with the // server's. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/research/casePipeline.test.ts import test from "node:test"; import assert from "node:assert/strict"; import { BATCH_LINE_MAX, NAME_WITHHELD, type CaseDefinition, type CaseEvidence, type FindingRow } from "./caseTypes"; import { CasePipelineError, NAMING_RULE, batchText, checkFindingRow, dateChecks, emptyCounts, emptyDefinition, familyHits, foldCues, groupFor, longestLine, mergeFindings, mergeHitWindows, normalizeDefinition, planBatches, privateNameHashWeb, privateTermProblem, readerPrompt, recordingWindows, reportHtml, reportMarkdown, trackOfFile, wrapLine, } from "./casePipeline"; import { privateNameHash } from "./privateNames-server"; const def = (over: Partial = {}): CaseDefinition => normalizeDefinition( { subjects: [{ name: "Wren Halloway", aliases: ["Wren"], channels: ["wren-own"] }], scope: { channels: ["wren-own", "talk-show"], groups: [], sites: [] }, eras: [ { id: "early", from: "2014-01-01", to: "2016-12-31", families: { name: "\\bwren\\b", shop: "lantern shop" } }, { id: "late", from: "2020-01-01", to: "2022-12-31", families: { name: "\\bwren\\b", shop: "lantern shop" }, strictFamilies: ["shop"] }, ], groups: [ { id: "own", label: "Her own words", channels: "subject" }, { id: "others", label: "Coverage", channels: "coverage" }, ], readerPrompts: { common: "Quote verbatim.", own: "She is the speaker unless said otherwise." }, ...over, }, "wren", ); test("normalizeDefinition: a whole case passes, every bad field is refused by name", () => { const d = def(); assert.equal(d.case, "wren"); assert.equal(d.eras[1].strictFamilies?.[0], "shop"); const bad = (raw: Record, re: RegExp) => assert.throws(() => normalizeDefinition(raw, "wren"), (e: Error) => e instanceof CasePipelineError && re.test(e.message)); bad({ eras: [{ id: "x", from: "2014-01-01", to: "2014-02-01", families: { a: "(" } }] }, /era x, family a: not a regex/); bad({ eras: [{ id: "x", from: "2015-01-01", to: "2014-02-01", families: {} }] }, /after/); bad({ eras: [{ id: "x", from: "2015-02-30", to: "2016-02-01", families: {} }] }, /dates/); bad({ privateNames: { sha256: ["Jane Doe"] } }, /never a name/); bad({ readerPrompts: { common: "", ghost: "x" } }, /no group "ghost"/); bad({ groups: [{ id: "g", channels: [] }] }, /channels is "subject"/); bad({ scope: { groups: ["nosite"] } }, /:/); bad({ case: "other" }, /filed under "wren"/); assert.equal(emptyDefinition("wren").status, "defining"); }); test("readerPrompt always carries the naming rule, even when the case's prompts are empty", () => { assert.ok(readerPrompt(def(), "own").includes(NAMING_RULE)); assert.ok(readerPrompt(def(), "own").includes("She is the speaker")); assert.ok(readerPrompt(def(), "own").includes("Wren Halloway / Wren")); const empty = def({ readerPrompts: { common: "" } }); assert.ok(readerPrompt(empty, "others").endsWith(NAMING_RULE)); assert.ok(NAMING_RULE.includes(NAME_WITHHELD)); }); test("privateTermProblem: at most three words, and something to hash", () => { assert.equal(privateTermProblem("Jane Q Private"), null); assert.match(privateTermProblem("one two three four") ?? "", /three words/); assert.match(privateTermProblem(" .. ") ?? "", /letters/); }); test("privateNameHashWeb is the server's hash (a term typed on the page never leaves it)", async () => { for (const t of ["Jane Q Private", " JANE q private ", "Zoë Ł"]) assert.equal(await privateNameHashWeb(t), privateNameHash(t)); }); test("foldCues drops a rolling caption's repeated head, and a cue that only repeats", () => { const f = foldCues([ { start: 0, end: 2, text: "so the lantern" }, { start: 2, end: 4, text: "so the lantern shop opened" }, { start: 4, end: 6, text: "lantern shop opened" }, { start: 6, end: 8, text: "in the spring" }, ]); assert.equal(f.text, "so the lantern shop opened in the spring"); assert.deepEqual(f.offsets.map((o) => o.t), [0, 2, 6]); }); test("familyHits puts each match at its cue's second; mergeHitWindows merges ±W and caps a span", () => { const cues = [ { start: 10, end: 12, text: "talking about Wren" }, { start: 30, end: 32, text: "and the lantern shop" }, { start: 400, end: 402, text: "wren again" }, ]; const hits = familyHits(cues, [ { id: "name", re: /\bwren\b/iu }, { id: "shop", re: /lantern shop/iu }, ]); assert.deepEqual(hits.map((h) => [h.t, h.family]), [[10, "name"], [30, "shop"], [400, "name"]]); const w = mergeHitWindows(hits, 30, 240); assert.deepEqual(w.map((x) => [x.from, x.to, x.hits.length]), [[0, 60, 2], [370, 430, 1]]); const capped = mergeHitWindows(Array.from({ length: 10 }, (_, i) => ({ t: i * 50, family: "f", match: "x" })), 30, 120); assert.ok(capped.every((x) => x.to - x.from <= 150)); assert.ok(capped.length > 1); }); test("trackOfFile: en-orig, en, a transcript, cues", () => { assert.equal(trackOfFile("transcript.en-orig.vtt"), "en-orig"); assert.equal(trackOfFile("transcript.en.vtt"), "en"); assert.equal(trackOfFile("transcript.en-US.vtt"), "en"); assert.equal(trackOfFile("transcript.json"), "transcript"); assert.equal(trackOfFile(undefined), "cues"); }); test("groupFor: a named channel, else the subject's group, else coverage", () => { const d = def({ groups: [{ id: "own", label: "Own", channels: "subject" }, { id: "talk", label: "Talk", channels: ["talk-show"] }, { id: "others", label: "Coverage", channels: "coverage" }] }); assert.equal(groupFor(d, "talk-show", "early")?.id, "talk"); assert.equal(groupFor(d, "wren-own", "early")?.id, "own"); assert.equal(groupFor(d, "elsewhere", "early")?.id, "others"); assert.equal(groupFor(def({ groups: [{ id: "own", label: "Own", channels: "subject", era: "early" }] }), "wren-own", "late"), null); }); const cuesSaying = (lines: [number, string][]) => lines.map(([t, text]) => ({ start: t, end: t + 3, text })); test("recordingWindows: coverage needs a subject named, a strict era wants its strict family, a title hit stands alone", () => { const d = def(); const counts = emptyCounts(); // Coverage: the family matches ("lantern shop") but no subject is named -> noise. const none = recordingWindows(d, { slug: "talk-show", id: "t1", date: "20150301", title: "A show", track: "en", cues: cuesSaying([[100, "the lantern shop downtown"]]) }, counts); assert.equal(none.length, 0); assert.equal(counts.noise.noSubject, 1); // Coverage naming her: a window, in the coverage group. const named = recordingWindows(d, { slug: "talk-show", id: "t2", date: "20150301", title: "A show", track: "en", cues: cuesSaying([[100, "Wren and the lantern shop"]]) }, counts); assert.equal(named.length, 1); assert.equal(named[0].group, "others"); assert.equal(named[0].key, "talk-show/t2@70"); // Her own channel, the late (strict) era: "wren" alone makes nothing; "lantern shop" does. const loose = recordingWindows(d, { slug: "wren-own", id: "o1", date: "20210101", title: "Vlog", track: "en-orig", cues: cuesSaying([[50, "hi I'm wren"]]) }, counts); assert.equal(loose.length, 0); assert.equal(counts.noise.notStrict, 1); const strict = recordingWindows(d, { slug: "wren-own", id: "o2", date: "20210101", title: "Vlog", track: "en-orig", cues: cuesSaying([[50, "the lantern shop is closing"]]) }, counts); assert.equal(strict.length, 1); assert.equal(strict[0].group, "own"); assert.equal(strict[0].era, "late"); // A title hit with no word hit is a window of its own at the start. const titled = recordingWindows(d, { slug: "wren-own", id: "o3", date: "20150101", title: "Wren answers", track: "en-orig", cues: cuesSaying([[5, "garbled"], [20, "words"]]) }, counts); assert.equal(titled.length, 1); assert.equal(titled[0].from, 0); assert.equal(titled[0].titleHit, true); assert.deepEqual(titled[0].titleFamilies, ["name"]); // Out of every era: nothing. assert.equal(recordingWindows(d, { slug: "wren-own", id: "o4", date: "20180101", title: "Wren", track: "en", cues: cuesSaying([[5, "wren"]]) }, counts).length, 0); assert.equal(counts.windows, 3); assert.equal(counts.byGroup.own, 2); assert.equal(counts.byFamily.shop, 2); assert.equal(counts.byYear["2015"], 2); assert.equal(counts.titleHits, 1); }); test("wrapLine: no line over the limit, a long word cut, the words kept", () => { const long = `${"word ".repeat(120)}${"x".repeat(450)} tail`; const lines = wrapLine(long); assert.ok(lines.every((l) => [...l].length <= BATCH_LINE_MAX), `longest ${Math.max(...lines.map((l) => l.length))}`); assert.equal(lines.join(" ").replace(/\s+/g, " ").replace(/x /g, "x").length > 0, true); assert.equal(lines.join("").replace(/\s/g, ""), long.replace(/\s/g, "")); assert.deepEqual(wrapLine(""), [""]); }); test("THE BATCH RULE: no line of a batch file is over BATCH_LINE_MAX, whatever the window holds", () => { const d = def(); const huge = { key: "talk-show/t9@0", slug: "talk-show", id: "t9", date: "20150301", title: `A very long title ${"that goes on ".repeat(40)}`, from: 0, to: 3600, era: "early", group: "others", track: "en" as const, hits: Array.from({ length: 30 }, (_, i) => ({ t: i * 10, family: "name", match: "Wren" })), url: `https://www.youtube.com/watch?v=t9&${"pad=1&".repeat(60)}`, text: `${"Wren said a thing about the lantern shop and then ".repeat(400)}${"y".repeat(900)}`, }; const { batches, texts } = planBatches(d, [huge, { ...huge, key: "talk-show/t9@4000", from: 4000 }], { round: 1, budget: 30_000 }); assert.equal(batches.length, 2, "a window over the budget is a batch of its own"); assert.deepEqual(batches.map((b) => b.id), ["others-1-001", "others-1-002"]); for (const b of batches) { const t = texts.get(b.id)!; assert.ok(longestLine(t) <= BATCH_LINE_MAX, `${b.id}: a line of ${longestLine(t)}`); assert.ok(t.includes("Naming rule")); assert.equal(b.chars, t.length); assert.equal(b.state, "pending"); } assert.ok(longestLine(batchText({ id: "x", group: "others", round: 1 }, "Coverage", [huge])) <= BATCH_LINE_MAX); }); test("planBatches: per group, under the budget, and never a window a read batch covers", () => { const d = def(); const mk = (slug: string, from: number, group: string) => ({ key: `${slug}/v@${from}`, slug, id: "v", date: "20150101", title: "T", from, to: from + 60, era: "early", group, track: "en" as const, hits: [], text: "w ".repeat(400) }); const ws = [mk("a", 0, "own"), mk("a", 100, "own"), mk("a", 200, "own"), mk("b", 0, "others")]; const { batches } = planBatches(d, ws, { round: 2, budget: 1200, exclude: new Set(["a/v@100"]) }); assert.deepEqual(batches.map((b) => [b.id, b.windows]), [["own-2-001", ["a/v@0"]], ["own-2-002", ["a/v@200"]], ["others-2-001", ["b/v@0"]]]); }); const row = (over: Partial): FindingRow => ({ row: "f1", batch: "own-1-001", slug: "wren-own", id: "o2", date: "20210101", title: "Vlog", t: 50, url: "https://www.youtube.com/watch?v=o2", category: "shop", relevance: 2, quote: "the lantern shop is closing", summary: "She says the shop is closing", speaker: "Wren Halloway", confidence: "high", round: 1, by: "hand", quoteCheck: "found", ...over, }); test("checkFindingRow: a quote over 45 words, a relevance of 4, a missing batch -- refused by name", () => { const ok = checkFindingRow({ ...row({}), row: undefined, quoteCheck: undefined }); assert.equal(ok.ok, true); if (ok.ok) assert.equal(ok.row.quoteCheck, "unchecked"); const bad = checkFindingRow({ ...row({}), relevance: 4, quote: "w ".repeat(46), batch: "" }); assert.equal(bad.ok, false); if (!bad.ok) { assert.ok(bad.errors.some((e) => /relevance/.test(e))); assert.ok(bad.errors.some((e) => /45 words/.test(e))); assert.ok(bad.errors.some((e) => /batch/.test(e))); } const dashed = checkFindingRow({ ...row({}), date: "2021-01-01" }); assert.ok(dashed.ok && dashed.row.date === "20210101"); }); test("mergeFindings: within 20 s on one recording is one finding (higher relevance, then later round); sections; quarantine; the floor", () => { const d = def(); const rows = [ row({ row: "f1", t: 50, relevance: 2, round: 1 }), row({ row: "f2", t: 60, relevance: 3, round: 1 }), row({ row: "f3", t: 65, relevance: 3, round: 2 }), row({ row: "f4", t: 200, relevance: 1 }), row({ row: "f5", slug: "talk-show", id: "t2", batch: "others-1-001", t: 10, relevance: 3 }), row({ row: "f6", slug: "forum", id: "p1", batch: "others-1-001", t: 0, relevance: 3, verify: { status: "quarantined", at: "x" } }), ]; const groupOf = (r: FindingRow) => r.batch.replace(/-\d+-\d+$/, ""); const m = mergeFindings(d, rows, groupOf); assert.deepEqual(m.duplicates, [{ row: "f1", of: "f3" }, { row: "f2", of: "f3" }]); assert.deepEqual(m.sections.map((s) => [s.group, s.rows.map((r) => r.row)]), [["own", ["f3"]], ["others", ["f5"]]]); assert.deepEqual(m.quarantined.map((r) => r.row), ["f6"]); assert.deepEqual(m.belowFloor.map((r) => r.row), ["f4"]); assert.deepEqual(mergeFindings(d, rows, groupOf, { minRelevance: 1 }).sections[0].rows.map((r) => r.row), ["f3", "f4"]); const md = reportMarkdown({ title: "Wren", summary: { text: "What she said.", draft: true, by: "local", model: "qwen3:8b", at: "x" }, merged: m, coverage: "Scope: two channels." }); assert.match(md, /^# Wren\n/); assert.match(md, /Draft summary, by qwen3:8b: not yet reviewed\./); assert.match(md, /## Her own words\n\n- She says the shop is closing: "the lantern shop is closing" — \[Vlog @ 1:05\]\(https:\/\/www\.youtube\.com\/watch\?v=o2&t=65s\)/); assert.match(md, /## Quarantined/); assert.match(md, /row f6/); assert.match(md, /## Coverage\n\nScope: two channels\./); const html = reportHtml(md.replace("Wren", "Wren &")); assert.match(html, /

Wren <b>&<\/h1>/); assert.match(html, //); assert.doesNotMatch(html, /