import path from "node:path"; import { readdir, readFile } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { isPermanentlyGone } from "../lib/availability"; import { loadAvailability } from "../lib/availability-server"; import { assertChannelTextReadable } from "../lib/channelMedia"; import type { DoNotCleanEvidence } from "../lib/doNotClean"; import { loadDoNotClean, relabelDoNotCleanInferred, unlabelDoNotCleanInferred } from "../lib/doNotClean-server"; import { readJobMeta, type JobMeta } from "../jobs/jobMeta"; // MARKS-BACKFILL (lane mark-provenance): relabel an OLD do-not-clean mark — one // written before marks said who set them, so the operator's by rule — as set // by the availability check, `inferred: true`, ONLY when other records prove // it. Never from the mark's free-text note, which a person can write too. // // THE PROOF, both halves required: // 1. availability.json says the CHECK found the video gone (deleted / // private / members-only) AT MOST A MINUTE BEFORE the mark's setAt: a // history entry by source "check", or the record's top level (checkedAt, // checkedBy "check"). ONE-SIDED (review F5): the gate pins only after the // check has written what it saw (tier C: runAvailabilityCheck records, // then verifyBeforeClean reads it and pins), on the same clock, so the // observation can never come after the pin. An observation after setAt // is some other check, not the one that set this mark. // 2. A FINISHED clean job of the video's channel (clean-audio-transcribed or // clean-audio-retry — the only jobs whose gate pins), whose start is at or // before setAt and whose end at or after it — the pin is written inside // the job's run, between the two times its record holds — and whose log // names the pin: the gate's own line `Pinned as do-not-clean ()`. // What it cannot prove, it leaves the operator's and says why. Its limits: // tier A of the gate pins on a CACHED verdict (the check ran days or weeks // before), so (1) fails for those; a job record is gone once retention prunes // it, so (2) fails for any mark older than the oldest record; a later recheck // moves checkedAt, and a same-state recheck adds no history entry. // // Dry run by default. A real run writes each relabel through the one writer // (relabelDoNotCleanInferred), which refuses a mark that changed since it was // judged (a person re-set it, or a writer labelled it). export const MARK_PROOF_WINDOW_MS = 60_000; const CLEAN_JOB_KINDS = new Set(["clean-audio-transcribed", "clean-audio-retry"]); export type MarkNotProvenReason = | "no-availability-record" | "not-gone" | "no-check-within-a-minute" | "no-clean-job-naming-it" | "changed-since"; export type MarkBackfillResult = { slug: string; dryRun: boolean; // Marks on the channel, and those already saying who set them. marks: number; labelled: number; // Relabelled (would be, on a dry run), each with its evidence. relabelled: { id: string; setAt: string; evidence: DoNotCleanEvidence }[]; // Left the operator's, each with the first half of the proof it failed. notProven: { id: string; setAt: string; reason: MarkNotProvenReason }[]; // What the job records reach back to: the oldest clean job on record (null: // none), so "no clean job naming it" can be read against it. oldestCleanJobAt: string | null; }; // THE UNDO (marks-backfill {"undo": true}): every INFERRED label of the // channel returns to unlabelled — the operator's, as before the backfill. // Only marks with `inferred: true` are touched; setAt, note and audioRemoved // stay. A dry run unless `dryRun` is false; the same listing, with each // label's evidence. export type MarkUndoResult = { slug: string; dryRun: boolean; undo: true; marks: number; unlabelled: { id: string; setAt: string; evidence: DoNotCleanEvidence | null }[]; // Changed between the listing and the write (a person or a writer set it since). changedSince: string[]; }; export async function undoMarkProvenanceBackfill({ paths, channelSlug, dryRun = true, }: { paths: Paths; channelSlug: string; dryRun?: boolean; }): Promise { await assertChannelTextReadable(paths, channelSlug); const dataDir = path.join(paths.channelsDir, channelSlug, "data"); const ids = (await readdir(dataDir).catch(() => [] as string[])).sort(); const out: MarkUndoResult = { slug: channelSlug, dryRun, undo: true, marks: 0, unlabelled: [], changedSince: [] }; for (const id of ids) { const videoDir = path.join(dataDir, id); const mark = await loadDoNotClean(videoDir); if (!mark) continue; out.marks++; if (mark.inferred !== true || mark.by !== "availability-check") continue; if (!dryRun && !(await unlabelDoNotCleanInferred(videoDir, { setAt: mark.setAt }))) { out.changedSince.push(id); continue; } out.unlabelled.push({ id, setAt: mark.setAt, evidence: mark.evidence ?? null }); } return out; } export const NOT_PROVEN_SENTENCE: Record = { "no-availability-record": "no availability.json", "not-gone": "availability.json does not say gone", "no-check-within-a-minute": "no check found it gone within a minute of the mark", "no-clean-job-naming-it": "no clean job on record, running then, names the pin", "changed-since": "the mark changed while this ran", }; type CleanJob = { meta: JobMeta; log: string | null }; async function loadCleanJobs(paths: Paths, slug: string): Promise { const names = await readdir(paths.jobsDir).catch(() => [] as string[]); const out: CleanJob[] = []; for (const n of names) { if (!n.endsWith(".meta.json")) continue; const meta = await readJobMeta(paths, n.slice(0, -".meta.json".length)); if (!meta || !CLEAN_JOB_KINDS.has(meta.kind)) continue; if ((meta.channelSlug ?? meta.spec?.slug) !== slug) continue; // Running or queued: no end to bound it by. if (typeof meta.startedAt !== "number" || typeof meta.endedAt !== "number") continue; out.push({ meta, log: null }); } return out; } async function logOf(paths: Paths, job: CleanJob): Promise { if (job.log === null) { job.log = await readFile(path.join(paths.jobsDir, `${job.meta.id}.log`), "utf8").catch(() => ""); } return job.log; } export async function backfillMarkProvenance({ paths, channelSlug, dryRun = true, now = new Date(), }: { paths: Paths; channelSlug: string; dryRun?: boolean; now?: Date; }): Promise { await assertChannelTextReadable(paths, channelSlug); const dataDir = path.join(paths.channelsDir, channelSlug, "data"); const ids = (await readdir(dataDir).catch(() => [] as string[])).sort(); const jobs = await loadCleanJobs(paths, channelSlug); const oldest = jobs.reduce((m, j) => Math.min(m, j.meta.startedAt!), Infinity); const result: MarkBackfillResult = { slug: channelSlug, dryRun, marks: 0, labelled: 0, relabelled: [], notProven: [], oldestCleanJobAt: Number.isFinite(oldest) ? new Date(oldest).toISOString() : null, }; for (const id of ids) { const videoDir = path.join(dataDir, id); const mark = await loadDoNotClean(videoDir); if (!mark) continue; result.marks++; if (mark.by !== undefined) { result.labelled++; continue; } const setAt = Date.parse(mark.setAt); const fail = (reason: MarkNotProvenReason) => result.notProven.push({ id, setAt: mark.setAt, reason }); // (1) The availability record. const av = await loadAvailability(videoDir); if (!av) { fail("no-availability-record"); continue; } // One-sided: observed, then pinned within the minute. const near = (iso: string) => { const lead = setAt - Date.parse(iso); return Number.isFinite(lead) && lead >= 0 && lead <= MARK_PROOF_WINDOW_MS; }; const seen: { availability: string; observedAt: string; field: "history" | "checkedAt" }[] = []; for (const h of av.history ?? []) { if (h.source === "check" && isPermanentlyGone(h.availability) && near(h.observedAt)) { seen.push({ availability: h.availability, observedAt: h.observedAt, field: "history" }); } } if (av.checkedBy === "check" && isPermanentlyGone(av.availability) && near(av.checkedAt)) { seen.push({ availability: av.availability, observedAt: av.checkedAt, field: "checkedAt" }); } if (seen.length === 0) { const everGone = isPermanentlyGone(av.availability) || (av.history ?? []).some((h) => isPermanentlyGone(h.availability)); fail(everGone ? "no-check-within-a-minute" : "not-gone"); continue; } // (2) A clean job running then, whose log names this pin. let evidence: DoNotCleanEvidence | null = null; for (const job of jobs) { const { startedAt, endedAt } = job.meta; if (setAt < startedAt! || setAt > endedAt!) continue; const log = await logOf(paths, job); const obs = seen.find((o) => log.includes(`Pinned ${id} as do-not-clean (${o.availability})`)); if (obs) { evidence = { ...obs, jobId: job.meta.id, jobKind: job.meta.kind }; break; } } if (!evidence) { fail("no-clean-job-naming-it"); continue; } if (!dryRun && !(await relabelDoNotCleanInferred(videoDir, { setAt: mark.setAt }, evidence, now))) { fail("changed-since"); continue; } result.relabelled.push({ id, setAt: mark.setAt, evidence }); } return result; }