import { test } from "node:test"; import assert from "node:assert/strict"; import { access, lstat, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { Operation } from "../lib/operations"; import { cleanAudioForVideo, cleanAudioFromTranscribed } from "./cleanAudioFromTranscribed"; import { runOperationUnit, type OperationRun } from "./operationBatch"; import { readSpeakersLedger } from "../lib/speakersLedger-server"; import { readAvailabilityVerdict, requestAvailabilityCheck, writeAvailabilityVerdict, type CheckRequestDeps } from "./availabilityVerdict"; // Any test that reaches the request path without saying otherwise fails loudly. const NO_NETWORK: CheckRequestDeps = { start: async () => { throw new Error("a test asked for a real availability check"); }, platformRefusal: async () => null, serviceAlert: async () => null, }; import { defaultSiteSettings, getSettings } from "../lib/settings"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test common/controller/cleanAfterCapture.test.ts // // Temp corpus, temp settings.json. Nothing here probes the network: availability // is checked from availability.json (tier A) or switched off per test. const ROOT = await mkdtemp(path.join(tmpdir(), "clean-after-capture-")); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.E2E_AVAILABILITY_PROBE_GAP_MS = "0"; async function settings(diarization: Record, over: Record = {}) { await writeFile( process.env.SETTINGS_FILE!, JSON.stringify({ verifyAvailabilityBeforeClean: false, diarization: { enabled: true, segModel: "/m/seg.onnx", embModel: "/m/emb.onnx", ...diarization }, ...over, }), ); } const VOICEPRINTS = [{ speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb.onnx" }]; function sidecar(voiceprints: boolean): string { return JSON.stringify({ videoId: "v", generatedAt: "2026-08-07T00:00:00.000Z", speakers: 1, turns: [{ start: 0, end: 4, speaker: 0 }], engine: { engine: "sherpa-onnx", segmentationModel: "seg.onnx", embeddingModel: "emb.onnx", threshold: 0.9 }, ...(voiceprints ? { voiceprints: VOICEPRINTS } : {}), }); } let n = 0; async function corpus() { const dir = path.join(ROOT, `c${n++}`); const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, ytdlpBin: path.join(dir, "no-such-ytdlp"), } as unknown as Paths; await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); await writeFile(path.join(paths.channelsDir, "ch", "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.youtube.com/@ch" })); const video = async ( id: string, o: { transcript?: boolean; diarization?: "none" | "plain" | "voiceprints"; doNotClean?: boolean; gone?: boolean; bytes?: number; // Named in a fresh availability listing of the channel (the verdict the // automatic clean always reads). Default true; false = never listed. listed?: boolean; } = {}, ) => { const v = path.join(paths.channelsDir, "ch", "data", id); await mkdir(v, { recursive: true }); if (o.transcript !== false) await writeFile(path.join(v, "transcript.json"), "{}"); await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(o.bytes ?? 1000)); if (o.diarization === "plain") await writeFile(path.join(v, "diarization.json"), sidecar(false)); if (o.diarization === "voiceprints") await writeFile(path.join(v, "diarization.json"), sidecar(true)); if (o.doNotClean) await writeFile(path.join(v, "do-not-clean.json"), JSON.stringify({ setAt: "now" })); if (o.listed !== false) { const cur = await readAvailabilityVerdict(paths, "ch"); await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: [...(cur?.ids ?? []), id] }); } if (o.gone) { await writeFile(path.join(v, "availability.json"), JSON.stringify({ checkedAt: new Date().toISOString(), availability: "deleted" })); } return v; }; return { paths, video }; } const exists = (f: string) => access(f).then(() => true, () => false); test("Clean audio holds a diarized video whose sidecar has no voice fingerprints, and says so", async () => { await settings({}); const { paths, video } = await corpus(); const plain = await video("plain", { diarization: "plain" }); const done = await video("done", { diarization: "voiceprints", bytes: 4096 }); const logs: string[] = []; const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => logs.push(m) }); assert.equal(await exists(path.join(plain, "audio.mp3")), true, "awaiting its fingerprint"); assert.equal(await exists(path.join(done, "audio.mp3")), false); assert.equal(r.awaitingVoiceprint, 1); assert.equal(r.bytesFreed, 4096); assert.ok(logs.includes("Skipped plain (awaiting voice fingerprint)")); assert.ok( logs.some((l) => l.endsWith("Skipped 1 (0 protected, 0 gone-from-source pinned, 0 unverified, 1 awaiting voice fingerprint).")), logs.join("\n"), ); }); test("requireVoiceprints off: the old rule — a diarization.json is enough", async () => { await settings({ requireVoiceprints: false }); const { paths, video } = await corpus(); const plain = await video("plain", { diarization: "plain" }); const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {} }); assert.equal(await exists(path.join(plain, "audio.mp3")), false); assert.equal(r.awaitingVoiceprint, 0); }); test("defaults: requireVoiceprints ON, cleanAfterCapture OFF", () => { assert.equal(defaultSiteSettings().diarization.requireVoiceprints, true); assert.equal(defaultSiteSettings().diarization.cleanAfterCapture, false); }); test("cleanAudioForVideo keeps every gate of the channel sweep", async () => { await settings({}, { verifyAvailabilityBeforeClean: true }); const { paths, video } = await corpus(); await video("untranscribed", { transcript: false, diarization: "voiceprints" }); await video("pinned", { diarization: "voiceprints", doNotClean: true }); await video("nodiar"); await video("plain", { diarization: "plain" }); const gone = await video("gone", { diarization: "voiceprints", gone: true }); const ok = await video("ok", { diarization: "voiceprints", bytes: 2048 }); await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: ["ok", "gone"] }); const one = (videoId: string) => cleanAudioForVideo({ channelSlug: "ch", paths, videoId, onLog: () => {}, checkDeps: NO_NETWORK }); assert.deepEqual(await one("untranscribed"), { outcome: "held", gate: "no-transcript", removedFiles: 0, bytesFreed: 0 }); assert.equal((await one("pinned")).gate, "do-not-clean"); assert.equal((await one("nodiar")).gate, "awaiting-diarization"); assert.equal((await one("plain")).gate, "awaiting-voiceprint"); // Gone upstream: pinned do-not-clean, audio kept. assert.equal((await one("gone")).outcome, "pinned"); assert.equal(await exists(path.join(gone, "audio.mp3")), true); assert.equal(await exists(path.join(gone, "do-not-clean.json")), true); assert.deepEqual(await one("ok"), { outcome: "cleaned", removedFiles: 1, bytesFreed: 2048 }); assert.equal(await exists(path.join(ok, "audio.mp3")), false); }); // ---- the hook: a diarization unit that returns done -------------------------- function fakeDiarization(write: "voiceprints" | "plain"): Operation { return { id: "diarization", lane: { queueKey: "backfill", contendsFor: "cpu" }, resolveTarget: () => ({}), state: async () => "missing", run: async ({ videoDir }: { videoDir: string }) => { await writeFile(path.join(videoDir, "diarization.json"), sidecar(write === "voiceprints")); return "done"; }, inputs: () => [], outputs: ["diarization.json"], } as unknown as Operation; } function fakeRun(paths: Paths): OperationRun { return { lane: "backfill", paths, settings: getSettings(), force: false, allowRedownload: false, live: { llmActive: 0, unitActive: 0, costUsd: 0, diskFloorHit: false }, backfill: { targets: new Map(), llmFanout: null }, log: () => {}, } as unknown as OperationRun; } test("clean after capture: on, a captured video's audio goes at once, counted and ledgered", async () => { await settings({ cleanAfterCapture: true }); const { paths, video } = await corpus(); const v = await video("v1", { bytes: 5000 }); const logs: string[] = []; const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("voiceprints") }, { onLog: (m) => logs.push(m) }); assert.equal(report.outcome, "done"); assert.equal(await exists(path.join(v, "audio.mp3")), false); assert.equal(report.audioCleaned, 1); assert.equal(report.audioFreedBytes, 5000); const ledger = await readSpeakersLedger(paths); // Runtime state, at a dot path beside the corpus root's others. assert.equal(await exists(path.join(paths.transcriptsDir, ".speakers-run.json")), true); assert.equal(ledger.freedBytes, 5000); assert.equal(ledger.freedVideos, 1); assert.ok(logs.some((l) => l.startsWith("Freed 4.9 KB of audio from v1")), logs.join("\n")); }); test("clean after capture: never before the fingerprint exists", async () => { await settings({ cleanAfterCapture: true, requireVoiceprints: false }); const { paths, video } = await corpus(); const v = await video("v1"); const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("plain") }, { onLog: () => {} }); assert.equal(report.outcome, "done"); assert.equal(await exists(path.join(v, "audio.mp3")), true); assert.equal(report.audioCleaned, 0); }); test("clean after capture: off by default, and a protected video stays protected", async () => { await settings({}); const { paths, video } = await corpus(); const a = await video("v1"); await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("voiceprints") }, { onLog: () => {} }); assert.equal(await exists(path.join(a, "audio.mp3")), true, "off by default"); await settings({ cleanAfterCapture: true }); const b = await video("v2", { doNotClean: true }); const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v2", op: fakeDiarization("voiceprints") }, { onLog: () => {} }); assert.equal(await exists(path.join(b, "audio.mp3")), true, "do-not-clean holds"); assert.equal(report.audioCleaned, 0); }); test("cleanAudioForVideo: an unmounted media drive keeps the audio link where it is", async () => { await settings({}); const { paths, video } = await corpus(); const v = await video("v1", { diarization: "voiceprints" }); // Tier the audio by hand onto a "drive" that is not mounted: a dangling // media link and a relative link into it, as mediaTier writes them. await rm(path.join(v, "audio.mp3")); const channelDir = path.join(paths.channelsDir, "ch"); const target = path.join(ROOT, "platter-not-mounted", "ch", "media"); await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.youtube.com/@ch", mediaDir: target })); await symlink(target, path.join(channelDir, "media")); await symlink("../../media/v1/audio.mp3", path.join(v, "audio.mp3")); const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {} }); assert.deepEqual(out, { outcome: "held", gate: "media-unreachable", removedFiles: 0, bytesFreed: 0 }); assert.ok((await lstat(path.join(v, "audio.mp3"))).isSymbolicLink(), "the link is untouched"); }); test("cleanAudioForVideo removes the audio and nothing else: no source media, clip, transcript, sidecar or saved-video pointer", async () => { await settings({}); const { paths, video } = await corpus(); const v = await video("v1", { diarization: "voiceprints" }); const keep = ["source-media.mp4", "transcript.json", "transcript.cues.json", "diarization.json", "saved-video.json"]; for (const f of keep.filter((f) => !["transcript.json", "diarization.json"].includes(f))) await writeFile(path.join(v, f), "keep"); await mkdir(path.join(v, "clips")); await writeFile(path.join(v, "clips", "10.00-20.00.m4a"), "clip"); const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {} }); assert.equal(out.outcome, "cleaned"); assert.equal(await exists(path.join(v, "audio.mp3")), false); for (const f of keep) assert.equal(await exists(path.join(v, f)), true, f); assert.equal(await readFile(path.join(v, "clips", "10.00-20.00.m4a"), "utf8"), "clip"); }); // ---- B1: the availability verdict cache, never a listing per video ------------ test("no fresh listing: N captured videos of one channel are held, and at most ONE check is asked for", async () => { await settings({}, { verifyAvailabilityBeforeClean: true }); const { paths, video } = await corpus(); const ids = ["a1", "a2", "a3", "a4", "a5"]; for (const id of ids) await video(id, { diarization: "voiceprints", listed: false }); const started: string[] = []; const deps: CheckRequestDeps = { start: async (_p, slug) => { started.push(slug); return { ok: true, jobId: "job-1" } as never; }, platformRefusal: async () => null, }; for (const id of ids) { const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: id, onLog: () => {}, checkDeps: deps }); assert.equal(out.gate, "awaiting-availability", id); } assert.deepEqual(started, ["ch"], "one check, on the channel, for five videos"); for (const id of ids) assert.equal(await exists(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")), true); assert.equal(typeof (await readAvailabilityVerdict(paths, "ch"))?.requestedAt, "string"); // An OLD listing is no listing: still held, and the request is not repeated // inside the max age. await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date(Date.now() - 48 * 3_600_000).toISOString(), ids }); assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: deps })).gate, "awaiting-availability"); assert.equal(started.length, 1); // The check lands (a fresh listing naming them): cleaned, nothing asked. await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: ["a1", "a2"] }); assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: deps })).outcome, "cleaned"); // A fresh listing that does NOT name a video holds it: maybe missing. assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a3", onLog: () => {}, checkDeps: deps })).gate, "maybe-missing"); assert.equal(started.length, 1); }); test("a held platform: the video is held, nothing deleted, nothing requested", async () => { await settings({}, { verifyAvailabilityBeforeClean: true }); const { paths, video } = await corpus(); const v = await video("v1", { diarization: "voiceprints", listed: false }); let started = 0; const logs: string[] = []; const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: (m) => logs.push(m), checkDeps: { start: async () => { started++; return { ok: true, jobId: "x" } as never; }, platformRefusal: async (platform) => `${platform} is held after a 429`, }, }); assert.equal(out.gate, "awaiting-availability"); assert.equal(started, 0); assert.equal(await exists(path.join(v, "audio.mp3")), true); assert.equal((await readAvailabilityVerdict(paths, "ch"))?.requestedAt, undefined, "not even marked as asked"); assert.ok(logs.some((l) => l.includes("youtube is held after a 429")), logs.join("\n")); }); // ---- B2: a channel with no source URL --------------------------------------- test("no source URL: the automatic clean holds; the channel's opt-in lets it through; the manual sweep is unchanged", async () => { await settings({}, { verifyAvailabilityBeforeClean: true }); const { paths, video } = await corpus(); const cfg = path.join(paths.channelsDir, "ch", "config.json"); await writeFile(cfg, JSON.stringify({ handling: "transcribe", name: "ch" })); const a = await video("a1", { diarization: "voiceprints" }); const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: NO_NETWORK }); assert.deepEqual(out, { outcome: "held", gate: "no-source-url", removedFiles: 0, bytesFreed: 0 }); assert.equal(await exists(path.join(a, "audio.mp3")), true); await writeFile(cfg, JSON.stringify({ handling: "transcribe", name: "ch", cleanAfterCaptureUnverified: true })); assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: NO_NETWORK })).outcome, "cleaned"); // The manual sweep: as today — a channel with no URL cannot be verified and // is cleaned (verifyBeforeClean fails open), opt-in or not. await writeFile(cfg, JSON.stringify({ handling: "transcribe", name: "ch" })); const b = await video("b1", { diarization: "voiceprints" }); const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {} }); assert.equal(r.cleanedDirs, 1); assert.equal(await exists(path.join(b, "audio.mp3")), false); }); // ---- whole-recording platforms ------------------------------------------------ test("a whole-recording channel (Rumble): clean after capture holds its audio — the recording clock's source — unless cleanWholeRecordingAudio", async () => { await settings({}, { verifyAvailabilityBeforeClean: false }); const { paths, video } = await corpus(); await writeFile( path.join(paths.channelsDir, "ch", "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://rumble.com/c/ch" }), ); const v = await video("v1", { diarization: "voiceprints" }); const held = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {}, checkDeps: NO_NETWORK }); assert.deepEqual(held, { outcome: "held", gate: "whole-recording", removedFiles: 0, bytesFreed: 0 }); assert.equal(await exists(path.join(v, "audio.mp3")), true); assert.equal(defaultSiteSettings().diarization.cleanWholeRecordingAudio, false); await settings({ cleanWholeRecordingAudio: true }, { verifyAvailabilityBeforeClean: false }); assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {}, checkDeps: NO_NETWORK })).outcome, "cleaned"); }); test("the automatic clean requires the verdict even with verifyAvailabilityBeforeClean off (that setting is the manual sweep's)", async () => { await settings({}, { verifyAvailabilityBeforeClean: false }); const { paths, video } = await corpus(); const v = await video("v1", { diarization: "voiceprints", listed: false }); let started = 0; const deps: CheckRequestDeps = { start: async () => { started++; return { ok: true, jobId: "x" } as never; }, platformRefusal: async () => null, }; const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {}, checkDeps: deps }); assert.equal(out.gate, "awaiting-availability"); assert.equal(started, 1); assert.equal(await exists(path.join(v, "audio.mp3")), true); // …while the manual sweep, with the setting off, cleans without asking. const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {} }); assert.equal(r.cleanedDirs, 1); }); test("an open service alert for the platform: held \"awaiting an availability check (service alert open)\", nothing requested", async () => { await settings({}); const { paths, video } = await corpus(); const v = await video("v1", { diarization: "voiceprints", listed: false }); let started = 0; const logs: string[] = []; const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: (m) => logs.push(m), checkDeps: { start: async () => { started++; return { ok: true, jobId: "x" } as never; }, platformRefusal: async () => null, serviceAlert: async (platform) => (platform === "youtube" ? "Sign in to confirm you're not a bot" : null), }, }); assert.equal(out.gate, "awaiting-availability"); assert.equal(started, 0); assert.equal((await readAvailabilityVerdict(paths, "ch"))?.requestedAt, undefined); assert.equal(await exists(path.join(v, "audio.mp3")), true); assert.ok(logs.some((l) => l.includes("awaiting an availability check (service alert open: Sign in to confirm")), logs.join("\n")); }); test("the real alert store: a raised yt-dlp service alert for the channel's platform is read", async () => { await settings({}); const { paths, video } = await corpus(); await video("v1", { diarization: "voiceprints", listed: false }); await writeFile( path.join(paths.transcriptsDir, ".service-cookies.json"), JSON.stringify({ version: 1, services: { youtube: { since: new Date().toISOString(), raisedAt: new Date().toISOString(), kind: "challenge", evidence: { line: "bot check", at: new Date().toISOString() }, signals: 3 } } }), ); const asked = await requestAvailabilityCheck(paths, "ch", 24, { start: async () => { throw new Error("must not start"); }, platformRefusal: async () => null, }); assert.equal(asked.status, "service-alert"); }); test.after(() => rm(ROOT, { recursive: true, force: true })); test("concurrency stays 1: one diarization at a time, one backfill unit at a time", () => { // Load-bearing (plans/FACTS.md): two sherpa runs at once doubled the 11 GB // transients that OOM-killed the box; the Speakers lane runs beside GPU // transcription on four of eight threads. assert.equal(defaultSiteSettings().diarization.concurrency, 1); assert.equal(defaultSiteSettings().backfill.concurrency, 1); });