commit 805d3c01770466a363532a5aaef69e873a323b05
parent db9e6086342454ee4634f237ec1fc1c48a4f458f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 16:35:56 -0500
Merge lane/mark-provenance: a do-not-clean mark says who set it
Every mark records who set it and how, through one writer. A person's keep or note makes a machine-set
mark theirs. The one-off confirmed unchecked clean may also remove audio kept only because the source was
gone, on an explicit opt-in with its own count; the mark stays.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
38 files changed, 2266 insertions(+), 140 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -204,9 +204,10 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` |
| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. Only a download waits on the platform's queue: the transcription runs as a transcribe-one job on the video's own queue (transcribe-one:<slug>:<id>), at once when nothing is downloaded, else handed off by the whisper-video once the audio is down. A job; --wait follows it through the hand-off to the end of the transcription. "queueKey" names another queue. A youtube-handling video with no audio whose metadata lists English captions has those fetched instead ({"instead": "captions", "message"}, the job the caption download), one with an English caption track on disk is refused; "asr": true transcribes it anyway (no "file"). "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false — once its full audio was tried: when its record stores an Odysee media URL, that URL is downloaded first, up to 2 times (20 min apart), and the salvage follows only if neither download is clean. "storedUrl": "only" \| "fallback" \| "never" downloads missing audio from the media URL the record stores (Odysee's CDN), read in ranges as its player reads it — no page request with "only", the page first with "fallback" — through the audio check; one new file per platform per 20 min. Absent = the channel's storedUrlDownloads. "whilePaused": true runs this one transcription during a pause-all on a worker the pause alone switched off; the pause stays on (the video page's "Transcribe now (workers paused)"). A video its record says is live, scheduled or still processing its VOD (live\_status is\_live, is\_upcoming, post\_live) is refused before anything is queued — a download would read the stream at 1x and hold the platform queue: record it with record-live, or wait for the VOD (refresh-metadata re-reads the record once it has ended). With its audio on disk it transcribes. | |
| `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. A raw live chat named in one form while the other is there (transcript.live\_chat.json and its .zst): only the named one goes, never the other, and "note" says the other is still there. | |
-| `do-not-clean` | 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.) | |
+| `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true, "note"?}; "keep": false removes it. (keep-videos is the bulk form.) On a mark another writer set (the availability check, an import, a live recording) "keep": true MAKES IT YOURS (the video page's "Make it mine"): {outcome: "taken-over"}; a "note" is written on it, and on a mark already yours. keep-videos takes such marks over too. | |
| `drop-saved-alternate` | 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 active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. An ORIGINAL ("keptAs": "original", the source of a compacted copy) needs "confirmOriginal": true; the compacted copy is read back from disk (size, sha256, container, length) before it goes; a video not freshly checked on its platform needs a review of this copy recorded first; and nothing goes while a download or persist of the video is queued or running, or while it is being compacted. A FORMER original ("former-original") needs its own "confirmFormerOriginal": true, and the same gone/review rule. | |
-| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. "unchecked": true (transcribed only) is "Clean without checking": the source is not asked, so the audio of videos no longer available anywhere goes too; every other protection holds; the job is "Clean audio without checking". With "dryRun": true it answers what it would remove — {plan: {ids, videos, files, bytes, protected, awaitingDiarization, awaitingVoiceprint, inspected}} — and starts nothing; without it the plan is counted at the call, its counts answered ({jobId, plan}) and logged, and the job removes at most those 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). 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. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait`<br>`pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}'` |
+| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. "unchecked": true (transcribed only) is "Clean without checking": the source is not asked, so the audio of videos no longer available anywhere goes too; every other protection holds; the job is "Clean audio without checking". With "dryRun": true it answers what it would remove — {plan: {ids, videos, files, bytes, protected, awaitingDiarization, awaitingVoiceprint, inspected}} — and starts nothing; without it the plan is counted at the call, its counts answered ({jobId, plan}) and logged, and the job removes at most those 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. The reply and the job's log state that group's counts; "expectSourceGone": <the dry run's plan.sourceGone.videos> refuses (409) a count that changed. 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. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait`<br>`pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}'`<br>`pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"includeSourceGone":true}' --wait` |
+| `marks-backfill` | 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}. The proof is one-sided: observed by the check, then pinned within the minute, inside the job's run. {"slug", "undo": true, "dryRun"?: true} returns every INFERRED label to unlabelled (the operator's): {unlabelled: \[{id, setAt, evidence}\], changedSince}. | `pnpm ops marks-backfill --json '{"slug":"x"}'` |
| `diarize` | diarize runs a channel's "Diarize speakers" as a job: {"slug"}. Every video still holding audio with no current diarization.json is diarized, and a diarized one without voice fingerprints gets them from its own turns — the voiceprint backfill, one channel at a time. Runs while the Speakers lane is paused; nothing is deleted. | `pnpm ops diarize --json '{"slug":"x"}' --wait` |
| `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -> {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` |
| `web-fetch` | web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at most 60000)} -> {page: {url, finalUrl, status, contentType, title?, text, truncated}}. http and https only; a private or loopback host (by name, by address, or by what its name resolves to, every redirect checked) is refused before any request, and so is a page that is not text (a PDF, an image). Read only, on the same web queue as web-search. | `pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'` |
@@ -269,6 +270,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get saved-alternates [<slug>]
pnpm ops get compaction-review [<slug>]
pnpm ops get kept-originals [<slug>]
+ pnpm ops get marks <slug>
pnpm ops get services
pnpm ops get x-session [<slug>]
pnpm ops get cookies [fresh]
@@ -340,6 +342,11 @@ get compaction-review [<slug>] lists every compacted saved video and what
availability and why, the original's entry, sizes, checks, the re-check,
"watch" (both files and an smplayer command that plays them) and any
"leftover" of an interrupted drop.
+get marks <slug> lists the channel's do-not-clean marks and who set each
+ one and when, as the video page says it ("setBy": "availability check,
+ 3 Nov; the source was gone" | "you, 20 Nov" | "import, …" | "live
+ recording, …"), with "mine" and "sourceGone" (the marks Clean without
+ checking's opt-in can reach). `do-not-clean {"keep": true}` makes one yours.
get kept-originals [<slug>] lists every saved video that keeps an original
("keptAs": "original") or a former original ("former-original") beside
its active copy, or has a drop in flight (pendingDrops: a file the pointer
diff --git a/OPERATING.md b/OPERATING.md
@@ -1102,6 +1102,12 @@ pnpm ops diarize --json '{"slug":"example"}' --wait # one channe
pnpm ops cleanup --json '{"slug":"example","sweep":"transcribed","unchecked":true,"dryRun":true}' # what it would remove
pnpm ops cleanup --json '{"slug":"example","sweep":"transcribed","unchecked":true}' --wait # Clean without checking
pnpm ops channel-config --json '{"slug":"example","cleanAudioWithoutChecking":true}' # always, for this channel
+pnpm ops cleanup --json '{"slug":"example","sweep":"transcribed","unchecked":true,"includeSourceGone":true}' --wait # and audio kept only because the source was gone
+pnpm ops marks-backfill --json '{"slug":"example"}' # which old marks the records prove (dry run)
+pnpm ops marks-backfill --json '{"slug":"example","dryRun":false}' # relabel them
+pnpm ops marks-backfill --json '{"slug":"example","undo":true}' # which inferred labels an undo returns (dry run)
+pnpm ops get marks example # who set each mark, and when
+pnpm ops do-not-clean --json '{"slug":"example","id":"<id>","keep":true}' # make a machine-set mark yours
```
- **Clean audio checks first**: before deleting a transcribed video's audio it asks the source whether the video is
@@ -1135,8 +1141,46 @@ pnpm ops channel-config --json '{"slug":"example","cleanAudioWithoutChecking":tr
new channel never starts with it. Clean after capture still holds a URL-less channel
(`cleanAfterCaptureUnverified`) and a whole-recording one (`diarization.cleanWholeRecordingAudio`) — those holds
are not the availability check. Audio an earlier checked clean pinned as "deleted from source (pre-clean check)"
- stays do-not-clean: unpin it on the video page (or `pnpm ops do-not-clean --json '{"slug":"example","id":"<id>","keep":false}'`) to let
- it go.
+ stays do-not-clean: let it go with the opt-in below, or unpin it on the video page (or `pnpm ops do-not-clean
+ --json '{"slug":"example","id":"<id>","keep":false}'`).
+- **Who set a do-not-clean mark** is in the mark (`data/<id>/do-not-clean.json`): `by` is `availability-check` (the
+ checked clean's gate, clean after capture, the keep-latest window's deletion check), `live-recording`
+ (`record-live`), `import` (`import-media`) or `operator` (the video page's toggle, `do-not-clean`, `keep-videos`,
+ and a keep asked for before the video landed); `via` says which, `surface` where a person asked (`button` or
+ `ops`) and `jobId` the job that wrote it. A machine never replaces a mark that is there. **Any keep by a person
+ makes a mark set by another writer theirs** (`by: "operator"`, with its via, surface and the note given, else the
+ mark's own note; `takenOver` records who had set it): keep-videos by pattern or by ids, a keep asked for before
+ the video landed, the video page's toggle and **Make it mine**, `do-not-clean {"keep": true}`, and writing a note
+ on it. "Already kept" is said only of a mark that is already a person's (a note given is still written on it).
+ A mark from before this has no `by` and is treated as the operator's. **Every surface says who set it and when**:
+ the video page ("Do not clean: on (availability check, 3 Nov; the source was gone)" or "(you, 20 Nov)"), the
+ Keep matching control's lists, keep-videos' answer (`keptBy`, `takenOver`) and `pnpm ops get marks <slug>`
+ (`setBy`, `mine`, `sourceGone`).
+- **"Also remove audio kept only because the source was gone"** — a checkbox on Clean without checking's
+ confirmation, off by default, and `"includeSourceGone": true` with `"unchecked": true` over ops. Never implied by
+ `cleanAudioWithoutChecking`, never on Clean audio, never carried by a Retry or a restart. It reaches ONLY marks
+ with `by: "availability-check"` (inferred ones included) that nothing else holds (the keep-latest window, the
+ speaker holds); a mark set by a person, an import, a live recording, or one with no `by`, is never reached. The
+ plan always counts that group apart (`plan.sourceGone`: ids, videos, files, bytes, and `inferred` the same), and
+ the ticked confirmation gives it its own line: "Also removed, kept only because the source was gone: N audio files
+ (X) from M videos the availability check marked do not clean. Their marks stay." — with the inferred part named
+ after it. The job carries those ids; each removal happens under the mark's lock, after re-reading it there, and
+ its record is written before the lock is released — a person's keep is either first (nothing removed) or after.
+ Over ops the reply answers the group's counts and the job's log states them before anything is removed;
+ `"expectSourceGone": <the dry run's plan.sourceGone.videos>` refuses (409) a count that changed since. The mark
+ stays (the video is still gone, so every other cleaner and the saved-video prune keep it) and gains
+ `audioRemoved: [{at, jobId, files, bytes, why}]`.
+- **`marks-backfill`** relabels an OLD mark (no `by`) as `by: "availability-check", inferred: true` only when the
+ records prove it, never from its note: `availability.json` says a **check** found the video gone at most a minute
+ **before** the mark's `setAt` (one-sided: the gate pins only after the check has recorded what it saw, on the
+ same clock), AND a finished Clean audio job of the channel (or its rate-limit retry) that started at or before
+ `setAt` and ended at or after it has the line `Pinned <id> as do-not-clean (<that state>)` in its log. A dry run unless `"dryRun": false`; it lists
+ every mark it would relabel with that evidence, and every other with why not (`notProven`, and
+ `oldestCleanJobAt` — job logs are pruned by retention). What it cannot prove: a pin made on a **cached** verdict
+ (the check ran days before the clean), any mark older than the oldest job log kept, a mark whose availability
+ record a later recheck moved, and every keep-latest-check or clean-after-capture pin (not a clean job's). Those
+ stay the operator's; unpin them by hand. `{"undo": true}` (a dry run unless `"dryRun": false`, the same listing)
+ returns every **inferred** label to unlabelled — the operator's again; setAt, note and audioRemoved stay.
- **A checked clean the source rate-limits** (HTTP 429 on the channel listing or on a confirmation probe) deletes
nothing it could not verify and ends **deferred** on /jobs, with its counts. **The 429 counts toward the
platform's pace and hold**: a rate-limited listing records the platform's cooldown as Sync does
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, removeUnderSourceGoneMark, 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,53 @@ 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;
+ // UNDER THE MARK'S LOCK (review F3): the mark is re-checked after the
+ // lock is taken and the removal and its record happen before it is
+ // released, so a person who re-marks the video — before or meanwhile —
+ // is either first (theirs: nothing removed) or after (the audio is gone
+ // and recorded on the mark they then take over).
+ let removed = 0;
+ const done = await removeUnderSourceGoneMark(
+ c.videoDir,
+ async () => {
+ const r = await removeCandidateAudio(c, log);
+ removed = r.removed;
+ return { files: c.audioFiles, bytes: r.bytes };
+ },
+ {
+ at: new Date().toISOString(),
+ ...(jobId ? { jobId } : {}),
+ 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.",
+ },
+ );
+ if (!done) {
+ log(`Skipped ${c.id} (marked do not clean — no longer by the availability check)`);
+ protectedCount++;
+ continue;
+ }
+ const out = { removed, bytes: done.bytes };
+ log(
+ done.recorded
+ ? `Removed the audio of ${c.id}, kept only because the source was gone${c.inferred ? " (mark inferred)" : ""}; its mark stays.`
+ : `Removed the audio of ${c.id}, but its mark could not record it: this log is the record.`,
+ );
+ 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 +483,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 +501,7 @@ async function discoverAudioCandidates({
dirs,
log,
signal,
+ sourceGone = false,
}: {
paths: Paths;
channelSlug: string;
@@ -389,8 +509,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 +533,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 +563,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 +601,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 +731,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));
@@ -123,7 +123,10 @@ test("an already-kept video is counted and not rewritten", async () => {
downloaded: true,
alreadyKept: true,
marked: false,
+ // Who had set it, in the page's words (lane mark-provenance review F2).
+ keptBy: r.matched[0].keptBy,
});
+ assert.match(String(r.matched[0].keptBy), /^you, /);
assert.equal((await stat(markerFile)).mtimeMs, before);
assert.equal((await loadDoNotClean(dir))?.note, "by hand");
},
diff --git a/common/controller/keepVideosMatching.ts b/common/controller/keepVideosMatching.ts
@@ -2,7 +2,9 @@ import path from "node:path";
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 { keepByPerson } from "../lib/doNotClean-server";
+import { describeDoNotCleanMark } from "../lib/doNotClean";
+import type { DoNotCleanSurface } from "../lib/doNotClean";
import { addPendingKeep, loadPendingKeep, type PendingKeepEntry } from "../lib/pendingKeep-server";
import {
classifyAgainstFilter,
@@ -71,6 +73,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 = {
@@ -78,10 +83,20 @@ export type KeepVideosMatch = {
title: string;
// Has a data/<id>/ dir — the only kind that can carry the marker.
downloaded: boolean;
- // Already carried a marker before this call; left untouched.
+ // Already carried a PERSON's marker before this call (by "operator", or one
+ // from before marks said who set them); left untouched unless a note was
+ // given.
alreadyKept: boolean;
// This call wrote the marker (always false on a dry run).
marked: boolean;
+ // The marker another writer set (the availability check, an import, a live
+ // recording) was taken over: it is the operator's now (would be, on a dry
+ // run). Counted in `marked` too when written.
+ takenOver?: boolean;
+ // Who had set the marker there before this call, and when
+ // (describeDoNotCleanMark): "availability check, 3 Nov; the source was
+ // gone", "you, 20 Nov". Absent when there was none.
+ keptBy?: string;
};
export type KeepVideosResult = {
@@ -92,6 +107,9 @@ export type KeepVideosResult = {
matched: KeepVideosMatch[];
marked: number;
alreadyKept: number;
+ // Of `marked` (would be, on a dry run): marks another writer set, now the
+ // operator's.
+ takenOver: number;
// Matched ids with no data/<id>/ — download them, then re-run.
notDownloaded: string[];
// Ids in playlist / roster.json with neither a dir nor a scan entry: the
@@ -180,9 +198,11 @@ export async function keepVideosMatching(
const notDownloaded: string[] = [];
let marked = 0;
let alreadyKept = 0;
+ let takenOver = 0;
let noMetadata = 0;
let considered = 0;
- const note = opts.note?.trim() || `keep-videos: matched /${pattern}/i`;
+ const given = opts.note?.trim() || undefined;
+ const note = given ?? `keep-videos: matched /${pattern}/i`;
for (const id of ids) {
const downloaded = dirs.has(id);
@@ -213,19 +233,23 @@ export async function keepVideosMatching(
matched.push({ id, title, downloaded, alreadyKept: false, marked: false });
continue;
}
- const kept = await isDoNotClean(videoDir);
- if (kept) {
- alreadyKept++;
- } else if (!dryRun) {
- await setDoNotClean(videoDir, true, note);
- marked++;
- }
+ const { outcome, before } = await keepByPerson(
+ videoDir,
+ { via: "keep-videos-match", surface: opts.surface ?? "ops", ...(given ? { note: given } : {}) },
+ { dryRun, defaultNote: note },
+ );
+ const kept = outcome === "already-kept";
+ if (kept) alreadyKept++;
+ else if (!dryRun) marked++;
+ if (outcome === "taken-over") takenOver++;
matched.push({
id,
title,
downloaded,
alreadyKept: kept,
marked: !kept && !dryRun,
+ ...(outcome === "taken-over" ? { takenOver: true } : {}),
+ ...(before ? { keptBy: describeDoNotCleanMark(before).text } : {}),
});
}
@@ -241,6 +265,7 @@ export async function keepVideosMatching(
matched,
marked,
alreadyKept,
+ takenOver,
notDownloaded,
unscanned,
noMetadata,
@@ -254,8 +279,14 @@ export type KeepVideosByIdsResult = {
ids: string[];
// Held, marked by this call (would be, on a dry run).
marked: string[];
- // Held and already marked.
+ // Held and already marked by a person.
alreadyKept: string[];
+ // Of `marked`: held with a mark another writer set (the availability check,
+ // an import, a live recording), now the operator's (would be, on a dry run).
+ takenOver: string[];
+ // Who had set each held id's marker before this call, and when
+ // (describeDoNotCleanMark), for every id that had one.
+ keptBy: Record<string, string>;
// Not held: recorded as pending by this call (would be, on a dry run). The
// marker is set when the record is first written (lib/pendingKeep-server.ts).
pending: string[];
@@ -273,6 +304,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;
@@ -287,23 +321,30 @@ export async function keepVideosByIds(opts: {
const config = await readChannelConfig(paths, channelSlug);
await assertChannelMediaReachable(paths, channelSlug, config);
const held = new Set(await listChannelVideoIds(paths, channelSlug));
- const note = opts.note?.trim() || "keep-videos: by id";
- const result: KeepVideosByIdsResult = { ids, marked: [], alreadyKept: [], pending: [], pendingAll: [], dryRun };
+ const given = opts.note?.trim() || undefined;
+ const note = given ?? "keep-videos: by id";
+ const result: KeepVideosByIdsResult = { ids, marked: [], alreadyKept: [], takenOver: [], keptBy: {}, pending: [], pendingAll: [], dryRun };
for (const id of ids) {
if (!held.has(id)) {
result.pending.push(id);
continue;
}
const videoDir = path.join(paths.channelsDir, channelSlug, "data", id);
- if (await isDoNotClean(videoDir)) result.alreadyKept.push(id);
+ const { outcome, before } = await keepByPerson(
+ videoDir,
+ { via: "keep-videos-ids", ...(opts.surface ? { surface: opts.surface } : {}), ...(given ? { note: given } : {}) },
+ { dryRun, defaultNote: note },
+ );
+ if (before) result.keptBy[id] = describeDoNotCleanMark(before).text;
+ if (outcome === "already-kept") result.alreadyKept.push(id);
else {
- if (!dryRun) await setDoNotClean(videoDir, true, note);
result.marked.push(id);
+ if (outcome === "taken-over") result.takenOver.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,648 @@
+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");
+});
+
+// --- Review 1 ---------------------------------------------------------------
+// New symbols are imported inside each test, so each fails on its own before
+// the fix (the run of these against the pre-fix code is the RED one).
+
+const MACHINE = { setAt: "2026-11-03T08:00:00.000Z", note: "deleted from source (pre-clean check): deleted", by: "availability-check", via: "pre-clean-check" };
+
+async function optInGroup(paths: Paths) {
+ return (await planAudioClean({ channelSlug: "ch", paths })).sourceGone.ids;
+}
+
+test("F1: keep-videos by ids on a machine-set mark makes it the operator's, with the note; the opt-in then never reaches it", async () => {
+ const { paths, video } = await corpus();
+ const v = await video("mach", { mark: MACHINE });
+ const mine = await video("mine", { mark: { setAt: "2026-11-01T00:00:00.000Z", by: "operator", via: "toggle", note: "mine" } });
+ assert.deepEqual(await optInGroup(paths), ["mach"]);
+ const r = await keepVideosByIds({ paths, channelSlug: "ch", ids: ["mach", "mine"], note: "the only copy, keep", surface: "ops" });
+ assert.deepEqual(r.marked, ["mach"]);
+ assert.deepEqual((r as unknown as { takenOver: string[] }).takenOver, ["mach"]);
+ assert.deepEqual(r.alreadyKept, ["mine"], "already kept only for a mark already the operator's");
+ const m = await mark(v);
+ assert.deepEqual([m.by, m.via, m.surface, m.note], ["operator", "keep-videos-ids", "ops", "the only copy, keep"]);
+ assert.equal((m as { takenOver?: { by?: string } }).takenOver?.by, "availability-check");
+ assert.equal((await mark(mine)).note, "the only copy, keep", "a note given is written on the person's own mark");
+ assert.deepEqual(await optInGroup(paths), [], "the opt-in never reaches it now");
+ const logs: string[] = [];
+ await cleanAudioFromTranscribed({ channelSlug: "ch", paths, unchecked: "button", onlyIds: [], sourceGone: ["mach"], probes: THROWING, onLog: (l) => logs.push(l) });
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+});
+
+test("F1: keep-videos by pattern takes over a machine-set mark (and a dry run only says it would)", async () => {
+ const { paths, video } = await corpus();
+ const v = await video("pat", { mark: { ...MACHINE, by: "import", via: "import-media" } });
+ await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id: "pat", title: "keep me", description: "" }));
+ const dry = await keepVideosMatching({ paths, channelSlug: "ch", pattern: "keep me", dryRun: true });
+ assert.equal((dry as unknown as { takenOver: number }).takenOver, 1);
+ assert.equal((await mark(v)).by, "import", "a dry run writes nothing");
+ const r = await keepVideosMatching({ paths, channelSlug: "ch", pattern: "keep me" });
+ assert.deepEqual([r.marked, r.alreadyKept], [1, 0]);
+ assert.match(String((r.matched[0] as { keptBy?: string }).keptBy), /^import, 3 Nov/);
+ const m = await mark(v);
+ assert.deepEqual([m.by, m.via, m.note], ["operator", "keep-videos-match", MACHINE.note], "no note given: the mark's own stays");
+});
+
+test("F1: a pending keep landing on a machine-set mark takes it over", async () => {
+ const { paths, video } = await corpus();
+ await addPendingKeep(paths, "ch", ["later"], "asked first", new Date(), "button");
+ const v = await video("later", { mark: { ...MACHINE, via: "kept-deleted-check" } });
+ assert.equal(await applyPendingKeep(paths, "ch", "later", undefined, "JOB-L"), true);
+ const m = await mark(v);
+ assert.deepEqual([m.by, m.via, m.surface, m.note, m.jobId], ["operator", "pending-keep", "button", "asked first", "JOB-L"]);
+ assert.deepEqual(await optInGroup(paths), []);
+});
+
+test("F1: the toggle, Make it mine and a note — keepByPerson takes a machine mark over; a person's stays unless given a note", async () => {
+ const { keepByPerson } = (await import("../lib/doNotClean-server")) as unknown as {
+ keepByPerson: (d: string, m: Record<string, unknown>, o?: Record<string, unknown>) => Promise<{ outcome: string }>;
+ };
+ const { paths, video } = await corpus();
+ const v = await video("tg", { mark: MACHINE });
+ assert.equal((await keepByPerson(v, { via: "toggle", surface: "button" })).outcome, "taken-over");
+ const m = await mark(v);
+ assert.deepEqual([m.by, m.via, m.note], ["operator", "toggle", MACHINE.note]);
+ const setAt = m.setAt;
+ assert.equal((await keepByPerson(v, { via: "toggle", surface: "button" })).outcome, "already-kept");
+ assert.equal((await mark(v)).setAt, setAt, "nothing rewritten");
+ assert.equal((await keepByPerson(v, { via: "toggle", surface: "ops", note: "edited" })).outcome, "already-kept");
+ assert.equal((await mark(v)).note, "edited");
+ // A note written on a machine mark takes it over.
+ const n2 = await video("nt", { mark: MACHINE });
+ await keepByPerson(n2, { via: "toggle", surface: "button", note: "mine now" });
+ assert.deepEqual([(await mark(n2)).by, (await mark(n2)).note], ["operator", "mine now"]);
+ assert.deepEqual(await optInGroup(paths), []);
+});
+
+test("F2: who set a mark and when, in the page's words", async () => {
+ const { describeDoNotCleanMark } = (await import("../lib/doNotClean")) as unknown as {
+ describeDoNotCleanMark: (m: Record<string, unknown>, now?: Date) => { text: string; mine: boolean; sourceGone: boolean };
+ };
+ const now = new Date("2026-11-21T00:00:00.000Z");
+ const d = (m: Record<string, unknown>) => describeDoNotCleanMark(m, now);
+ assert.deepEqual(d(MACHINE), { who: "availability check", day: "3 Nov", text: "availability check, 3 Nov; the source was gone", mine: false, sourceGone: true });
+ assert.equal(d({ setAt: "2026-11-20T09:00:00.000Z", by: "operator", via: "toggle" }).text, "you, 20 Nov");
+ assert.equal(d({ ...MACHINE, inferred: true }).text, "availability check (inferred from the records), 3 Nov; the source was gone");
+ assert.equal(d({ setAt: "2026-11-03T00:00:00.000Z", by: "import", via: "import-media" }).text, "import, 3 Nov");
+ assert.equal(d({ setAt: "2026-11-03T00:00:00.000Z", by: "live-recording", via: "record-live" }).text, "live recording, 3 Nov");
+ assert.equal(d({ setAt: "2025-09-11T00:00:00.000Z" }).text, "you, 11 Sep 2025 (set before marks said who set them)");
+ assert.equal(d({ setAt: "2025-09-11T00:00:00.000Z" }).mine, true);
+});
+
+test("F3: a person's re-mark that takes the mark's lock first (not yet written when the sweep re-reads) keeps the audio", async () => {
+ const { paths, video } = await corpus();
+ const v = await video("lockrace", { mark: MACHINE });
+ const logs: string[] = [];
+ let person: Promise<unknown> | undefined;
+ await cleanAudioFromTranscribed({
+ channelSlug: "ch",
+ paths,
+ unchecked: "button",
+ onlyIds: [],
+ sourceGone: ["lockrace"],
+ probes: THROWING,
+ // Just before the removals the person presses Make it mine; the sweep
+ // does not wait for the write to land.
+ assertReachable: async () => {
+ person = setDoNotClean(v, true, { by: "operator", via: "toggle", surface: "button" });
+ },
+ onLog: (m) => logs.push(m),
+ });
+ await person;
+ assert.equal(await exists(path.join(v, "audio.mp3")), true, "the audio stays");
+ assert.equal((await mark(v)).by, "operator");
+ assert.equal((await mark(v)).audioRemoved, undefined);
+});
+
+test("F4: the job states the source-gone group's counts before it removes anything", async () => {
+ const { paths, video } = await corpus();
+ await video("g4", { mark: MACHINE });
+ const logs: string[] = [];
+ const counts = { files: 0, bytes: 0, videos: 0, protected: 1, awaitingDiarization: 0, awaitingVoiceprint: 0, sourceGone: { videos: 1, files: 1, bytes: 1000, inferred: { videos: 0, files: 0, bytes: 0 } } };
+ await runCleanAudioJob({
+ channelSlug: "ch", paths, jobId: "J4", unchecked: "button", plan: [], planCounts: counts, sourceGone: ["g4"],
+ onLog: (m) => logs.push(m),
+ deps: { scheduleRetry: async () => ({ ok: false, error: "no" }), probes: THROWING },
+ });
+ const said = logs.findIndex((l) => l.includes("Also, kept only because the source was gone: 1 audio file(s) (1000 bytes) from 1 video(s)"));
+ const removed = logs.findIndex((l) => l.startsWith("Removed "));
+ assert.ok(said >= 0 && removed > said, logs.join("\n"));
+});
+
+test("F5: the proof is one-sided — an observation AFTER the mark, or a job that started after it, is not proof", async () => {
+ const c = await corpus();
+ await c.video("after", {
+ mark: { setAt: SET_AT },
+ availability: { checkedAt: "2026-11-01T00:00:00.000Z", checkedBy: "check", availability: "deleted", history: [{ availability: "deleted", observedAt: "2026-10-20T10:00:50.000Z", source: "check" }] },
+ });
+ await provable(c, "jobafter");
+ await c.job("J-AFTER", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: Date.parse(SET_AT) + 20_000, endedAt: Date.parse(SET_AT) + 90_000 },
+ "Pinned after as do-not-clean (deleted) — gone from source.\nPinned jobafter as do-not-clean (deleted) — gone from source.\n");
+ const r = await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch" });
+ assert.deepEqual(r.relabelled, []);
+ assert.deepEqual(Object.fromEntries(r.notProven.map((x) => [x.id, x.reason])), { after: "no-check-within-a-minute", jobafter: "no-clean-job-naming-it" });
+});
+
+test("F5: undo returns every inferred label to unlabelled — dry run first, the same listing — and nothing else", async () => {
+ const { undoMarkProvenanceBackfill } = (await import("./marksBackfill")) as unknown as {
+ undoMarkProvenanceBackfill: (o: Record<string, unknown>) => Promise<{ dryRun: boolean; unlabelled: { id: string; evidence: unknown }[]; changedSince: string[] }>;
+ };
+ const c = await corpus();
+ const v = await provable(c);
+ await c.job("J-CLEAN", { kind: "clean-audio-transcribed", channelSlug: "ch", startedAt: T0, endedAt: T0 + 120_000 }, "Pinned pv as do-not-clean (deleted) — gone from source.\n");
+ await backfillMarkProvenance({ paths: c.paths, channelSlug: "ch", dryRun: false });
+ const machine = await c.video("machine", { mark: MACHINE });
+ const dry = await undoMarkProvenanceBackfill({ paths: c.paths, channelSlug: "ch" });
+ assert.equal(dry.dryRun, true);
+ assert.deepEqual(dry.unlabelled.map((x) => x.id), ["pv"]);
+ assert.equal((await mark(v)).inferred, true, "a dry run writes nothing");
+ await undoMarkProvenanceBackfill({ paths: c.paths, channelSlug: "ch", dryRun: false });
+ assert.deepEqual(await mark(v), { setAt: SET_AT, note: "anything at all" });
+ assert.equal((await mark(machine)).by, "availability-check", "a mark the check itself wrote is not touched");
+});
diff --git a/common/controller/marksBackfill.ts b/common/controller/marksBackfill.ts
@@ -0,0 +1,226 @@
+import path from "node:path";
+import { readdir, readFile } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { isPermanentlyGone } from "../lib/availability";
+import { loadAvailability } from "../lib/availability-server";
+import { assertChannelTextReadable } from "../lib/channelMedia";
+import type { DoNotCleanEvidence } from "../lib/doNotClean";
+import { loadDoNotClean, relabelDoNotCleanInferred, unlabelDoNotCleanInferred } from "../lib/doNotClean-server";
+import { readJobMeta, type JobMeta } from "../jobs/jobMeta";
+
+// MARKS-BACKFILL (lane mark-provenance): relabel an OLD do-not-clean mark — one
+// written before marks said who set them, so the operator's by rule — as set
+// by the availability check, `inferred: true`, ONLY when other records prove
+// it. Never from the mark's free-text note, which a person can write too.
+//
+// THE PROOF, both halves required:
+// 1. availability.json says the CHECK found the video gone (deleted /
+// private / members-only) AT MOST A MINUTE BEFORE the mark's setAt: a
+// history entry by source "check", or the record's top level (checkedAt,
+// checkedBy "check"). ONE-SIDED (review F5): the gate pins only after the
+// check has written what it saw (tier C: runAvailabilityCheck records,
+// then verifyBeforeClean reads it and pins), on the same clock, so the
+// observation can never come after the pin. An observation after setAt
+// is some other check, not the one that set this mark.
+// 2. A FINISHED clean job of the video's channel (clean-audio-transcribed or
+// clean-audio-retry — the only jobs whose gate pins), whose start is at or
+// before setAt and whose end at or after it — the pin is written inside
+// the job's run, between the two times its record holds — and whose log
+// names the pin: the gate's own line `Pinned <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;
+};
+
+// THE UNDO (marks-backfill {"undo": true}): every INFERRED label of the
+// channel returns to unlabelled — the operator's, as before the backfill.
+// Only marks with `inferred: true` are touched; setAt, note and audioRemoved
+// stay. A dry run unless `dryRun` is false; the same listing, with each
+// label's evidence.
+export type MarkUndoResult = {
+ slug: string;
+ dryRun: boolean;
+ undo: true;
+ marks: number;
+ unlabelled: { id: string; setAt: string; evidence: DoNotCleanEvidence | null }[];
+ // Changed between the listing and the write (a person or a writer set it since).
+ changedSince: string[];
+};
+
+export async function undoMarkProvenanceBackfill({
+ paths,
+ channelSlug,
+ dryRun = true,
+}: {
+ paths: Paths;
+ channelSlug: string;
+ dryRun?: boolean;
+}): Promise<MarkUndoResult> {
+ await assertChannelTextReadable(paths, channelSlug);
+ const dataDir = path.join(paths.channelsDir, channelSlug, "data");
+ const ids = (await readdir(dataDir).catch(() => [] as string[])).sort();
+ const out: MarkUndoResult = { slug: channelSlug, dryRun, undo: true, marks: 0, unlabelled: [], changedSince: [] };
+ for (const id of ids) {
+ const videoDir = path.join(dataDir, id);
+ const mark = await loadDoNotClean(videoDir);
+ if (!mark) continue;
+ out.marks++;
+ if (mark.inferred !== true || mark.by !== "availability-check") continue;
+ if (!dryRun && !(await unlabelDoNotCleanInferred(videoDir, { setAt: mark.setAt }))) {
+ out.changedSince.push(id);
+ continue;
+ }
+ out.unlabelled.push({ id, setAt: mark.setAt, evidence: mark.evidence ?? null });
+ }
+ return out;
+}
+
+export const NOT_PROVEN_SENTENCE: Record<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;
+ }
+ // One-sided: observed, then pinned within the minute.
+ const near = (iso: string) => {
+ const lead = setAt - Date.parse(iso);
+ return Number.isFinite(lead) && lead >= 0 && lead <= MARK_PROOF_WINDOW_MS;
+ };
+ const seen: { availability: string; observedAt: string; field: "history" | "checkedAt" }[] = [];
+ for (const h of av.history ?? []) {
+ if (h.source === "check" && isPermanentlyGone(h.availability) && near(h.observedAt)) {
+ seen.push({ availability: h.availability, observedAt: h.observedAt, field: "history" });
+ }
+ }
+ if (av.checkedBy === "check" && isPermanentlyGone(av.availability) && near(av.checkedAt)) {
+ seen.push({ availability: av.availability, observedAt: av.checkedAt, field: "checkedAt" });
+ }
+ if (seen.length === 0) {
+ const everGone = isPermanentlyGone(av.availability) || (av.history ?? []).some((h) => isPermanentlyGone(h.availability));
+ fail(everGone ? "no-check-within-a-minute" : "not-gone");
+ continue;
+ }
+ // (2) A clean job running then, whose log names this pin.
+ let evidence: DoNotCleanEvidence | null = null;
+ for (const job of jobs) {
+ const { startedAt, endedAt } = job.meta;
+ if (setAt < startedAt! || setAt > endedAt!) continue;
+ const log = await logOf(paths, job);
+ const obs = seen.find((o) => log.includes(`Pinned ${id} as do-not-clean (${o.availability})`));
+ if (obs) {
+ evidence = { ...obs, jobId: job.meta.id, jobKind: job.meta.kind };
+ break;
+ }
+ }
+ if (!evidence) {
+ fail("no-clean-job-naming-it");
+ continue;
+ }
+ if (!dryRun && !(await relabelDoNotCleanInferred(videoDir, { setAt: mark.setAt }, evidence, now))) {
+ fail("changed-since");
+ continue;
+ }
+ result.relabelled.push({ id, setAt: mark.setAt, evidence });
+ }
+ return result;
+}
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,39 +1,230 @@
import {
+ DO_NOT_CLEAN_BY,
DO_NOT_CLEAN_FILENAME,
+ type DoNotCleanAudioRemoved,
+ type DoNotCleanEvidence,
+ type DoNotCleanProvenance,
type DoNotCleanRecord,
} from "./doNotClean";
+import { isOperatorsMark, isSourceGoneMark } from "./doNotClean";
+import { withJsonFileLock } from "./jsonFile-server";
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.
+//
+// EVERY WRITE HOLDS THE MARK'S LOCK (withJsonFileLock on its path), so a
+// read-then-write here never interleaves with another: a person's keep and the
+// opt-in's removal under a machine mark (removeUnderSourceGoneMark) are
+// ordered, one after the other.
+
// 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),
);
export const { path: doNotCleanPath, load: loadDoNotClean } = doNotCleanSidecar;
+const locked = <T>(videoDir: string, fn: () => Promise<T>): Promise<T> => withJsonFileLock(doNotCleanPath(videoDir), fn);
+
// Presence of a valid sidecar = protected. Cheap existence check for the
// cleanup controllers' per-dir loops.
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; with
+// no note of its own it keeps the earlier note; a mark replaced that was
+// not already a person's is recorded in `takenOver`.
+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) {
+ return locked(videoDir, async () => {
+ 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).");
+ }
+ return locked(videoDir, async () => {
+ const existing = await loadDoNotClean(videoDir);
+ if (existing && mark.by === "availability-check") return false;
+ await doNotCleanSidecar.write(videoDir, replacing(existing, mark));
+ return true;
+ });
+}
+
+function replacing(existing: DoNotCleanRecord | null, mark: DoNotCleanProvenance): DoNotCleanRecord {
+ const note = mark.note ?? existing?.note;
+ const takenOver =
+ existing && !isOperatorsMark(existing)
+ ? {
+ ...(existing.by ? { by: existing.by } : {}),
+ ...(existing.via ? { via: existing.via } : {}),
+ setAt: existing.setAt,
+ ...(existing.inferred ? { inferred: true as const } : {}),
+ }
+ : existing?.takenOver;
+ return {
setAt: new Date().toISOString(),
...(note ? { note } : {}),
+ by: mark.by,
+ via: mark.via,
+ ...(mark.surface ? { surface: mark.surface } : {}),
+ ...(mark.jobId ? { jobId: mark.jobId } : {}),
+ ...(existing?.audioRemoved?.length ? { audioRemoved: existing.audioRemoved } : {}),
+ ...(takenOver ? { takenOver } : {}),
+ };
+}
+
+// A PERSON'S KEEP (lane mark-provenance review F1): keep-videos by pattern or
+// by ids, a pending keep applied on landing, the toggle, "Make it mine", a
+// note a person writes. A video already marked by a person stays as it is —
+// "already kept" — unless the person gives a note, which is then theirs. A
+// mark ANY other writer set (the availability check, an import, a live
+// recording) is TAKEN OVER: it becomes the operator's, with this writer's
+// via/surface and the given note (else the mark's own), and records what it
+// was. Under the mark's lock. A dry run writes nothing and answers the same.
+export type PersonKeep = "marked" | "taken-over" | "already-kept";
+
+export async function keepByPerson(
+ videoDir: string,
+ mark: Omit<DoNotCleanProvenance, "by">,
+ // `defaultNote`: the note a NEW mark gets when the person gave none (a
+ // taken-over mark keeps its own; a person's mark is not rewritten for it).
+ opts: { dryRun?: boolean; defaultNote?: string } = {},
+): Promise<{ outcome: PersonKeep; before: DoNotCleanRecord | null }> {
+ if (!mark.via) throw new Error("A do-not-clean mark needs its writer (by and via).");
+ return locked(videoDir, async () => {
+ const before = await loadDoNotClean(videoDir);
+ const outcome: PersonKeep = !before ? "marked" : isOperatorsMark(before) ? "already-kept" : "taken-over";
+ if (outcome === "already-kept" && mark.note === undefined) return { outcome, before };
+ const note = mark.note ?? (before ? undefined : opts.defaultNote);
+ if (!opts.dryRun) {
+ await doNotCleanSidecar.write(videoDir, replacing(before, { ...mark, by: "operator", ...(note !== undefined ? { note } : {}) }));
+ }
+ return { outcome, before };
+ });
+}
+
+// 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> {
+ return locked(videoDir, async () => {
+ 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 BACKFILL'S UNDO (marks-backfill {"undo": true}): an INFERRED label —
+// and only that — returns to unlabelled (the operator's): by, via, inferred,
+// inferredAt and evidence go; setAt, note and any audioRemoved stay. A mark
+// a person or a writer set since (no longer inferred, or another setAt) is
+// left alone.
+export async function unlabelDoNotCleanInferred(videoDir: string, expect: { setAt: string }): Promise<boolean> {
+ return locked(videoDir, async () => {
+ const existing = await loadDoNotClean(videoDir);
+ if (!existing || existing.inferred !== true || existing.by !== "availability-check" || existing.setAt !== expect.setAt) {
+ return false;
+ }
+ const { by: _by, via: _via, inferred: _i, inferredAt: _ia, evidence: _e, ...rest } = existing;
+ await doNotCleanSidecar.write(videoDir, rest);
+ 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> {
+ return locked(videoDir, () => appendAudioRemoved(videoDir, entry));
+}
+
+async function appendAudioRemoved(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;
+}
+
+// THE OPT-IN'S REMOVAL, UNDER THE MARK'S LOCK (review F3): the mark is
+// re-checked AFTER the lock is taken, and `remove` runs only while it still
+// says by "availability-check"; the audioRemoved entry is written before the
+// lock is released. A person's keep queued meanwhile runs after, and finds
+// the audio gone and recorded; one that got the lock first makes the mark
+// theirs, and nothing is removed (null).
+export async function removeUnderSourceGoneMark(
+ videoDir: string,
+ remove: () => Promise<{ files: string[]; bytes: number }>,
+ entry: Omit<DoNotCleanAudioRemoved, "files" | "bytes">,
+): Promise<{ files: string[]; bytes: number; recorded: boolean } | null> {
+ return locked(videoDir, async () => {
+ if (!isSourceGoneMark(await loadDoNotClean(videoDir))) return null;
+ const out = await remove();
+ const recorded = await appendAudioRemoved(videoDir, { ...entry, files: out.files, bytes: out.bytes });
+ return { ...out, recorded };
+ });
+}
+
+// Every mark of a channel's videos, as the reads show them (`pnpm ops get
+// marks`): who set it, when, and the record.
+export async function listDoNotCleanMarks(dataDir: string, ids: readonly string[]): Promise<{ id: string; mark: DoNotCleanRecord }[]> {
+ const out: { id: string; mark: DoNotCleanRecord }[] = [];
+ for (const id of ids) {
+ const mark = await loadDoNotClean(`${dataDir}/${id}`);
+ if (mark) out.push({ id, mark });
+ }
+ return out;
+}
diff --git a/common/lib/doNotClean.ts b/common/lib/doNotClean.ts
@@ -10,9 +10,138 @@
// 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[];
+ // A person took over a mark another writer set (a keep, a note, "Make it
+ // mine"): who had set it, and when.
+ takenOver?: { by?: DoNotCleanBy; via?: DoNotCleanVia; setAt: string; inferred?: true };
};
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";
+}
+
+// A mark that is already a PERSON's: by "operator", or no `by` at all (written
+// before marks said who set them, so the operator's). Every other mark — the
+// availability check's, an import's, a live recording's — a person's keep
+// takes over.
+export function isOperatorsMark(m: DoNotCleanRecord | null | undefined): boolean {
+ return !!m && (m.by === undefined || m.by === "operator");
+}
+
+const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+// "3 Nov" (UTC), with the year when it is not `now`'s; null for no date.
+export function markDay(iso: string | undefined, now: Date = new Date()): string | null {
+ const t = iso ? Date.parse(iso) : NaN;
+ if (!Number.isFinite(t)) return null;
+ const d = new Date(t);
+ const day = `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]}`;
+ return d.getUTCFullYear() === now.getUTCFullYear() ? day : `${day} ${d.getUTCFullYear()}`;
+}
+
+// WHO SET IT AND WHEN, in words — the one wording every surface shows (the
+// video page, the keep lists, `pnpm ops get marks`): "availability check, 3
+// Nov; the source was gone", "you, 20 Nov", "import, 3 Nov", "live recording,
+// 3 Nov", and for a mark from before marks said who set them "you, 11 Sep (set
+// before marks said who set them)".
+export function describeDoNotCleanMark(
+ m: DoNotCleanRecord,
+ now: Date = new Date(),
+): { who: string; day: string | null; text: string; mine: boolean; sourceGone: boolean } {
+ const day = markDay(m.setAt, now);
+ const mine = isOperatorsMark(m);
+ const sourceGone = isSourceGoneMark(m);
+ const who =
+ m.by === "availability-check"
+ ? m.inferred
+ ? "availability check (inferred from the records)"
+ : "availability check"
+ : m.by === "import"
+ ? "import"
+ : m.by === "live-recording"
+ ? "live recording"
+ : "you";
+ const text =
+ who +
+ (day ? `, ${day}` : "") +
+ (sourceGone ? "; the source was gone" : "") +
+ (m.by === undefined ? " (set before marks said who set them)" : "");
+ return { who, day, text, mine, sourceGone };
+}
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
@@ -16,11 +16,15 @@ import path from "node:path";
import { stat } from "node:fs/promises";
import type { Paths } from "./paths";
import { readJsonFile, writeJsonAtomic } from "./jsonFile-server";
-import { isDoNotClean, setDoNotClean } from "./doNotClean-server";
+import { keepByPerson } 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,19 @@ 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");
+ // A person's ask: it takes over a mark another writer set meanwhile (the
+ // availability check, an import, a live recording); a person's own mark
+ // stays, gaining the note if one was asked with.
+ await keepByPerson(
+ videoDir,
+ {
+ via: "pending-keep",
+ ...(entry.surface === "button" || entry.surface === "ops" ? { surface: entry.surface } : {}),
+ ...(jobId ? { jobId } : {}),
+ ...(entry.note ? { note: entry.note } : {}),
+ },
+ { defaultNote: "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/CHANGELOG.md b/editor/CHANGELOG.md
@@ -16,6 +16,32 @@
- The scan's result and log carry `advice`: a channel dated from its titles with no rule set, with the exact
`pnpm ops channel-config` patch that sets one; videos dated only by their upload; and, when no two members'
videos are dated near each other, each member's dated span. `dating` gives each channel's count by source.
+- **A do-not-clean mark says who set it, and Clean without checking can drop the audio kept only because the source was gone.**
+ - Every mark now records `by`: `availability-check` (the checked clean's gate, clean after capture, the keep-latest
+ window's deletion check), `live-recording`, `import` or `operator` (the video page's toggle, `do-not-clean`,
+ `keep-videos`, a keep asked before the video landed), with `via`, the `surface` a person used (`button` or
+ `ops`) and the job's id. One writer writes the file; a test fails the build if anything else does. A machine
+ never replaces a mark that is there; a person's replaces the machine's.
+ - A mark from before this has no `by` and is the operator's. `pnpm ops marks-backfill {slug, dryRun}` (a dry run
+ unless `"dryRun": false`) relabels one as `by: "availability-check", inferred: true` only on proof from other
+ records: availability.json says a 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 note. It lists every relabel with its evidence and every other mark
+ with why not. On a corpus whose old pins were made on cached verdicts, or whose job logs are pruned, it relabels
+ nothing.
+ - Clean without checking's confirmation has a new checkbox, off by default: "Also remove audio kept only because
+ the source was gone" (`"includeSourceGone": true` with `"unchecked": true` over ops). It reaches only marks by
+ the availability check, inferred ones counted on their own, and never a mark a person, an import or a live
+ recording set. The group has its own line in the confirmation (videos, files, bytes) and in the plan
+ (`plan.sourceGone`). The job carries its ids and re-reads each mark before removing. The mark stays and records
+ `audioRemoved` (when, which job, the files, why). The channel key never implies it, and a Retry or a restart
+ never carries it.
+ - A person's keep makes a mark another writer set theirs: keep-videos (by pattern or ids), a keep asked before the
+ video landed, the toggle, a note, and the video page's new **Make it mine** (`do-not-clean {"keep": true}`).
+ "Already kept" now means a person's mark.
+ - The video page, the Keep matching lists, keep-videos' answer and the new `pnpm ops get marks <slug>` say who set
+ a mark and when: "Do not clean: on (availability check, 3 Nov; the source was gone)" or "(you, 20 Nov)".
+ - The opt-in's removal runs under the mark's lock. `"expectSourceGone"` makes the dry run's count binding. The
+ backfill's proof is one-sided in time, and `marks-backfill {"undo": true}` returns inferred labels.
- **A clip window past the end of a saved recording is cut from the saved video, clamped at the end.**
- Before, the last clip of a recording asked for a window that ended past the saved container (its cut plus a
3 s pad). The window was "not-covering" and went to the platform's download queue: a network fetch for footage
diff --git a/editor/app/api/ops/_markProvenance.test.ts b/editor/app/api/ops/_markProvenance.test.ts
@@ -0,0 +1,94 @@
+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/);
+});
+
+// --- Review 1 ---------------------------------------------------------------
+
+const MACHINE = { setAt: "2026-11-03T08:00:00.000Z", note: "deleted from source (pre-clean check): deleted", by: "availability-check", via: "pre-clean-check" };
+
+test("F4: expectSourceGone makes the dry run binding — a changed count is refused and nothing is queued", async () => {
+ const cleanup = await route("cleanup");
+ await writeFile(path.join(videoDir(), "do-not-clean.json"), JSON.stringify(MACHINE));
+ const alone = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, expectSourceGone: 1 });
+ assert.equal(alone.status, 400);
+ assert.match(String(alone.body.error), /"expectSourceGone" goes with "includeSourceGone": true/);
+ const dry = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, dryRun: true, includeSourceGone: true });
+ const now = (dry.body.plan as { sourceGone: { videos: number } }).sourceGone.videos;
+ const off = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, includeSourceGone: true, expectSourceGone: now + 1 });
+ assert.equal(off.status, 409, JSON.stringify(off.body));
+ assert.match(String(off.body.error), new RegExp(`is now ${now} video\\(s\\), not the ${now + 1} expected: nothing was queued`));
+ assert.deepEqual(await corpus.listJobIds(), []);
+});
+
+test("F2: get marks says who set each mark and when; marks-backfill undo is a dry run first", async () => {
+ await writeFile(path.join(videoDir(), "do-not-clean.json"), JSON.stringify(MACHINE));
+ const { GET } = (await import("./marks/route")) as { GET: (r: Request) => Promise<Response> };
+ const res = await GET(new Request(`http://x/api/ops/marks?slug=${SLUG}`, { headers: { authorization: `Bearer ${process.env.WORKER_TOKEN}` } }));
+ const body = (await res.json()) as { count: number; sourceGone: number; marks: { id: string; setBy: string; mine: boolean }[] };
+ assert.equal(res.status, 200, JSON.stringify(body));
+ assert.equal(body.count, 1);
+ assert.equal(body.sourceGone, 1);
+ assert.match(body.marks[0].setBy, /^availability check, 3 Nov( 2026)?; the source was gone$/);
+ assert.equal(body.marks[0].mine, false);
+
+ const backfill = await route("marks-backfill");
+ const undo = await callPost(backfill, { slug: SLUG, undo: true });
+ assert.equal(undo.status, 200, JSON.stringify(undo.body));
+ assert.deepEqual([undo.body.undo, undo.body.dryRun, undo.body.unlabelled], [true, true, []]);
+ const keep = await route("do-not-clean");
+ const badNote = await callPost(keep, { slug: SLUG, id: VIDEO, note: 5 });
+ assert.equal(badNote.status, 400, "the note is checked at the door");
+});
diff --git a/editor/app/api/ops/cleanup/route.ts b/editor/app/api/ops/cleanup/route.ts
@@ -7,7 +7,7 @@ import {
planCleanAudioUncheckedAction,
removeWrongFormatAudioAction,
} from "../../../channels/[slug]/whisperActions";
-import { jobResponse, oneOf, ops, opsFail, OpsInputError, optBool, reqSlug } from "../_lib";
+import { jobResponse, oneOf, ops, opsFail, OpsInputError, optBool, optNonNegativeInt, reqSlug } from "../_lib";
export const dynamic = "force-dynamic";
@@ -44,6 +44,20 @@ 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. A non-dry call answers that group's counts beside the main
+// group's, and the job logs both before removing anything. `"expectSourceGone":
+// <n>` (the dry run's `plan.sourceGone.videos`) makes the dry run binding: a
+// fresh count that differs is refused and nothing is queued.
const SWEEPS = {
transcribed: cleanAudioAction,
"extra-formats": cleanExtraAudioFormatsAction,
@@ -52,11 +66,19 @@ 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", "expectSourceGone"], 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');
+ }
+ const expectSourceGone = optNonNegativeInt(body, "expectSourceGone");
+ if (expectSourceGone !== undefined && !includeSourceGone) {
+ throw new OpsInputError('"expectSourceGone" goes with "includeSourceGone": true');
+ }
if (unchecked && sweep !== "transcribed") {
throw new OpsInputError('"unchecked" applies to the "transcribed" sweep only');
}
@@ -66,7 +88,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 +98,36 @@ 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;
+ if (expectSourceGone !== undefined && expectSourceGone !== sourceGone.videos) {
+ return opsFail(
+ `The audio kept only because the source was gone is now ${sourceGone.videos} video(s), not the ${expectSourceGone} expected: nothing was queued. Run the dry run again.`,
+ 409,
+ { plan: { sourceGone: { videos: sourceGone.videos, files: sourceGone.files, bytes: sourceGone.bytes } } },
+ );
+ }
+ 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
@@ -1,23 +1,30 @@
import { NextResponse } from "next/server";
import { toggleDoNotCleanAction } from "../../../channels/[slug]/videos/[id]/videoActions";
-import { ops, opsFail, optBool, reqSlug, reqVideoId } from "../_lib";
+import { ops, opsFail, optBool, optString, reqSlug, reqVideoId } from "../_lib";
export const dynamic = "force-dynamic";
-// POST { slug, id, keep?: boolean }
+// POST { slug, id, keep?: boolean, note?: string }
+// -> { ok, outcome: "marked" | "taken-over" | "already-kept" | "removed" }
//
// One video's "Do not clean" marker (do-not-clean.json), set to the value
// given — `keep` defaults to true; false removes it. Set, not toggled: a retry
// of the same body is the same answer. The cleanup sweeps skip a marked
// video's audio. `keep-videos` is the bulk form, by title/description match.
+// `keep: true` on a mark another writer set (the availability check, an
+// import, a live recording) MAKES IT YOURS — the video page's "Make it mine"
+// ("taken-over"); `note` is written on it, and on a mark that is already
+// yours.
export async function POST(request: Request) {
- return ops(request, ["slug", "id", "keep"], async (body) => {
+ return ops(request, ["slug", "id", "keep", "note"], async (body) => {
const res = await toggleDoNotCleanAction(
reqSlug(body, "slug"),
reqVideoId(body, "id"),
optBool(body, "keep") ?? true,
+ "ops",
+ optString(body, "note"),
);
if (!res.ok) return opsFail(res.error);
- return NextResponse.json({ ok: true });
+ return NextResponse.json({ ok: true, outcome: res.outcome });
});
}
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,30 @@
+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.
+//
+// POST { slug, undo: true, dryRun?: true }
+// -> { ok, slug, dryRun, undo: true, marks, unlabelled: [{id, setAt,
+// evidence}], changedSince }
+// Every INFERRED label of the channel back to unlabelled (the operator's):
+// only marks with "inferred": true; setAt, note and audioRemoved stay.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "dryRun", "undo"], async (body) => {
+ const r = await marksBackfillAction(reqSlug(body, "slug"), optBool(body, "dryRun") ?? true, optBool(body, "undo") ?? false);
+ if (!r.ok) return opsFail(r.error);
+ return NextResponse.json({ ok: true, ...r.result });
+ });
+}
diff --git a/editor/app/api/ops/marks/route.ts b/editor/app/api/ops/marks/route.ts
@@ -0,0 +1,25 @@
+import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { listMarksAction } from "../../../channels/actions";
+import { readRoute } from "../_read";
+import { opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET ?slug=<channel>
+// -> { ok, count, sourceGone, marks: [{ id, setBy, mine, sourceGone, mark }] }
+//
+// Every do-not-clean mark of one channel and WHO SET IT AND WHEN, in the
+// video page's words ("availability check, 3 Nov; the source was gone",
+// "you, 20 Nov"). `mine`: a person's (by "operator", or from before marks said
+// who set them). `sourceGone`: set by the availability check, so Clean without
+// checking's opt-in can reach its audio; `do-not-clean {"keep": true}` makes
+// it yours.
+export async function GET(request: Request) {
+ return readRoute(request, ["slug"], async (q) => {
+ const slug = q.get("slug")?.trim() ?? "";
+ if (!isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`);
+ const r = await listMarksAction(slug);
+ if (!r.ok) return opsFail(r.error);
+ return { count: r.marks.length, sourceGone: r.marks.filter((m) => m.sourceGone).length, marks: r.marks };
+ });
+}
diff --git a/editor/app/channels/[slug]/components/KeepMatchingControl.tsx b/editor/app/channels/[slug]/components/KeepMatchingControl.tsx
@@ -67,7 +67,16 @@ export function KeepByIdControl({ slug }: { slug: string }) {
)}
{result && (
<p role="status" className="text-xs">
- {result.marked.length} kept now, {result.alreadyKept.length} already kept, {result.pending.length} pending (not here yet)
+ {result.marked.length} kept now
+ {result.takenOver.length > 0 && ` (${result.takenOver.length} made yours: another writer had set them)`},{" "}
+ {result.alreadyKept.length} already kept, {result.pending.length} pending (not here yet)
+ {Object.keys(result.keptBy).length > 0 && (
+ <span className="block text-muted-foreground">
+ {Object.entries(result.keptBy)
+ .map(([id, by]) => `${id}: was set by ${by}`)
+ .join("; ")}
+ </span>
+ )}
</p>
)}
{pendingList && pendingList.length > 0 && (
@@ -161,7 +170,8 @@ export function KeepMatchingControl({ slug }: { slug: string }) {
<div className="flex flex-col gap-1 text-xs" aria-label="keep matches">
<p role="status">
{result.matched.length} match{result.matched.length === 1 ? "" : "es"} of {result.considered}
- {result.dryRun ? "" : `; ${result.marked} kept now`}, {result.alreadyKept} already kept
+ {result.dryRun ? "" : `; ${result.marked} kept now`}
+ {result.takenOver > 0 && ` (${result.takenOver} ${result.dryRun ? "would be" : ""} made yours)`}, {result.alreadyKept} already kept
{result.notDownloaded.length > 0 && `, ${result.notDownloaded.length} not downloaded`}
{result.unscanned > 0 && `, ${result.unscanned} never scanned (not tested)`}
</p>
@@ -172,7 +182,13 @@ export function KeepMatchingControl({ slug }: { slug: string }) {
{m.id}
</Link>{" "}
{m.title}
- {m.alreadyKept ? " (kept)" : m.marked ? " (kept now)" : ""}
+ {m.alreadyKept
+ ? ` (kept: ${m.keptBy ?? "you"})`
+ : m.takenOver
+ ? ` (${m.marked ? "made yours" : "would be made yours"}; was set by ${m.keptBy})`
+ : m.marked
+ ? " (kept now)"
+ : ""}
</li>
))}
</ul>
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]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx
@@ -31,6 +31,7 @@ import { PipelineStatusStrip } from "./PipelineStatusStrip";
import { AvailabilityHistoryList } from "./cards/AvailabilityHistoryList";
import { DeleteVideoDirSection } from "./cards/DeleteVideoDirSection";
import { DoNotCleanSection } from "./cards/DoNotCleanSection";
+import { describeDoNotCleanMark, type DoNotCleanRecord } from "yt-dlp-transcript-common/lib/doNotClean";
import { DownloadOutcomeBadge } from "./cards/DownloadOutcomeBadge";
import { ExcludeTruncatedCheckSection } from "./cards/ExcludeTruncatedCheckSection";
import { FetchedWindows, type FetchedWindow } from "./cards/FetchedWindows";
@@ -78,6 +79,8 @@ type Props = {
availabilityHistory: AvailabilityHistoryEntry[];
channelAudioFormat?: AudioFormat;
doNotClean?: boolean;
+ // The mark's record: who set it and when (DoNotCleanSection says so).
+ doNotCleanMark?: DoNotCleanRecord | null;
// When true the user has opted this video out of the truncated/incomplete
// check, so the "looks truncated" banner is suppressed and the toggle reads
// as on. Drives ExcludeTruncatedCheckSection.
@@ -134,6 +137,7 @@ export function VideoPanel({
availabilityHistory,
channelAudioFormat,
doNotClean = false,
+ doNotCleanMark = null,
excludedFromTruncatedCheck = false,
savedVideo = null,
sourceVideoQuality,
@@ -491,9 +495,11 @@ export function VideoPanel({
id="archive-media"
title="Archive media"
summary={
- doNotClean
- ? "Protected — cleanup will skip this video."
- : "Exclude this video's media from cleanup jobs."
+ doNotCleanMark
+ ? `Do not clean: on (${describeDoNotCleanMark(doNotCleanMark).text})`
+ : doNotClean
+ ? "Protected — cleanup will skip this video."
+ : "Exclude this video's media from cleanup jobs."
}
defaultOpen={true}
tone={doNotClean ? "ok" : "neutral"}
@@ -502,6 +508,7 @@ export function VideoPanel({
slug={slug}
videoId={videoId}
doNotClean={doNotClean}
+ mark={doNotCleanMark}
/>
</PipelineStageCard>
diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/DoNotCleanSection.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/DoNotCleanSection.tsx
@@ -1,52 +1,104 @@
"use client";
import { useState, useTransition } from "react";
+import { describeDoNotCleanMark, type DoNotCleanRecord } from "yt-dlp-transcript-common/lib/doNotClean";
import {
toggleDoNotCleanAction,
} from "../../videoActions";
+// The video's "Do not clean" marker: on or off, WHO SET IT AND WHEN (lane
+// mark-provenance review F2), "Make it mine" for a mark another writer set —
+// the one kind Clean without checking's opt-in can remove audio under is the
+// availability check's — and the mark's note, which a person writes (writing
+// it makes the mark theirs too).
export function DoNotCleanSection({
slug,
videoId,
doNotClean,
+ mark = null,
}: {
slug: string;
videoId: string;
doNotClean: boolean;
+ mark?: DoNotCleanRecord | null;
}) {
const [pending, startTransition] = useTransition();
const [error, setError] = useState<string | null>(null);
+ const [note, setNote] = useState(mark?.note ?? "");
const next = !doNotClean;
+ const who = mark ? describeDoNotCleanMark(mark) : null;
+ const run = (enabled: boolean, withNote?: string) => {
+ setError(null);
+ startTransition(async () => {
+ const res = await toggleDoNotCleanAction(slug, videoId, enabled, "button", withNote);
+ if (!res.ok) setError(res.error);
+ });
+ };
return (
<div className="flex flex-col gap-2">
+ {who && (
+ <p className="text-sm font-medium" aria-label="do not clean set by">
+ Do not clean: on ({who.text})
+ </p>
+ )}
<p className="text-sm text-muted-foreground">
{doNotClean
- ? "This video is marked “do not clean”. The transcribed-audio and extra-format cleanup jobs will skip it, so its media is preserved for archiving. Reversible — allow cleanup to remove the marker."
+ ? who && !who.mine
+ ? who.sourceGone
+ ? "Set by the availability check, not by you: Clean without checking can remove its audio when its “also remove audio kept only because the source was gone” box is ticked. Make it yours to keep it from that too."
+ : "Set by another writer, not by you. Make it yours to say you want it kept."
+ : "This video is marked “do not clean”. The transcribed-audio and extra-format cleanup jobs will skip it, so its media is preserved for archiving. Reversible — allow cleanup to remove the marker."
: "Mark this video “do not clean” so the cleanup jobs never delete its audio (e.g. a deleted or members-only upload you want to keep). Reversible at any time."}
</p>
- <button
- type="button"
- disabled={pending}
- aria-label={
- next
- ? `mark video ${videoId} do not clean`
- : `allow cleanup for video ${videoId}`
- }
- onClick={() => {
- setError(null);
- startTransition(async () => {
- const res = await toggleDoNotCleanAction(slug, videoId, next);
- if (!res.ok) setError(res.error);
- });
- }}
- className="self-start px-3 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50"
- >
- {pending
- ? "Saving…"
- : doNotClean
- ? "Allow cleanup"
- : "Mark do not clean"}
- </button>
+ <div className="flex flex-wrap gap-2">
+ {who && !who.mine && (
+ <button
+ type="button"
+ disabled={pending}
+ aria-label={`make the do not clean mark of ${videoId} mine`}
+ onClick={() => run(true)}
+ className="px-3 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50"
+ >
+ {pending ? "Saving…" : "Make it mine"}
+ </button>
+ )}
+ <button
+ type="button"
+ disabled={pending}
+ aria-label={
+ next
+ ? `mark video ${videoId} do not clean`
+ : `allow cleanup for video ${videoId}`
+ }
+ onClick={() => run(next)}
+ className="self-start px-3 py-2 rounded-md bg-primary text-primary-foreground text-sm font-medium hover:opacity-90 disabled:opacity-50"
+ >
+ {pending
+ ? "Saving…"
+ : doNotClean
+ ? "Allow cleanup"
+ : "Mark do not clean"}
+ </button>
+ </div>
+ {doNotClean && (
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ aria-label="do not clean note"
+ placeholder="note"
+ className="rounded border border-border bg-card px-2 py-1 text-sm w-64 max-w-full"
+ />
+ <button
+ type="button"
+ disabled={pending || !note.trim() || note.trim() === (mark?.note ?? "")}
+ onClick={() => run(true, note)}
+ className="rounded border border-border px-3 py-1 text-sm hover:bg-accent disabled:opacity-50"
+ >
+ {who && !who.mine ? "Save note (makes it mine)" : "Save note"}
+ </button>
+ </div>
+ )}
{error && (
<span
className="text-sm text-destructive"
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -11,7 +11,7 @@ import { loadAvailability } from "yt-dlp-transcript-common/lib/availability-serv
import { loadMetadataHistory } from "yt-dlp-transcript-common/lib/metadataHistory-server";
import { metadataHistoryView } from "yt-dlp-transcript-common/views/metadataHistoryView";
import { listClipWindows } from "yt-dlp-transcript-common/lib/clipWindow-server";
-import { isDoNotClean } from "yt-dlp-transcript-common/lib/doNotClean-server";
+import { loadDoNotClean } from "yt-dlp-transcript-common/lib/doNotClean-server";
import { isExcludedFromTruncatedCheck } from "yt-dlp-transcript-common/lib/excludeTruncatedCheck-server";
import { loadSavedVideo } from "yt-dlp-transcript-common/lib/savedVideo-server";
import { loadArchiveOrgProvenance } from "yt-dlp-transcript-common/lib/archiveOrg-server";
@@ -170,7 +170,10 @@ export default async function VideoDetailPage({
await loadMetadataHistory(videoDir),
Date.now(),
);
- const doNotClean = await isDoNotClean(videoDir);
+ // The mark itself, so the page says who set it and when (lane
+ // mark-provenance review F2).
+ const doNotCleanMark = await loadDoNotClean(videoDir);
+ const doNotClean = doNotCleanMark !== null;
const excludedFromTruncatedCheck =
await isExcludedFromTruncatedCheck(videoDir);
const savedVideo = await loadSavedVideo(videoDir);
@@ -263,6 +266,7 @@ export default async function VideoDetailPage({
availabilityHistory,
metadataHistory,
doNotClean,
+ doNotCleanMark,
excludedFromTruncatedCheck,
savedVideo,
archiveOrg,
@@ -299,6 +303,7 @@ export default async function VideoDetailPage({
availabilityHistory,
metadataHistory,
doNotClean,
+ doNotCleanMark,
excludedFromTruncatedCheck,
savedVideo,
archiveOrg,
@@ -438,6 +443,7 @@ export default async function VideoDetailPage({
availabilityHistory={availabilityHistory}
channelAudioFormat={config.audioFormat}
doNotClean={doNotClean}
+ doNotCleanMark={doNotCleanMark}
excludedFromTruncatedCheck={excludedFromTruncatedCheck}
savedVideo={savedVideo}
sourceVideoQuality={resolveSourceVideoQuality({
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -42,7 +42,7 @@ import { isXUrl, X_QUEUE_KEY, xJobContextRefusal } from "yt-dlp-transcript-commo
import { windowInFlight } from "yt-dlp-transcript-common/jobs/windowJobs";
import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
-import { setDoNotClean } from "yt-dlp-transcript-common/lib/doNotClean-server";
+import { keepByPerson, setDoNotClean } from "yt-dlp-transcript-common/lib/doNotClean-server";
import { loadPendingKeep, type PendingKeepEntry } from "yt-dlp-transcript-common/lib/pendingKeep-server";
import {
KeepVideosError,
@@ -1310,11 +1310,20 @@ 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.
+// ON IS A PERSON'S KEEP (keepByPerson): a mark another writer set — the
+// availability check, an import, a live recording — becomes the operator's
+// ("Make it mine" on the video page; `do-not-clean {keep: true}`), keeping
+// its note unless `note` is given; a person's own mark is left as it is, or
+// gains the `note`.
export async function toggleDoNotCleanAction(
slug: string,
videoId: string,
enabled: boolean,
-): Promise<{ ok: true } | { ok: false; error: string }> {
+ surface: "button" | "ops" = "button",
+ note?: string,
+): Promise<{ ok: true; outcome?: "marked" | "taken-over" | "already-kept" | "removed" } | { ok: false; error: string }> {
const videoDir = videoDirOf(slug, videoId);
try {
const s = await stat(videoDir);
@@ -1324,11 +1333,20 @@ export async function toggleDoNotCleanAction(
} catch {
return { ok: false, error: `Video directory not found: ${videoId}` };
}
- await setDoNotClean(videoDir, enabled);
+ const trimmed = typeof note === "string" ? note.trim() : "";
+ const outcome = enabled
+ ? (
+ await keepByPerson(videoDir, {
+ via: "toggle",
+ surface: surface === "ops" ? "ops" : "button",
+ ...(trimmed ? { note: trimmed } : {}),
+ })
+ ).outcome
+ : (await setDoNotClean(videoDir, false), "removed" as const);
revalidatePath(`/channels/${slug}/videos/${videoId}`);
revalidatePath(`/channels/${slug}`);
requestChannelSnapshot(getPaths(), slug);
- return { ok: true };
+ return { ok: true, outcome };
}
// The BULK form of the toggle above: set the do-not-clean marker on every video
@@ -1344,6 +1362,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 {
@@ -1354,6 +1373,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) {
@@ -1379,6 +1399,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 {
@@ -1388,6 +1411,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,11 +1,21 @@
"use server";
import { cancelCleanRetries } from "yt-dlp-transcript-common/controller/cleanRetrySchedule";
+import {
+ backfillMarkProvenance,
+ undoMarkProvenanceBackfill,
+ type MarkBackfillResult,
+ type MarkUndoResult,
+} from "yt-dlp-transcript-common/controller/marksBackfill";
+import { describeDoNotCleanMark, type DoNotCleanRecord } from "yt-dlp-transcript-common/lib/doNotClean";
+import { listDoNotCleanMarks } from "yt-dlp-transcript-common/lib/doNotClean-server";
import { cleanRetryDeps } from "./[slug]/cleanRetryScheduler";
import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import { prepareLocalArchiveChannel } from "./lib/prepareLocalArchiveChannel";
import { withRumbleDefaults } from "yt-dlp-transcript-common/lib/rumbleDefaults";
import { revalidatePath } from "next/cache";
+import path from "node:path";
+import { readdir } from "node:fs/promises";
import { redirect } from "next/navigation";
import slugify from "@sindresorhus/slugify";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
@@ -667,6 +677,56 @@ 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.
+// `undo`: every INFERRED label of the channel back to unlabelled.
+export async function marksBackfillAction(
+ slug: string,
+ dryRun = true,
+ undo = false,
+): Promise<{ ok: true; result: MarkBackfillResult | MarkUndoResult } | { ok: false; error: string }> {
+ const paths = getPaths();
+ if (!(await readChannelConfig(paths, slug))) return { ok: false, error: `Channel "${slug}" not found` };
+ try {
+ const result = undo
+ ? await undoMarkProvenanceBackfill({ paths, channelSlug: slug, dryRun: dryRun !== false })
+ : await backfillMarkProvenance({ paths, channelSlug: slug, dryRun: dryRun !== false });
+ const changed = "undo" in result ? result.unlabelled.length : result.relabelled.length;
+ if (!result.dryRun && changed > 0) {
+ revalidatePath(`/channels/${slug}`);
+ revalidatePath("/cleanup");
+ }
+ return { ok: true, result };
+ } catch (err) {
+ return { ok: false, error: (err as Error).message };
+ }
+}
+
+// THE MARKS OF A CHANNEL (`pnpm ops get marks <slug>`): every do-not-clean
+// mark, who set it and when (describeDoNotCleanMark, the video page's words),
+// and whether Clean without checking's opt-in could reach it.
+export async function listMarksAction(
+ slug: string,
+): Promise<
+ | { ok: true; marks: { id: string; setBy: string; mine: boolean; sourceGone: boolean; mark: DoNotCleanRecord }[] }
+ | { ok: false; error: string }
+> {
+ const paths = getPaths();
+ if (!(await readChannelConfig(paths, slug))) return { ok: false, error: `Channel "${slug}" not found` };
+ const dataDir = path.join(paths.channelsDir, slug, "data");
+ const ids = (await readdir(dataDir).catch(() => [] as string[])).sort();
+ const rows = await listDoNotCleanMarks(dataDir, ids);
+ return {
+ ok: true,
+ marks: rows.map(({ id, mark }) => {
+ const d = describeDoNotCleanMark(mark);
+ return { id, setBy: d.text, mine: d.mine, sourceGone: d.sourceGone, mark };
+ }),
+ };
+}
+
// 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
@@ -328,6 +330,8 @@ const GETTERS = {
// rolled back past compaction would mistreat), and drops in flight.
"kept-originals": (slug) =>
slug ? `/api/ops/kept-originals?slug=${encodeURIComponent(slug)}` : "/api/ops/kept-originals",
+ // A channel's do-not-clean marks: who set each one and when.
+ marks: (slug) => `/api/ops/marks?slug=${encodeURIComponent(slug)}`,
// Every site: id, title, siteUrl, Pages project, audience, policy, channels.
sites: () => "/api/ops/sites",
// The connected archives (settings.remoteArchives, plus TRANSCRIPT_SITE_URL's,
@@ -709,6 +713,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",
@@ -1398,6 +1406,7 @@ export function usage() {
" pnpm ops get saved-alternates [<slug>]",
" pnpm ops get compaction-review [<slug>]",
" pnpm ops get kept-originals [<slug>]",
+ " pnpm ops get marks <slug>",
" pnpm ops get services",
" pnpm ops get x-session [<slug>]",
" pnpm ops get cookies [fresh]",
@@ -1471,6 +1480,11 @@ export function usage() {
" availability and why, the original's entry, sizes, checks, the re-check,",
' "watch" (both files and an smplayer command that plays them) and any',
' "leftover" of an interrupted drop.',
+ "get marks <slug> lists the channel's do-not-clean marks and who set each",
+ ' one and when, as the video page says it ("setBy": "availability check,',
+ ' 3 Nov; the source was gone" | "you, 20 Nov" | "import, …" | "live',
+ ' recording, …"), with "mine" and "sourceGone" (the marks Clean without',
+ ' checking\'s opt-in can reach). `do-not-clean {"keep": true}` makes one yours.',
"get kept-originals [<slug>] lists every saved video that keeps an original",
' ("keptAs": "original") or a former original ("former-original") beside',
" its active copy, or has a drop in flight (pendingDrops: a file the pointer",
@@ -1793,7 +1807,23 @@ export function usage() {
' never the other, and "note" says the other is still there.',
"",
'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.)',
+ ' "keep"?: true, "note"?}; "keep": false removes it. (keep-videos is the',
+ ' bulk form.) On a mark another writer set (the availability check, an',
+ ' import, a live recording) "keep": true MAKES IT YOURS (the video page\'s',
+ ' "Make it mine"): {outcome: "taken-over"}; a "note" is written on it, and',
+ ' on a mark already yours. keep-videos takes such marks over too.',
+ "",
+ '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}. The proof is one-sided: observed by the check, then',
+ ' pinned within the minute, inside the job\'s run. {"slug", "undo": true,',
+ ' "dryRun"?: true} returns every INFERRED label to unlabelled (the',
+ ' operator\'s): {unlabelled: [{id, setAt, evidence}], changedSince}.',
"",
'drop-saved-alternate deletes one saved alternate of one video, as its',
' "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}.',
@@ -1833,6 +1863,16 @@ 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.',
+ ' The reply and the job\'s log state that group\'s counts; "expectSourceGone":',
+ ' <the dry run\'s plan.sourceGone.videos> refuses (409) a count that changed.',
' 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.