commit 66a2329201ad0326ad9c4720acaca10f67a2af18 parent ee840110e67c29ee010f75f94972136ef72d546d Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sat, 21 Nov 2026 14:12:49 -0500 common, editor: a do-not-clean mark says who set it; Clean without checking may drop audio kept only because the source was gone - One writer of do-not-clean.json (lib/doNotClean-server.ts): setDoNotClean requires the writer's provenance {by, via, surface?, jobId?}. by is availability-check | live-recording | import | operator. A machine mark never replaces one that is there; a person's replaces the machine's and keeps its audioRemoved history. A gate test fails the build if any other source file names the sidecar or its file name on a code line. - Every writer labelled: the pre-clean gate (tiers A and C), clean after capture and the keep-latest deletion check (availability-check, with the job); record-live; import-media; the toggle and keep-videos with their surface (button / ops), and a pending keep applied on landing. - A mark with no by is the operator's. marks-backfill (controller, server action, ops route; a dry run unless dryRun is false) relabels one as availability-check, inferred, only when availability.json shows a check found the video gone within a minute of setAt AND a finished clean job of the channel running then names the pin in its log. Never from the note. - The opt-in: planAudioClean counts sourceGone (marks by the availability check that nothing else holds; inferred apart). Only a confirmed "button" unchecked clean, given those ids, removes their audio; each mark is re-read just before; the mark stays and records audioRemoved. Never on the channel key, a checked clean, a retry or a replay. Checkbox on Clean without checking (off by default), ops cleanup "includeSourceGone". Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
30 files changed, 1460 insertions(+), 82 deletions(-)
diff --git a/common/controller/checkKeptDeleted.ts b/common/controller/checkKeptDeleted.ts @@ -20,6 +20,8 @@ export type CheckKeptDeletedOptions = { onLog?: (msg: string) => void; signal?: AbortSignal; concurrency?: number; + // The job this check runs in, recorded on every mark it writes. + jobId?: string; }; export type CheckKeptDeletedResult = { @@ -37,6 +39,7 @@ export async function checkKeptDeleted({ onLog, signal, concurrency, + jobId, }: CheckKeptDeletedOptions): Promise<CheckKeptDeletedResult> { const log = onLog ?? ((m: string) => console.log(m)); const config = await readChannelConfig(paths, channelSlug); @@ -78,7 +81,13 @@ export async function checkKeptDeleted({ const already = await loadDoNotClean(videoDir); if (already) continue; const note = `deleted from source (keep-latest): ${availability}`; - await setDoNotClean(videoDir, true, note); + const wrote = await setDoNotClean(videoDir, true, { + by: "availability-check", + via: "kept-deleted-check", + ...(jobId ? { jobId } : {}), + note, + }); + if (!wrote) continue; pinned++; log(`Pinned ${id} as do-not-clean (${availability}).`); } diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts @@ -3,7 +3,8 @@ import { isPermanentlyGone } from "../lib/availability"; import { detectPlatform } from "../lib/platform"; import { DEFAULT_CLIPS_SETTINGS } from "../lib/clipSettings"; import { resolveEffectiveAvailability } from "../lib/availability-server"; -import { loadDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; +import { loadDoNotClean, recordDoNotCleanAudioRemoved, setDoNotClean } from "../lib/doNotClean-server"; +import { isSourceGoneMark } from "../lib/doNotClean"; import { readAvailabilityVerdict, requestAvailabilityCheck, @@ -52,6 +53,19 @@ export type CleanAudioOptions = { // plan". Absent = discover at start (the checked clean, a channel-key clean // nobody confirmed). onlyIds?: readonly string[]; + // ALSO REMOVE AUDIO KEPT ONLY BECAUSE THE SOURCE WAS GONE (lane + // mark-provenance): the ids of the plan's `sourceGone` group a person + // confirmed with that explicit opt-in. Honoured ONLY by a "button" unchecked + // sweep (a person confirmed the count); ignored, and said so, anywhere else. + // A video in it loses its audio only when its mark STILL says by + // "availability-check" (inferred included) and it passes every other gate; + // a mark by anything else — a person, an import, a live recording, or a mark + // from before marks said who set them — is never reached. The mark stays, + // and records when and why the audio went. + sourceGone?: readonly string[]; + // The job running the sweep: recorded on every mark the gate writes and on + // every audioRemoved entry. + jobId?: string; // Test seam for the availability probes (verifyBeforeClean). probes?: VerifyProbes; // Test seam for the media guard asked immediately before anything is @@ -106,6 +120,10 @@ export type CleanAudioResult = { // since the plan was made), skipped. notInPlan?: number; planNoLongerEligible?: number; + // The opt-in's group, when it was confirmed: audio removed from videos kept + // only because the source was gone (their marks stay). Counted inside + // cleanedDirs / removedFiles / bytesFreed too. + sourceGoneRemoved?: { videos: number; files: number; bytes: number; inferredVideos: number }; // Set when the availability gate stopped short — the source rate-limited it // (`rate-limit`) or it failed (`error`) — and so cleaned nothing it could // not verify (verifyBeforeClean's CleanVerdicts.stopped). @@ -129,6 +147,10 @@ export type AudioCleanGate = | "no-audio" | "keep-latest" | "do-not-clean" + // Only when the caller asks (ctx.sourceGone, the opt-in's discover): a + // video whose mark says by "availability-check" and that passes every gate + // after the mark. It stays protected unless a person confirmed the opt-in. + | "source-gone" | "awaiting-diarization" | "awaiting-voiceprint" // cleanAudioForVideo only: the channel's media drive is not answering. The @@ -153,14 +175,27 @@ export type AudioCleanGate = export async function audioCleanGate( videoDir: string, id: string, - ctx: { keptIds: Set<string>; diarization: DiarizationSettings }, -): Promise<{ gate: AudioCleanGate; audioFiles: string[] }> { + ctx: { keptIds: Set<string>; diarization: DiarizationSettings; sourceGone?: boolean }, +): Promise<{ gate: AudioCleanGate; audioFiles: string[]; inferred?: boolean }> { const entries = await readdir(videoDir).catch(() => [] as string[]); if (!entries.includes("transcript.json")) return { gate: "no-transcript", audioFiles: [] }; const audioFiles = audioFilesToRemove(entries); if (audioFiles.length === 0) return { gate: "no-audio", audioFiles }; if (ctx.keptIds.has(id)) return { gate: "keep-latest", audioFiles }; - if (await isDoNotClean(videoDir)) return { gate: "do-not-clean", audioFiles }; + // THE MARK. Without ctx.sourceGone (every caller but the opt-in's discover) + // any mark protects, as it always has. With it, a mark the availability + // check wrote goes on through the gates below; every other mark protects. + let sourceGone: { inferred: boolean } | null = null; + if (ctx.sourceGone) { + const mark = await loadDoNotClean(videoDir); + if (mark && !isSourceGoneMark(mark)) return { gate: "do-not-clean", audioFiles }; + if (mark) sourceGone = { inferred: mark.inferred === true }; + } else if (await isDoNotClean(videoDir)) { + return { gate: "do-not-clean", audioFiles }; + } + // A source-gone video held by a gate below stays "do-not-clean": its mark + // keeps it first. + const held = (gate: AudioCleanGate) => ({ gate: sourceGone ? ("do-not-clean" as const) : gate, audioFiles }); // While diarization is enabled, a transcribed video that still has audio but // no diarization.json is NOT cleanable yet — its diarize job hasn't run. // @@ -174,19 +209,22 @@ export async function audioCleanGate( const record = entries.includes("diarization.json") ? await loadDiarization(videoDir) : null; - if (!record) return { gate: "awaiting-diarization", audioFiles }; + if (!record) return held("awaiting-diarization"); // The voice fingerprint is the part of a diarization that cannot be made // again without the audio, so it is waited for too. if (ctx.diarization.requireVoiceprints && !hasVoiceprints(record)) { - return { gate: "awaiting-voiceprint", audioFiles }; + return held("awaiting-voiceprint"); } } + if (sourceGone) return { gate: "source-gone", audioFiles, inferred: sourceGone.inferred }; return { gate: "candidate", audioFiles }; } const SKIP_LOG: Partial<Record<AudioCleanGate, string>> = { "keep-latest": "in keep-latest window", "do-not-clean": "marked do not clean", + // Unreleased, it reads exactly as any other mark does. + "source-gone": "marked do not clean", "awaiting-diarization": "awaiting diarization", "awaiting-voiceprint": "awaiting voice fingerprint", }; @@ -216,6 +254,8 @@ export async function cleanAudioFromTranscribed({ verifyAvailability, unchecked, onlyIds, + sourceGone: sourceGoneAsked, + jobId, probes, assertReachable = assertChannelMediaReachable, onLog, @@ -246,12 +286,40 @@ export async function cleanAudioFromTranscribed({ let removedFiles = 0; let bytesFreed = 0; + // --- The opt-in: only a person-confirmed unchecked clean ----------------- + // ("button"). A checked sweep, a channel-key sweep and a retry never release + // a mark, whatever their spec carries. + const releaseSourceGone = unchecked === "button" && sourceGoneAsked !== undefined; + if (sourceGoneAsked !== undefined && !releaseSourceGone) { + log("Audio kept only because the source was gone is NOT removed: only a confirmed Clean without checking can opt in to that."); + } + // --- Discover ------------------------------------------------------------- - const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log, signal }); + const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log, signal, sourceGone: releaseSourceGone }); let candidates = found.candidates; let protectedCount = found.protectedCount; const { awaitingDiarization, awaitingVoiceprint } = found; + // The opt-in's group: the confirmed ids still marked by the availability + // check now; every other source-gone video stays protected, as before. + let released: SourceGoneCandidate[] = []; + if (releaseSourceGone) { + const asked = new Set(sourceGoneAsked); + released = found.sourceGone.filter((c) => asked.has(c.id)); + for (const c of found.sourceGone) { + if (!asked.has(c.id)) { + log(`Skipped ${c.id} (${SKIP_LOG["source-gone"]})`); + protectedCount++; + } + } + const gone = asked.size - released.length; + log( + `Also remove audio kept only because the source was gone (confirmed): ${asked.size} video(s) asked, ${released.length} still marked by the availability check` + + (gone > 0 ? `; ${gone} no longer (re-marked by a person, unmarked, or held since) and kept` : "") + + ". Their marks stay.", + ); + } + // --- The confirmed plan: never more than a person was shown --------------- let notInPlan: number | undefined; let planNoLongerEligible: number | undefined; @@ -284,6 +352,7 @@ export async function cleanAudioFromTranscribed({ candidateIds: candidates.map((c) => c.id), onLog: log, signal, + ...(jobId ? { jobId } : {}), ...(probes ? { probes } : {}), }); excluded = excludedIds(verdicts); @@ -300,7 +369,7 @@ export async function cleanAudioFromTranscribed({ // listing can take minutes. A drive that went away or a relocation that // started since (its marker) stops the sweep here, removing nothing: a // removed tier link on an absent drive strands its bytes there. - if (candidates.some((c) => !excluded.has(c.id)) && !signal?.aborted) { + if ((candidates.some((c) => !excluded.has(c.id)) || released.length > 0) && !signal?.aborted) { await assertReachable(paths, channelSlug); } for (const candidate of candidates) { @@ -311,6 +380,39 @@ export async function cleanAudioFromTranscribed({ bytesFreed += out.bytes; cleanedDirs++; } + let sourceGoneRemoved: CleanAudioResult["sourceGoneRemoved"]; + if (releaseSourceGone) { + sourceGoneRemoved = { videos: 0, files: 0, bytes: 0, inferredVideos: 0 }; + for (const c of released) { + if (signal?.aborted) break; + // Re-read the mark immediately before: a person who re-marked the + // video since discover made it theirs, and theirs is never reached. + if (!isSourceGoneMark(await loadDoNotClean(c.videoDir))) { + log(`Skipped ${c.id} (marked do not clean — no longer by the availability check)`); + protectedCount++; + continue; + } + const out = await removeCandidateAudio(c, log); + await recordDoNotCleanAudioRemoved(c.videoDir, { + at: new Date().toISOString(), + ...(jobId ? { jobId } : {}), + files: c.audioFiles, + bytes: out.bytes, + why: + "Clean without checking, with \"also remove audio kept only because the source was gone\" confirmed: the mark was set by the availability check" + + (c.inferred ? " (inferred from the records by marks-backfill)" : "") + + "; the mark stays.", + }); + log(`Removed the audio of ${c.id}, kept only because the source was gone${c.inferred ? " (mark inferred)" : ""}; its mark stays.`); + removedFiles += out.removed; + bytesFreed += out.bytes; + cleanedDirs++; + sourceGoneRemoved.videos++; + sourceGoneRemoved.files += out.removed; + sourceGoneRemoved.bytes += out.bytes; + if (c.inferred) sourceGoneRemoved.inferredVideos++; + } + } const skipped = protectedCount + pinned + unverified + awaitingDiarization + awaitingVoiceprint; @@ -367,10 +469,13 @@ export async function cleanAudioFromTranscribed({ prunedSavedVideos: prune.pruned, prunedBytes: prune.bytesFreed, ...(notInPlan !== undefined ? { notInPlan, planNoLongerEligible } : {}), + ...(sourceGoneRemoved ? { sourceGoneRemoved } : {}), ...(stopped ? { stopped } : {}), }; } +type SourceGoneCandidate = CleanCandidate & { inferred: boolean }; + // THE DISCOVER PASS of the channel sweep, shared with the dry plan below so // the two can never disagree about what a clean would remove. Nothing is // deleted here. Protected videos are filtered out, so the availability gate @@ -382,6 +487,7 @@ async function discoverAudioCandidates({ dirs, log, signal, + sourceGone = false, }: { paths: Paths; channelSlug: string; @@ -389,8 +495,13 @@ async function discoverAudioCandidates({ dirs: string[]; log: (m: string) => void; signal?: AbortSignal; + // Tell apart the marks the availability check wrote (the opt-in's group, + // returned in `sourceGone`, NOT counted in protectedCount — the caller + // decides). Off: every mark is "do-not-clean", as always. + sourceGone?: boolean; }): Promise<{ candidates: CleanCandidate[]; + sourceGone: SourceGoneCandidate[]; protectedCount: number; awaitingDiarization: number; awaitingVoiceprint: number; @@ -408,18 +519,23 @@ async function discoverAudioCandidates({ let awaitingDiarization = 0; let awaitingVoiceprint = 0; const candidates: CleanCandidate[] = []; + const goneGroup: SourceGoneCandidate[] = []; for (const id of dirs) { if (signal?.aborted) break; const videoDir = path.join(dataDir, id); - const { gate, audioFiles } = await audioCleanGate(videoDir, id, { keptIds, diarization }); + const { gate, audioFiles, inferred } = await audioCleanGate(videoDir, id, { keptIds, diarization, sourceGone }); if (gate === "no-transcript" || gate === "no-audio") continue; + if (gate === "source-gone") { + goneGroup.push({ id, videoDir, audioFiles, inferred: inferred === true }); + continue; + } if (gate !== "candidate") log(`Skipped ${id} (${SKIP_LOG[gate]})`); if (gate === "keep-latest" || gate === "do-not-clean") protectedCount++; else if (gate === "awaiting-diarization") awaitingDiarization++; else if (gate === "awaiting-voiceprint") awaitingVoiceprint++; else candidates.push({ id, videoDir, audioFiles }); } - return { candidates, protectedCount, awaitingDiarization, awaitingVoiceprint }; + return { candidates, sourceGone: goneGroup, protectedCount, awaitingDiarization, awaitingVoiceprint }; } export type AudioCleanPlan = { @@ -433,9 +549,25 @@ export type AudioCleanPlan = { files: number; bytes: number; // What it would keep: do-not-clean or keep-latest, and the two speaker holds. + // `protected` INCLUDES the sourceGone group (kept unless the opt-in is + // confirmed). protected: number; awaitingDiarization: number; awaitingVoiceprint: number; + // THE OPT-IN'S GROUP (lane mark-provenance): videos kept ONLY because the + // availability check found the source gone (their mark says by + // "availability-check") and held by nothing else. What "also remove audio + // kept only because the source was gone" would remove; `inferred` is the + // part whose marks the backfill relabelled from the records. + sourceGone: SourceGonePlan; +}; + +export type SourceGonePlan = { + ids: string[]; + videos: number; + files: number; + bytes: number; + inferred: { ids: string[]; videos: number; files: number; bytes: number }; }; // THE DRY PLAN of a clean without checking — the confirmation's numbers and @@ -455,24 +587,28 @@ export async function planAudioClean({ await assertChannelMediaReachable(paths, channelSlug); const dataDir = path.join(paths.channelsDir, channelSlug, "data"); const dirs = (await pathExists(dataDir)) ? await readdir(dataDir) : []; - const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log: () => {}, signal }); - let files = 0; - let bytes = 0; - for (const c of found.candidates) { - for (const f of c.audioFiles) { - files++; - bytes += await stat(path.join(c.videoDir, f)).then((st) => st.size, () => 0); + const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log: () => {}, signal, sourceGone: true }); + const count = async (group: readonly CleanCandidate[]) => { + let files = 0; + let bytes = 0; + for (const c of group) { + for (const f of c.audioFiles) { + files++; + bytes += await stat(path.join(c.videoDir, f)).then((st) => st.size, () => 0); + } } - } + return { ids: group.map((c) => c.id), videos: group.length, files, bytes }; + }; + const main = await count(found.candidates); + const gone = await count(found.sourceGone); + const inferred = await count(found.sourceGone.filter((c) => c.inferred)); return { inspected: dirs.length, - ids: found.candidates.map((c) => c.id), - videos: found.candidates.length, - files, - bytes, - protected: found.protectedCount, + ...main, + protected: found.protectedCount + found.sourceGone.length, awaitingDiarization: found.awaitingDiarization, awaitingVoiceprint: found.awaitingVoiceprint, + sourceGone: { ...gone, inferred }, }; } @@ -581,8 +717,12 @@ export async function cleanAudioForVideo({ const cached = await resolveEffectiveAvailability(videoDir); if (isPermanentlyGone(cached)) { if (!(await loadDoNotClean(videoDir))) { - await setDoNotClean(videoDir, true, `deleted from source (pre-clean check): ${cached}`); - log(`Pinned ${videoId} as do-not-clean (${cached}) — gone from source.`); + const wrote = await setDoNotClean(videoDir, true, { + by: "availability-check", + via: "clean-after-capture", + note: `deleted from source (pre-clean check): ${cached}`, + }); + if (wrote) log(`Pinned ${videoId} as do-not-clean (${cached}) — gone from source.`); } return { outcome: "pinned", removedFiles: 0, bytesFreed: 0 }; } diff --git a/common/controller/cleanAudioJob.ts b/common/controller/cleanAudioJob.ts @@ -86,19 +86,26 @@ export function uncheckedReasonFor(config: ChannelConfig | null | undefined): Un // a person confirmed one, else discovered at start; the key is re-read // when the job starts (runCleanAudioJob); // - otherwise the checked clean (bounded by a plan when one was confirmed). +// - `sourceGone` (the opt-in "also remove audio kept only because the source +// was gone", lane mark-provenance) rides ONLY on an explicit "button" +// request: never implied by the channel key, never on a checked clean. export type CleanAudioRequest = { kind: "clean-audio-transcribed" | "clean-audio-unchecked"; unchecked?: UncheckedReason; plan?: string[]; + sourceGone?: string[]; }; export function cleanAudioRequestFor( config: ChannelConfig | null | undefined, - opts: { explicit?: "button"; plan?: readonly string[] } = {}, + opts: { explicit?: "button"; plan?: readonly string[]; sourceGone?: readonly string[] } = {}, ): CleanAudioRequest { const plan = opts.plan ? [...opts.plan] : undefined; const reason: UncheckedReason | undefined = opts.explicit ?? uncheckedReasonFor(config); - if (reason) return { kind: "clean-audio-unchecked", unchecked: reason, ...(plan ? { plan } : {}) }; + if (reason) { + const sourceGone = opts.explicit === "button" && opts.sourceGone ? [...opts.sourceGone] : undefined; + return { kind: "clean-audio-unchecked", unchecked: reason, ...(plan ? { plan } : {}), ...(sourceGone ? { sourceGone } : {}) }; + } return { kind: "clean-audio-transcribed", ...(plan ? { plan } : {}) }; } @@ -108,6 +115,13 @@ export function planFromParams(p: Record<string, unknown> | undefined): string[] return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined; } +// A spec's carried source-gone ids (the opt-in), or undefined. Read only by the +// job that carries them — no replay passes them on (below). +export function sourceGoneFromParams(p: Record<string, unknown> | undefined): string[] | undefined { + const v = p?.sourceGone; + return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined; +} + // HOW A CLEAN JOB IS REPLAYED — by every replay path alike: a /jobs Retry, // Retry all failed, `pnpm ops job retry`, and the boot's re-queue of a job a // restart caught queued (all four go through the editor's runJobSpec). Operator @@ -127,6 +141,9 @@ export function planFromParams(p: Record<string, unknown> | undefined): string[] // plan lost; confirm again". On a key-OFF channel it is REFUSED: it would // be an unchecked run nobody asked for now; // - anything else is refused. +// THE OPT-IN IS NEVER REPLAYED (lane mark-provenance): a replay carries the +// plan only, so audio kept because the source was gone is removed only by the +// run a person confirmed it for. export type CleanReplay = | { ok: true; call: "clean" | "unchecked"; plan?: string[] } | { ok: false; error: string; info?: boolean }; @@ -183,13 +200,20 @@ export type CleanPlanCountsLog = { protected: number; awaitingDiarization: number; awaitingVoiceprint: number; + // The opt-in's group as counted, when it was confirmed. + sourceGone?: { videos: number; files: number; bytes: number; inferred: { videos: number; files: number; bytes: number } }; }; export function planCountsLine(c: CleanPlanCountsLog): string { + const g = c.sourceGone; return ( `Plan counted when this clean was asked for: ${c.files} audio file(s) (${c.bytes} bytes) from ${c.videos} video(s); ` + - `kept: ${c.protected} marked do not clean or in the keep-latest window, ${c.awaitingDiarization} awaiting diarization, ` + - `${c.awaitingVoiceprint} awaiting voice fingerprint.` + `kept: ${g ? c.protected - g.videos : c.protected} marked do not clean or in the keep-latest window, ${c.awaitingDiarization} awaiting diarization, ` + + `${c.awaitingVoiceprint} awaiting voice fingerprint.` + + (g + ? ` Also, kept only because the source was gone: ${g.files} audio file(s) (${g.bytes} bytes) from ${g.videos} video(s)` + + ` (${g.inferred.videos} of them with marks inferred from the records: ${g.inferred.files} file(s), ${g.inferred.bytes} bytes).` + : "") ); } @@ -204,6 +228,7 @@ export async function runCleanAudioJob({ unchecked, plan, planCounts, + sourceGone, retry, onLog, signal, @@ -220,6 +245,8 @@ export async function runCleanAudioJob({ plan?: readonly string[]; // The plan's counts, logged before anything is removed (an ops call). planCounts?: CleanPlanCountsLog; + // The opt-in's confirmed ids: honoured only while the job runs as "button". + sourceGone?: readonly string[]; retry?: CleanRetry; onLog: (m: string) => void; signal?: AbortSignal; @@ -265,6 +292,8 @@ export async function runCleanAudioJob({ signal, ...(mode ? { unchecked: mode } : {}), ...(plan ? { onlyIds: plan } : {}), + ...(sourceGone ? { sourceGone } : {}), + jobId, ...(deps.probes ? { probes: deps.probes } : {}), ...(deps.assertReachable ? { assertReachable: deps.assertReachable } : {}), }); diff --git a/common/controller/cleanUnchecked.test.ts b/common/controller/cleanUnchecked.test.ts @@ -176,6 +176,10 @@ test("the dry plan counts exactly what the unchecked clean removes, and asks not protected: 1, awaitingDiarization: 1, awaitingVoiceprint: 1, + // The pinned video's mark carries the gate's note but no `by` (written + // before marks said who set them): the operator's, never in the opt-in's + // group (lane mark-provenance). + sourceGone: { ids: [], videos: 0, files: 0, bytes: 0, inferred: { ids: [], videos: 0, files: 0, bytes: 0 } }, }); // Nothing was deleted by the plan. assert.equal(await exists(path.join(v.plain, "audio.mp3")), true); diff --git a/common/controller/importMedia.ts b/common/controller/importMedia.ts @@ -142,6 +142,8 @@ export type ImportMediaJobOpts = { // queues the transcribe-one job (held by any pause, as every one is). requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>; afterRun?: () => void | Promise<void>; + // The job running it, recorded on the do-not-clean mark it sets. + jobId?: string; deps?: { refresh?: RefreshRunner; land?: LandMediaDeps; @@ -281,10 +283,17 @@ export async function importMediaRun( } if (req.doNotClean) { - if (!req.dryRun) await setDoNotClean(videoDir, true, req.note); + if (!req.dryRun) { + await setDoNotClean(videoDir, true, { + by: "import", + via: "import-media", + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(req.note ? { note: req.note } : {}), + }); + } say(`${req.dryRun ? "Would mark" : "Marked"} "Do not clean"${req.note ? `: ${req.note}` : ""}.`); } - if (!req.dryRun) await applyPendingKeep(paths, req.slug, target.id, onLog); + if (!req.dryRun) await applyPendingKeep(paths, req.slug, target.id, onLog, opts.jobId); let transcribeJob: string | undefined; if (!req.dryRun && landed.audio !== "skipped") { @@ -358,8 +367,8 @@ export async function runImportMediaJob(opts: ImportMediaJobOpts): Promise<Strea paths, channelSlug: req.slug, videoId: target.id, - fn: async (onLog, signal) => { - await importMediaRun({ ...opts, target, onLog, signal }); + fn: async (onLog, signal, _progress, ctx) => { + await importMediaRun({ ...opts, target, onLog, signal, jobId: ctx.jobId }); await opts.afterRun?.(); }, }); diff --git a/common/controller/keepVideosMatching.test.ts b/common/controller/keepVideosMatching.test.ts @@ -106,7 +106,7 @@ test("an already-kept video is counted and not rewritten", async () => { { dirs: { aaaaaaaaaaa: ["TheQuartering live", ""] } }, async (paths, channelDir) => { const dir = dirOf(channelDir, "aaaaaaaaaaa"); - await setDoNotClean(dir, true, "by hand"); + await setDoNotClean(dir, true, { by: "operator", via: "toggle", note: "by hand" }); const markerFile = path.join(dir, "do-not-clean.json"); const before = (await stat(markerFile)).mtimeMs; await new Promise((r) => setTimeout(r, 20)); diff --git a/common/controller/keepVideosMatching.ts b/common/controller/keepVideosMatching.ts @@ -3,6 +3,7 @@ import { readFile } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { assertChannelMediaReachable } from "../lib/channelMedia"; import { isDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; +import type { DoNotCleanSurface } from "../lib/doNotClean"; import { addPendingKeep, loadPendingKeep, type PendingKeepEntry } from "../lib/pendingKeep-server"; import { classifyAgainstFilter, @@ -71,6 +72,9 @@ export type KeepVideosOptions = { fields?: readonly KeepVideosField[]; note?: string; dryRun?: boolean; + // Where the person asked: recorded on every mark (default "ops" — the only + // caller today is `pnpm ops keep-videos`). + surface?: DoNotCleanSurface; }; export type KeepVideosMatch = { @@ -217,7 +221,7 @@ export async function keepVideosMatching( if (kept) { alreadyKept++; } else if (!dryRun) { - await setDoNotClean(videoDir, true, note); + await setDoNotClean(videoDir, true, { by: "operator", via: "keep-videos-match", surface: opts.surface ?? "ops", note }); marked++; } matched.push({ @@ -273,6 +277,9 @@ export async function keepVideosByIds(opts: { ids: readonly string[]; note?: string; dryRun?: boolean; + // Where the person asked (the Keep matching control's button, or pnpm ops), + // recorded on each mark and on each pending entry. + surface?: DoNotCleanSurface; }): Promise<KeepVideosByIdsResult> { const { paths, channelSlug } = opts; const dryRun = opts.dryRun === true; @@ -297,13 +304,13 @@ export async function keepVideosByIds(opts: { const videoDir = path.join(paths.channelsDir, channelSlug, "data", id); if (await isDoNotClean(videoDir)) result.alreadyKept.push(id); else { - if (!dryRun) await setDoNotClean(videoDir, true, note); + if (!dryRun) await setDoNotClean(videoDir, true, { by: "operator", via: "keep-videos-ids", ...(opts.surface ? { surface: opts.surface } : {}), note }); result.marked.push(id); } } result.pendingAll = !dryRun && result.pending.length - ? await addPendingKeep(paths, channelSlug, result.pending, note) + ? await addPendingKeep(paths, channelSlug, result.pending, note, new Date(), opts.surface) : await loadPendingKeep(paths, channelSlug); return result; } diff --git a/common/controller/markProvenance.test.ts b/common/controller/markProvenance.test.ts @@ -0,0 +1,487 @@ +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<string, unknown> = {}) { + 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<string, unknown>; availability?: Record<string, unknown>; 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<string, unknown>, 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<ReturnType<typeof corpus>>, 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"); +}); diff --git a/common/controller/marksBackfill.ts b/common/controller/marksBackfill.ts @@ -0,0 +1,173 @@ +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 } 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) within a minute of the mark's setAt: a history +// entry by source "check", or the record's top level (checkedAt, +// checkedBy "check"). +// 2. A FINISHED clean job of the video's channel (clean-audio-transcribed or +// clean-audio-retry — the only jobs whose gate pins), running at setAt +// (start - 1 min .. end + 1 min), whose log names the pin: the gate's own +// line `Pinned <id> as do-not-clean (<that availability>)`. +// 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; +}; + +export const NOT_PROVEN_SENTENCE: Record<MarkNotProvenReason, string> = { + "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<CleanJob[]> { + 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<string> { + 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<MarkBackfillResult> { + 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; + } + const near = (iso: string) => Number.isFinite(setAt) && Math.abs(Date.parse(iso) - setAt) <= 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! - MARK_PROOF_WINDOW_MS || setAt > endedAt! + MARK_PROOF_WINDOW_MS) 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; +} diff --git a/common/controller/pruneSavedVideos.test.ts b/common/controller/pruneSavedVideos.test.ts @@ -91,7 +91,7 @@ test("never evicts override or pinned containers, even out of window", async () await setDoNotClean( path.join(paths.channelsDir, "ch", "data", "deleted"), true, - "deleted from source", + { by: "availability-check", via: "pre-clean-check", note: "deleted from source" }, ); const res = await pruneSavedVideos({ channelSlug: "ch", paths }); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -1590,10 +1590,15 @@ async function recordLiveRunInner( // 4. Keep it, and hand it on. if (req.doNotClean) { - await setDoNotClean(videoDir, true, req.note); + await setDoNotClean(videoDir, true, { + by: "live-recording", + via: "record-live", + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(req.note ? { note: req.note } : {}), + }); say(`Marked "Do not clean"${req.note ? `: ${req.note}` : ""}.`); } - await applyPendingKeep(paths, req.slug, id, onLog); + await applyPendingKeep(paths, req.slug, id, onLog, opts.jobId); const facts = await (deps.handoff ?? readHandoffFacts)({ slug: req.slug, channelConfig: opts.channelConfig, diff --git a/common/controller/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts @@ -75,6 +75,8 @@ export type VerifyBeforeCleanOptions = { onLog?: (msg: string) => void; signal?: AbortSignal; probes?: VerifyProbes; + // The clean job this gate runs in, recorded on every mark it writes. + jobId?: string; }; function emptyVerdicts(): CleanVerdicts { @@ -97,6 +99,7 @@ export async function verifyBeforeClean({ onLog, signal, probes, + jobId, }: VerifyBeforeCleanOptions): Promise<CleanVerdicts> { const log = onLog ?? ((m: string) => console.log(m)); const verdicts = emptyVerdicts(); @@ -111,11 +114,17 @@ export async function verifyBeforeClean({ verdicts.alreadyGone.add(id); return; } - await setDoNotClean( - videoDir, - true, - `deleted from source (pre-clean check): ${availability}`, - ); + const wrote = await setDoNotClean(videoDir, true, { + by: "availability-check", + via: "pre-clean-check", + ...(jobId ? { jobId } : {}), + note: `deleted from source (pre-clean check): ${availability}`, + }); + // A mark that appeared between the read above and the write is kept. + if (!wrote) { + verdicts.alreadyGone.add(id); + return; + } verdicts.pinned.set(id, availability); log(`Pinned ${id} as do-not-clean (${availability}) — gone from source.`); }; diff --git a/common/lib/cleanAudioConfirm.ts b/common/lib/cleanAudioConfirm.ts @@ -7,6 +7,7 @@ import { formatBytes } from "./format"; // The counts it states: the structural part of controller // cleanAudioFromTranscribed's AudioCleanPlan (lib may not import controller). +// `protected` includes the sourceGone group. export type CleanPlanCounts = { files: number; bytes: number; @@ -14,22 +15,59 @@ export type CleanPlanCounts = { protected: number; awaitingDiarization: number; awaitingVoiceprint: number; + sourceGone?: SourceGoneCounts; +}; + +export type SourceGoneCounts = { + videos: number; + files: number; + bytes: number; + inferred: { videos: number; files: number; bytes: number }; }; const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; -export function cleanConfirmationText(plan: CleanPlanCounts): { ask: string; kept: string; button: string } { +// THE OPT-IN'S CHECKBOX (lane mark-provenance), off by default, with its count. +export function sourceGoneOptInLabel(g: SourceGoneCounts): string { + return ( + `Also remove audio kept only because the source was gone (${plural(g.videos, "video")}, ` + + `${plural(g.files, "file")}, ${formatBytes(g.bytes)})` + ); +} + +// `includeSourceGone`: the opt-in is ticked. The group then has its own line +// (videos, files, bytes; the inferred part separately) and leaves the kept +// count; the button counts both. +export function cleanConfirmationText( + plan: CleanPlanCounts, + opts: { includeSourceGone?: boolean } = {}, +): { ask: string; sourceGone: string | null; kept: string; button: string; files: number } { + const g = plan.sourceGone; + const include = opts.includeSourceGone === true && !!g && g.videos > 0; + const files = plan.files + (include ? g!.files : 0); + const keptMarked = include ? plan.protected - g!.videos : plan.protected; return { ask: - plan.files === 0 + files === 0 ? "Nothing to remove: no transcribed video here holds audio a clean would take." : `Remove ${plural(plan.files, "audio file")} (${formatBytes(plan.bytes)}) from ${plural(plan.videos, "transcribed video")} without checking? ` + "The source is not asked, so the audio of videos no longer available anywhere is removed too.", + sourceGone: include + ? `Also removed, kept only because the source was gone: ${plural(g!.files, "audio file")} (${formatBytes(g!.bytes)}) ` + + `from ${plural(g!.videos, "video")} the availability check marked do not clean. Their marks stay.` + + (g!.inferred.videos > 0 + ? ` Of these, ${plural(g!.inferred.videos, "video")} (${plural(g!.inferred.files, "file")}, ${formatBytes(g!.inferred.bytes)}) ` + + "carry marks inferred from the records (marks-backfill), not written by the check itself." + : "") + : null, kept: - `Kept: ${plan.protected} marked do not clean or in the keep-latest window, ` + - `${plan.awaitingDiarization} awaiting diarization, ${plan.awaitingVoiceprint} awaiting voice fingerprint. ` + - "Videos with no transcript are not touched, and no saved video is.", - button: `Remove ${plural(plan.files, "file")} without checking`, + `Kept: ${keptMarked} marked do not clean or in the keep-latest window` + + (!include && g && g.videos > 0 ? ` (${g.videos} of them only because the source was gone)` : "") + + `, ${plan.awaitingDiarization} awaiting diarization, ${plan.awaitingVoiceprint} awaiting voice fingerprint. ` + + "Videos with no transcript are not touched, and no saved video is." + + (include ? " A mark set by a person, an import or a live recording is never touched." : ""), + button: `Remove ${plural(files, "file")} without checking`, + files, }; } diff --git a/common/lib/doNotClean-server.ts b/common/lib/doNotClean-server.ts @@ -1,19 +1,32 @@ import { + DO_NOT_CLEAN_BY, DO_NOT_CLEAN_FILENAME, + type DoNotCleanAudioRemoved, + type DoNotCleanEvidence, + type DoNotCleanProvenance, type DoNotCleanRecord, } from "./doNotClean"; import { sidecar, sidecarField } from "./sidecar-server"; +// THE ONE WRITER of `data/<id>/do-not-clean.json` (lane mark-provenance). Every +// mark is set, cleared, relabelled or annotated here and nowhere else; +// common/lib/doNotCleanGate.test.ts fails the build when any other source file +// names the sidecar or its file name on a code line. + // A parseable-but-malformed marker still means "protected" — it reads as an // empty record rather than as absent. Only an absent, unreadable or -// unparseable file reads as null (sidecar-server's rule). +// unparseable file reads as null (sidecar-server's rule). A `by` that is not +// one of the known writers is dropped: an unknown writer reads as the +// operator's (protected, never machine-set). export function coerceDoNotClean(value: unknown): DoNotCleanRecord { const parsed = value as Partial<DoNotCleanRecord> | null; - if (typeof parsed?.setAt === "string") return parsed as DoNotCleanRecord; - return { setAt: "" }; + if (typeof parsed?.setAt !== "string") return { setAt: "" }; + const out = { ...parsed } as DoNotCleanRecord; + if (out.by !== undefined && !(DO_NOT_CLEAN_BY as readonly string[]).includes(out.by)) delete out.by; + return out; } -export const doNotCleanSidecar = sidecar( +const doNotCleanSidecar = sidecar( DO_NOT_CLEAN_FILENAME, sidecarField(coerceDoNotClean), ); @@ -26,14 +39,80 @@ export async function isDoNotClean(videoDir: string): Promise<boolean> { return (await loadDoNotClean(videoDir)) !== null; } +// SET OR CLEAR a video's mark. Setting requires the writer's provenance. +// - by "availability-check" NEVER replaces a mark already there (a person's +// mark and note survive a machine's later finding): it writes only where +// there is none, and answers whether it wrote. +// - any other writer (a person, an import, a live recording) REPLACES the +// mark — a person's ask outranks the machine's, so a source-gone mark a +// person re-marks becomes theirs — and carries the earlier record's +// audioRemoved history over, so what was removed stays on record. +export async function setDoNotClean(videoDir: string, enabled: false): Promise<boolean>; +export async function setDoNotClean(videoDir: string, enabled: true, mark: DoNotCleanProvenance): Promise<boolean>; export async function setDoNotClean( videoDir: string, enabled: boolean, - note?: string, -): Promise<void> { - if (!enabled) return doNotCleanSidecar.remove(videoDir); - await doNotCleanSidecar.write(videoDir, { + mark?: DoNotCleanProvenance, +): Promise<boolean> { + if (!enabled) { + await doNotCleanSidecar.remove(videoDir); + return true; + } + if (!mark || !(DO_NOT_CLEAN_BY as readonly string[]).includes(mark.by) || !mark.via) { + throw new Error("A do-not-clean mark needs its writer (by and via)."); + } + const existing = await loadDoNotClean(videoDir); + if (existing && mark.by === "availability-check") return false; + const record: DoNotCleanRecord = { setAt: new Date().toISOString(), - ...(note ? { note } : {}), + ...(mark.note ? { note: mark.note } : {}), + by: mark.by, + via: mark.via, + ...(mark.surface ? { surface: mark.surface } : {}), + ...(mark.jobId ? { jobId: mark.jobId } : {}), + ...(existing?.audioRemoved?.length ? { audioRemoved: existing.audioRemoved } : {}), + }; + await doNotCleanSidecar.write(videoDir, record); + return true; +} + +// THE BACKFILL'S RELABEL (controller/marksBackfill.ts): only a mark that STILL +// has no `by` and the very setAt the proof was made against — a mark a person +// re-set since, or one a writer labelled since, is left alone. Everything the +// mark said is kept; it gains by/via, `inferred: true` and its evidence. +export async function relabelDoNotCleanInferred( + videoDir: string, + expect: { setAt: string }, + evidence: DoNotCleanEvidence, + now: Date = new Date(), +): Promise<boolean> { + const existing = await loadDoNotClean(videoDir); + if (!existing || existing.by !== undefined || existing.setAt !== expect.setAt) return false; + await doNotCleanSidecar.write(videoDir, { + ...existing, + by: "availability-check", + via: "pre-clean-check", + inferred: true, + inferredAt: now.toISOString(), + evidence, + }); + return true; +} + +// THE RECORD OF AUDIO REMOVED UNDER A MARK THAT STAYS (the opt-in "also remove +// audio kept only because the source was gone"): appended to a mark that +// still says by "availability-check". The mark is not removed — the video is +// still gone from its source — so every other cleaner (and the saved-video +// prune) keeps treating the video as protected. +export async function recordDoNotCleanAudioRemoved( + videoDir: string, + entry: DoNotCleanAudioRemoved, +): Promise<boolean> { + const existing = await loadDoNotClean(videoDir); + if (!existing || existing.by !== "availability-check") return false; + await doNotCleanSidecar.write(videoDir, { + ...existing, + audioRemoved: [...(existing.audioRemoved ?? []), entry], }); + return true; } diff --git a/common/lib/doNotClean.ts b/common/lib/doNotClean.ts @@ -10,9 +10,86 @@ // Marker semantics: presence of the file = protected. There is no stored // `enabled: false` state — toggling off removes the file — which keeps // isDoNotClean a simple existence check for the controllers' hot loops. +// +// WHO SET IT (lane mark-provenance). Every writer names itself: `by` is the +// kind of writer, `via` which one, `surface` where a person asked (a button or +// pnpm ops), `jobId` the job that wrote it when there is one. A mark with NO +// `by` was written before this was recorded and is the OPERATOR's: nothing +// reads it as machine-set — except a mark the explicit backfill +// (controller/marksBackfill.ts) proved from other records, which says +// `inferred: true` and carries its evidence. +export type DoNotCleanBy = "availability-check" | "live-recording" | "import" | "operator"; + +export const DO_NOT_CLEAN_BY: readonly DoNotCleanBy[] = ["availability-check", "live-recording", "import", "operator"]; + +export type DoNotCleanVia = + // by "availability-check": the checked clean's gate (verifyBeforeClean), the + // per-video clean after capture, the keep-latest window's deletion check. + | "pre-clean-check" + | "clean-after-capture" + | "kept-deleted-check" + // by "live-recording" / "import". + | "record-live" + | "import-media" + // by "operator": the video page's toggle (or `do-not-clean`), keep-videos by + // pattern, keep-videos by ids, and a by-ids keep applied when the video landed. + | "toggle" + | "keep-videos-match" + | "keep-videos-ids" + | "pending-keep"; + +export type DoNotCleanSurface = "button" | "ops"; + +// What a writer declares. Required by setDoNotClean: no mark is written +// without saying who wrote it. +export type DoNotCleanProvenance = { + by: DoNotCleanBy; + via: DoNotCleanVia; + surface?: DoNotCleanSurface; + jobId?: string; + note?: string; +}; + +// The proof a backfilled mark was relabelled on (marksBackfill.ts). +export type DoNotCleanEvidence = { + // availability.json's observation: the gone state, when the check saw it, + // and which part of the record said so. + availability: string; + observedAt: string; + field: "history" | "checkedAt"; + // The clean job whose log names the pin, running at setAt. + jobId: string; + jobKind: string; +}; + +// The audio a clean removed while the mark stayed (the opt-in "also remove +// audio kept only because the source was gone"): when, by which job, and why. +export type DoNotCleanAudioRemoved = { + at: string; + jobId?: string; + files: string[]; + bytes: number; + why: string; +}; + export type DoNotCleanRecord = { setAt: string; note?: string; + by?: DoNotCleanBy; + via?: DoNotCleanVia; + surface?: DoNotCleanSurface; + jobId?: string; + inferred?: true; + inferredAt?: string; + evidence?: DoNotCleanEvidence; + audioRemoved?: DoNotCleanAudioRemoved[]; }; export const DO_NOT_CLEAN_FILENAME = "do-not-clean.json"; + +// THE ONE READING of "kept only because the source was gone": a mark the +// availability check wrote (or one the backfill proved it wrote). An absent +// `by` is the operator's; every other `by` is a person's or a capture's ask. +export function isSourceGoneMark(m: DoNotCleanRecord | null | undefined): boolean { + return m?.by === "availability-check"; +} diff --git a/common/lib/doNotCleanGate.test.ts b/common/lib/doNotCleanGate.test.ts @@ -0,0 +1,85 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/doNotCleanGate.test.ts +// +// THE ONE WRITER OF do-not-clean.json, ENFORCED (lane mark-provenance). Every +// mark says who set it only if every write goes through lib/doNotClean-server.ts +// (setDoNotClean, which requires the writer's provenance, and the backfill's +// relabel and the opt-in's audioRemoved note beside it). A context-blind grep +// over every source file of the workspace, tests and e2e specs excepted (they +// build fixtures): no other file may name the sidecar's handle, its file-name +// constant or its file name on a code line. Comments may. + +const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); +const ROOTS = ["common", "editor", "umtool", "mcp", "scripts", "export", "homepage", "plans"]; +const SKIP_DIRS = new Set(["node_modules", ".next", "out", "dist", "public", "e2e", ".e2e-song", "test-results", ".git", "coverage"]); +const EXT = /\.(ts|tsx|mts|cts|js|mjs|cjs)$/; +const TEST = /\.(test|spec)\.[cm]?[jt]sx?$|\.unit\.ts$/; + +// The files that may name it, and why. +const ALLOWED = new Map<string, string>([ + ["common/lib/doNotClean.ts", "declares the file name"], + ["common/lib/doNotClean-server.ts", "THE writer"], + ["plans/tools/phase3-files-numbers.ts", "a read-only count of sidecars (loads through loadDoNotClean)"], +]); + +export const FORBIDDEN = [/do-not-clean\.json/, /\bdoNotCleanSidecar\b/, /\bDO_NOT_CLEAN_FILENAME\b/]; + +// A line's code, with `//` comments and block-comment lines dropped. +export function codeOf(line: string): string { + const t = line.trim(); + if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return ""; + const i = line.indexOf("//"); + // A `//` inside a string (a URL) is rare in these files; good enough for a gate. + return i >= 0 && !/["'`][^"'`]*\/\//.test(line.slice(0, i + 2)) ? line.slice(0, i) : line; +} + +export function offendingLines(text: string): number[] { + const out: number[] = []; + text.split("\n").forEach((line, i) => { + const code = codeOf(line); + if (FORBIDDEN.some((re) => re.test(code))) out.push(i + 1); + }); + return out; +} + +async function* walk(dir: string): AsyncGenerator<string> { + const entries = await readdir(dir, { withFileTypes: true }).catch(() => []); + for (const e of entries) { + if (e.isDirectory()) { + if (SKIP_DIRS.has(e.name) || e.name.startsWith(".")) continue; + yield* walk(path.join(dir, e.name)); + } else if (e.isFile() && EXT.test(e.name) && !TEST.test(e.name)) { + yield path.join(dir, e.name); + } + } +} + +test("the gate itself: a write outside the writer is caught; a comment is not", () => { + assert.deepEqual(offendingLines(`// do-not-clean.json is set by the toggle\nawait writeFile(path.join(dir, "do-not-clean.json"), "{}");`), [2]); + assert.deepEqual(offendingLines(`await doNotCleanSidecar.write(dir, {});`), [1]); + assert.deepEqual(offendingLines(`const f = path.join(dir, DO_NOT_CLEAN_FILENAME);`), [1]); + assert.deepEqual(offendingLines(` * the do-not-clean.json marker`), []); +}); + +test("nothing but lib/doNotClean-server.ts writes do-not-clean.json", async () => { + const offenders: string[] = []; + const seen = new Set<string>(); + for (const root of ROOTS) { + for await (const file of walk(path.join(REPO, root))) { + const rel = path.relative(REPO, file).split(path.sep).join("/"); + const lines = offendingLines(await readFile(file, "utf8")); + if (lines.length === 0) continue; + seen.add(rel); + if (!ALLOWED.has(rel)) offenders.push(`${rel}:${lines.join(",")}`); + } + } + assert.deepEqual(offenders, [], "write a do-not-clean mark through lib/doNotClean-server.ts (setDoNotClean, with its writer)"); + // The allow-list cannot rot: every entry still names it. + for (const rel of ALLOWED.keys()) assert.ok(seen.has(rel), `${rel} no longer names it: drop it from ALLOWED`); +}); diff --git a/common/lib/pendingKeep-server.ts b/common/lib/pendingKeep-server.ts @@ -17,10 +17,14 @@ import { stat } from "node:fs/promises"; import type { Paths } from "./paths"; import { readJsonFile, writeJsonAtomic } from "./jsonFile-server"; import { isDoNotClean, setDoNotClean } from "./doNotClean-server"; +import type { DoNotCleanSurface } from "./doNotClean"; export const PENDING_KEEP_FILENAME = "pending-keep.json"; -export type PendingKeepEntry = { id: string; note?: string; at: string }; +// `surface`: where the person asked (the Keep matching control's button or +// pnpm ops), carried onto the mark when it is applied. Absent on entries +// written before it was recorded. +export type PendingKeepEntry = { id: string; note?: string; at: string; surface?: DoNotCleanSurface }; function fileOf(paths: Pick<Paths, "channelsDir">, slug: string): string { return path.join(paths.channelsDir, slug, PENDING_KEEP_FILENAME); @@ -48,11 +52,12 @@ export async function addPendingKeep( ids: readonly string[], note: string | undefined, now: Date = new Date(), + surface?: DoNotCleanSurface, ): Promise<PendingKeepEntry[]> { const entries = await loadPendingKeep(paths, slug); for (const id of ids) { const i = entries.findIndex((e) => e.id === id); - const entry: PendingKeepEntry = { id, ...(note ? { note } : {}), at: now.toISOString() }; + const entry: PendingKeepEntry = { id, ...(note ? { note } : {}), at: now.toISOString(), ...(surface ? { surface } : {}) }; if (i >= 0) entries[i] = entry; else entries.push(entry); } @@ -69,6 +74,8 @@ export async function applyPendingKeep( slug: string, id: string, onLog?: (s: string) => void, + // The landing job (an import, a live recording), recorded on the mark. + jobId?: string, ): Promise<boolean> { try { const entries = await loadPendingKeep(paths, slug); @@ -76,7 +83,15 @@ export async function applyPendingKeep( if (!entry) return false; const videoDir = path.join(paths.channelsDir, slug, "data", id); if (!(await stat(videoDir).then((s) => s.isDirectory(), () => false))) return false; - if (!(await isDoNotClean(videoDir))) await setDoNotClean(videoDir, true, entry.note ?? "keep-videos: asked before it was fetched"); + if (!(await isDoNotClean(videoDir))) { + await setDoNotClean(videoDir, true, { + by: "operator", + via: "pending-keep", + ...(entry.surface === "button" || entry.surface === "ops" ? { surface: entry.surface } : {}), + ...(jobId ? { jobId } : {}), + note: entry.note ?? "keep-videos: asked before it was fetched", + }); + } await save( paths, slug, diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts @@ -134,7 +134,7 @@ test("doNotClean / excludeTruncatedCheck: a malformed marker still reads as pres test("setDoNotClean / setExcludedFromTruncatedCheck: write, load, remove", async () => { const dir = await scratch(); - await setDoNotClean(dir, true, "kept"); + await setDoNotClean(dir, true, { by: "operator", via: "toggle", note: "kept" }); const dnc = await loadDoNotClean(dir); assert.equal(dnc?.note, "kept"); assert.ok(dnc?.setAt); diff --git a/common/ytdlp/savedAlternates.test.ts b/common/ytdlp/savedAlternates.test.ts @@ -150,7 +150,7 @@ async function storeFiles(p: SavedVideoPointer): Promise<string[]> { test("an explicit persist over a landed copy: both kept, the download active, the landed one flagged; the pin stays", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "v7h6xzw", { landed: true }); - await setDoNotClean(dir, true, "keep"); + await setDoNotClean(dir, true, { by: "operator", via: "toggle", note: "keep" }); const log = await download(paths, dir, { explicit: true }); assert.match( log, @@ -207,7 +207,7 @@ test("an explicit persist much shorter than the landed copy still becomes active test("an automatic download over a landed copy of the same length: both kept, the landed one stays active", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vauto", { landed: true }); - await setDoNotClean(dir, true); + await setDoNotClean(dir, true, { by: "operator", via: "toggle" }); const log = await download(paths, dir, { explicit: false }); assert.match( log, diff --git a/editor/app/api/ops/_markProvenance.test.ts b/editor/app/api/ops/_markProvenance.test.ts @@ -0,0 +1,56 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFile, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { callPost, setupOpsCorpus } from "./_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/_markProvenance.test.ts" +// +// Lane mark-provenance over ops, against a temp corpus: the opt-in flag is +// checked at the door and the plan counts its group apart; marks-backfill is a +// dry run unless told otherwise, writes nothing then, and refuses an unknown +// key. Nothing here starts a job or revalidates a page. + +const corpus = await setupOpsCorpus("one-youtube-channel-with-data"); +type Post = Parameters<typeof callPost>[0]; +const route = async (name: string) => (await import(`./${name}/route`)).POST as Post; +const SLUG = "test-youtube"; +const VIDEO = "20240101_test1234567"; +test.after(() => corpus.cleanup()); + +const videoDir = () => path.join(corpus.transcripts, "channels", SLUG, "data", VIDEO); + +test("cleanup: includeSourceGone needs unchecked; the dry plan answers the source-gone group on its own", async () => { + const cleanup = await route("cleanup"); + const refused = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", includeSourceGone: true }); + assert.equal(refused.status, 400); + assert.match(String(refused.body.error), /"includeSourceGone" applies to a clean without checking only/); + const bad = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, dryRun: true, includeSourceGone: "yes" }); + assert.equal(bad.status, 400); + + const dry = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, dryRun: true, includeSourceGone: true }); + assert.equal(dry.status, 200, JSON.stringify(dry.body)); + const plan = dry.body.plan as { sourceGone: Record<string, unknown> }; + assert.deepEqual(Object.keys(plan.sourceGone).sort(), ["bytes", "files", "ids", "inferred", "videos"]); + assert.equal(dry.body.includeSourceGone, true); +}); + +test("marks-backfill: a dry run by default, writes nothing, says why a mark is not proven; unknown keys refused", async () => { + const backfill = await route("marks-backfill"); + const markFile = path.join(videoDir(), "do-not-clean.json"); + const before = JSON.stringify({ setAt: "2026-10-20T10:00:30.000Z", note: "deleted from source (pre-clean check): deleted" }); + await writeFile(markFile, before); + const r = await callPost(backfill, { slug: SLUG }); + assert.equal(r.status, 200, JSON.stringify(r.body)); + assert.equal(r.body.dryRun, true); + assert.deepEqual(r.body.relabelled, []); + assert.deepEqual(r.body.notProven, [{ id: VIDEO, setAt: "2026-10-20T10:00:30.000Z", reason: "no-availability-record" }]); + assert.equal(await readFile(markFile, "utf8"), before); + + const unknown = await callPost(backfill, { slug: SLUG, apply: true }); + assert.equal(unknown.status, 400); + const noChannel = await callPost(backfill, { slug: "no-such" }); + assert.equal(noChannel.status, 400); + assert.match(String(noChannel.body.error), /no-such/); +}); diff --git a/editor/app/api/ops/cleanup/route.ts b/editor/app/api/ops/cleanup/route.ts @@ -44,6 +44,17 @@ export const dynamic = "force-dynamic"; // whose config sets cleanAudioWithoutChecking runs "transcribed" unchecked // without the flag, discovering at start (nobody confirmed a count); the key // is re-read when the job starts. +// +// ALSO REMOVE AUDIO KEPT ONLY BECAUSE THE SOURCE WAS GONE (lane +// mark-provenance): "includeSourceGone": true, with "unchecked": true only — an +// explicit opt-in, default off, never implied by the channel key. The plan +// always answers that group on its own, {plan: {sourceGone: {ids, videos, +// files, bytes, inferred: {…}}}}: videos whose do-not-clean mark the +// availability check set (or marks-backfill proved it set) and that nothing +// else holds. With the flag the job carries those ids too and removes their +// audio; the marks stay and record it. A mark set by a person, an import or a +// live recording (or one from before marks said who set them) is never +// reached. const SWEEPS = { transcribed: cleanAudioAction, "extra-formats": cleanExtraAudioFormatsAction, @@ -52,11 +63,15 @@ const SWEEPS = { } as const; export async function POST(request: Request) { - return ops(request, ["slug", "sweep", "unchecked", "dryRun"], async (body) => { + return ops(request, ["slug", "sweep", "unchecked", "dryRun", "includeSourceGone"], async (body) => { const slug = reqSlug(body, "slug"); const sweep = oneOf(body, "sweep", Object.keys(SWEEPS) as (keyof typeof SWEEPS)[]); const unchecked = optBool(body, "unchecked") ?? false; const dryRun = optBool(body, "dryRun") ?? false; + const includeSourceGone = optBool(body, "includeSourceGone") ?? false; + if (includeSourceGone && !unchecked) { + throw new OpsInputError('"includeSourceGone" applies to a clean without checking only — give "unchecked": true'); + } if (unchecked && sweep !== "transcribed") { throw new OpsInputError('"unchecked" applies to the "transcribed" sweep only'); } @@ -66,7 +81,7 @@ export async function POST(request: Request) { if (unchecked && dryRun) { const r = await planCleanAudioUncheckedAction(slug); if (!r.ok) return opsFail(r.error); - return NextResponse.json({ ok: true, dryRun: true, plan: r.plan }); + return NextResponse.json({ ok: true, dryRun: true, ...(includeSourceGone ? { includeSourceGone: true } : {}), plan: r.plan }); } // A non-dry unchecked call is its own confirmation: its plan is computed // NOW and carried, so the job removes at most what this call would have @@ -76,11 +91,29 @@ export async function POST(request: Request) { if (unchecked) { const r = await planCleanAudioUncheckedAction(slug); if (!r.ok) return opsFail(r.error); - const { ids, ...counts } = r.plan; - const job = await cleanAudioUncheckedAction(slug, undefined, ids, counts); + const { ids, sourceGone, ...rest } = r.plan; + const groupCounts = { + videos: sourceGone.videos, + files: sourceGone.files, + bytes: sourceGone.bytes, + inferred: { videos: sourceGone.inferred.videos, files: sourceGone.inferred.files, bytes: sourceGone.inferred.bytes }, + }; + const counts = { ...rest, ...(includeSourceGone ? { sourceGone: groupCounts } : {}) }; + const job = await cleanAudioUncheckedAction( + slug, + undefined, + ids, + counts, + includeSourceGone ? sourceGone.ids : undefined, + ); if (!job.ok) return jobResponse(job); void job.stream.cancel(); - return NextResponse.json({ ok: true, jobId: job.jobId, plan: counts }); + return NextResponse.json({ + ok: true, + jobId: job.jobId, + plan: { ...rest, sourceGone: groupCounts }, + includeSourceGone, + }); } return jobResponse(await SWEEPS[sweep](slug)); }); diff --git a/editor/app/api/ops/do-not-clean/route.ts b/editor/app/api/ops/do-not-clean/route.ts @@ -16,6 +16,7 @@ export async function POST(request: Request) { reqSlug(body, "slug"), reqVideoId(body, "id"), optBool(body, "keep") ?? true, + "ops", ); if (!res.ok) return opsFail(res.error); return NextResponse.json({ ok: true }); diff --git a/editor/app/api/ops/keep-videos/route.ts b/editor/app/api/ops/keep-videos/route.ts @@ -46,6 +46,7 @@ export async function POST(request: Request) { ids: reqStringArray(body, "ids"), note: optString(body, "note"), dryRun: optBool(body, "dryRun"), + surface: "ops", }); if (!result.ok) return opsFail(result.error); return NextResponse.json({ ok: true, ...result.result }); @@ -71,6 +72,7 @@ export async function POST(request: Request) { fields, note: optString(body, "note"), dryRun: optBool(body, "dryRun"), + surface: "ops", }); if (!result.ok) return opsFail(result.error); return NextResponse.json({ ok: true, ...result.result }); diff --git a/editor/app/api/ops/marks-backfill/route.ts b/editor/app/api/ops/marks-backfill/route.ts @@ -0,0 +1,24 @@ +import { NextResponse } from "next/server"; +import { marksBackfillAction } from "../../../channels/actions"; +import { ops, opsFail, optBool, reqSlug } from "../_lib"; + +export const dynamic = "force-dynamic"; + +// POST { slug, dryRun?: true } +// -> { ok, slug, dryRun, marks, labelled, relabelled: [{id, setAt, evidence: +// {availability, observedAt, field, jobId, jobKind}}], notProven: [{id, +// setAt, reason}], oldestCleanJobAt } +// +// Relabel a channel's do-not-clean marks written before marks said who set +// them as set by the availability check (`by: "availability-check", +// inferred: true`) — ONLY where the records prove it: availability.json says +// the check found the video gone within a minute of the mark, and a clean +// job's log, running then, names the pin. Never from the mark's note. Every +// other old mark stays the operator's. A DRY RUN unless "dryRun": false. +export async function POST(request: Request) { + return ops(request, ["slug", "dryRun"], async (body) => { + const r = await marksBackfillAction(reqSlug(body, "slug"), optBool(body, "dryRun") ?? true); + if (!r.ok) return opsFail(r.error); + return NextResponse.json({ ok: true, ...r.result }); + }); +} diff --git a/editor/app/channels/[slug]/components/stages/CleanWithoutChecking.tsx b/editor/app/channels/[slug]/components/stages/CleanWithoutChecking.tsx @@ -7,6 +7,7 @@ import type { ScheduledCleanRetry } from "yt-dlp-transcript-common/controller/cl import { TURN_ON_CONFIRMATION, cleanConfirmationText, + sourceGoneOptInLabel, } from "yt-dlp-transcript-common/lib/cleanAudioConfirm"; import { cancelJobAction } from "../../../../jobs/actions"; import { setCleanAudioWithoutCheckingAction } from "../../../actions"; @@ -27,7 +28,11 @@ const EXPIRING_VOD_PLATFORMS = new Set(["twitch", "kick"]); // deletes) and stated, then a second button runs THAT plan — the job carries // its video ids and removes at most those. `mode`: "button" is the one-off // "Clean without checking"; "channel-setting" is Clean audio on a channel whose -// key is on (the key is read again when the job starts). +// key is on (the key is read again when the job starts). The one-off also +// offers the opt-in "also remove audio kept only because the source was gone" +// (lane mark-provenance): unticked by default, never offered on the +// channel-key path; ticked, its group gets its own line and the job carries +// its ids. export function CleanWithoutCheckingSection({ slug, mode = "button", @@ -41,17 +46,23 @@ export function CleanWithoutCheckingSection({ const [plan, setPlan] = useState<AudioCleanPlan | null>(null); const [error, setError] = useState<string | null>(null); const [busy, setBusy] = useState(false); + const [includeSourceGone, setIncludeSourceGone] = useState(false); const ask = async () => { setBusy(true); setError(null); + setIncludeSourceGone(false); const r = await planCleanAudioUncheckedAction(slug); setBusy(false); if (r.ok) setPlan(r.plan); else setError(r.error); }; - const text = plan ? cleanConfirmationText(plan) : null; - const run = (ids: string[]) => - mode === "button" ? cleanAudioUncheckedAction(slug, queueKey, ids) : cleanAudioAction(slug, queueKey, ids); + const offerSourceGone = mode === "button" && !!plan && plan.sourceGone.videos > 0; + const include = offerSourceGone && includeSourceGone; + const text = plan ? cleanConfirmationText(plan, { includeSourceGone: include }) : null; + const run = (p: AudioCleanPlan) => + mode === "button" + ? cleanAudioUncheckedAction(slug, queueKey, p.ids, undefined, include ? p.sourceGone.ids : undefined) + : cleanAudioAction(slug, queueKey, p.ids); return ( <div aria-label="clean without checking section" className="flex flex-col gap-2 rounded border border-border p-3"> <div> @@ -84,11 +95,24 @@ export function CleanWithoutCheckingSection({ {plan && text && ( <div role="group" aria-label="confirm clean without checking" className="flex flex-col gap-2"> <p className="text-sm font-medium">{text.ask}</p> + {offerSourceGone && ( + <label className="flex items-center gap-2 text-sm"> + <input + type="checkbox" + checked={includeSourceGone} + onChange={(e) => setIncludeSourceGone(e.target.checked)} + aria-label="also remove audio kept only because the source was gone" + /> + {sourceGoneOptInLabel(plan.sourceGone)} + </label> + )} + {text.sourceGone && <p className="text-sm font-medium">{text.sourceGone}</p>} <p className="text-xs text-muted-foreground">{text.kept}</p> <div className="flex flex-wrap items-start gap-2"> - {plan.files > 0 && ( + {text.files > 0 && ( <StreamActionLog - trigger={() => run(plan.ids)} + key={include ? "with-source-gone" : "plain"} + trigger={() => run(plan)} cancelAction={cancelJobAction} buttonLabel={text.button} runningLabel="Cleaning…" diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -1294,10 +1294,13 @@ export async function markVideoUntranscribableAction( return { ok: true }; } +// `surface`: where the person asked — the video page's toggle ("button", the +// default) or `pnpm ops do-not-clean` ("ops"); recorded on the mark. export async function toggleDoNotCleanAction( slug: string, videoId: string, enabled: boolean, + surface: "button" | "ops" = "button", ): Promise<{ ok: true } | { ok: false; error: string }> { const videoDir = videoDirOf(slug, videoId); try { @@ -1308,7 +1311,8 @@ export async function toggleDoNotCleanAction( } catch { return { ok: false, error: `Video directory not found: ${videoId}` }; } - await setDoNotClean(videoDir, enabled); + if (enabled) await setDoNotClean(videoDir, true, { by: "operator", via: "toggle", surface: surface === "ops" ? "ops" : "button" }); + else await setDoNotClean(videoDir, false); revalidatePath(`/channels/${slug}/videos/${videoId}`); revalidatePath(`/channels/${slug}`); requestChannelSnapshot(getPaths(), slug); @@ -1328,6 +1332,7 @@ export async function keepVideosAction(input: { fields?: KeepVideosField[]; note?: string; dryRun?: boolean; + surface?: "button" | "ops"; }): Promise<{ ok: true; result: KeepVideosResult } | { ok: false; error: string }> { let result: KeepVideosResult; try { @@ -1338,6 +1343,7 @@ export async function keepVideosAction(input: { fields: input.fields, note: input.note, dryRun: input.dryRun, + surface: input.surface === "button" ? "button" : "ops", }); } catch (e) { if (e instanceof KeepVideosError || e instanceof ChannelMediaUnreachableError) { @@ -1363,6 +1369,9 @@ export async function keepVideoIdsAction(input: { ids: string[]; note?: string; dryRun?: boolean; + // Where the person asked: the Keep matching control ("button", the + // default) or `pnpm ops keep-videos` ("ops"). + surface?: "button" | "ops"; }): Promise<{ ok: true; result: KeepVideosByIdsResult } | { ok: false; error: string }> { let result: KeepVideosByIdsResult; try { @@ -1372,6 +1381,7 @@ export async function keepVideoIdsAction(input: { ids: input.ids, note: input.note, dryRun: input.dryRun, + surface: input.surface === "ops" ? "ops" : "button", }); } catch (e) { if (e instanceof KeepVideosError || e instanceof ChannelMediaUnreachableError) { diff --git a/editor/app/channels/[slug]/whisperActions.ts b/editor/app/channels/[slug]/whisperActions.ts @@ -354,6 +354,8 @@ export async function cleanAudioButtonAction( // not asked; every other protection of the sweep holds; at most the plan's // videos lose their audio. A call with no plan queues a job that removes // nothing and ends failed, "Confirmed plan lost; confirm again". +// `sourceGone`: the opt-in "also remove audio kept only because the source was +// gone", as the plan's sourceGone ids a person confirmed (default: none — off). export async function cleanAudioUncheckedAction( slug: string, queueKey?: string, @@ -361,9 +363,16 @@ export async function cleanAudioUncheckedAction( // The plan's counts, stated in the job's log before anything is removed // (`pnpm ops cleanup {"unchecked": true}` counts at the call). planCounts?: CleanPlanCountsLog, + sourceGone?: string[], ): Promise<StreamActionResult> { await supersedeCleanRetries(slug); - return runCleanAudio(slug, queueKey, cleanAudioRequestFor(null, { explicit: "button", plan }), undefined, planCounts); + return runCleanAudio( + slug, + queueKey, + cleanAudioRequestFor(null, { explicit: "button", plan, ...(sourceGone ? { sourceGone } : {}) }), + undefined, + planCounts, + ); } // The retry of a rate-limited clean, queued by its schedule at its not-before @@ -426,7 +435,7 @@ function runCleanAudio( ): Promise<StreamActionResult> { const paths = getPaths(); const kind = retry ? "clean-audio-retry" : req.kind; - const { unchecked, plan } = req; + const { unchecked, plan, sourceGone } = req; // A retry runs on the CHANNEL's queue, whatever queue the request took. const key = retry ? channelQueueKey(slug) : resolveQueueKey(channelQueueKey(slug), queueKey); return runManagedFunction({ @@ -442,6 +451,7 @@ function runCleanAudio( ...(unchecked ? { unchecked } : {}), ...(plan ? { plan } : {}), ...(plan && planCounts ? { planCounts } : {}), + ...(sourceGone ? { sourceGone } : {}), ...(retry ? { retry } : {}), }, }, @@ -459,6 +469,7 @@ function runCleanAudio( ...(unchecked ? { unchecked } : {}), ...(plan ? { plan } : {}), ...(plan && planCounts ? { planCounts } : {}), + ...(sourceGone ? { sourceGone } : {}), ...(retry ? { retry } : {}), onLog, signal, @@ -571,12 +582,13 @@ export async function checkKeptDeletedAction( paths, channelSlug: slug, spec: { kind: "check-kept-deleted", slug, params: { queueKey } }, - fn: async (onLog, signal) => { + fn: async (onLog, signal, _setProgress, ctx) => { const result = await checkKeptDeleted({ channelSlug: slug, paths, onLog, signal, + jobId: ctx.jobId, }); onLog( `Kept-deletion check: inspected ${result.kept}, ${result.deleted} gone from source, pinned ${result.pinned}.`, diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts @@ -1,6 +1,7 @@ "use server"; import { cancelCleanRetries } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; +import { backfillMarkProvenance, type MarkBackfillResult } from "yt-dlp-transcript-common/controller/marksBackfill"; import { cleanRetryDeps } from "./[slug]/cleanRetryScheduler"; import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { prepareLocalArchiveChannel } from "./lib/prepareLocalArchiveChannel"; @@ -667,6 +668,28 @@ export async function setCleanAudioWithoutCheckingAction( return undefined; } +// MARKS-BACKFILL (lane mark-provenance; `pnpm ops marks-backfill`): relabel a +// channel's old do-not-clean marks as set by the availability check, inferred, +// only where availability.json and a clean job's log prove it. Dry run unless +// `dryRun` is exactly false. No UI: an operator's one-off, from the CLI. +export async function marksBackfillAction( + slug: string, + dryRun = true, +): Promise<{ ok: true; result: MarkBackfillResult } | { ok: false; error: string }> { + const paths = getPaths(); + if (!(await readChannelConfig(paths, slug))) return { ok: false, error: `Channel "${slug}" not found` }; + try { + const result = await backfillMarkProvenance({ paths, channelSlug: slug, dryRun: dryRun !== false }); + if (!result.dryRun && result.relabelled.length > 0) { + revalidatePath(`/channels/${slug}`); + revalidatePath("/cleanup"); + } + return { ok: true, result }; + } catch (err) { + return { ok: false, error: (err as Error).message }; + } +} + // Toggle whether this channel's reclaimable bytes count toward the aggregate // "cleanable data" total on the /cleanup page (and its sidebar badge). The // cleanup sweeps themselves stay available regardless; this only flips the diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -121,6 +121,8 @@ // pnpm ops lane --json '{"lane":"publish","action":"drain"}' // pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait // pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}' +// pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"includeSourceGone":true}' --wait +// pnpm ops marks-backfill --json '{"slug":"x"}' // pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}' // pnpm ops get job <jobId> --tail 20 // pnpm ops get jobs --failed --slug x @@ -709,6 +711,10 @@ const ACTIONS = [ "do-not-clean", "drop-saved-alternate", "cleanup", + // Relabel a channel's old do-not-clean marks as set by the availability + // check, inferred, where its records prove it ({slug, dryRun?: true}). + // Synchronous; a dry run unless "dryRun": false. + "marks-backfill", // The Cleanup stage's "Diarize speakers" for one channel: diarization and // voice fingerprints for the videos still holding audio. "diarize", @@ -1795,6 +1801,15 @@ export function usage() { 'do-not-clean sets one video\'s "Do not clean" marker: {"slug", "id",', ' "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.)', "", + 'marks-backfill relabels a channel\'s old do-not-clean marks (no "by") as', + ' set by the availability check, "inferred": true, only where the records', + ' prove it: availability.json says a check found the video gone within a', + ' minute of the mark, and a clean job of the channel running then names', + ' the pin in its log. Never from the note. {"slug", "dryRun"?: true} — a', + ' dry run unless "dryRun": false; answers {marks, labelled, relabelled:', + ' [{id, setAt, evidence}], notProven: [{id, setAt, reason}],', + ' oldestCleanJobAt}.', + "", 'drop-saved-alternate deletes one saved alternate of one video, as its', ' "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}.', ' "file" is a name `get saved-alternates` lists under "alternates"; the', @@ -1833,6 +1848,14 @@ export function usage() { ' videos\' audio. It never touches a saved video. With the channel\'s', ' cleanAudioWithoutChecking on, "transcribed" with no flag runs unchecked', ' with no count (so do job retry and retry-failed of a clean).', + ' "includeSourceGone": true (with "unchecked" only; off by default, never', + ' implied by the channel key, never replayed) also removes the audio of', + ' videos kept ONLY because the source was gone: a mark by the', + ' availability check (inferred ones included) that nothing else holds.', + ' The plan counts that group apart, {plan: {sourceGone: {ids, videos,', + ' files, bytes, inferred: {ids, videos, files, bytes}}}}; the marks stay', + ' and record the removal. A mark a person, an import or a live recording', + ' set, or one from before marks said who set them, is never reached.', ' A checked clean the source rate-limits ends deferred and schedules a', ' retry off the queue after at least 15 min (twice at most), then gives', ' up; `job cancel <the deferred job id>` cancels the retry.', diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -939,6 +939,7 @@ test("the archival writes are POSTs to their routes, each named in the usage", ( "do-not-clean", "drop-saved-alternate", "cleanup", + "marks-backfill", ]) { const p = parseArgs([action, "--json", "{}"]); assert.equal(p.method, "POST", action); @@ -949,6 +950,9 @@ test("the archival writes are POSTs to their routes, each named in the usage", ( assert.equal(parseArgs(["get", "settings"]).method, "GET"); assert.match(usage(), /"dryRun": true answers each channel's preview/); assert.match(usage(), /"publish", "enabled"\?, "held"\?, "action"\?/); + // Lane mark-provenance: the opt-in and the backfill are named with their limits. + assert.match(usage(), /"includeSourceGone": true \(with "unchecked" only; off by default, never/); + assert.match(usage(), /dry run unless "dryRun": false/); }); // COOKIE REFRESH ALERTS: the read side and the banner's three buttons.