// The copies scan and the lanes' copy holds over a TEMP corpus (lane // cross-source-dupes, slice 1). Never the real corpus, never the network; // every channel, id and word is synthetic. import "./autoRunner.settings.fixture"; import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { readdir as fsReaddir, readFile, readFile as fsReadFile, stat as fsStat } from "node:fs/promises"; import { tmpdir } from "node:os"; import { fileURLToPath } from "node:url"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { computeLeafPending } from "./autoRunner"; import { applyCopiesDecision, copiesReport, copiesScanRefusal, CopiesScanCancelled, parseCopiesReleaseBody, runCopiesScan, } from "./copiesScan"; import { copyHoldsForLane, readCopyDone, resetCopiesLaneCacheForTest, setCopiesLaneIoForTest, copiesLaneSettledForTest, type CopiesLaneIo, } from "./copiesLane"; import { emptyAutoQueueState } from "../jobs/autoQueueState"; import { bucketLaneOperationId } from "../lib/operations"; import { sanitizeSourceGroups } from "../lib/copies/settings"; import { copiesDecisionsPath, copiesPath, updateCopiesDecisions } from "../lib/copies/file-server"; import { defaultSiteSettings, type SiteSettings } from "../lib/settings"; import { DEFAULT_DIARIZATION_THRESHOLD, DIARIZATION_FILENAME, type DiarizationRecord } from "../lib/diarization"; import { ATTRIBUTION_FILENAME, ATTRIBUTION_PROMPT_VERSION, type AttributionRecord } from "../lib/attribution"; import { OLLAMA_DIGEST_APP_ID } from "../lib/digest"; const CATCH_ALL_ROOT = { id: "root", mode: "strict", weight: 1, maxWorkers: null, children: [{ id: "all", match: { type: "all" }, weight: 1, maxWorkers: null }], }; function writeSettings(extra: Record): void { writeFileSync( process.env.SETTINGS_FILE!, JSON.stringify({ autoQueue: { transcription: { root: CATCH_ALL_ROOT }, download: { root: CATCH_ALL_ROOT } }, ...extra }), ); } const GROUP = { id: "stream-copies", channels: ["pref-chan", "mirror-chan"] }; function corpus(): Paths { const dir = mkdtempSync(path.join(tmpdir(), "copies-")); const transcriptsDir = path.join(dir, "transcripts"); mkdirSync(transcriptsDir, { recursive: true }); return { transcriptsDir, channelsDir: path.join(transcriptsDir, "channels"), sitesDir: path.join(transcriptsDir, "sites"), jobsDir: path.join(dir, "jobs"), lmdbPath: path.join(transcriptsDir, "index.mdb"), autoQueueStateFile: path.join(dir, "auto-queue.json"), } as Paths; } 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`); // 3000 nonsense words as 10-word cues, one word every 0.4 s, from `start`. function cues(seed: number, start = 0) { const r = rng(seed); const words = Array.from({ length: 3000 }, () => VOCAB[Math.floor(r() * VOCAB.length)]); const out = []; for (let i = 0; i < words.length; i += 10) { out.push({ start: start + i * 0.4, end: start + (i + 10) * 0.4, text: words.slice(i, i + 10).join(" ") }); } return out; } // A transcript.json of `words` words of speech (whisper's shape). function whisperJson(words: number): string { const segs = []; for (let i = 0; i < words; i += 10) segs.push({ text: Array.from({ length: Math.min(10, words - i) }, (_, j) => `word${(i + j) % 97}`).join(" "), offsets: { from: i * 400, to: (i + 10) * 400 } }); return JSON.stringify({ transcription: segs }); } // A VTT of `lines` cues, each `text`; `asr` marks it as YouTube's speech recognition. function vtt(lines: number, text: (i: number) => string, asr = false): string { const ts = (s: number) => `${String(Math.floor(s / 3600)).padStart(2, "0")}:${String(Math.floor((s % 3600) / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}.000`; let out = "WEBVTT\nKind: captions\nLanguage: en\n\n"; for (let i = 0; i < lines; i++) { out += `${ts(i * 4)} --> ${ts(i * 4 + 4)}${asr ? " align:start position:0%" : ""}\n${text(i)}\n\n`; } return out; } function channel(p: Paths, slug: string, extra: Record = {}): void { mkdirSync(path.join(p.channelsDir, slug, "data"), { recursive: true }); writeFileSync(path.join(p.channelsDir, slug, "config.json"), JSON.stringify({ url: `https://www.youtube.com/@${slug.replace(/-/g, "")}`, handling: "transcribe", ...extra })); } function video( p: Paths, slug: string, dir: string, o: { date: string; duration: number; cues?: ReturnType; transcript?: boolean | number; audio?: boolean; id?: string; title?: string; // A finished live stream (yt-dlp's live_status "was_live"). live?: boolean; }, ): void { const d = path.join(p.channelsDir, slug, "data", dir); mkdirSync(d, { recursive: true }); const id = o.id ?? dir; writeFileSync( path.join(d, "metadata.info.json"), JSON.stringify({ id, title: o.title ?? `Stream ${id}`, duration: o.duration, upload_date: o.date, ...(o.live ? { live_status: "was_live", was_live: true } : {}), }), ); if (o.cues) writeFileSync(path.join(d, "transcript.cues.json"), JSON.stringify({ version: 2, id, cues: o.cues })); // A real-length transcript by default: 20 words a minute of runtime. if (o.transcript) writeFileSync(path.join(d, "transcript.json"), whisperJson(typeof o.transcript === "number" ? o.transcript : Math.ceil((o.duration / 60) * 20))); if (o.audio) writeFileSync(path.join(d, "audio.mp3"), Buffer.alloc(1234)); } function snapshot(p: Paths, slug: string, pending: string[]): void { const opId = bucketLaneOperationId("transcription"); writeFileSync( path.join(p.channelsDir, slug, "snapshot.json"), JSON.stringify({ generatedAt: new Date().toISOString(), totals: { videos: pending.length, downloaded: pending.length, transcribed: 0 }, buckets: { downloadedNoTranscript: pending, noTranscript: pending }, ...(opId ? { backfill: { [opId]: { ids: pending } } } : {}), }), ); } // p1/m1 one recording with words on both sides (m1 has the transcript); // p2/m2 a date+runtime match where p2 has no words; p3/m3 the same day and // runtime but different words; m4 alone. function streams(p: Paths): void { channel(p, "pref-chan"); channel(p, "mirror-chan"); video(p, "pref-chan", "p1", { date: "20260301", duration: 7200, cues: cues(1), audio: true }); video(p, "mirror-chan", "m1", { date: "20260301", duration: 7260, cues: cues(1, 45), transcript: true, audio: true }); video(p, "pref-chan", "p2", { date: "20260305", duration: 7200 }); video(p, "mirror-chan", "m2", { date: "20260306", duration: 7230, cues: cues(2), audio: true }); video(p, "pref-chan", "p3", { date: "20260310", duration: 7200, cues: cues(3) }); video(p, "mirror-chan", "m3", { date: "20260310", duration: 7200, cues: cues(4), audio: true }); video(p, "mirror-chan", "m4", { date: "20260320", duration: 5000, audio: true }); } const settingsWith = (groups: unknown[]) => ({ sourceGroups: sanitizeSourceGroups(groups) }); test("the scan records how each pair was matched, and its evidence", async () => { const p = corpus(); streams(p); const out = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); assert.ok(out.path, "written"); const f = out.file; assert.deepEqual( f.pairs.map((x) => [x.key, x.link, x.evidence.kind]), [ ["pref-chan/p1|mirror-chan/m1", "confirmed", "text"], ["pref-chan/p2|mirror-chan/m2", "metadata", "metadata"], ], ); assert.equal(f.pairs[0].evidence.text?.verdict, "same"); assert.equal(f.pairs[0].evidence.text?.offsetMedianSeconds, 45); assert.ok(f.pairs[0].evidence.text!.bInA.fraction >= 0.75, "probed both ways"); assert.equal(f.totals.rejected, 1, "p3/m3: the words say different, whatever the runtime"); assert.deepEqual(f.totals.videos, { "pref-chan": 3, "mirror-chan": 4 }); }); test("a part of a stream is recorded part-of, and never reaches a lane", async () => { const p = corpus(); channel(p, "pref-chan"); channel(p, "mirror-chan"); const whole = cues(9); video(p, "mirror-chan", "m1", { date: "20260301", duration: 1200, cues: whole, transcript: true, audio: true }); // The preferred copy is the stream's middle fifth, on its own clock. const part = whole.slice(100, 160).map((c) => ({ ...c, start: c.start - 400, end: c.end - 400 })); video(p, "pref-chan", "p1", { date: "20260301", duration: 240, cues: part, audio: true }); const out = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); assert.deepEqual(out.file.pairs.map((x) => [x.link, x.part]), [["part-of", "a"]]); assert.equal(out.file.totals.partOf, 1); snapshot(p, "pref-chan", ["p1"]); snapshot(p, "mirror-chan", []); writeSettings({ sourceGroups: [GROUP] }); const r = await lane(p); assert.deepEqual(allPending(r), ["p1"], "a part is transcribed for itself"); assert.equal(r.copies, undefined, "no pair the lanes act on, so the lane is today's"); }); test("the scan is idempotent: a second run changes nothing and keeps firstSeenAt", async () => { const p = corpus(); streams(p); const first = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { now: () => new Date("2026-03-21T00:00:00Z") }); const file = copiesPath(p.transcriptsDir, "stream-copies"); const bytes = await readFile(file, "utf8"); const mtime = statSync(file).mtimeMs; const second = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { now: () => new Date("2026-03-22T00:00:00Z") }); assert.equal(second.unchanged, true); assert.equal(second.path, undefined); assert.equal(await readFile(file, "utf8"), bytes); assert.equal(statSync(file).mtimeMs, mtime); // A new pair joins with its own firstSeenAt; the old ones keep theirs. video(p, "pref-chan", "p4", { date: "20260320", duration: 5010 }); const third = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { now: () => new Date("2026-03-23T00:00:00Z") }); assert.deepEqual( third.file.pairs.map((x) => [x.key, x.firstSeenAt]), [ ["pref-chan/p1|mirror-chan/m1", first.file.generatedAt], ["pref-chan/p2|mirror-chan/m2", first.file.generatedAt], ["pref-chan/p4|mirror-chan/m4", "2026-03-23T00:00:00.000Z"], ], ); }); test("a dry run writes nothing, over an existing file too; an unknown group or a group short of channels is refused", async () => { const p = corpus(); streams(p); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true }); assert.deepEqual(readdirSync(p.transcriptsDir), ["channels"]); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); const file = copiesPath(p.transcriptsDir, "stream-copies"); const bytes = readFileSync(file); const mtime = statSync(file).mtimeMs; video(p, "pref-chan", "p4", { date: "20260320", duration: 5010 }); const dry = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true }); assert.equal(dry.unchanged, false, "the dry run sees the new pair"); assert.equal(dry.path, undefined); assert.ok(readFileSync(file).equals(bytes), "and leaves the file byte for byte"); assert.equal(statSync(file).mtimeMs, mtime); assert.match((await copiesScanRefusal(p, settingsWith([GROUP]), "nope"))!, /no source group "nope"/); assert.match( (await copiesScanRefusal(p, settingsWith([{ id: "short", channels: ["pref-chan", "not-here"] }]), "short"))!, /needs two of its channels/, ); assert.throws(() => parseCopiesReleaseBody({ group: "stream-copies", video: "../x" }), /not a video key/); }); test("a cancelled scan stops between pairs and writes nothing", async () => { const p = corpus(); streams(p); const early = new AbortController(); early.abort(); await assert.rejects(runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { signal: early.signal }), CopiesScanCancelled); // Mid-scan: cancelled once the candidates are listed. const mid = new AbortController(); await assert.rejects( runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { signal: mid.signal, onLog: (l) => { if (/candidate pairs/.test(l)) mid.abort(); }, }), CopiesScanCancelled, ); assert.deepEqual(readdirSync(p.transcriptsDir), ["channels"], "no copies file"); }); // A RE-UPLOAD channel and a LIVE mirror of the same streams (the shape of the // first real scan's fault): the re-uploads went up months after the streams and // carry the stream's day only in their titles; the mirror's videos are the live // streams themselves, dated by their own day. No recordedDate rule is set. function reuploads(p: Paths, prefConfig: Record = {}): void { channel(p, "pref-chan", prefConfig); channel(p, "mirror-chan"); video(p, "pref-chan", "p1", { date: "20260310", duration: 7200, title: "2023-04-05 the long stream", cues: cues(1) }); video(p, "pref-chan", "p2", { date: "20260311", duration: 7200, title: "2023 04 08 another stream" }); video(p, "pref-chan", "p3", { date: "20260312", duration: 3000, title: "2023 Apr 20 a short one" }); video(p, "mirror-chan", "m1", { date: "20230405", duration: 7260, live: true, title: "[Copy] stream", cues: cues(1, 45), audio: true }); video(p, "mirror-chan", "m2", { date: "20230408", duration: 7230, live: true, title: "[Copy] stream", cues: cues(2), audio: true }); } test("a re-upload channel dated only in its titles is paired with the live copies (fails against upload-date dating)", async () => { const p = corpus(); reuploads(p); const out = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true }); const f = out.file; assert.deepEqual( f.pairs.map((x) => [x.key, x.link, x.a.dateFrom, x.b.dateFrom]), [ ["pref-chan/p1|mirror-chan/m1", "confirmed", "title", "live"], ["pref-chan/p2|mirror-chan/m2", "metadata", "title", "live"], ], ); assert.deepEqual(f.pairs[0].a.date, "20230405", "the stream's day, not the upload's"); assert.equal(f.dating?.["pref-chan"].detectedPattern !== undefined, true); assert.deepEqual(f.dating?.["pref-chan"].byFrom, { rule: 0, live: 0, title: 3, upload: 0, none: 0 }); assert.deepEqual(f.dating?.["mirror-chan"].byFrom, { rule: 0, live: 2, title: 0, upload: 0, none: 0 }); // The scan SAYS the channel lacks its rule, with the exact patch to set it. const advice = (f.advice ?? []).join("\n"); assert.match(advice, /pref-chan: 3 of 3 videos are dated by a date their titles carry/); const patch = /pnpm ops channel-config --json '(.*?)'/.exec(advice)?.[1]; assert.ok(patch, advice); const body = JSON.parse(patch!); assert.equal(body.slug, "pref-chan"); assert.equal(new RegExp(body.patch.recordedDateTitlePattern, "i").test("2023-04-05 the long stream"), true); assert.doesNotMatch(advice, /mirror-chan/, "a live channel is dated by its streams: nothing to set"); }); test("the channel's own recordedDate rule dates its videos first, and no advice asks for one", async () => { const p = corpus(); reuploads(p, { recordedDate: { titlePattern: "^(?\\d{4})[- ](?\\d{2})[- ](?\\d{2})" } }); const f = (await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true })).file; assert.deepEqual( f.pairs.map((x) => [x.key, x.link, x.a.dateFrom]), [ ["pref-chan/p1|mirror-chan/m1", "confirmed", "rule"], ["pref-chan/p2|mirror-chan/m2", "metadata", "rule"], ], ); // p3's "2023 Apr 20" is not the rule's shape: the rule is the operator's word, // so the scan does not guess past it — p3 keeps its upload date. assert.deepEqual(f.dating?.["pref-chan"].byFrom, { rule: 2, live: 0, title: 0, upload: 1, none: 0 }); assert.equal(f.dating?.["pref-chan"].detectedPattern, undefined); assert.doesNotMatch((f.advice ?? []).join("\n"), /recordedDateTitlePattern/); // A ruled channel is never searched by runtime: the scan is main's. assert.equal(f.totals.runtime, undefined); }); test("with no date to go by, a copy is found by runtime and words, never held on runtime alone, and the search is bounded", async () => { const p = corpus(); channel(p, "pref-chan"); channel(p, "mirror-chan"); // Re-uploads whose titles carry no date: their upload day is the copy's. video(p, "pref-chan", "p1", { date: "20260310", duration: 7200, title: "Stream highlights", cues: cues(1) }); video(p, "pref-chan", "p2", { date: "20260311", duration: 7200, title: "Another stream" }); video(p, "mirror-chan", "m1", { date: "20230405", duration: 7260, live: true, cues: cues(1, 45), audio: true }); video(p, "mirror-chan", "m2", { date: "20230408", duration: 7230, live: true, cues: cues(2), audio: true }); video(p, "mirror-chan", "m3", { date: "20230409", duration: 7190, live: true, cues: cues(3), audio: true }); const f = (await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true })).file; assert.deepEqual( f.pairs.map((x) => [x.key, x.link, x.evidence.via]), [["pref-chan/p1|mirror-chan/m1", "confirmed", "runtime"]], "p2 has no words: a runtime alone is no evidence, so no pair (and no hold)", ); assert.equal(f.totals.candidates, 0, "nothing was dated near anything"); assert.deepEqual(f.totals.runtime, { searched: 1, candidates: 3, rejected: 2, capped: 0 }); const advice = (f.advice ?? []).join("\n"); assert.match(advice, /pref-chan: 2 of 2 videos have only an upload date/); assert.match(advice, /no two members' videos are dated within 1 day/); }); async function lane(p: Paths, kind: "transcription" | "backfill" = "transcription") { resetCopiesLaneCacheForTest(); return computeLeafPending(kind, p, { state: emptyAutoQueueState() }); } const allPending = (r: Awaited>) => Object.values(r.head).flat().sort(); // Counts every disk call the lanes' copies code makes. function countingIo(): { io: CopiesLaneIo; calls: string[] } { const calls: string[] = []; return { calls, io: { readFile: (f) => (calls.push(`readFile ${path.basename(f)}`), fsReadFile(f, "utf8")), readdir: (f) => (calls.push(`readdir ${path.basename(f)}`), fsReaddir(f)), stat: (f) => (calls.push(`stat ${path.basename(f)}`), fsStat(f)), }, }; } test("no group configured: the lane is exactly what it was, with no copies disk call (and a group with lanes off too)", async () => { const p = corpus(); streams(p); snapshot(p, "pref-chan", ["p1"]); snapshot(p, "mirror-chan", ["m2", "m3", "m4"]); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); const { io, calls } = countingIo(); setCopiesLaneIoForTest(io); try { writeSettings({}); const before = await lane(p); assert.equal("copies" in before, false, "no copies field on the payload"); assert.deepEqual(allPending(before), ["m2", "m3", "m4", "p1"]); writeSettings({ sourceGroups: [] }); assert.deepEqual(await lane(p), before); writeSettings({ sourceGroups: [{ ...GROUP, lanes: false }] }); assert.deepEqual(await lane(p), before, "the scan's file is there, but the group does not act"); assert.deepEqual(calls, [], "not one stat, readdir or read"); } finally { setCopiesLaneIoForTest(null); } }); test("with the group: the done copy's twin is skipped, the metadata match held, and both are reversible", async () => { const p = corpus(); streams(p); snapshot(p, "pref-chan", ["p1"]); snapshot(p, "mirror-chan", ["m2", "m3", "m4"]); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); writeSettings({ sourceGroups: [GROUP] }); const r = await lane(p); // p1: its fallback copy m1 has the transcript — not transcribed again. // m2: probably p2 (date + runtime only), p2 not done but queued? No: p2 is // not pending here (no audio), so nothing waits on it — m2 runs. assert.deepEqual(allPending(r), ["m2", "m3", "m4"]); assert.equal(r.copies?.skipped, 1); const [skip] = r.copies!.head; assert.deepEqual([skip.channel, skip.id, skip.action, skip.link, skip.partner], ["pref-chan", "p1", "skip", "confirmed", "mirror-chan/m1"]); // p2 queued: m2 is held behind it, with the date its hold ends. snapshot(p, "pref-chan", ["p1", "p2"]); const held = await lane(p); assert.deepEqual(allPending(held), ["m3", "m4", "p2"]); const hold = held.copies!.head.find((d) => d.id === "m2")!; assert.deepEqual([hold.action, hold.link], ["hold", "metadata"]); assert.ok(hold.until, "a metadata hold ends by itself"); // The release brings m2 back, and undoing it holds it again. await updateCopiesDecisions(p.transcriptsDir, "stream-copies", { release: ["mirror-chan/m2"], by: "operator" }); assert.deepEqual(allPending(await lane(p)), ["m2", "m3", "m4", "p2"]); await updateCopiesDecisions(p.transcriptsDir, "stream-copies", { release: ["mirror-chan/m2"], undo: true, by: "operator" }); assert.deepEqual(allPending(await lane(p)), ["m3", "m4", "p2"]); // Removing the group restores the lane; nothing was deleted on the way. writeSettings({}); assert.deepEqual(allPending(await lane(p)), ["m2", "m3", "m4", "p1", "p2"]); for (const [slug, id, name] of [["mirror-chan", "m1", "transcript.json"], ["pref-chan", "p1", "audio.mp3"], ["mirror-chan", "m2", "audio.mp3"]]) { assert.ok(statSync(path.join(p.channelsDir, slug, "data", id, name)).isFile(), `${slug}/${id}/${name} kept`); } }); test("a channel taken out of the group, or renamed in it, drops its pairs and restores the lane", async () => { const p = corpus(); streams(p); snapshot(p, "pref-chan", ["p1"]); snapshot(p, "mirror-chan", []); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); writeSettings({ sourceGroups: [GROUP] }); assert.deepEqual(allPending(await lane(p)), []); writeSettings({ sourceGroups: [{ id: "stream-copies", channels: ["pref-chan", "mirror-chan-renamed"] }] }); assert.deepEqual(allPending(await lane(p)), ["p1"]); }); test("confirm, reject and release: checked against the scan, by dir or id, with who and when", async () => { const p = corpus(); streams(p); // A Rumble-like video: its dir (the URL slug) is not its id (the embed id). video(p, "mirror-chan", "stream-slug-m5", { id: "v5embed", date: "20260325", duration: 6000, audio: true }); video(p, "pref-chan", "p5", { date: "20260325", duration: 6010, audio: true }); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); const settings = settingsWith([GROUP]); const now = () => new Date("2026-03-26T00:00:00Z"); // Named by the EMBED id, in the other order: resolves to the pair keyed by dir. const c = await applyCopiesDecision(p, settings, "confirm", { group: "stream-copies", pair: "mirror-chan/v5embed|pref-chan/p5", by: "operator", note: "listened" }, { now }); assert.equal(c.ok, true); if (!c.ok) return; assert.deepEqual(c.applied, ["pref-chan/p5|mirror-chan/stream-slug-m5"]); const file = JSON.parse(readFileSync(copiesDecisionsPath(p.transcriptsDir, "stream-copies"), "utf8")); assert.deepEqual(file.confirmed["pref-chan/p5|mirror-chan/stream-slug-m5"], { at: "2026-03-26T00:00:00.000Z", by: "operator", note: "listened" }); // A text-confirmed pair cannot be confirmed again; an unknown one is reported, nothing stored for it. const c2 = await applyCopiesDecision(p, settings, "confirm", { group: "stream-copies", pairs: ["pref-chan/p1|mirror-chan/m1", "pref-chan/nope|mirror-chan/m9"] }); assert.ok(c2.ok); if (!c2.ok) return; assert.deepEqual(c2.applied, []); assert.deepEqual(c2.unknown, ["pref-chan/nope|mirror-chan/m9"]); assert.match(c2.skipped[0].reason, /already confirmed/); // Release by the id form lands on the dir key; an unknown video is reported. const rel = await applyCopiesDecision(p, settings, "release", { group: "stream-copies", videos: ["mirror-chan/v5embed", "mirror-chan/zzz"] }); assert.ok(rel.ok); if (!rel.ok) return; assert.deepEqual([rel.applied, rel.unknown], [["mirror-chan/stream-slug-m5"], ["mirror-chan/zzz"]]); // Reject replaces the confirm. const rj = await applyCopiesDecision(p, settings, "reject", { group: "stream-copies", pair: "pref-chan/p5|mirror-chan/stream-slug-m5" }); assert.ok(rj.ok); const after = JSON.parse(readFileSync(copiesDecisionsPath(p.transcriptsDir, "stream-copies"), "utf8")); assert.deepEqual(Object.keys(after.confirmed), []); assert.equal(after.rejected["pref-chan/p5|mirror-chan/stream-slug-m5"].by, "agent", "the default hand"); const bad = await applyCopiesDecision(p, settings, "confirm", { group: "stream-copies", pair: "p5" }); assert.equal(bad.ok, false); assert.equal((await applyCopiesDecision(p, settings, "reject", { group: "other", pair: "a/b|c/d" })).ok, false); }); test("the lanes key a Rumble-like video by its dir: held under the dir the snapshot lists, released by its id", async () => { const p = corpus(); channel(p, "pref-chan"); channel(p, "mirror-chan"); video(p, "mirror-chan", "stream-slug-m5", { id: "v5embed", date: "20260325", duration: 6000, audio: true }); video(p, "pref-chan", "p5", { date: "20260325", duration: 6010, audio: true }); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); snapshot(p, "pref-chan", ["p5"]); snapshot(p, "mirror-chan", ["stream-slug-m5"]); writeSettings({ sourceGroups: [GROUP] }); const r = await lane(p); assert.deepEqual(allPending(r), ["p5"]); assert.deepEqual(r.copies!.head.map((d) => [d.channel, d.id, d.action]), [["mirror-chan", "stream-slug-m5", "hold"]]); await applyCopiesDecision(p, settingsWith([GROUP]), "release", { group: "stream-copies", video: "mirror-chan/v5embed" }); assert.deepEqual(allPending(await lane(p)), ["p5", "stream-slug-m5"]); }); test("a confirmed pair whose other copy is done skips; a rejected pair never acts again", async () => { const p = corpus(); channel(p, "pref-chan"); channel(p, "mirror-chan"); video(p, "pref-chan", "p5", { date: "20260325", duration: 6010, transcript: true }); video(p, "mirror-chan", "m5", { date: "20260325", duration: 6000, audio: true }); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); snapshot(p, "pref-chan", []); snapshot(p, "mirror-chan", ["m5"]); writeSettings({ sourceGroups: [GROUP] }); assert.equal((await lane(p)).copies!.head[0].action, "hold", "metadata only: held within the wait"); await applyCopiesDecision(p, settingsWith([GROUP]), "confirm", { group: "stream-copies", pair: "pref-chan/p5|mirror-chan/m5", by: "operator" }); const confirmed = await lane(p); assert.deepEqual(allPending(confirmed), []); assert.equal(confirmed.copies!.head[0].action, "skip"); assert.match(confirmed.copies!.head[0].reason, /operator's word/); await applyCopiesDecision(p, settingsWith([GROUP]), "reject", { group: "stream-copies", pair: "pref-chan/p5|mirror-chan/m5" }); assert.deepEqual(allPending(await lane(p)), ["m5"]); const [g] = await copiesReport(p, settingsWith([GROUP])); assert.equal(g.pairs.rejected, 1); }); // --- What counts as the other copy's work done ------------------------------ async function doneOf(p: Paths, key: string, o: { captions?: boolean; duration?: number; settings?: SiteSettings } = {}) { resetCopiesLaneCacheForTest(); const settings = o.settings ?? defaultSiteSettings(); const facts = new Map([[key, { duration: o.duration ?? 600, captionsCountAsDone: o.captions ?? false }]]); return (await readCopyDone("transcription", p, settings, [key], facts)).get(key); } test("transcription done is a transcript the lane would not redo, with real words for its length (fails against any non-empty file)", async () => { const p = corpus(); channel(p, "pref-chan"); const dir = (id: string) => { const d = path.join(p.channelsDir, "pref-chan", "data", id); mkdirSync(d, { recursive: true }); return d; }; // Headers only. writeFileSync(path.join(dir("h1"), "transcript.en.vtt"), "WEBVTT\nKind: captions\nLanguage: en\n\n"); // Music only. writeFileSync(path.join(dir("h2"), "transcript.en.vtt"), vtt(200, () => "[Music]")); // Real human captions: 200 cues of 8 words = 1600 words for 10 minutes. writeFileSync(path.join(dir("h3"), "transcript.en.vtt"), vtt(200, (i) => `caption line ${i} with some more spoken words`)); // YouTube ASR captions, as many words. writeFileSync(path.join(dir("h4"), "transcript.en.vtt"), vtt(200, (i) => `auto line ${i} with some more spoken words`, true)); // Our own transcript, too short for 10 minutes, and one of real length. writeFileSync(path.join(dir("h5"), "transcript.json"), whisperJson(20)); writeFileSync(path.join(dir("h6"), "transcript.json"), whisperJson(400)); // captionsCountAsDone is off by default: no caption track counts. for (const id of ["h1", "h2", "h3", "h4"]) assert.equal(await doneOf(p, `pref-chan/${id}`), false, id); assert.equal(await doneOf(p, "pref-chan/h5"), false, "20 words for 10 minutes"); assert.equal(await doneOf(p, "pref-chan/h6"), true); // With it on: real captions count, headers-only and music-only never do. assert.equal(await doneOf(p, "pref-chan/h1", { captions: true }), false); assert.equal(await doneOf(p, "pref-chan/h2", { captions: true }), false); assert.equal(await doneOf(p, "pref-chan/h3", { captions: true }), true); assert.equal(await doneOf(p, "pref-chan/h4", { captions: true }), true, "ASR counts while nothing would replace it"); // …but not while the transcription lane would replace auto-captions. const replacing = defaultSiteSettings(); replacing.autoQueue.transcription.replaceAutoSubs = true; assert.equal(await doneOf(p, "pref-chan/h4", { captions: true, settings: replacing }), false); assert.equal(await doneOf(p, "pref-chan/h3", { captions: true, settings: replacing }), true, "human captions are not replaced"); }); test("the fallback copy still gets its own transcript when the preferred copy has captions only", async () => { const p = corpus(); channel(p, "pref-chan"); channel(p, "mirror-chan"); const words = cues(21); video(p, "pref-chan", "p1", { date: "20260301", duration: 1200, cues: words }); writeFileSync(path.join(p.channelsDir, "pref-chan", "data", "p1", "transcript.en.vtt"), vtt(300, (i) => `caption line ${i} with some more spoken words`)); video(p, "mirror-chan", "m1", { date: "20260301", duration: 1210, cues: words, audio: true }); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); snapshot(p, "pref-chan", []); snapshot(p, "mirror-chan", ["m1"]); writeSettings({ sourceGroups: [GROUP] }); assert.deepEqual(allPending(await lane(p)), ["m1"], "captionsCountAsDone off: m1 is transcribed"); writeSettings({ sourceGroups: [{ ...GROUP, captionsCountAsDone: true }] }); assert.deepEqual(allPending(await lane(p)), [], "on: the captions stand for the recording"); }); test("a tick with nothing changed reads no transcript file; a changed transcript is read again, off the tick", async () => { const p = corpus(); streams(p); snapshot(p, "pref-chan", ["p1"]); snapshot(p, "mirror-chan", []); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); writeSettings({ sourceGroups: [GROUP] }); const { io, calls } = countingIo(); // Re-checked on every tick (0 ms), to prove the re-check itself reads nothing. setCopiesLaneIoForTest(io, { revalidateMs: 0 }); try { resetCopiesLaneCacheForTest(); const tick = () => computeLeafPending("transcription", p, { state: emptyAutoQueueState() }); assert.deepEqual(allPending(await tick()), []); const reads = () => calls.filter((c) => c.startsWith("readFile")).length; assert.equal(reads(), 1, "the first sight of m1 reads its transcript once"); for (let i = 0; i < 3; i++) { assert.deepEqual(allPending(await tick()), []); await copiesLaneSettledForTest(); } assert.equal(reads(), 1, "three more ticks, nothing changed: no transcript read"); assert.ok(calls.some((c) => c === "stat transcript.json"), "only stats"); // m1's transcript replaced by a header-only one: the next re-check reads it. writeFileSync(path.join(p.channelsDir, "mirror-chan", "data", "m1", "transcript.json"), JSON.stringify({ transcription: [] })); await tick(); await copiesLaneSettledForTest(); assert.equal(reads(), 2); assert.deepEqual(allPending(await tick()), ["p1"], "and the tick after knows m1 is not done"); } finally { setCopiesLaneIoForTest(null); } }); test("a confirmed copy is skipped only when the other copy's transcript is actually there and readable", async () => { const p = corpus(); streams(p); snapshot(p, "pref-chan", ["p1"]); snapshot(p, "mirror-chan", []); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); writeSettings({ sourceGroups: [GROUP] }); // m1's transcript replaced by an unreadable one: p1 is not skipped. writeFileSync(path.join(p.channelsDir, "mirror-chan", "data", "m1", "transcript.json"), "{not json"); const r = await lane(p); assert.deepEqual(allPending(r), ["p1"]); assert.equal(r.copies?.skipped, 0); }); // --- Speakers, over real-shaped files ---------------------------------------- function speakersSettings(): SiteSettings { const s = defaultSiteSettings(); return { ...s, diarization: { ...s.diarization, enabled: true, segModel: "/opt/models/seg-1.onnx", embModel: "/opt/models/emb-1.onnx", threshold: DEFAULT_DIARIZATION_THRESHOLD, }, attribution: { ...s.attribution, enabled: true, diarizedEnabled: true, textOnlyEnabled: true, appId: OLLAMA_DIGEST_APP_ID, model: "qwen2.5:7b", }, }; } const DIARIZED_AT = "2026-08-06T00:00:00.000Z"; function speakersFiles(d: string, o: { diarization?: boolean; attribution?: boolean }): void { writeFileSync(path.join(d, "transcript.json"), whisperJson(400)); if (o.diarization) { writeFileSync( path.join(d, DIARIZATION_FILENAME), JSON.stringify({ videoId: path.basename(d), generatedAt: DIARIZED_AT, speakers: 2, turns: [{ start: 0, end: 4, speaker: 0 }], engine: { engine: "sherpa-onnx", segmentationModel: "seg-1.onnx", embeddingModel: "emb-1.onnx", threshold: DEFAULT_DIARIZATION_THRESHOLD }, voiceprints: [{ speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb-1.onnx" }], } satisfies DiarizationRecord), ); } if (o.attribution) { writeFileSync( path.join(d, ATTRIBUTION_FILENAME), JSON.stringify({ videoId: path.basename(d), generatedAt: "2026-08-07T00:00:00.000Z", speakers: [{ index: 0, label: "Host" }], segments: [{ start: 0, end: 10, speaker: 0 }], provenance: { method: "diarized", appId: OLLAMA_DIGEST_APP_ID, model: "qwen2.5:7b", modelRequested: "qwen2.5:7b", promptVersion: ATTRIBUTION_PROMPT_VERSION, generatedAt: "2026-08-07T00:00:00.000Z", diarizationGeneratedAt: DIARIZED_AT, }, } satisfies AttributionRecord), ); } } test("Speakers: the other copy's diarization and names on disk skip the copy; anything less does not", async () => { const p = corpus(); streams(p); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies"); const settings = { ...speakersSettings(), sourceGroups: sanitizeSourceGroups([GROUP]) }; const m1 = path.join(p.channelsDir, "mirror-chan", "data", "m1"); const holds = async () => { resetCopiesLaneCacheForTest(); return copyHoldsForLane({ kind: "backfill", paths: p, settings, pending: { all: ["p1"] }, owner: new Map([["p1", "pref-chan"]]), inFlight: [], }); }; // m1 has a transcript but no Speakers outputs: p1 gets its own. assert.deepEqual((await holds())!.pending.all, ["p1"]); // Diarized, not yet named: still work on m1, so p1 is not skipped. speakersFiles(m1, { diarization: true }); assert.deepEqual((await holds())!.pending.all, ["p1"]); // Diarized and named, both fresh: p1 is skipped. speakersFiles(m1, { diarization: true, attribution: true }); const done = (await holds())!; assert.deepEqual(done.pending.all, []); assert.equal(done.decisions[0].action, "skip"); assert.match(done.decisions[0].reason, /speakers work is done/); // A malformed diarization file is not done. writeFileSync(path.join(m1, DIARIZATION_FILENAME), "{half written"); assert.deepEqual((await holds())!.pending.all, ["p1"]); }); test("the report reads the scan, counts the duplicated copies' audio, lists the metadata pairs in their wait, and writes nothing", async () => { const p = corpus(); streams(p); await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { now: () => new Date("2026-03-21T00:00:00Z") }); const before = readdirSync(path.join(p.transcriptsDir, "copies")).sort(); const [g] = await copiesReport(p, settingsWith([GROUP]), { pairs: true, now: Date.parse("2026-03-22T00:00:00Z") }); assert.equal(g.id, "stream-copies"); assert.deepEqual(g.pairs, { confirmed: 1, confirmedByDecision: 0, metadata: 1, partOf: 0, overlaps: 0, rejected: 0, withinChannel: 0 }); assert.deepEqual(g.duplicated, { seconds: 7260, byChannel: { "mirror-chan": { bytes: 1234, videos: 1 } } }); assert.equal(g.list?.length, 2); assert.deepEqual( g.metadataPairs.map((x) => [x.key, x.a.title, x.b.date, x.durationDifferenceSeconds, x.dateDeltaDays, x.waitEnds]), [["pref-chan/p2|mirror-chan/m2", "Stream p2", "20260306", 30, 1, "2026-03-28T00:00:00.000Z"]], ); const [late] = await copiesReport(p, settingsWith([GROUP]), { now: Date.parse("2026-04-01T00:00:00Z") }); assert.deepEqual(late.metadataPairs, [], "past its wait a pair holds nothing"); assert.deepEqual(readdirSync(path.join(p.transcriptsDir, "copies")).sort(), before); }); test("the lanes' copies are applied in one place: the runner tick and its panel twin, never a manual run", async () => { // A manual transcribe or Speakers run goes through its own route and never // asks copyHoldsForLane; only autoRunner.ts does (twice: the tick and // computeLeafPending). const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const hits: string[] = []; const walk = (dir: string) => { for (const e of readdirSync(dir, { withFileTypes: true })) { if (e.name === "node_modules" || e.name.startsWith(".")) continue; const f = path.join(dir, e.name); if (e.isDirectory()) walk(f); else if (/\.(ts|tsx|mjs)$/.test(e.name) && !/\.test\./.test(e.name)) { const n = (readFileSync(f, "utf8").match(/\bcopyHoldsForLane\(/g) ?? []).length; if (n > 0) hits.push(`${path.relative(root, f)}:${n}`); } } }; for (const d of ["common", "editor/app", "scripts"]) walk(path.join(root, d)); assert.deepEqual(hits.sort(), ["common/controller/autoRunner.ts:2", "common/controller/copiesLane.ts:1"]); }); test("the runner says once when the copies it skips or holds change, and nothing with no group", async () => { const { makeCopyHoldReporter } = await import("./autoRunner"); const lines: string[] = []; const report = makeCopyHoldReporter("transcription", (l) => lines.push(l)); report(null); report({ skipped: 0, held: 0, head: [] }); assert.deepEqual(lines, []); report({ skipped: 2, held: 1, head: [] }); report({ skipped: 2, held: 1, head: [] }); assert.equal(lines.length, 1); assert.match(lines[0], /^Auto-transcription: 2 copies skipped .* 1 held .*pnpm ops get copies/); report({ skipped: 0, held: 0, head: [] }); assert.equal(lines.length, 2); });