import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, mkdir, rm, writeFile, readdir } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { sanitizeLookoutItem } from "../lib/lookoutSettings"; import { metaDatesOf, planLookout, LookoutPlanRefusal } from "./lookoutPlan"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/lookoutPlan.test.ts // // The dry run over a fixture corpus (lane/lookout slice 1, acceptance a): a // stream whose UTC upload date is the next day, its twin upload on another // channel and a cut-down of it → the plan lists the stream ONCE, on the local // date, with both alternates. Every channel name here is invented. // The real start of an evening stream: 2026-11-04T01:20:53Z, which is // 2026-11-03 20:20 in New York — `upload_date` says 4 Nov, the air says 3 Nov. const STREAM_RELEASE = 1793755253; const STREAM_UPLOAD = 1793754765; // Deterministic words: a small LCG over a synthetic vocabulary, so the texts // have real shingles and two "transcripts" of the same speech differ the way // two ASR engines do (a word in ten replaced). function words(seed: number, n: number): string[] { let x = seed >>> 0; const out: string[] = []; for (let i = 0; i < n; i++) { x = (Math.imul(x, 1664525) + 1013904223) >>> 0; out.push(`w${(x >>> 16) % 2000}`); } return out; } function garble(ws: string[], seed: number, every = 10): string[] { return ws.map((w, i) => (i % every === seed % every ? `x${i}` : w)); } function cuesOf(ws: string[], seconds: number) { const per = 10; const n = Math.ceil(ws.length / per); const step = seconds / n; return Array.from({ length: n }, (_, i) => ({ start: Math.round(i * step * 100) / 100, end: Math.round((i + 1) * step * 100) / 100, text: ws.slice(i * per, (i + 1) * per).join(" "), })); } type VideoFixture = { channel: string; dir: string; id?: string; title: string; platform: string; duration: number; uploadDate: string; timestamp?: number; releaseTimestamp?: number; liveStatus?: string; text?: string[]; }; async function writeVideo(channelsDir: string, v: VideoFixture): Promise { const dir = path.join(channelsDir, v.channel, "data", v.dir); await mkdir(dir, { recursive: true }); const meta: Record = { id: v.id ?? v.dir, title: v.title, formats: [{ format_id: "1", url: "https://example.invalid/f" }], duration: v.duration, live_status: v.liveStatus ?? "not_live", webpage_url: `https://example.invalid/watch/${v.dir}`, upload_date: v.uploadDate, }; if (v.timestamp !== undefined) meta.timestamp = v.timestamp; if (v.releaseTimestamp !== undefined) meta.release_timestamp = v.releaseTimestamp; await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(meta, null, 1)); if (v.text) { await writeFile( path.join(dir, "transcript.cues.json"), JSON.stringify({ version: 2, source: v.platform === "youtube" ? "vtt" : "whisper", slug: `${v.channel}/${v.id ?? v.dir}`, id: v.id ?? v.dir, channelSlug: v.channel, title: v.title, uploadDate: v.uploadDate, duration: v.duration, channel: v.channel, description: "", platform: v.platform, webpageUrl: `https://example.invalid/${v.dir}`, cues: cuesOf(v.text, v.duration), }), ); } } async function fixture(): Promise<{ root: string; paths: Paths }> { const root = await mkdtemp(path.join(os.tmpdir(), "lookout-plan-")); const transcriptsDir = path.join(root, "transcripts"); const channelsDir = path.join(transcriptsDir, "channels"); const channel = async (slug: string, config: Record) => { await mkdir(path.join(channelsDir, slug, "data"), { recursive: true }); await writeFile(path.join(channelsDir, slug, "config.json"), JSON.stringify(config)); }; await channel("alpha-rumble", { name: "Alpha", handling: "transcribe", url: "https://rumble.com/c/alpha-invented" }); await channel("alpha-clips", { name: "Alpha Clips", handling: "youtube", url: "https://www.youtube.com/@alpha-invented" }); await channel("alpha-library", { name: "Library", handling: "transcribe", localMedia: { sourceId: "library-1", directory: "/mnt/recordings" } }); const stream = words(1, 6000); // The stream on one channel, dated by its start. await writeVideo(channelsDir, { channel: "alpha-rumble", dir: "v1stream", id: "v0embed1", title: "Election Night LIVE!", platform: "rumble", duration: 7200, uploadDate: "20261104", timestamp: STREAM_UPLOAD, releaseTimestamp: STREAM_RELEASE, liveStatus: "was_live", text: stream, }); // Its twin upload on another channel: the same title, a second longer, // captions from another engine; uploaded the next morning. await writeVideo(channelsDir, { channel: "alpha-clips", dir: "TwinUpload1", title: "Election Night LIVE!", platform: "youtube", duration: 7201, uploadDate: "20261104", timestamp: 1793790000, text: garble(stream, 3), }); // A cut-down: twelve minutes of the stream, re-titled. await writeVideo(channelsDir, { channel: "alpha-clips", dir: "CutDown0001", title: "He SNAPPED On Air", platform: "youtube", duration: 720, uploadDate: "20261104", timestamp: 1793800000, text: garble(stream.slice(2000, 2600), 7), }); // An unrelated video in the window. await writeVideo(channelsDir, { channel: "alpha-clips", dir: "Unrelated01", title: "Something Else Entirely", platform: "youtube", duration: 600, uploadDate: "20261105", timestamp: 1793880000, text: words(99, 1500), }); // A short. await writeVideo(channelsDir, { channel: "alpha-clips", dir: "ShortOne001", title: "A Short #shorts", platform: "youtube", duration: 58, uploadDate: "20261104", timestamp: 1793810000, text: words(7, 120), }); // In the window, no transcript yet. await writeVideo(channelsDir, { channel: "alpha-clips", dir: "NoCues00001", title: "Not Transcribed", platform: "youtube", duration: 900, uploadDate: "20261105", timestamp: 1793870000, }); // The UTC trap the other way: 2026-11-03T04:30Z is 2 Nov in New York — // `upload_date` puts it inside a 3–5 Nov window, the air date does not. await writeVideo(channelsDir, { channel: "alpha-rumble", dir: "v1latenight", title: "Late Night", platform: "rumble", duration: 1200, uploadDate: "20261103", timestamp: 1793680200, text: words(55, 2000), }); // Long before the window. await writeVideo(channelsDir, { channel: "alpha-rumble", dir: "v1old", title: "Old", platform: "rumble", duration: 1200, uploadDate: "20260101", timestamp: 1767268800, text: words(56, 2000), }); return { root, paths: { transcriptsDir, channelsDir } as Paths }; } function lookout(over: Record = {}) { const item = sanitizeLookoutItem({ id: "alpha-week", channels: ["alpha-rumble", "alpha-clips"], days: 3, timeZone: "America/New_York", ...over, }); assert.ok(item); return item; } test("the stream is listed once, on its local date, with its twin and its cut-down", async () => { const { root, paths } = await fixture(); try { const plan = await planLookout(paths, lookout(), { until: "2026-11-05" }); assert.deepEqual(plan.refused, []); assert.deepEqual(plan.window, { from: "2026-11-03", to: "2026-11-05", days: 3, timeZone: "America/New_York" }); const keys = plan.read.map((r) => `${r.channel}/${r.video}`); assert.deepEqual(keys, ["alpha-rumble/v1stream", "alpha-clips/Unrelated01"]); const s = plan.read[0]!; assert.equal(s.airDate, "2026-11-03", "the air date in New York, not the UTC upload date"); assert.equal(s.dateSource, "release_timestamp"); assert.equal(s.airAt, "2026-11-04T01:20:53.000Z"); assert.equal(s.id, "v0embed1", "the record's id beside its directory"); assert.deepEqual( s.folded.map((f) => [`${f.channel}/${f.video}`, f.reason]), [ ["alpha-clips/TwinUpload1", "duplicate-upload"], ["alpha-clips/CutDown0001", "covered-by-stream"], ], ); assert.equal(s.folded[0]!.titleMatch, true); assert.ok(s.folded[1]!.score >= 0.4, `cut-down share ${s.folded[1]!.score}`); assert.equal(s.folded[0]!.airDate, "2026-11-04"); assert.equal(plan.counts.inWindow, 5, "stream, twin, cut-down, unrelated, short — not the late-night one"); assert.equal(plan.counts.noTranscript, 1); assert.equal(plan.counts.underMinSeconds, 1); assert.equal(plan.counts.qualified, 4); assert.equal(plan.counts.duplicateUploads, 1); assert.equal(plan.counts.coveredByStream, 1); assert.equal(plan.counts.recordings, 2); assert.equal(plan.counts.read, 2); assert.equal(plan.counts.skippedForCap, 0); assert.deepEqual( plan.skipped.map((k) => [k.video, k.reason]), [ ["ShortOne001", "under-min-seconds"], ["NoCues00001", "no-transcript"], ], ); const bare = plan.skipped.find((k) => k.video === "NoCues00001")!; assert.equal(bare.title, "Not Transcribed", "named from its metadata"); assert.equal(bare.url, "https://example.invalid/watch/NoCues00001"); assert.ok(!keys.includes("alpha-rumble/v1latenight"), "aired 2 Nov in New York"); assert.ok(s.chunks > 1, "a two-hour stream is several chunks"); assert.equal(plan.estimate.readCalls, plan.read.reduce((n, r) => n + r.chunks, 0)); assert.equal(plan.estimate.secondsPerCall, null, "no run measured yet"); // Nothing was written: the corpus holds exactly what the fixture put there. assert.deepEqual((await readdir(paths.transcriptsDir)).sort(), ["channels"]); } finally { await rm(root, { recursive: true, force: true }); } }); test("in UTC the late-night video is in the window and the stream moves to 4 Nov", async () => { const { root, paths } = await fixture(); try { const plan = await planLookout(paths, lookout({ timeZone: "UTC" }), { until: "2026-11-05" }); const byKey = new Map(plan.read.map((r) => [`${r.channel}/${r.video}`, r])); assert.equal(byKey.get("alpha-rumble/v1stream")?.airDate, "2026-11-04"); assert.equal(byKey.get("alpha-rumble/v1latenight")?.airDate, "2026-11-03"); } finally { await rm(root, { recursive: true, force: true }); } }); test("the cap reads the longest recordings and lists the rest with what folded into them", async () => { const { root, paths } = await fixture(); try { const plan = await planLookout(paths, lookout(), { until: "2026-11-05", maxVideos: 1 }); assert.deepEqual(plan.read.map((r) => r.video), ["v1stream"]); assert.equal(plan.counts.skippedForCap, 1); const cap = plan.skipped.find((k) => k.reason === "cap"); assert.equal(cap?.video, "Unrelated01"); assert.deepEqual(cap?.folded, []); assert.ok((cap?.chunks ?? 0) >= 1); } finally { await rm(root, { recursive: true, force: true }); } }); test("a local library and a slug the archive does not hold are refused by name; the rest is read", async () => { const { root, paths } = await fixture(); try { const plan = await planLookout( paths, lookout({ channels: ["alpha-library", "remote-only-invented", "alpha-rumble"] }), { until: "2026-11-05" }, ); assert.deepEqual( plan.refused.map((r) => r.channel), ["alpha-library", "remote-only-invented"], ); assert.match(plan.refused[0]!.reason, /local media library/); assert.match(plan.refused[1]!.reason, /remote site/); assert.deepEqual(plan.read.map((r) => r.video), ["v1stream"]); } finally { await rm(root, { recursive: true, force: true }); } }); test("a directory unchanged since before the window is listed, not opened", async () => { const { root, paths } = await fixture(); try { // Every fixture directory was made just now; a window years later starts // after all of their ctimes, so none can hold a video aired in it. const plan = await planLookout(paths, lookout(), { until: "2031-01-10" }); assert.equal(plan.counts.scanned, 8); assert.equal(plan.counts.examined, 0); assert.equal(plan.counts.inWindow, 0); const now = await planLookout(paths, lookout(), { until: "2026-11-05" }); assert.equal(now.counts.examined, 8); } finally { await rm(root, { recursive: true, force: true }); } }); test("a lookout with no channels is refused", async () => { const { root, paths } = await fixture(); try { await assert.rejects(planLookout(paths, lookout({ channels: [] })), LookoutPlanRefusal); } finally { await rm(root, { recursive: true, force: true }); } }); test("metaDatesOf reads the scalars wherever yt-dlp put them", () => { // YouTube's order: upload_date then timestamp, near the end; a comment's // nested timestamp earlier is not taken, nor a storyboard fragment's duration. const yt = '{"id": "a", "formats": [{"format_id": "sb0", "fragments": [{"url": "u", "duration": 496.98}, {"url": "u", "duration": 250.02}]}], ' + '"comments": [{"timestamp": 1600000000}], "duration": 747, "live_status": "not_live", "webpage_url": "https://example.invalid/a", ' + '"upload_date": "20261106", "timestamp": 1793993883, "is_live": false}'; assert.deepEqual(metaDatesOf(yt), { releaseTimestamp: null, timestamp: 1793993883, uploadDate: "20261106", liveStatus: "not_live", duration: 747, title: null, webpageUrl: "https://example.invalid/a", }); // Rumble's order: timestamp early, release_timestamp later, upload_date last. const rumble = '{"id": "v", "title": "She said \\"no\\" \\u2014 caf\u00c3\u00a9", "timestamp": 1793754765, "duration": 12970, "live_status": "was_live", ' + '"release_timestamp": 1793755253, "upload_date": "20261104"}'; assert.deepEqual(metaDatesOf(rumble), { releaseTimestamp: 1793755253, timestamp: 1793754765, uploadDate: "20261104", liveStatus: "was_live", duration: 12970, // Escapes decoded, and the file's UTF-8 bytes (a string argument stands for them, one char a byte). title: 'She said "no" — café', webpageUrl: null, }); });