// lib/copies/match.ts: the metadata stage and the text-anchor stage. Every // word, channel and id here is synthetic. import { test } from "node:test"; import assert from "node:assert/strict"; import { classifyCandidate, copyCandidates, cuesToWords, runtimeCandidates, textEvidence, COPY_PHRASE_WORDS, type CopyRecord, type Word, } from "./match"; import { sanitizeSourceGroups } from "./settings"; // A deterministic stream of nonsense words, one every 0.4 s. function rng(seed: number): () => number { let s = seed >>> 0; return () => { s = (s * 1664525 + 1013904223) >>> 0; return s / 2 ** 32; }; } const VOCAB = Array.from({ length: 800 }, (_, i) => `w${i.toString(36)}x`); function stream(seed: number, n: number, start = 0): Word[] { const r = rng(seed); return Array.from({ length: n }, (_, i) => ({ w: VOCAB[Math.floor(r() * VOCAB.length)], t: start + i * 0.4 })); } const shift = (ws: readonly Word[], by: number): Word[] => ws.map((x) => ({ w: x.w, t: x.t + by })); const retime = (ws: readonly Word[], start: number): Word[] => ws.map((x, i) => ({ w: x.w, t: start + i * 0.4 })); test("the same recording on another clock is the same, with its offset as evidence", () => { const a = stream(1, 3000); const b = shift(a.slice(100), 30); const e = textEvidence(a, b); assert.equal(e.verdict, "same"); assert.ok(e.aInB.fraction >= 0.9 && e.bInA.fraction >= 0.9, JSON.stringify(e)); assert.equal(e.offsetMedianSeconds, 30); }); test("collisions at random offsets do not confirm (fails against a match-count verdict)", () => { // Another recording that happens to share 12 of the 40 probed phrases, each // at a random place: a match COUNT says 12 (≥ 8, 'same'); the consistent // offsets say different. const a = stream(2, 3000); const usable = a.length - COPY_PHRASE_WORDS + 1; const b = stream(3, 3000).map((x) => ({ ...x })); const r = rng(99); for (let k = 0; k < 12; k++) { const pos = Math.floor((usable * k * 3) / 40); const at = 50 + Math.floor(r() * 2800); for (let j = 0; j < COPY_PHRASE_WORDS; j++) b[at + j] = { w: a[pos + j].w, t: b[at + j].t }; } const e = textEvidence(a, b); assert.ok(e.aInB.matched >= 10, `the collisions are found (${e.aInB.matched})`); assert.equal(e.verdict, "different"); assert.equal(e.aInB.consistent, 0); }); test("a stepped pair is the same recording: its runs are summed", () => { const a = stream(4, 3000); const b = [...shift(a.slice(0, 1500), 10), ...shift(a.slice(1500), 60)]; const e = textEvidence(a, b); assert.equal(e.verdict, "same"); assert.ok(e.aInB.runs >= 2, `runs ${e.aInB.runs}`); }); test("one shared phrase counts once, however many probes could reach it (fails against the old probe search)", () => { // A short side: every probe's old 300-word search reached the same phrase. const a = stream(30, 400); const b = stream(31, 3000).map((x) => ({ ...x })); for (let j = 0; j < COPY_PHRASE_WORDS; j++) b[1500 + j] = { w: a[200 + j].w, t: b[1500 + j].t }; const e = textEvidence(a, b); assert.ok(e.aInB.matched <= 1, `matched ${e.aInB.matched}`); assert.equal(e.verdict, "different"); }); test("a passage of one recording inside another overlaps; it is not the same", () => { const a = stream(5, 3000); const b = retime([...stream(6, 300), ...a.slice(1000, 1100), ...stream(7, 300)], 0); const e = textEvidence(a, b); assert.equal(e.verdict, "overlaps", JSON.stringify(e)); }); const cand = (aDur: number, bDur: number, durationOk: boolean) => ({ a: { channel: "pref-chan", dir: "p1", id: "p1", title: "p1", duration: aDur, date: "20260301" }, b: { channel: "mirror-chan", dir: "m1", id: "m1", title: "m1", duration: bDur, date: "20260301" }, dateDeltaDays: 0, durationOk, }); test("a short part of a long stream is part-of, never confirmed, even when the runtimes are read as agreeing", () => { const whole = stream(40, 3000); const part = retime(whole.slice(1000, 1600), 0); const e = textEvidence(whole, part); assert.equal(e.verdict, "b-part-of-a", JSON.stringify(e)); assert.deepEqual(classifyCandidate(cand(1200, 240, false), e), { link: "part-of", part: "b" }); assert.deepEqual(classifyCandidate(cand(1200, 1200, true), e), { link: "part-of", part: "b" }); // The other way round (the PREFERRED side is the part): the old one-way probe // found every one of its phrases and confirmed. const r = textEvidence(part, whole); assert.equal(r.verdict, "a-part-of-b"); assert.deepEqual(classifyCandidate(cand(240, 1200, true), r), { link: "part-of", part: "a" }); }); test("a short sharing one passage with a different stream overlaps; it does not confirm", () => { const other = stream(50, 3000); const short = retime([...stream(51, 100), ...other.slice(2000, 2080), ...stream(52, 70)], 0); const e = textEvidence(short, other); assert.notEqual(e.verdict, "same"); assert.notEqual(e.verdict, "a-part-of-b"); assert.equal(classifyCandidate(cand(100, 1200, true), e)?.link, "overlaps"); }); test("two different streams that both play the same long third-party video only overlap", () => { const video = stream(60, 1500); const s1 = retime([...stream(61, 900), ...video, ...stream(62, 600)], 0); const s2 = retime([...stream(63, 300), ...video, ...stream(64, 1200)], 0); const e = textEvidence(s1, s2); assert.equal(e.verdict, "overlaps", JSON.stringify(e)); assert.ok(e.aInB.fraction < 0.75 && e.bInA.fraction < 0.75); assert.equal(classifyCandidate(cand(1200, 1200, true), e)?.link, "overlaps"); }); test("boilerplate two different streams share (intro, outro, a sponsor read) cannot confirm", () => { const intro = stream(70, 150); const sponsor = stream(71, 100); const outro = stream(72, 150); const s1 = retime([...intro, ...stream(73, 1300), ...sponsor, ...stream(74, 1300), ...outro], 0); const s2 = retime([...intro, ...stream(75, 1300), ...sponsor, ...stream(76, 1300), ...outro], 0); const e = textEvidence(s1, s2); // At most a reported overlap (here every shared stretch sits at one offset). assert.ok(e.verdict === "different" || e.verdict === "overlaps", JSON.stringify(e)); assert.ok(e.aInB.fraction < 0.75 && e.bInA.fraction < 0.75); assert.notEqual(classifyCandidate(cand(1200, 1200, true), e)?.link, "confirmed"); }); test("a rerun inside a longer broadcast is part-of the broadcast: the words agree, the runtimes do not", () => { const original = stream(80, 3000); const rerun = retime([...stream(81, 900), ...original], 0); const e = textEvidence(original, rerun); assert.ok(e.aInB.fraction >= 0.9, JSON.stringify(e)); // 1200 s against 1560 s: apart by more than max(120 s, 2 %). assert.deepEqual(classifyCandidate(cand(1200, 1560, false), e), { link: "part-of", part: "a" }); }); test("too few words on either side is no text", () => { assert.equal(textEvidence(stream(8, 150), stream(8, 3000)).verdict, "no-text"); }); test("cues become words spread across each cue", () => { const ws = cuesToWords([{ start: 10, end: 12, text: "Hello, there world" }, { start: 13, text: "again" }]); assert.deepEqual(ws.map((w) => w.w), ["hello", "there", "world", "again"]); assert.equal(ws[0].t, 10); assert.ok(ws[2].t > 11 && ws[2].t < 12); assert.equal(ws[3].t, 13); }); const [GROUP] = sanitizeSourceGroups([{ id: "g", channels: ["pref-chan", "mirror-chan"] }]); const rec = (channel: string, dir: string, date: string | null, duration: number): CopyRecord => ({ channel, dir, id: dir, title: `${dir} title`, duration, date, }); test("candidates: dated within the window, across channels only, the preferred channel as `a`", () => { const records = [ rec("mirror-chan", "m1", "20260301", 7200), rec("pref-chan", "p1", "20260302", 7210), rec("pref-chan", "p2", "20260304", 7200), rec("pref-chan", "p3", "20260301", 3000), rec("mirror-chan", "m0", null, 7200), ]; const c = copyCandidates(GROUP, records); assert.deepEqual( c.map((x) => [x.a.dir, x.b.dir, x.dateDeltaDays, x.durationOk]), [ ["p1", "m1", 1, true], ["p3", "m1", 0, false], ], ); // Inside one channel only when asked. const [within] = sanitizeSourceGroups([{ id: "g", channels: ["pref-chan", "mirror-chan"], withinChannels: true }]); const w = copyCandidates(within, records); assert.ok(w.some((x) => x.a.dir === "p1" && x.b.dir === "p3")); }); test("the adjacent day's stream with the closer runtime is not linked over the text-confirmed one", () => { const recorded = stream(10, 3000); const other = stream(11, 3000); const mirror = rec("mirror-chan", "m1", "20260301", 7200); const sameDay = { a: rec("pref-chan", "p-same", "20260301", 6500), b: mirror, dateDeltaDays: 0, durationOk: false }; const nextDay = { a: rec("pref-chan", "p-next", "20260302", 7200), b: mirror, dateDeltaDays: 1, durationOk: true }; // The words say same, the runtimes do not: a trim, never confirmed. assert.deepEqual(classifyCandidate(sameDay, textEvidence(recorded, shift(recorded, -50))), { link: "part-of", part: "a" }); assert.deepEqual( classifyCandidate({ ...sameDay, durationOk: true }, textEvidence(recorded, shift(recorded, -50))), { link: "confirmed" }, ); assert.equal(classifyCandidate(nextDay, textEvidence(other, shift(recorded, -50))), null, "text overrules the runtime"); // With no text on one side the runtime is all there is: metadata only. assert.deepEqual(classifyCandidate(nextDay, null), { link: "metadata" }); assert.equal(classifyCandidate(sameDay, null), null); }); test("the runtime search: only for a video its date cannot pair, both sides with words, nearest runtimes first, bounded", async () => { const up = (channel: string, dir: string, duration: number): CopyRecord => ({ ...rec(channel, dir, "20260310", duration), dateFrom: "upload" }); const lv = (dir: string, date: string, duration: number): CopyRecord => ({ ...rec("mirror-chan", dir, date, duration), dateFrom: "live" }); const records = [ up("pref-chan", "p1", 7200), up("pref-chan", "p2", 7200), // no words up("pref-chan", "p3", 7200), // already paired by date up("pref-chan", "p4", 7205), // same channel: never its own candidate lv("m1", "20230101", 7260), lv("m2", "20230102", 7100), lv("m3", "20230103", 7400), // runtimes apart lv("m4", "20230104", 7210), lv("m5", "20230105", 7190), ]; const noWords = new Set(["pref-chan/p2"]); const hasText = (r: CopyRecord) => !noWords.has(`${r.channel}/${r.dir}`); const dated = new Set(["pref-chan/p3"]); const s = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3 }); assert.deepEqual( s.candidates.map((c) => [c.a.dir, c.b.dir, c.via, c.durationOk]), [ ["p1", "m5", "runtime", true], ["p1", "m4", "runtime", true], ["p1", "m1", "runtime", true], ["p4", "m4", "runtime", true], ["p4", "m5", "runtime", true], ["p4", "m1", "runtime", true], ], "nearest three each; never p2 (no words), p3 (paired by date), m3 (runtimes apart) or p1 with p4", ); assert.equal(s.searched, 2, "p1 and p4; a live mirror's own day pairs it, so it is never searched from"); // The scan's cap: once reached, the rest are counted, not searched. const capped = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3, maxPairs: 2 }); assert.equal(capped.candidates.length, 2); assert.deepEqual([capped.searched, capped.capped], [1, 1]); // A channel with a recordedDate rule is dated by it and never searched from. const ruled = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3, ruled: new Set(["pref-chan"]) }); assert.deepEqual([ruled.candidates.length, ruled.searched, ruled.capped], [0, 0, 0]); // A runtime candidate has nothing but its runtime: without words, no pair at all. assert.equal(classifyCandidate(s.candidates[0], null), null); assert.deepEqual(classifyCandidate(s.candidates[0], textEvidence(stream(5, 3000), shift(stream(5, 3000), 30))), { link: "confirmed", }); });