import { test } from "node:test"; import assert from "node:assert/strict"; import { access, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { DoNotCleanRecord } from "../lib/doNotClean"; import { loadDoNotClean, recordDoNotCleanAudioRemoved, relabelDoNotCleanInferred, setDoNotClean, } from "../lib/doNotClean-server"; import { addPendingKeep, applyPendingKeep } from "../lib/pendingKeep-server"; import { cleanConfirmationText, sourceGoneOptInLabel } from "../lib/cleanAudioConfirm"; import { cleanAudioForVideo, cleanAudioFromTranscribed, planAudioClean } from "./cleanAudioFromTranscribed"; import { cleanAudioRequestFor, planCountsLine, replayCleanSpec, runCleanAudioJob } from "./cleanAudioJob"; import { verifyBeforeClean, type VerifyProbes } from "./verifyBeforeClean"; import { checkKeptDeleted } from "./checkKeptDeleted"; import { keepVideosByIds, keepVideosMatching } from "./keepVideosMatching"; import { backfillMarkProvenance, MARK_PROOF_WINDOW_MS } from "./marksBackfill"; import type { CheckRequestDeps } from "./availabilityVerdict"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/markProvenance.test.ts // // LANE MARK-PROVENANCE. Who set a do-not-clean mark, recorded by every writer; // the backfill that relabels an old mark only on proof from other records; and // the unchecked clean's explicit opt-in that removes audio kept ONLY because // the source was gone — never reaching a mark anything else set. Temp corpus, // temp settings, synthetic ids; every probe a stub. const ROOT = await mkdtemp(path.join(tmpdir(), "mark-provenance-")); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); process.env.E2E_AVAILABILITY_PROBE_GAP_MS = "0"; await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ verifyAvailabilityBeforeClean: true, diarization: { enabled: false } })); const exists = (f: string) => access(f).then(() => true, () => false); const mark = async (dir: string) => (await loadDoNotClean(dir)) as DoNotCleanRecord; const NO_CHECK: CheckRequestDeps = { start: async () => { throw new Error("a test asked for a real availability check"); }, platformRefusal: async () => null, serviceAlert: async () => null, }; const THROWING: VerifyProbes = { quick: async () => { throw new Error("the source was asked"); }, full: async () => { throw new Error("the source was asked"); }, recordBackoff: async () => {}, }; let n = 0; async function corpus(config: Record = {}) { const dir = path.join(ROOT, `c${n++}`); const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, jobsDir: path.join(dir, ".jobs"), savedVideosDir: path.join(dir, "saved"), ytdlpBin: path.join(dir, "no-such-ytdlp"), } as unknown as Paths; await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); await mkdir(paths.jobsDir, { recursive: true }); await writeFile( path.join(paths.channelsDir, "ch", "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.twitch.tv/example", ...config }), ); const video = async ( id: string, o: { transcript?: boolean; audio?: number; mark?: Record; availability?: Record; uploadDate?: string } = {}, ) => { const v = path.join(paths.channelsDir, "ch", "data", id); await mkdir(v, { recursive: true }); if (o.uploadDate) await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id, title: id, upload_date: o.uploadDate })); if (o.transcript !== false) await writeFile(path.join(v, "transcript.json"), "{}"); if (o.audio !== 0) await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(o.audio ?? 1000)); if (o.mark) await writeFile(path.join(v, "do-not-clean.json"), JSON.stringify(o.mark)); if (o.availability) await writeFile(path.join(v, "availability.json"), JSON.stringify(o.availability)); return v; }; const job = async (id: string, meta: Record, log: string) => { await writeFile(path.join(paths.jobsDir, `${id}.meta.json`), JSON.stringify({ id, queueKey: "channel:ch", status: "done", queuedAt: 0, ...meta })); await writeFile(path.join(paths.jobsDir, `${id}.log`), log); }; return { paths, video, job }; } // --- The one writer --------------------------------------------------------- test("the writer: a mark needs its writer; availability-check never replaces a mark; a person's replaces and keeps what was removed", async () => { const { video } = await corpus(); const v = await video("w1"); await assert.rejects( // @ts-expect-error — no provenance: refused by the type and at run time. setDoNotClean(v, true), /needs its writer/, ); assert.equal(await setDoNotClean(v, true, { by: "operator", via: "toggle", surface: "button", note: "mine" }), true); assert.equal(await setDoNotClean(v, true, { by: "availability-check", via: "pre-clean-check", note: "gone" }), false); assert.deepEqual({ ...(await mark(v)), setAt: "x" }, { setAt: "x", note: "mine", by: "operator", via: "toggle", surface: "button" }); const g = await video("w2"); assert.equal(await setDoNotClean(g, true, { by: "availability-check", via: "pre-clean-check", jobId: "J1" }), true); assert.equal(await recordDoNotCleanAudioRemoved(g, { at: "t", files: ["audio.mp3"], bytes: 5, why: "w" }), true); await setDoNotClean(g, true, { by: "live-recording", via: "record-live", jobId: "J2" }); const after = await mark(g); assert.equal(after.by, "live-recording"); assert.equal(after.jobId, "J2"); assert.equal(after.audioRemoved?.length, 1, "the removal stays on record"); // An annotation reaches only a mark by the availability check. assert.equal(await recordDoNotCleanAudioRemoved(g, { at: "t", files: [], bytes: 0, why: "w" }), false); // An unknown `by` reads as the operator's. await writeFile(path.join(g, "do-not-clean.json"), JSON.stringify({ setAt: "s", by: "robot" })); assert.equal((await mark(g)).by, undefined); }); // --- Every writer's `by` ---------------------------------------------------- test("verifyBeforeClean: tier A and tier C pins say availability-check / pre-clean-check with the job", async () => { const { paths, video } = await corpus(); const cached = await video("cachedgone", { availability: { checkedAt: "2026-01-01T00:00:00.000Z", availability: "private" } }); const suspect = await video("suspect"); const probes: VerifyProbes = { quick: async () => ({ knownCount: 2, freshCount: 1, maybeMissingCount: 1, ids: ["suspect"] }), full: (async () => { await writeFile(path.join(suspect, "availability.json"), JSON.stringify({ checkedAt: new Date().toISOString(), checkedBy: "check", availability: "deleted" })); return { attempted: 1, checked: 1, skipped: 0, byStatus: {}, blocked: false, probedIds: ["suspect"] }; }) as unknown as VerifyProbes["full"], }; const v = await verifyBeforeClean({ channelSlug: "ch", paths, candidateIds: ["cachedgone", "suspect"], probes, jobId: "JOB-A", onLog: () => {} }); assert.deepEqual([...v.pinned.keys()].sort(), ["cachedgone", "suspect"]); for (const dir of [cached, suspect]) { const m = await mark(dir); assert.equal(m.by, "availability-check"); assert.equal(m.via, "pre-clean-check"); assert.equal(m.jobId, "JOB-A"); } }); test("clean after capture pins as availability-check / clean-after-capture; the keep-latest check as kept-deleted-check", async () => { const { paths, video } = await corpus({ keepLatest: 1 }); const v = await video("capgone", { availability: { checkedAt: "2026-01-01T00:00:00.000Z", availability: "deleted" }, uploadDate: "20260101" }); // In the keep-latest window: the kept-deleted check pins it. const k = await checkKeptDeleted({ channelSlug: "ch", paths, onLog: () => {}, jobId: "JOB-K" }); assert.equal(k.pinned, 1); assert.deepEqual({ by: (await mark(v)).by, via: (await mark(v)).via, jobId: (await mark(v)).jobId }, { by: "availability-check", via: "kept-deleted-check", jobId: "JOB-K" }); const c2 = await corpus(); const w = await c2.video("capgone2", { availability: { checkedAt: "2026-01-01T00:00:00.000Z", availability: "deleted" } }); const r = await cleanAudioForVideo({ channelSlug: "ch", paths: c2.paths, videoId: "capgone2", onLog: () => {}, checkDeps: NO_CHECK }); assert.equal(r.outcome, "pinned"); assert.equal((await mark(w)).by, "availability-check"); assert.equal((await mark(w)).via, "clean-after-capture"); }); test("keep-videos (by pattern, by ids, pending) and its surfaces say operator", async () => { const { paths, video } = await corpus(); const a = await video("kmatch", { uploadDate: "20260101" }); await writeFile(path.join(a, "metadata.info.json"), JSON.stringify({ id: "kmatch", title: "keep me", description: "" })); await keepVideosMatching({ paths, channelSlug: "ch", pattern: "keep me" }); assert.deepEqual({ by: (await mark(a)).by, via: (await mark(a)).via, surface: (await mark(a)).surface }, { by: "operator", via: "keep-videos-match", surface: "ops" }); const b = await video("kids"); const r = await keepVideosByIds({ paths, channelSlug: "ch", ids: ["kids", "notyet"], surface: "button" }); assert.deepEqual(r.pending, ["notyet"]); assert.deepEqual({ by: (await mark(b)).by, via: (await mark(b)).via, surface: (await mark(b)).surface }, { by: "operator", via: "keep-videos-ids", surface: "button" }); // The pending one lands later (an import's job): operator / pending-keep, the surface carried. const c = await video("notyet"); assert.equal(await applyPendingKeep(paths, "ch", "notyet", undefined, "JOB-LAND"), true); assert.deepEqual( { by: (await mark(c)).by, via: (await mark(c)).via, surface: (await mark(c)).surface, jobId: (await mark(c)).jobId }, { by: "operator", via: "pending-keep", surface: "button", jobId: "JOB-LAND" }, ); // An entry from before surfaces were recorded: no surface, still operator. await addPendingKeep(paths, "ch", ["old"], "n"); const d = await video("old"); await applyPendingKeep(paths, "ch", "old"); assert.equal((await mark(d)).by, "operator"); assert.equal((await mark(d)).surface, undefined); }); // --- The gate: one writer --------------------------------------------------- test("the opt-in plan: only marks by the availability check are in the group, inferred counted apart; legacy, operator, import, live never", async () => { const { paths, video } = await corpus(); await video("plain", { audio: 100 }); await video("gone", { audio: 200, mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); await video("goneinf", { audio: 300, mark: { setAt: "s", by: "availability-check", via: "pre-clean-check", inferred: true } }); await video("legacy", { audio: 400, mark: { setAt: "s", note: "deleted from source (pre-clean check): deleted" } }); await video("person", { audio: 500, mark: { setAt: "s", by: "operator", via: "toggle", surface: "button" } }); await video("imp", { audio: 600, mark: { setAt: "s", by: "import", via: "import-media" } }); await video("live", { audio: 700, mark: { setAt: "s", by: "live-recording", via: "record-live" } }); const plan = await planAudioClean({ channelSlug: "ch", paths }); assert.deepEqual(plan.ids, ["plain"]); assert.equal(plan.protected, 6, "every mark is kept without the opt-in"); assert.deepEqual(plan.sourceGone, { ids: ["gone", "goneinf"], videos: 2, files: 2, bytes: 500, inferred: { ids: ["goneinf"], videos: 1, files: 1, bytes: 300 }, }); const off = cleanConfirmationText(plan); assert.equal(off.sourceGone, null); assert.equal(off.button, "Remove 1 file without checking"); assert.match(off.kept, /^Kept: 6 marked do not clean or in the keep-latest window \(2 of them only because the source was gone\), /); assert.equal(sourceGoneOptInLabel(plan.sourceGone), "Also remove audio kept only because the source was gone (2 videos, 2 files, 500 B)"); const on = cleanConfirmationText(plan, { includeSourceGone: true }); assert.equal( on.sourceGone, "Also removed, kept only because the source was gone: 2 audio files (500 B) from 2 videos the availability check marked do not clean. Their marks stay. " + "Of these, 1 video (1 file, 300 B) carry marks inferred from the records (marks-backfill), not written by the check itself.", ); assert.equal(on.button, "Remove 3 files without checking"); assert.equal(on.files, 3); assert.match(on.kept, /^Kept: 4 marked do not clean/); assert.match(on.kept, /A mark set by a person, an import or a live recording is never touched\.$/); }); test("the opt-in run: removes only the confirmed source-gone group, the marks stay and record it; nothing else is reachable", async () => { const { paths, video } = await corpus(); const plain = await video("plain"); const gone = await video("gone", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); const goneinf = await video("goneinf", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check", inferred: true } }); const notAsked = await video("notasked", { mark: { setAt: "s", by: "availability-check", via: "kept-deleted-check" } }); const legacy = await video("legacy", { mark: { setAt: "s", note: "deleted from source (pre-clean check): deleted" } }); const person = await video("person", { mark: { setAt: "s", by: "operator", via: "toggle" } }); const imp = await video("imp", { mark: { setAt: "s", by: "import", via: "import-media" } }); const live = await video("live", { mark: { setAt: "s", by: "live-recording", via: "record-live" } }); const logs: string[] = []; const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, unchecked: "button", onlyIds: ["plain"], // A caller that names other kinds of marks too reaches none of them. sourceGone: ["gone", "goneinf", "legacy", "person", "imp", "live"], jobId: "JOB-U", probes: THROWING, onLog: (m) => logs.push(m), }); for (const d of [plain, gone, goneinf]) assert.equal(await exists(path.join(d, "audio.mp3")), false); for (const d of [notAsked, legacy, person, imp, live]) assert.equal(await exists(path.join(d, "audio.mp3")), true, d); for (const d of [gone, goneinf]) { const m = await mark(d); assert.equal(m.by, "availability-check", "the mark stays"); assert.equal(m.audioRemoved?.length, 1); assert.equal(m.audioRemoved![0].jobId, "JOB-U"); assert.deepEqual(m.audioRemoved![0].files, ["audio.mp3"]); assert.match(m.audioRemoved![0].why, /also remove audio kept only because the source was gone/); } assert.match((await mark(goneinf)).audioRemoved![0].why, /inferred from the records/); assert.deepEqual(r.sourceGoneRemoved, { videos: 2, files: 2, bytes: 2000, inferredVideos: 1 }); assert.equal(r.cleanedDirs, 3); assert.ok(logs.some((l) => l.startsWith("Also remove audio kept only because the source was gone (confirmed): 6 video(s) asked, 2 still marked")), logs.join("\n")); }); test("the opt-in is honoured only by a confirmed unchecked clean: not checked, not the channel key, not without it", async () => { for (const mode of [undefined, "channel-setting"] as const) { const { paths, video } = await corpus(); const gone = await video("gone", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); const probes: VerifyProbes = { quick: async () => ({ knownCount: 1, freshCount: 1, maybeMissingCount: 0, ids: [] }) }; const logs: string[] = []; await cleanAudioFromTranscribed({ channelSlug: "ch", paths, ...(mode ? { unchecked: mode } : {}), sourceGone: ["gone"], probes, onLog: (m) => logs.push(m) }); assert.equal(await exists(path.join(gone, "audio.mp3")), true, String(mode)); assert.ok(logs.some((l) => l.startsWith("Audio kept only because the source was gone is NOT removed")), logs.join("\n")); } // A button clean without the opt-in: kept, and logged as any mark is. const { paths, video } = await corpus(); const gone = await video("gone", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); const logs: string[] = []; await cleanAudioFromTranscribed({ channelSlug: "ch", paths, unchecked: "button", onlyIds: [], probes: THROWING, onLog: (m) => logs.push(m) }); assert.equal(await exists(path.join(gone, "audio.mp3")), true); assert.ok(logs.includes("Skipped gone (marked do not clean)"), logs.join("\n")); // The request: only an explicit button carries it. assert.equal(cleanAudioRequestFor({ cleanAudioWithoutChecking: true } as never, { sourceGone: ["gone"] }).sourceGone, undefined); assert.deepEqual(cleanAudioRequestFor(null, { explicit: "button", plan: [], sourceGone: ["gone"] }).sourceGone, ["gone"]); }); test("the opt-in: a mark a person set since the plan, or a speaker hold, keeps the audio", async () => { await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ diarization: { enabled: true, segModel: "/m/s.onnx", embModel: "/m/e.onnx" } })); try { const { paths, video } = await corpus(); const held = await video("held", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); const remarked = await video("remarked", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); await writeFile( path.join(remarked, "diarization.json"), JSON.stringify({ videoId: "remarked", 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: [{ speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb.onnx" }], }), ); const plan = await planAudioClean({ channelSlug: "ch", paths }); assert.deepEqual(plan.sourceGone.ids, ["remarked"], "awaiting diarization stays held under its mark"); // A person re-marks it after the plan was counted. await setDoNotClean(remarked, true, { by: "operator", via: "toggle", surface: "button" }); await cleanAudioFromTranscribed({ channelSlug: "ch", paths, unchecked: "button", onlyIds: [], sourceGone: ["held", "remarked"], probes: THROWING, onLog: () => {} }); assert.equal(await exists(path.join(held, "audio.mp3")), true); assert.equal(await exists(path.join(remarked, "audio.mp3")), true); assert.equal((await mark(remarked)).audioRemoved, undefined); } finally { await writeFile(process.env.SETTINGS_FILE!, JSON.stringify({ verifyAvailabilityBeforeClean: true, diarization: { enabled: false } })); } }); test("the opt-in: a person who re-marks the video after discover (just before removal) keeps its audio", async () => { const { paths, video } = await corpus(); const v = await video("race", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); const logs: string[] = []; await cleanAudioFromTranscribed({ channelSlug: "ch", paths, unchecked: "button", onlyIds: [], sourceGone: ["race"], probes: THROWING, // The media guard runs between discover and the removals: the person acts then. assertReachable: async () => { await setDoNotClean(v, true, { by: "operator", via: "toggle", surface: "button" }); }, onLog: (m) => logs.push(m), }); assert.equal(await exists(path.join(v, "audio.mp3")), true); assert.equal((await mark(v)).by, "operator"); assert.ok(logs.includes("Skipped race (marked do not clean — no longer by the availability check)"), logs.join("\n")); }); test("the job: a button job carries the opt-in into the sweep and logs its counts; a retry and a replay never carry it", async () => { const { paths, video } = await corpus(); const gone = await video("gone", { mark: { setAt: "s", by: "availability-check", via: "pre-clean-check" } }); const logs: string[] = []; const counts = { files: 0, bytes: 0, videos: 0, protected: 1, awaitingDiarization: 0, awaitingVoiceprint: 0, sourceGone: { videos: 1, files: 1, bytes: 1000, inferred: { videos: 0, files: 0, bytes: 0 } } }; const out = await runCleanAudioJob({ channelSlug: "ch", paths, jobId: "JOB-B", unchecked: "button", plan: [], planCounts: counts, sourceGone: ["gone"], onLog: (m) => logs.push(m), deps: { scheduleRetry: async () => ({ ok: false, error: "no" }), probes: THROWING }, }); assert.equal(out.end, "done"); assert.equal(await exists(path.join(gone, "audio.mp3")), false); assert.equal((await mark(gone)).audioRemoved?.[0].jobId, "JOB-B"); assert.ok(logs.includes(planCountsLine(counts)), logs.join("\n")); assert.match(planCountsLine(counts), /kept: 0 marked do not clean .* Also, kept only because the source was gone: 1 audio file\(s\) \(1000 bytes\) from 1 video\(s\) \(0 of them/); // Replay of a button job on a key-on channel: the plan only. const calls: unknown[][] = []; await replayCleanSpec( { kind: "clean-audio-unchecked", slug: "ch", params: { unchecked: "button", plan: ["a"], sourceGone: ["gone"] } }, { readConfig: async () => ({ cleanAudioWithoutChecking: true }) as never, clean: async (...a) => calls.push(["clean", ...a]), unchecked: async (...a) => calls.push(["unchecked", ...a]), }, ); assert.deepEqual(calls, [["unchecked", "ch", undefined, ["a"]]]); }); // --- The backfill ----------------------------------------------------------- const SET_AT = "2026-10-20T10:00:30.000Z"; const T0 = Date.parse("2026-10-20T10:00:00.000Z"); async function provable(c: Awaited>, id = "pv") { const v = await c.video(id, { mark: { setAt: SET_AT, note: "anything at all" }, availability: { checkedAt: "2026-11-01T00:00:00.000Z", checkedBy: "check", availability: "deleted", history: [ { availability: "public", observedAt: "2026-01-01T00:00:00.000Z", source: "backfill" }, { availability: "deleted", observedAt: "2026-10-20T10:00:10.000Z", source: "check" }, ], }, }); return v; } test("backfill: relabels only on both proofs, dry run first, with its evidence; never from the note", async () => { const c = await corpus(); const v = await provable(c); await c.job("J-CLEAN", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: T0, endedAt: T0 + 120_000 }, `Verify before clean: …\nPinned pv as do-not-clean (deleted) — gone from source.\n`); const dry = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch" }); assert.equal(dry.dryRun, true); assert.deepEqual(dry.relabelled, [ { id: "pv", setAt: SET_AT, evidence: { availability: "deleted", observedAt: "2026-10-20T10:00:10.000Z", field: "history", jobId: "J-CLEAN", jobKind: "clean-audio-transcribed" } }, ]); assert.equal((await mark(v)).by, undefined, "a dry run writes nothing"); const real = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false, now: new Date("2026-11-21T00:00:00.000Z") }); assert.equal(real.relabelled.length, 1); const m = await mark(v); assert.deepEqual(m, { setAt: SET_AT, note: "anything at all", by: "availability-check", via: "pre-clean-check", inferred: true, inferredAt: "2026-11-21T00:00:00.000Z", evidence: real.relabelled[0].evidence, }); // Labelled now: a second run leaves it. const again = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false }); assert.deepEqual([again.labelled, again.relabelled.length], [1, 0]); }); test("backfill refuses: note only, a check far from the mark, no job, a job of another kind or channel or time, a line for another id", async () => { const c = await corpus(); // The gate's own note text, and nothing else: not proof. await c.video("noteonly", { mark: { setAt: SET_AT, note: "deleted from source (pre-clean check): deleted" } }); // A tier-A pin: the check ran weeks before the mark. await c.video("cached", { mark: { setAt: SET_AT, note: "deleted from source (pre-clean check): deleted" }, availability: { checkedAt: "2026-09-01T00:00:00.000Z", checkedBy: "check", availability: "deleted", history: [{ availability: "deleted", observedAt: "2026-09-01T00:00:00.000Z", source: "check" }] }, }); // A record that never said gone. await c.video("public", { mark: { setAt: SET_AT }, availability: { checkedAt: SET_AT, checkedBy: "check", availability: "public" } }); // Gone within the minute, but by a backfill, not a check. await c.video("assumed", { mark: { setAt: SET_AT }, availability: { checkedAt: SET_AT, checkedBy: "backfill", availability: "deleted", history: [{ availability: "deleted", observedAt: SET_AT, source: "backfill" }] } }); // Both halves would hold, but the only job naming it is the keep-latest check, another channel's clean, or one not running then. await provable(c, "wrongjob"); await c.job("J-KEPT", { kind: "check-kept-deleted", channelSlug: "ch", startedAt: T0, endedAt: T0 + 60_000 }, "Pinned wrongjob as do-not-clean (deleted).\n"); await c.job("J-OTHER", { kind: "clean-audio-transcribed", channelSlug: "other", startedAt: T0, endedAt: T0 + 60_000 }, "Pinned wrongjob as do-not-clean (deleted) — gone from source.\n"); await c.job("J-LATE", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: T0 + 10 * 60_000, endedAt: T0 + 11 * 60_000 }, "Pinned wrongjob as do-not-clean (deleted) — gone from source.\n"); await c.job("J-RUNNING", { kind: "clean-audio-transcribed", channelSlug: "ch", status: "running", startedAt: T0 }, "Pinned wrongjob as do-not-clean (deleted) — gone from source.\n"); // A clean job running then, whose line names a longer id / another availability. await provable(c, "idx"); await c.job("J-PREFIX", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: T0, endedAt: T0 + 60_000 }, "Pinned aidx as do-not-clean (deleted) — gone from source.\nPinned idx as do-not-clean (private) — gone from source.\n"); const r = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false }); assert.deepEqual(r.relabelled, []); assert.deepEqual( Object.fromEntries(r.notProven.map((x) => [x.id, x.reason])), { assumed: "no-check-within-a-minute", cached: "no-check-within-a-minute", idx: "no-clean-job-naming-it", noteonly: "no-availability-record", public: "not-gone", wrongjob: "no-clean-job-naming-it", }, ); for (const id of ["noteonly", "cached", "public", "assumed", "wrongjob", "idx"]) { assert.equal((await mark(path.join(c.paths.channelsDir, "ch", "data", id))).by, undefined, id); } assert.equal(r.oldestCleanJobAt, new Date(T0).toISOString()); assert.equal(MARK_PROOF_WINDOW_MS, 60_000); }); test("backfill's relabel refuses a mark that changed since it was judged", async () => { const c = await corpus(); const v = await provable(c); const evidence = { availability: "deleted", observedAt: SET_AT, field: "history" as const, jobId: "J", jobKind: "clean-audio-transcribed" }; assert.equal(await relabelDoNotCleanInferred(v, { setAt: "2026-01-01T00:00:00.000Z" }, evidence), false, "another setAt"); await setDoNotClean(v, true, { by: "operator", via: "toggle", surface: "ops" }); assert.equal(await relabelDoNotCleanInferred(v, { setAt: (await mark(v)).setAt }, evidence), false, "labelled since"); assert.equal((await mark(v)).by, "operator"); }); test("an inferred mark joins the opt-in group, counted apart", async () => { const c = await corpus(); await provable(c); await c.job("J-CLEAN", { kind: "clean-audio-retry", channelSlug: "ch", startedAt: T0, endedAt: T0 + 60_000 }, "Pinned pv as do-not-clean (deleted) — gone from source.\n"); assert.deepEqual((await planAudioClean({ channelSlug: "ch", paths: c.paths })).sourceGone.ids, [], "not before the relabel"); await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false }); const plan = await planAudioClean({ channelSlug: "ch", paths: c.paths }); assert.deepEqual(plan.sourceGone.inferred.ids, ["pv"]); const raw = JSON.parse(await readFile(path.join(c.paths.channelsDir, "ch", "data", "pv", "do-not-clean.json"), "utf8")); assert.equal(raw.evidence.jobKind, "clean-audio-retry"); }); // --- Review 1 --------------------------------------------------------------- // New symbols are imported inside each test, so each fails on its own before // the fix (the run of these against the pre-fix code is the RED one). const MACHINE = { setAt: "2026-11-03T08:00:00.000Z", note: "deleted from source (pre-clean check): deleted", by: "availability-check", via: "pre-clean-check" }; async function optInGroup(paths: Paths) { return (await planAudioClean({ channelSlug: "ch", paths })).sourceGone.ids; } test("F1: keep-videos by ids on a machine-set mark makes it the operator's, with the note; the opt-in then never reaches it", async () => { const { paths, video } = await corpus(); const v = await video("mach", { mark: MACHINE }); const mine = await video("mine", { mark: { setAt: "2026-11-01T00:00:00.000Z", by: "operator", via: "toggle", note: "mine" } }); assert.deepEqual(await optInGroup(paths), ["mach"]); const r = await keepVideosByIds({ paths, channelSlug: "ch", ids: ["mach", "mine"], note: "the only copy, keep", surface: "ops" }); assert.deepEqual(r.marked, ["mach"]); assert.deepEqual((r as unknown as { takenOver: string[] }).takenOver, ["mach"]); assert.deepEqual(r.alreadyKept, ["mine"], "already kept only for a mark already the operator's"); const m = await mark(v); assert.deepEqual([m.by, m.via, m.surface, m.note], ["operator", "keep-videos-ids", "ops", "the only copy, keep"]); assert.equal((m as { takenOver?: { by?: string } }).takenOver?.by, "availability-check"); assert.equal((await mark(mine)).note, "the only copy, keep", "a note given is written on the person's own mark"); assert.deepEqual(await optInGroup(paths), [], "the opt-in never reaches it now"); const logs: string[] = []; await cleanAudioFromTranscribed({ channelSlug: "ch", paths, unchecked: "button", onlyIds: [], sourceGone: ["mach"], probes: THROWING, onLog: (l) => logs.push(l) }); assert.equal(await exists(path.join(v, "audio.mp3")), true); }); test("F1: keep-videos by pattern takes over a machine-set mark (and a dry run only says it would)", async () => { const { paths, video } = await corpus(); const v = await video("pat", { mark: { ...MACHINE, by: "import", via: "import-media" } }); await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id: "pat", title: "keep me", description: "" })); const dry = await keepVideosMatching({ paths, channelSlug: "ch", pattern: "keep me", dryRun: true }); assert.equal((dry as unknown as { takenOver: number }).takenOver, 1); assert.equal((await mark(v)).by, "import", "a dry run writes nothing"); const r = await keepVideosMatching({ paths, channelSlug: "ch", pattern: "keep me" }); assert.deepEqual([r.marked, r.alreadyKept], [1, 0]); assert.match(String((r.matched[0] as { keptBy?: string }).keptBy), /^import, 3 Nov/); const m = await mark(v); assert.deepEqual([m.by, m.via, m.note], ["operator", "keep-videos-match", MACHINE.note], "no note given: the mark's own stays"); }); test("F1: a pending keep landing on a machine-set mark takes it over", async () => { const { paths, video } = await corpus(); await addPendingKeep(paths, "ch", ["later"], "asked first", new Date(), "button"); const v = await video("later", { mark: { ...MACHINE, via: "kept-deleted-check" } }); assert.equal(await applyPendingKeep(paths, "ch", "later", undefined, "JOB-L"), true); const m = await mark(v); assert.deepEqual([m.by, m.via, m.surface, m.note, m.jobId], ["operator", "pending-keep", "button", "asked first", "JOB-L"]); assert.deepEqual(await optInGroup(paths), []); }); test("F1: the toggle, Make it mine and a note — keepByPerson takes a machine mark over; a person's stays unless given a note", async () => { const { keepByPerson } = (await import("../lib/doNotClean-server")) as unknown as { keepByPerson: (d: string, m: Record, o?: Record) => Promise<{ outcome: string }>; }; const { paths, video } = await corpus(); const v = await video("tg", { mark: MACHINE }); assert.equal((await keepByPerson(v, { via: "toggle", surface: "button" })).outcome, "taken-over"); const m = await mark(v); assert.deepEqual([m.by, m.via, m.note], ["operator", "toggle", MACHINE.note]); const setAt = m.setAt; assert.equal((await keepByPerson(v, { via: "toggle", surface: "button" })).outcome, "already-kept"); assert.equal((await mark(v)).setAt, setAt, "nothing rewritten"); assert.equal((await keepByPerson(v, { via: "toggle", surface: "ops", note: "edited" })).outcome, "already-kept"); assert.equal((await mark(v)).note, "edited"); // A note written on a machine mark takes it over. const n2 = await video("nt", { mark: MACHINE }); await keepByPerson(n2, { via: "toggle", surface: "button", note: "mine now" }); assert.deepEqual([(await mark(n2)).by, (await mark(n2)).note], ["operator", "mine now"]); assert.deepEqual(await optInGroup(paths), []); }); test("F2: who set a mark and when, in the page's words", async () => { const { describeDoNotCleanMark } = (await import("../lib/doNotClean")) as unknown as { describeDoNotCleanMark: (m: Record, now?: Date) => { text: string; mine: boolean; sourceGone: boolean }; }; const now = new Date("2026-11-21T00:00:00.000Z"); const d = (m: Record) => describeDoNotCleanMark(m, now); assert.deepEqual(d(MACHINE), { who: "availability check", day: "3 Nov", text: "availability check, 3 Nov; the source was gone", mine: false, sourceGone: true }); assert.equal(d({ setAt: "2026-11-20T09:00:00.000Z", by: "operator", via: "toggle" }).text, "you, 20 Nov"); assert.equal(d({ ...MACHINE, inferred: true }).text, "availability check (inferred from the records), 3 Nov; the source was gone"); assert.equal(d({ setAt: "2026-11-03T00:00:00.000Z", by: "import", via: "import-media" }).text, "import, 3 Nov"); assert.equal(d({ setAt: "2026-11-03T00:00:00.000Z", by: "live-recording", via: "record-live" }).text, "live recording, 3 Nov"); assert.equal(d({ setAt: "2025-09-11T00:00:00.000Z" }).text, "you, 11 Sep 2025 (set before marks said who set them)"); assert.equal(d({ setAt: "2025-09-11T00:00:00.000Z" }).mine, true); }); test("F3: a person's re-mark that takes the mark's lock first (not yet written when the sweep re-reads) keeps the audio", async () => { const { paths, video } = await corpus(); const v = await video("lockrace", { mark: MACHINE }); const logs: string[] = []; let person: Promise | undefined; await cleanAudioFromTranscribed({ channelSlug: "ch", paths, unchecked: "button", onlyIds: [], sourceGone: ["lockrace"], probes: THROWING, // Just before the removals the person presses Make it mine; the sweep // does not wait for the write to land. assertReachable: async () => { person = setDoNotClean(v, true, { by: "operator", via: "toggle", surface: "button" }); }, onLog: (m) => logs.push(m), }); await person; assert.equal(await exists(path.join(v, "audio.mp3")), true, "the audio stays"); assert.equal((await mark(v)).by, "operator"); assert.equal((await mark(v)).audioRemoved, undefined); }); test("F4: the job states the source-gone group's counts before it removes anything", async () => { const { paths, video } = await corpus(); await video("g4", { mark: MACHINE }); const logs: string[] = []; const counts = { files: 0, bytes: 0, videos: 0, protected: 1, awaitingDiarization: 0, awaitingVoiceprint: 0, sourceGone: { videos: 1, files: 1, bytes: 1000, inferred: { videos: 0, files: 0, bytes: 0 } } }; await runCleanAudioJob({ channelSlug: "ch", paths, jobId: "J4", unchecked: "button", plan: [], planCounts: counts, sourceGone: ["g4"], onLog: (m) => logs.push(m), deps: { scheduleRetry: async () => ({ ok: false, error: "no" }), probes: THROWING }, }); const said = logs.findIndex((l) => l.includes("Also, kept only because the source was gone: 1 audio file(s) (1000 bytes) from 1 video(s)")); const removed = logs.findIndex((l) => l.startsWith("Removed ")); assert.ok(said >= 0 && removed > said, logs.join("\n")); }); test("F5: the proof is one-sided — an observation AFTER the mark, or a job that started after it, is not proof", async () => { const c = await corpus(); await c.video("after", { mark: { setAt: SET_AT }, availability: { checkedAt: "2026-11-01T00:00:00.000Z", checkedBy: "check", availability: "deleted", history: [{ availability: "deleted", observedAt: "2026-10-20T10:00:50.000Z", source: "check" }] }, }); await provable(c, "jobafter"); await c.job("J-AFTER", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: Date.parse(SET_AT) + 20_000, endedAt: Date.parse(SET_AT) + 90_000 }, "Pinned after as do-not-clean (deleted) — gone from source.\nPinned jobafter as do-not-clean (deleted) — gone from source.\n"); const r = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch" }); assert.deepEqual(r.relabelled, []); assert.deepEqual(Object.fromEntries(r.notProven.map((x) => [x.id, x.reason])), { after: "no-check-within-a-minute", jobafter: "no-clean-job-naming-it" }); }); test("F5: undo returns every inferred label to unlabelled — dry run first, the same listing — and nothing else", async () => { const { undoMarkProvenanceBackfill } = (await import("./marksBackfill")) as unknown as { undoMarkProvenanceBackfill: (o: Record) => Promise<{ dryRun: boolean; unlabelled: { id: string; evidence: unknown }[]; changedSince: string[] }>; }; const c = await corpus(); const v = await provable(c); await c.job("J-CLEAN", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: T0, endedAt: T0 + 120_000 }, "Pinned pv as do-not-clean (deleted) — gone from source.\n"); await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false }); const machine = await c.video("machine", { mark: MACHINE }); const dry = await undoMarkProvenanceBackfill({ paths: c.paths, channelSlug: "ch" }); assert.equal(dry.dryRun, true); assert.deepEqual(dry.unlabelled.map((x) => x.id), ["pv"]); assert.equal((await mark(v)).inferred, true, "a dry run writes nothing"); await undoMarkProvenanceBackfill({ paths: c.paths, channelSlug: "ch", dryRun: false }); assert.deepEqual(await mark(v), { setAt: SET_AT, note: "anything at all" }); assert.equal((await mark(machine)).by, "availability-check", "a mark the check itself wrote is not touched"); });