commit 1e8095876a08d256e917e6e487e9e9293b840994
parent e3327d26332765f9a959438a9bac07c4adf716e8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 16:35:31 -0500
mark-provenance review 1: a person's keep owns the mark, every surface says who set it, the opt-in removes under the mark's lock
- F1: keepByPerson (lib/doNotClean-server.ts) is every person's keep: keep-videos
by pattern and by ids, a pending keep on landing, the toggle, a note, Make it
mine. A mark another writer set (availability check, import, live recording)
becomes the operator's, with via, surface and the note given (else its own),
and records takenOver. "Already kept" only for a person's mark.
- F2: describeDoNotCleanMark gives one wording ("availability check, 3 Nov; the
source was gone", "you, 20 Nov"), shown on the video page with Make it mine and
a note field, in the Keep matching lists and keep-videos' answer (keptBy,
takenOver), and by the new `pnpm ops get marks <slug>`. do-not-clean takes a
note and answers its outcome.
- F3: every mark write holds the mark's lock; the opt-in's removal re-reads the
mark under it and records audioRemoved before releasing it.
- F4: ops cleanup "expectSourceGone" refuses (409) a source-gone count that
changed since the dry run.
- F5: the backfill's proof is one-sided (observed, then pinned within the
minute, inside the job's run); marks-backfill {"undo": true} returns inferred
labels to unlabelled, dry run first.
- Docs: OPERATING.md, COMMANDS.md regenerated, CLI help, editor CHANGELOG.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
23 files changed, 829 insertions(+), 131 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -204,10 +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). "includeSourceGone": true (with "unchecked" only; off by default, never implied by the channel key, never replayed) also removes the audio of videos kept ONLY because the source was gone: a mark by the availability check (inferred ones included) that nothing else holds. The plan counts that group apart, {plan: {sourceGone: {ids, videos, files, bytes, inferred: {ids, videos, files, bytes}}}}; the marks stay and record the removal. A mark a person, an import or a live recording set, or one from before marks said who set them, is never reached. A checked clean the source rate-limits ends deferred and schedules a retry off the queue after at least 15 min (twice at most), then gives up; `job cancel <the deferred job id>` cancels the retry. | `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}. | `pnpm ops marks-backfill --json '{"slug":"x"}'` |
+| `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}'` |
@@ -270,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]
@@ -341,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
@@ -1105,6 +1105,9 @@ pnpm ops channel-config --json '{"slug":"example","cleanAudioWithoutChecking":tr
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
@@ -1144,9 +1147,15 @@ pnpm ops marks-backfill --json '{"slug":"example","dryRun":false}'
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; a person's replaces the
- machine's (re-marking a source-gone video makes it yours). A mark from before this has no `by` and is treated as
- the operator's.
+ `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
@@ -1155,18 +1164,23 @@ pnpm ops marks-backfill --json '{"slug":"example","dryRun":false}'
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 and re-reads each mark just before removing. 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}]`.
+ 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 within a minute
- of the mark's `setAt`, AND a finished Clean audio job of the channel (or its rate-limit retry), running then, has
- the line `Pinned <id> as do-not-clean (<that state>)` in its log. A dry run unless `"dryRun": false`; it lists
+ 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.
+ 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/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts
@@ -3,7 +3,7 @@ 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, recordDoNotCleanAudioRemoved, setDoNotClean } from "../lib/doNotClean-server";
+import { loadDoNotClean, removeUnderSourceGoneMark, setDoNotClean } from "../lib/doNotClean-server";
import { isSourceGoneMark } from "../lib/doNotClean";
import {
readAvailabilityVerdict,
@@ -385,25 +385,39 @@ export async function cleanAudioFromTranscribed({
sourceGoneRemoved = { videos: 0, files: 0, bytes: 0, inferredVideos: 0 };
for (const c of released) {
if (signal?.aborted) break;
- // Re-read the mark immediately before: a person who re-marked the
- // video since discover made it theirs, and theirs is never reached.
- if (!isSourceGoneMark(await loadDoNotClean(c.videoDir))) {
+ // 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 = await removeCandidateAudio(c, log);
- await recordDoNotCleanAudioRemoved(c.videoDir, {
- at: new Date().toISOString(),
- ...(jobId ? { jobId } : {}),
- files: c.audioFiles,
- bytes: out.bytes,
- why:
- "Clean without checking, with \"also remove audio kept only because the source was gone\" confirmed: the mark was set by the availability check" +
- (c.inferred ? " (inferred from the records by marks-backfill)" : "") +
- "; the mark stays.",
- });
- log(`Removed the audio of ${c.id}, kept only because the source was gone${c.inferred ? " (mark inferred)" : ""}; its mark stays.`);
+ 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++;
diff --git a/common/controller/keepVideosMatching.test.ts b/common/controller/keepVideosMatching.test.ts
@@ -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,8 @@ 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 {
@@ -82,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 = {
@@ -96,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
@@ -184,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);
@@ -217,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, { by: "operator", via: "keep-videos-match", surface: opts.surface ?? "ops", 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 } : {}),
});
}
@@ -245,6 +265,7 @@ export async function keepVideosMatching(
matched,
marked,
alreadyKept,
+ takenOver,
notDownloaded,
unscanned,
noMetadata,
@@ -258,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[];
@@ -294,18 +321,25 @@ 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, { by: "operator", via: "keep-videos-ids", ...(opts.surface ? { surface: opts.surface } : {}), note });
result.marked.push(id);
+ if (outcome === "taken-over") result.takenOver.push(id);
}
}
result.pendingAll =
diff --git a/common/controller/markProvenance.test.ts b/common/controller/markProvenance.test.ts
@@ -485,3 +485,164 @@ test("an inferred mark joins the opt-in group, counted apart", async () => {
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
@@ -5,7 +5,7 @@ import { isPermanentlyGone } from "../lib/availability";
import { loadAvailability } from "../lib/availability-server";
import { assertChannelTextReadable } from "../lib/channelMedia";
import type { DoNotCleanEvidence } from "../lib/doNotClean";
-import { loadDoNotClean, relabelDoNotCleanInferred } from "../lib/doNotClean-server";
+import { 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
@@ -15,13 +15,19 @@ import { readJobMeta, type JobMeta } from "../jobs/jobMeta";
//
// THE PROOF, both halves required:
// 1. availability.json says the CHECK found the video gone (deleted /
-// private / members-only) within a minute of the mark's setAt: a history
-// entry by source "check", or the record's top level (checkedAt,
-// checkedBy "check").
+// 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), running at setAt
-// (start - 1 min .. end + 1 min), whose log names the pin: the gate's own
-// line `Pinned <id> as do-not-clean (<that availability>)`.
+// 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
@@ -57,6 +63,49 @@ export type MarkBackfillResult = {
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",
@@ -132,7 +181,11 @@ export async function backfillMarkProvenance({
fail("no-availability-record");
continue;
}
- const near = (iso: string) => Number.isFinite(setAt) && Math.abs(Date.parse(iso) - setAt) <= MARK_PROOF_WINDOW_MS;
+ // 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)) {
@@ -151,7 +204,7 @@ export async function backfillMarkProvenance({
let evidence: DoNotCleanEvidence | null = null;
for (const job of jobs) {
const { startedAt, endedAt } = job.meta;
- if (setAt < startedAt! - MARK_PROOF_WINDOW_MS || setAt > endedAt! + MARK_PROOF_WINDOW_MS) continue;
+ 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) {
diff --git a/common/lib/doNotClean-server.ts b/common/lib/doNotClean-server.ts
@@ -6,12 +6,19 @@ import {
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
@@ -33,6 +40,8 @@ const doNotCleanSidecar = sidecar(
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> {
@@ -46,7 +55,9 @@ export async function isDoNotClean(videoDir: string): Promise<boolean> {
// - 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.
+// 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(
@@ -55,25 +66,73 @@ export async function setDoNotClean(
mark?: DoNotCleanProvenance,
): Promise<boolean> {
if (!enabled) {
- await doNotCleanSidecar.remove(videoDir);
- return true;
+ 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).");
}
- const existing = await loadDoNotClean(videoDir);
- if (existing && mark.by === "availability-check") return false;
- const record: DoNotCleanRecord = {
+ 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(),
- ...(mark.note ? { note: mark.note } : {}),
+ ...(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 } : {}),
};
- await doNotCleanSidecar.write(videoDir, record);
- return true;
+}
+
+// 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
@@ -86,17 +145,36 @@ export async function relabelDoNotCleanInferred(
evidence: DoNotCleanEvidence,
now: Date = new Date(),
): Promise<boolean> {
- const existing = await loadDoNotClean(videoDir);
- if (!existing || existing.by !== undefined || existing.setAt !== expect.setAt) return false;
- await doNotCleanSidecar.write(videoDir, {
- ...existing,
- by: "availability-check",
- via: "pre-clean-check",
- inferred: true,
- inferredAt: now.toISOString(),
- evidence,
+ return 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;
});
- return true;
}
// THE RECORD OF AUDIO REMOVED UNDER A MARK THAT STAYS (the opt-in "also remove
@@ -108,6 +186,10 @@ 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, {
@@ -116,3 +198,33 @@ export async function recordDoNotCleanAudioRemoved(
});
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
@@ -83,6 +83,9 @@ export type DoNotCleanRecord = {
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";
@@ -93,3 +96,52 @@ export const DO_NOT_CLEAN_FILENAME = "do-not-clean.json";
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/pendingKeep-server.ts b/common/lib/pendingKeep-server.ts
@@ -16,7 +16,7 @@ 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";
@@ -83,15 +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, {
- by: "operator",
+ // 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 } : {}),
- note: entry.note ?? "keep-videos: asked before it was fetched",
- });
- }
+ ...(entry.note ? { note: entry.note } : {}),
+ },
+ { defaultNote: "keep-videos: asked before it was fetched" },
+ );
await save(
paths,
slug,
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -20,6 +20,13 @@
(`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
@@ -54,3 +54,41 @@ test("marks-backfill: a dry run by default, writes nothing, says why a mark is n
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";
@@ -54,7 +54,10 @@ export const dynamic = "force-dynamic";
// 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.
+// 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,
@@ -63,7 +66,7 @@ const SWEEPS = {
} as const;
export async function POST(request: Request) {
- return ops(request, ["slug", "sweep", "unchecked", "dryRun", "includeSourceGone"], 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;
@@ -72,6 +75,10 @@ export async function POST(request: Request) {
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');
}
@@ -92,6 +99,13 @@ export async function POST(request: Request) {
const r = await planCleanAudioUncheckedAction(slug);
if (!r.ok) return opsFail(r.error);
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,
diff --git a/editor/app/api/ops/do-not-clean/route.ts b/editor/app/api/ops/do-not-clean/route.ts
@@ -1,24 +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/marks-backfill/route.ts b/editor/app/api/ops/marks-backfill/route.ts
@@ -15,9 +15,15 @@ export const dynamic = "force-dynamic";
// 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"], async (body) => {
- const r = await marksBackfillAction(reqSlug(body, "slug"), optBool(body, "dryRun") ?? true);
+ 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]/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";
@@ -77,6 +78,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.
@@ -133,6 +136,7 @@ export function VideoPanel({
availabilityHistory,
channelAudioFormat,
doNotClean = false,
+ doNotCleanMark = null,
excludedFromTruncatedCheck = false,
savedVideo = null,
sourceVideoQuality,
@@ -489,9 +493,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"}
@@ -500,6 +506,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
@@ -10,7 +10,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";
@@ -169,7 +169,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);
@@ -260,6 +263,7 @@ export default async function VideoDetailPage({
availabilityHistory,
metadataHistory,
doNotClean,
+ doNotCleanMark,
excludedFromTruncatedCheck,
savedVideo,
archiveOrg,
@@ -296,6 +300,7 @@ export default async function VideoDetailPage({
availabilityHistory,
metadataHistory,
doNotClean,
+ doNotCleanMark,
excludedFromTruncatedCheck,
savedVideo,
archiveOrg,
@@ -435,6 +440,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,
@@ -1296,12 +1296,18 @@ export async function markVideoUntranscribableAction(
// `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,
surface: "button" | "ops" = "button",
-): Promise<{ ok: true } | { ok: false; error: string }> {
+ 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);
@@ -1311,12 +1317,20 @@ export async function toggleDoNotCleanAction(
} catch {
return { ok: false, error: `Video directory not found: ${videoId}` };
}
- if (enabled) await setDoNotClean(videoDir, true, { by: "operator", via: "toggle", surface: surface === "ops" ? "ops" : "button" });
- else await setDoNotClean(videoDir, false);
+ 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
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -1,12 +1,21 @@
"use server";
import { cancelCleanRetries } from "yt-dlp-transcript-common/controller/cleanRetrySchedule";
-import { backfillMarkProvenance, type MarkBackfillResult } from "yt-dlp-transcript-common/controller/marksBackfill";
+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";
@@ -672,15 +681,20 @@ export async function setCleanAudioWithoutCheckingAction(
// 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,
-): Promise<{ ok: true; result: MarkBackfillResult } | { ok: false; error: string }> {
+ 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 = await backfillMarkProvenance({ paths, channelSlug: slug, dryRun: dryRun !== false });
- if (!result.dryRun && result.relabelled.length > 0) {
+ 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");
}
@@ -690,6 +704,29 @@ export async function marksBackfillAction(
}
}
+// 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
@@ -330,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,
@@ -1404,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]",
@@ -1477,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",
@@ -1799,7 +1807,11 @@ 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',
@@ -1808,7 +1820,10 @@ export function usage() {
' 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}.',
+ ' 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"?}.',
@@ -1856,6 +1871,8 @@ export function usage() {
' 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.',