commit 2a95fb3259fa4194a4c707f171de24f5eb0f7254
parent cea68057fb5c4a8a0908d86210cdd7634f287927
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Fri, 23 Oct 2026 17:58:31 -0400
Keep both copies when a download lands over a saved container, flagged for a check
A landed recording (import, attach, live capture) as long as a later
download made the download be discarded, so an explicit 720p persist over
a 360p capture could never land. Now finalizeAppExtraction never discards
either copy (ytdlp/savedAlternates.ts): an explicit persist (persist-videos,
Persist source video, the whole-recording fetch — `explicitPersist`) makes
the download active; any other download keeps the saved copy active unless
it is longer. The other copy stays in the same store dir as
source-media.alt-<h>p-<stamp>.<ext> (no reader matches it) and is listed in
the pointer's `alternates`; keepReason and do-not-clean are kept. The
landed guard's container half (landedContainerWins) is removed; audio is
unchanged. persist-videos' above-height replace keeps the old copy too.
Readers: the pointer parses `alternates`/`probed`; persistSourceVideo
carries alternates; unpersist moves them back, drop removes them with the
video and counts their bytes; the keep-latest prune skips a video holding
any; inventory totals and /saved-videos count them. /saved-videos lists
"Two saved copies"; `pnpm ops get saved-alternates [<slug>]` reads them.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
22 files changed, 1024 insertions(+), 110 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -145,7 +145,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "<id>"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` |
| `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` |
| `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` |
-| `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. | `pnpm ops persist-videos --file list.json --wait` |
+| `persist-videos` | persist-videos saves specific videos, across channels, to the saved-video store: {"items": \[{"slug", "id"}, ...\]}. "format": "original" \| "video\_720" (default: each channel's own). "replace": "above-height" also re-fetches a saved one whose height is unknown or above that quality (default "never"). "gapMs" pauses between downloads (default the batch gap), "minFreeMemMb" waits for that much free memory before each. "dryRun": true answers with the buckets (saved, wrongHeight, toFetch, noUrl, unknown) and starts nothing. One job per channel, on its download queue; a low disk or a rate limit stops it, and running the same body again resumes — saved videos are skipped. Over a copy already in the store (an import, an attach, a live recording or an earlier download) the download becomes the active one and the old copy is kept beside it, flagged for a check (`get saved-alternates`); nothing is deleted. | `pnpm ops persist-videos --file list.json --wait` |
| `fetch-windows` | fetch-windows fetches clip windows, one paced job per platform queue (YouTube and Rumble side by side): {"siteId"} fetches every window the site's published reports cite and the disk does not hold; {"items": \[{"slug", "id", "from", "to", "clipId"?, "reason"?, "pad"?, "webpageUrl"?, "force"?}, ...\], "requestedBy", "manifest"?} fetches a list. A window of a recording whose availability says deleted or private is refused (unresolved) unless the item names a "webpageUrl" (a copy: find-copy) or "force": true (a stale reading; or check its availability again on the channel page's Diagnostics). "maxHeight" caps the source height (default 720). "dryRun": true lists the windows per platform, the ones already on disk ("cached") and the ones no fetch can fill ("unfetchable": deleted, off the site) and starts nothing. A platform cooling down or held is refused for its group; a 429, or two 403s in a row, backs the platform off and stops its job. Running the same body again resumes — fetched windows are cached, and a window a queued or running job will already write is answered in "inFlight" with that job, whose id joins "jobIds" (so --wait follows it) and no second job is queued. Windows run on the platform's clip queue (clips:youtube), never behind its long downloads. "storedUrl": "fallback" \| "only" (default "never") cuts a window from the media URL its record's metadata.info.json stores — Odysee's CDN file (\*.odycdn.com), the only platform allowed — when the page lookup is rate-limited ("fallback": after a 429) or without asking the page at all ("only"). A held or cooling platform still runs its windows that have one; the rest are refused or left for a later run. Same queue, same gaps; the window's provenance says source "stored-media-url". "minGapSeconds" (items only, 30–3600) sets this run's pause between two fetches in place of the platform's floor (Rumble's 120 s); still jittered up to half again. Shorter than the default risks Rumble's IP-wide Cloudflare challenge; a Retry keeps it. A window on a whole-recording platform (settings.clips .wholeRecordingPlatforms, default Rumble) is not seeked: the video is saved whole once, as "Persist source video" saves it, on the platform's download queue, and its windows are cut from it — a remote Rumble seek put the picture 1-4 s off the sound. A failed whole download fails its windows with the download's message. "wholeRecording": false fetches every window of the run by a remote seek instead. A fetched window whose picture still runs off its sound is set aside (<from>-<to>.desynced.<ext>) and fails; a held one is set aside and fetched again (check-windows). | `pnpm ops fetch-windows --json '{"siteId":"demo-site","dryRun":true}'`<br>`pnpm ops fetch-windows --file windows.json --wait` |
| `cut-release` | cut-release turns a changelog's \[Unreleased\] into "## \[<version>\] - <date>": {"workspace": "editor" \| "export" \| "all", "version": "X.Y.Z" \| "next" \| "next-minor", "commit": boolean (default false), "date": "YYYY-MM-DD" (default today)}. "all" cuts both with ONE version and commits each ("Release <workspace> <version>") — or neither: every check runs before either file is written. Only an editor built from release 10 or later has the route (an older one answers 404); with no editor running, `archilyzer release cut` does the same locally. | `pnpm ops cut-release --json '{"workspace":"all","version":"next","commit":true}'` |
| `transcribe` | transcribe runs ONE local file through a local transcription worker, as a job: {"path": "/abs/file"} (audio or video), "start"/"end" (seconds) for a window, "workerId" (a settings worker id; default: the one auto-transcribe would get), "out" (an absolute path for the result JSON, never inside the corpus). The result is {path, window, worker: {id, appId, model, device}, cues: \[{start, end, text}\], text, ...}, cue times on the file's own clock. "words": true adds words: \[{w, start, end, conf?}\] on the same clock -- from parakeet, which keeps its word timestamps; \[\] from an engine that does not. "whilePaused": true runs it during a pause-all on a worker the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. With --wait it is printed on stdout (the response and the log go to stderr), so `pnpm ops transcribe ... --wait \| jq -r .text` works. | `pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150}' --wait`<br>`pnpm ops transcribe --json '{"path":"/abs/a.wav","workerId":"parakeet-cpu","out":"/tmp/a.json"}' --wait` |
@@ -203,6 +203,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops job wait <id>... [--wait-timeout <seconds>]
pnpm ops get settings [<key>]
pnpm ops get storage | sites | workers | auto-queue | scheduler
+ pnpm ops get saved-alternates [<slug>]
pnpm ops get services
pnpm ops get cleanup <slug>
pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]
@@ -237,6 +238,13 @@ job <verb> <id>... is a /jobs row's button: cancel (a running job is
get settings [<key>] is settings.json as the editor reads it (migrated and
defaulted; a secret is "<redacted>"), or one top-level key of it.
get storage is /storage: each location, mounted or not, free space, tiers.
+get saved-alternates [<slug>] lists every saved video holding two copies:
+ a download over a container already in the store keeps both — an
+ explicit persist (persist-videos, Persist source video, a whole-recording
+ fetch) makes the download active, any other keeps the saved one unless
+ the download is longer — and the other stays beside it as
+ source-media.alt-<h>p-<stamp>.<ext>, flagged for a check. Each video:
+ its line, the active copy, the alternates (height, seconds, origin).
get sites lists every site: id, title, siteUrl, Pages project, audience,
listed, search, publish policy, channels, citedChannels. (`get publish`
is the status.)
diff --git a/common/controller/archiveOrgDownload.ts b/common/controller/archiveOrgDownload.ts
@@ -474,6 +474,7 @@ export async function downloadArchiveOrgManaged(
origin: opts.persistOrigin,
extractAudio: !keepTranscript,
sourceFilename: sourceName,
+ explicitPersist: opts.explicitPersist,
onLog: opts.onLog,
signal: opts.signal,
});
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts
@@ -344,6 +344,7 @@ async function saveWholeRecordingManaged(o: SaveWholeRecordingOpts): Promise<Sav
appendArchive: true,
keepSourceVideoOverride: true,
forceMedia: true,
+ explicitPersist: true,
persistOrigin: o.origin,
persistFormatPreset: resolveSourceVideoQuality({
channel: o.config.sourceVideoQuality,
diff --git a/common/controller/landMedia.test.ts b/common/controller/landMedia.test.ts
@@ -34,7 +34,8 @@ const { loadSavedVideo } = await import("../lib/savedVideo-server");
const { isDoNotClean } = await import("../lib/doNotClean-server");
const { addPendingKeep, applyPendingKeep, loadPendingKeep } = await import("../lib/pendingKeep-server");
const { keepVideosByIds } = await import("./keepVideosMatching");
-const { prepareLandedGuard, settleLandedGuard, landedContainerWins } = await import("../ytdlp/landedGuard");
+const { prepareLandedGuard, settleLandedGuard } = await import("../ytdlp/landedGuard");
+const { planSavedContainer } = await import("../ytdlp/savedAlternates");
const paths = getPaths();
test.after(() => rm(ROOT, { recursive: true, force: true }));
@@ -280,9 +281,11 @@ test("a later download shorter than the landed recording does not clobber it; a
assert.match(await readFile(path.join(dir, "audio.mp3"), "utf8"), /seconds=4000/);
const prov = await mediaImportSidecar.load(dir);
assert.deepEqual(prov?.challenges?.map((c) => c.kept), ["landed", "download"]);
- // The container: a shorter downloaded one loses.
+ // The container: a shorter download does not become the active one (it is
+ // kept beside it — ytdlp/savedAlternates.test.ts); an explicit persist does.
const newer = await fake("source-media.mp4", "mov,mp4", 100, dir);
- assert.equal(await landedContainerWins(dir, newer, { measure }, onLog), true);
+ assert.equal((await planSavedContainer({ videoDir: dir, newContainer: newer, explicit: false, deps: { measure } }))?.active, "existing");
+ assert.equal((await planSavedContainer({ videoDir: dir, newContainer: newer, explicit: true, deps: { measure } }))?.active, "download");
// A video that was never landed is an ordinary download.
assert.equal(await prepareLandedGuard(await record("plain"), onLog), null);
});
diff --git a/common/controller/persistVideos.test.ts b/common/controller/persistVideos.test.ts
@@ -10,17 +10,20 @@ import type { DiskGateStatus } from "../lib/diskSpace";
import type { DownloadOutcomeRecord } from "../lib/downloadOutcome";
import { loadSavedVideo, persistSourceVideo } from "../lib/savedVideo-server";
import {
+ PERSIST_VIDEOS_DOWNLOAD,
persistVideos,
type PersistVideoDownload,
type PersistVideosDeps,
} from "./persistVideos";
+import { finalizeAppExtraction } from "../ytdlp/finalizeAppExtraction";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/persistVideos.test.ts
//
// Every dependency that would reach the network, the clock or the machine's
-// memory is injected: the download writes a fake container and persists it the
-// way downloadOneManaged does, sleeps are recorded, MemAvailable is scripted.
+// memory is injected: the download writes a fake container and finalizes it the
+// way downloadOneManaged does (finalizeAppExtraction, as an explicit persist
+// over a transcript), sleeps are recorded, MemAvailable is scripted.
const CONFIG: ChannelConfig = {
handling: "transcribe",
@@ -135,12 +138,22 @@ function harness(
const dir = videoDir(paths, o.channelSlug, id);
const file = over.file ?? "source-media.mp4";
await writeFile(path.join(dir, file), `new ${id}`);
- await persistSourceVideo({
+ await finalizeAppExtraction({
+ paths,
+ channelSlug: o.channelSlug,
+ channelConfig: o.channelConfig,
videoDir: dir,
- sourceFilename: file,
- storeDir: path.join(paths.savedVideosDir, o.channelSlug, id),
- keepReason: "override",
+ videoId: id,
+ fmt: "mp3",
+ persist: true,
+ category: "override",
+ extractAudio: false,
format: { preset: o.quality, height: over.height ?? 720 },
+ sourceFilename: file,
+ explicitPersist: PERSIST_VIDEOS_DOWNLOAD.explicitPersist,
+ alternatesDeps: { measure: async () => null, height: async () => null },
+ onLog: () => {},
+ signal: o.signal,
});
return {
videoId: id,
@@ -170,6 +183,12 @@ function harness(
};
}
+test("every download is an explicit persist: forced media, the source kept, the download active", () => {
+ assert.equal(PERSIST_VIDEOS_DOWNLOAD.explicitPersist, true);
+ assert.equal(PERSIST_VIDEOS_DOWNLOAD.forceMedia, true);
+ assert.equal(PERSIST_VIDEOS_DOWNLOAD.keepSourceVideoOverride, true);
+});
+
test("already-saved items are skipped; the rest are fetched in order", async () => {
await withPaths(async (paths) => {
await seedSaved(paths, "demo-channel", "aaa111");
@@ -285,12 +304,18 @@ test("above-height replaces a too-tall or unmeasured container, keeping its prov
assert.equal(nohgt?.keepReason, "pin");
assert.deepEqual(nohgt?.origin, { requestedBy: "umtool" });
assert.equal(nohgt?.format?.height, 720);
- // The old, differently-named container went only after the new one landed.
+ // Nothing is deleted: the old container stays beside the new one under an
+ // alternate name, flagged on the pointer for a check.
await assert.rejects(stat(path.join(oldTall!.dir, oldTall!.file)));
assert.equal(
await readFile(path.join(tall!.dir, tall!.file), "utf8"),
"new tall111",
);
+ const alt = tall?.alternates?.[0];
+ assert.match(alt?.file ?? "", /^source-media\.alt-1080p-\d{14}\.webm$/);
+ assert.equal(alt?.height, 1080);
+ assert.equal(await readFile(path.join(tall!.dir, alt!.file), "utf8"), "old tall111");
+ assert.match(nohgt?.alternates?.[0]?.file ?? "", /^source-media\.alt-\d{14}\.mp4$/);
});
});
diff --git a/common/controller/persistVideos.ts b/common/controller/persistVideos.ts
@@ -1,5 +1,5 @@
import path from "node:path";
-import { readFile, rm, stat } from "node:fs/promises";
+import { readFile, stat } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
import type { SiteSettings } from "../lib/settings";
@@ -7,10 +7,7 @@ import { getSettings } from "../lib/settings";
import { diskGate, type DiskGateStatus } from "../lib/diskSpace";
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import type { DownloadOutcomeRecord } from "../lib/downloadOutcome";
-import {
- savedVideoPath,
- type SavedVideoPointer,
-} from "../lib/savedVideo";
+import type { SavedVideoPointer } from "../lib/savedVideo";
import {
loadSavedVideo,
restoreSavedVideoProvenance,
@@ -56,12 +53,13 @@ import { recordDownloadBackoff } from "../jobs/downloadBackoff";
// (`minFreeMemMb`), and the disk floor. Cancel and drain are honoured between
// videos; the one in flight is a cancel's business, as everywhere else.
//
-// REPLACING NEVER DELETES FIRST. `replace: "above-height"` re-fetches a saved
-// video whose recorded height is unknown or above the requested quality's
-// ceiling. The old container stays where it is until the new pointer is
-// written; only then is it removed (when its path differs — a same-named one
-// was already replaced by the store's atomic move). The replacement keeps the
-// old pointer's `keepReason` and `origin`, so a keep-latest container stays
+// REPLACING NEVER DELETES. `replace: "above-height"` re-fetches a saved video
+// whose recorded height is unknown or above the requested quality's ceiling.
+// The download becomes the ACTIVE copy and the old one is kept beside it as an
+// alternate, flagged on the pointer for a later check
+// (ytdlp/savedAlternates.ts — this run's downloads are `explicitPersist`).
+// The replacement keeps the old pointer's `keepReason` and `origin` (a landed
+// copy's origin stays with that copy), so a keep-latest container stays
// evictable and a requested one keeps its requester.
export type PersistVideoItem = { slug: string; id: string };
@@ -138,12 +136,22 @@ export type PersistVideosDeps = {
paths: Paths,
failureClass: "rate_limit" | "network",
) => Promise<void>;
- removeFile: (file: string) => Promise<void>;
};
// How often the memory wait re-reads /proc/meminfo.
export const MEM_POLL_MS = 10_000;
+// What every item's download asks of downloadOneManaged.
+export const PERSIST_VIDEOS_DOWNLOAD = {
+ appendArchive: true,
+ keepSourceVideoOverride: true,
+ // Persist means persist — see persistKept.
+ forceMedia: true,
+ // An operator's list: over a copy already saved, the download becomes the
+ // active one and the old copy is kept beside it (ytdlp/savedAlternates.ts).
+ explicitPersist: true,
+} as const;
+
const defaultDownload: PersistVideoDownload = (o) =>
downloadOneManaged({
channelSlug: o.channelSlug,
@@ -155,10 +163,7 @@ const defaultDownload: PersistVideoDownload = (o) =>
cookiePolicy: resolveCookiePolicy(o.settings, o.channelConfig),
inlineTranscribeOnFallback: o.settings.inlineTranscribeOnFallback,
globalSkipLiveDownloads: o.settings.skipLiveDownloads,
- appendArchive: true,
- keepSourceVideoOverride: true,
- // Persist means persist — see persistKept.
- forceMedia: true,
+ ...PERSIST_VIDEOS_DOWNLOAD,
persistFormatPreset: o.quality,
});
@@ -196,7 +201,6 @@ const DEFAULT_DEPS: PersistVideosDeps = {
readChannelConfig,
onPlatformBackoff: (platform, paths, failureClass) =>
recordDownloadBackoff(platform, paths, failureClass),
- removeFile: (file) => rm(file, { force: true }),
};
// The tallest height a quality accepts, or null for "original" (no ceiling).
@@ -500,14 +504,17 @@ export async function persistVideos({
continue;
}
if (p.pointer) {
- // The same video's container, so it keeps the old pointer's retention
- // class and requester: the forced persist writes "override", which
- // would make a keep-latest container permanent.
- await restoreSavedVideoProvenance(videoDir, p.pointer);
- const oldFile = savedVideoPath(p.pointer);
- if (oldFile !== savedVideoPath(pointer)) {
- await deps.removeFile(oldFile).catch(() => {});
- log(` ${label(p)}: removed the replaced container ${oldFile}.`);
+ const kept = pointer.alternates?.find((a) => a.storedAt === p.pointer!.storedAt);
+ if (kept) {
+ // The persist kept the old copy beside the new one and carried its
+ // provenance over itself (ytdlp/savedAlternates.ts).
+ log(` ${label(p)}: the replaced container stays beside it as ${kept.file}, flagged for a check.`);
+ } else {
+ // The old file was already gone: the same video's container, so it
+ // keeps the old pointer's retention class and requester — the forced
+ // persist writes "override", which would make a keep-latest container
+ // permanent.
+ await restoreSavedVideoProvenance(videoDir, p.pointer);
}
result.replaced.push({ slug: p.slug, id: p.id });
}
diff --git a/common/controller/pruneSavedVideos.ts b/common/controller/pruneSavedVideos.ts
@@ -63,6 +63,15 @@ export async function pruneSavedVideos({
if (pointer.keepReason !== "keep-latest") continue;
if (keptIds.has(id)) continue; // still inside the window
if (await isDoNotClean(videoDir)) continue; // pinned -> keep forever
+ // Two copies kept for a check (ytdlp/savedAlternates.ts): the prune never
+ // removes a flagged alternate, so it leaves the whole video for the check.
+ if (pointer.alternates?.length) {
+ log(
+ `Kept saved video ${id} although it rolled out of the keep-latest window: ` +
+ `it holds ${pointer.alternates.length} alternate cop${pointer.alternates.length === 1 ? "y" : "ies"} flagged for a check.`,
+ );
+ continue;
+ }
const bytes = await dropSavedVideo(videoDir);
bytesFreed += bytes;
pruned++;
diff --git a/common/controller/savedVideoInventory.ts b/common/controller/savedVideoInventory.ts
@@ -3,7 +3,11 @@ import fs from "fs-extra";
import type { Paths } from "../lib/paths";
import { mapConcurrent } from "../lib/concurrency";
import { loadSavedVideo } from "../lib/savedVideo-server";
-import { savedVideoPath, type SavedVideoPointer } from "../lib/savedVideo";
+import {
+ savedVideoBytes,
+ savedVideoPath,
+ type SavedVideoPointer,
+} from "../lib/savedVideo";
import {
isDriveNotAnswering,
onDrive,
@@ -115,6 +119,16 @@ export async function listSavedVideos({
return out;
}
+// Every saved video holding alternates (ytdlp/savedAlternates.ts): the flag a
+// later check reads. The same pointer walk as listSavedVideos.
+export async function listSavedAlternates(opts: {
+ paths: Paths;
+ channelSlug?: string;
+ notAnswering?: string[];
+}): Promise<SavedVideoEntry[]> {
+ return (await listSavedVideos(opts)).filter((e) => (e.pointer.alternates?.length ?? 0) > 0);
+}
+
export type SavedVideoTotals = {
count: number;
bytes: number;
@@ -129,6 +143,6 @@ export async function savedVideoTotals(opts: {
}): Promise<SavedVideoTotals> {
const entries = await listSavedVideos(opts);
let bytes = 0;
- for (const e of entries) bytes += e.pointer.bytes;
+ for (const e of entries) bytes += savedVideoBytes(e.pointer);
return { count: entries.length, bytes };
}
diff --git a/common/lib/mediaImport.ts b/common/lib/mediaImport.ts
@@ -70,7 +70,11 @@ export type MediaImportChallenge = {
what: "audio" | "container";
newSeconds: number | null;
landedSeconds: number | null;
+ // Audio: the copy kept. A container: the ACTIVE copy — the other one is
+ // kept too, as `alternate` in the store (ytdlp/savedAlternates.ts).
kept: "landed" | "download";
+ alternate?: string;
+ explicit?: boolean;
};
export type MediaImportRecord = { entries: MediaImportEntry[]; challenges?: MediaImportChallenge[] };
diff --git a/common/lib/savedVideo-server.ts b/common/lib/savedVideo-server.ts
@@ -10,6 +10,7 @@ import {
import {
SAVED_VIDEO_POINTER_FILENAME,
parseSavedVideoPointer,
+ savedVideoBytes,
savedVideoPath,
type SavedVideoFormat,
type SavedVideoKeepReason,
@@ -40,7 +41,7 @@ export async function isSavedVideo(videoDir: string): Promise<boolean> {
return (await loadSavedVideo(videoDir)) !== null;
}
-async function writePointer(
+export async function writePointer(
videoDir: string,
pointer: SavedVideoPointer,
): Promise<void> {
@@ -68,7 +69,7 @@ export async function rewriteSavedVideoDir(
// one filesystem; EXDEV (the store is on a different disk) falls back to a
// copy-to-temp + atomic rename + unlink so a crash mid-copy never leaves a
// partial file under the final name.
-async function moveFileCrossDevice(src: string, dest: string): Promise<void> {
+export async function moveFileCrossDevice(src: string, dest: string): Promise<void> {
await mkdir(path.dirname(dest), { recursive: true });
try {
await rename(src, dest);
@@ -135,6 +136,11 @@ export async function persistSourceVideo(opts: {
const src = opts.sourcePath ?? path.join(opts.videoDir, opts.sourceFilename);
const dest = path.join(opts.storeDir, opts.sourceFilename);
const st = await stat(src);
+ // The copies kept beside the one this replaces (savedVideo.ts `alternates`)
+ // are still in that dir: the new pointer carries them, or they would be
+ // files no pointer names.
+ const before = await loadSavedVideo(opts.videoDir);
+ const alternates = before?.dir === opts.storeDir ? before.alternates : undefined;
await moveFileCrossDevice(src, dest);
const pointer: SavedVideoPointer = {
storedAt: new Date().toISOString(),
@@ -145,6 +151,7 @@ export async function persistSourceVideo(opts: {
...(opts.sha256 ? { sha256: opts.sha256 } : {}),
...(opts.origin ? { origin: opts.origin } : {}),
...(opts.format ? { format: opts.format } : {}),
+ ...(alternates?.length ? { alternates } : {}),
};
await writePointer(opts.videoDir, pointer);
return pointer;
@@ -208,18 +215,28 @@ export async function unpersistSavedVideo(
} catch {
// The stored container is already gone; just drop the dangling pointer.
}
+ // Its alternates come back too, under their own names (no reader takes one
+ // for a source): with the pointer gone, nothing would name them in the store.
+ for (const alt of pointer.alternates ?? []) {
+ await moveFileCrossDevice(path.join(pointer.dir, alt.file), path.join(videoDir, alt.file)).catch(() => {});
+ }
await rm(savedVideoPointerPath(videoDir), { force: true });
await pruneEmptyStoreDirs(pointer.dir);
return true;
}
// Permanently delete a video's persisted container + pointer (retention prune of
-// a video that rolled out of the keep-latest window). Returns bytes freed.
+// a video that rolled out of the keep-latest window). Returns bytes freed. The
+// whole video goes, its alternates with it — the prune itself never calls this
+// for a video that holds any (pruneSavedVideos leaves those for the check).
export async function dropSavedVideo(videoDir: string): Promise<number> {
const pointer = await loadSavedVideo(videoDir);
if (!pointer) return 0;
await rm(savedVideoPath(pointer), { force: true });
+ for (const alt of pointer.alternates ?? []) {
+ await rm(path.join(pointer.dir, alt.file), { force: true });
+ }
await rm(savedVideoPointerPath(videoDir), { force: true });
await pruneEmptyStoreDirs(pointer.dir);
- return pointer.bytes;
+ return savedVideoBytes(pointer);
}
diff --git a/common/lib/savedVideo.ts b/common/lib/savedVideo.ts
@@ -61,6 +61,34 @@ export type SavedVideoPointer = {
// every pointer written before this; `height`/`vcodec` absent when yt-dlp
// did not report them.
format?: SavedVideoFormat;
+ // TWO COPIES OF ONE VIDEO, BOTH KEPT (finalizeAppExtraction, the download
+ // over a container already in the store — ytdlp/savedAlternates.ts). `file`
+ // stays the ACTIVE copy, the one every reader uses; each other copy sits in
+ // the same `dir` under a name no reader takes for a source
+ // (`source-media.alt-<h>p-<stamp>.<ext>`), listed here so a later check can
+ // decide between them. Absent on every pointer with one copy.
+ alternates?: SavedVideoAlternate[];
+ // The active copy's own measured length and height, written when an
+ // alternate was recorded beside it (a landed container has no `format`).
+ probed?: SavedVideoProbe;
+};
+
+export type SavedVideoProbe = { seconds?: number; height?: number };
+
+export type SavedVideoAlternate = {
+ // Basename in the pointer's `dir`.
+ file: string;
+ bytes: number;
+ // When this copy first entered the store, and when it stopped being active.
+ storedAt: string;
+ setAsideAt: string;
+ seconds?: number;
+ height?: number;
+ vcodec?: string;
+ // Who brought this copy: a landed one keeps its import/attach provenance.
+ origin?: SavedVideoOrigin;
+ // A download's copy: the quality it asked for.
+ preset?: SourceVideoQuality;
};
export type SavedVideoFormat = {
@@ -152,6 +180,67 @@ function parseOrigin(raw: unknown): SavedVideoOrigin | null {
return out;
}
+function positive(v: unknown): number | undefined {
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
+}
+
+function parseProbe(raw: unknown): SavedVideoProbe | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ const out: SavedVideoProbe = {};
+ const seconds = positive(r.seconds);
+ const height = positive(r.height);
+ if (seconds !== undefined) out.seconds = seconds;
+ if (height !== undefined) out.height = height;
+ return Object.keys(out).length ? out : null;
+}
+
+function parseAlternate(raw: unknown): SavedVideoAlternate | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as Record<string, unknown>;
+ if (typeof r.file !== "string" || r.file === "" || r.file.includes("/")) return null;
+ const out: SavedVideoAlternate = {
+ file: r.file,
+ bytes: typeof r.bytes === "number" && Number.isFinite(r.bytes) ? r.bytes : 0,
+ storedAt: typeof r.storedAt === "string" ? r.storedAt : "",
+ setAsideAt: typeof r.setAsideAt === "string" ? r.setAsideAt : "",
+ };
+ const seconds = positive(r.seconds);
+ const height = positive(r.height);
+ if (seconds !== undefined) out.seconds = seconds;
+ if (height !== undefined) out.height = height;
+ if (typeof r.vcodec === "string" && r.vcodec !== "") out.vcodec = r.vcodec;
+ const origin = parseOrigin(r.origin);
+ if (origin) out.origin = origin;
+ if (isSourceVideoQuality(r.preset)) out.preset = r.preset;
+ return out;
+}
+
+// One line for a video holding alternates, for the review listing:
+// "2 saved copies: active 720p, 4696.5 s (download); alternate 360p, 4696.6 s
+// (attach-media, source-media.alt-360p-20261023172312.mp4)".
+export function savedAlternatesLine(pointer: SavedVideoPointer): string {
+ const facts = (height: number | undefined, seconds: number | undefined, by: string) =>
+ `${height ? `${height}p` : "height unknown"}, ${seconds !== undefined ? `${seconds.toFixed(1)} s` : "length unknown"} (${by}`;
+ const alts = pointer.alternates ?? [];
+ const active = facts(
+ pointer.format?.height ?? pointer.probed?.height,
+ pointer.probed?.seconds,
+ pointer.origin?.requestedBy ?? "download",
+ );
+ return (
+ `${alts.length + 1} saved copies: active ${active}); ` +
+ alts
+ .map((a) => `alternate ${facts(a.height, a.seconds, a.origin?.requestedBy ?? "download")}, ${a.file})`)
+ .join("; ")
+ );
+}
+
+// Every byte a pointer accounts for: the active copy and its alternates.
+export function savedVideoBytes(pointer: SavedVideoPointer): number {
+ return pointer.bytes + (pointer.alternates ?? []).reduce((n, a) => n + a.bytes, 0);
+}
+
function isKeepReason(v: unknown): v is SavedVideoKeepReason {
return v === "keep-latest" || v === "pin" || v === "override";
}
@@ -203,5 +292,13 @@ export function parseSavedVideoPointer(raw: unknown): SavedVideoPointer | null {
// Same rule: a pointer without `format` (every one before it) parses as before.
const format = parseFormat(r.format);
if (format) pointer.format = format;
+ // And again: a pointer without `alternates` parses as before. An entry that
+ // does not name a file is dropped; the file itself is never touched here.
+ const alternates = Array.isArray(r.alternates)
+ ? r.alternates.map(parseAlternate).filter((a): a is SavedVideoAlternate => a !== null)
+ : [];
+ if (alternates.length) pointer.alternates = alternates;
+ const probed = parseProbe(r.probed);
+ if (probed) pointer.probed = probed;
return pointer;
}
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -211,6 +211,13 @@ export type ManagedDownloadOpts = {
// never by the download lane, re-acquire or import. Transcribe handling
// already downloads, so it is unaffected.
forceMedia?: boolean;
+ // A PERSON ASKED FOR THIS CONTAINER: over a copy already in the saved-video
+ // store, the download becomes the ACTIVE one and the other is kept beside it
+ // as an alternate (ytdlp/savedAlternates.ts); without it the copy in the
+ // store stays active unless the download is longer. Neither is discarded
+ // either way. Set by "Persist source video", persist-videos and the
+ // whole-recording fetch; never by an automatic download.
+ explicitPersist?: boolean;
// Per-run override of channelConfig.audioFormat for the extracted audio.
audioFormatOverride?: AudioFormat;
// Resolved yt-dlp `-f` download-format preset (override > channel > global),
@@ -1675,6 +1682,7 @@ async function runManagedDownload(
category: plan.category,
origin: opts.persistOrigin,
format: persistedFormat(),
+ explicitPersist: opts.explicitPersist,
onLog: opts.onLog,
signal: opts.signal,
});
@@ -1813,6 +1821,7 @@ async function runManagedDownload(
category: plan.category,
origin: opts.persistOrigin,
format: persistedFormat(),
+ explicitPersist: opts.explicitPersist,
extractAudio: false,
onLog: opts.onLog,
signal: opts.signal,
@@ -1834,6 +1843,7 @@ async function runManagedDownload(
category: plan.category,
origin: opts.persistOrigin,
format: persistedFormat(),
+ explicitPersist: opts.explicitPersist,
onLog: opts.onLog,
signal: opts.signal,
});
diff --git a/common/ytdlp/finalizeAppExtraction.ts b/common/ytdlp/finalizeAppExtraction.ts
@@ -18,8 +18,13 @@ import {
type SavedVideoOrigin,
} from "../lib/savedVideo";
import { persistSourceVideo } from "../lib/savedVideo-server";
-import { probeMediaDurationSec } from "./ffprobeDuration";
-import { landedContainerWins } from "./landedGuard";
+import { probeMediaDurationSec, probeVideoHeight } from "./ffprobeDuration";
+import {
+ keepDownloadAsAlternate,
+ persistOverExisting,
+ planSavedContainer,
+ type SavedAlternatesDeps,
+} from "./savedAlternates";
// After an app-mode transcribe download, produce audio.<fmt> from the downloaded
// source-media.<ext> container via ffmpeg. When the video is persisted the
@@ -54,6 +59,11 @@ export async function finalizeAppExtraction(opts: {
// The container's name in videoDir, when the caller knows it (the
// archive.org fetch). Absent: the sorted first source-media.<ext> there.
sourceFilename?: string;
+ // A PERSON ASKED FOR THIS CONTAINER (ManagedDownloadOpts.explicitPersist):
+ // over a copy already in the store, the download becomes the active one.
+ explicitPersist?: boolean;
+ // Test seam: how the two copies are measured. Production passes none.
+ alternatesDeps?: SavedAlternatesDeps;
onLog: (s: string) => void;
signal: AbortSignal;
}): Promise<void> {
@@ -66,17 +76,39 @@ export async function finalizeAppExtraction(opts: {
);
return;
}
- // A LANDED RECORDING AS LONG OR LONGER STAYS (ytdlp/landedGuard.ts): the
- // download's container is discarded, and nothing is extracted from it.
- if (
- await landedContainerWins(
- opts.videoDir,
- path.join(opts.videoDir, source),
- { measure: (file) => probeMediaDurationSec({ ffprobeBin: opts.paths.ffprobeBin, file }) },
- opts.onLog,
- )
- ) {
- await removeMediaFile(opts.videoDir, source);
+ // A COPY ALREADY IN THE STORE IS NEVER DISCARDED, NOR IS THE DOWNLOAD
+ // (ytdlp/savedAlternates.ts): both are kept, one active. When the one in the
+ // store stays active the download goes beside it and nothing is extracted
+ // from it.
+ const alternatesDeps: SavedAlternatesDeps = opts.alternatesDeps ?? {
+ measure: (file) => probeMediaDurationSec({ ffprobeBin: opts.paths.ffprobeBin, file }),
+ height: (file) => probeVideoHeight({ ffprobeBin: opts.paths.ffprobeBin, file }),
+ };
+ const plan = opts.persist
+ ? await planSavedContainer({
+ videoDir: opts.videoDir,
+ newContainer: path.join(opts.videoDir, source),
+ ...(opts.format?.height ? { newHeight: opts.format.height } : {}),
+ explicit: opts.explicitPersist === true,
+ deps: alternatesDeps,
+ })
+ : null;
+ if (plan?.active === "existing") {
+ try {
+ await keepDownloadAsAlternate(plan, {
+ sourceFilename: source,
+ origin: opts.origin,
+ format: opts.format,
+ paths: opts.paths,
+ deps: alternatesDeps,
+ onLog: opts.onLog,
+ });
+ } catch (err) {
+ opts.onLog(
+ `Failed to keep ${source} beside the saved container (${(err as Error).message}); leaving it in the data dir.
+`,
+ );
+ }
return;
}
if (opts.extractAudio === false) {
@@ -118,21 +150,32 @@ export async function finalizeAppExtraction(opts: {
opts.channelSlug,
opts.videoId,
);
+ const keepReason = opts.category === "none" ? undefined : opts.category;
try {
- const pointer = await persistSourceVideo({
- videoDir: opts.videoDir,
- sourceFilename: source,
- storeDir,
- keepReason: opts.category === "none" ? undefined : opts.category,
- origin: opts.origin,
- ...(opts.format ? { format: opts.format } : {}),
- // The store-in-transition guard. A move of the saved-video store is a
- // multi-hour copy, and a container landing in the middle of it is lost
- // three different ways — see lib/savedVideoStore.ts. The catch below is
- // already the right handling: the container stays in the data dir with a
- // line in the log, and the next persist (after the move) picks it up.
- paths: opts.paths,
- });
+ const pointer = plan
+ ? await persistOverExisting(plan, {
+ sourceFilename: source,
+ keepReason,
+ origin: opts.origin,
+ format: opts.format,
+ paths: opts.paths,
+ deps: alternatesDeps,
+ onLog: opts.onLog,
+ })
+ : await persistSourceVideo({
+ videoDir: opts.videoDir,
+ sourceFilename: source,
+ storeDir,
+ keepReason,
+ origin: opts.origin,
+ ...(opts.format ? { format: opts.format } : {}),
+ // The store-in-transition guard. A move of the saved-video store is a
+ // multi-hour copy, and a container landing in the middle of it is lost
+ // three different ways — see lib/savedVideoStore.ts. The catch below is
+ // already the right handling: the container stays in the data dir with a
+ // line in the log, and the next persist (after the move) picks it up.
+ paths: opts.paths,
+ });
opts.onLog(
`Persisted source video to ${path.join(pointer.dir, pointer.file)} (${pointer.bytes} bytes).\n`,
);
diff --git a/common/ytdlp/landedGuard.ts b/common/ytdlp/landedGuard.ts
@@ -14,10 +14,10 @@
// (KEEP_LONGER_TOLERANCE_SECONDS of slack; a tie keeps the landed
// one) and the other is removed with removeMediaFile. No new file
// (a failed or skipped download): the aside one goes back.
-// container finalizeAppExtraction asks `landedContainerWins` before it
-// extracts or persists: when the store holds a landed container
-// as long or longer than the new one, the new one is discarded,
-// and so is its audio extraction.
+// container NEITHER COPY IS DISCARDED (ytdlp/savedAlternates.ts, asked by
+// finalizeAppExtraction for any video with a container already
+// in the store): both are kept, one active, the other an
+// alternate flagged on the pointer for a later check.
//
// Every decision is appended to media-import.json's `challenges`.
@@ -27,7 +27,6 @@ import { KEEP_LONGER_TOLERANCE_SECONDS, type MediaImportChallenge } from "../lib
import { isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles";
import { mediaImportSidecar } from "../lib/mediaImport-server";
import { removeMediaFile, renameMediaFile } from "../lib/mediaTier-server";
-import { savedVideoPath } from "../lib/savedVideo";
import { loadSavedVideo } from "../lib/savedVideo-server";
export const LANDED_KEPT_SUFFIX = ".landed-kept";
@@ -42,7 +41,7 @@ export type LandedGuardPlan = { videoDir: string; asides: string[] };
// attach-media too: a container attached from a local archive is a recording
// somebody kept on purpose (keepReason "pin"), as an import is.
-const LANDED_BY: ReadonlySet<string> = new Set(["import-media", "record-live", "attach-media"]);
+export const LANDED_BY: ReadonlySet<string> = new Set(["import-media", "record-live", "attach-media"]);
// Was this video's source landed (rather than downloaded)?
export async function isLandedVideo(videoDir: string): Promise<boolean> {
@@ -51,7 +50,7 @@ export async function isLandedVideo(videoDir: string): Promise<boolean> {
return pointer?.origin?.requestedBy !== undefined && LANDED_BY.has(pointer.origin.requestedBy);
}
-async function recordChallenge(videoDir: string, c: MediaImportChallenge): Promise<void> {
+export async function recordChallenge(videoDir: string, c: MediaImportChallenge): Promise<void> {
const prev = await mediaImportSidecar.load(videoDir);
if (!prev) return;
await mediaImportSidecar.write(videoDir, { ...prev, challenges: [...(prev.challenges ?? []), c].slice(-50) });
@@ -126,33 +125,3 @@ export async function settleLandedGuard(
kept: newWins ? "download" : "landed",
});
}
-
-// Before a downloaded container is extracted and persisted: does a landed
-// container in the store, as long or longer, win? Then the caller discards the
-// new one (and extracts nothing from it).
-export async function landedContainerWins(
- videoDir: string,
- newContainer: string,
- deps: LandedGuardDeps,
- onLog: (s: string) => void,
-): Promise<boolean> {
- const pointer = await loadSavedVideo(videoDir);
- if (!pointer?.origin?.requestedBy || !LANDED_BY.has(pointer.origin.requestedBy)) return false;
- const landedSeconds = await deps.measure(savedVideoPath(pointer));
- if (landedSeconds === null) return false;
- const newSeconds = await deps.measure(newContainer);
- const landedWins = newSeconds === null || newSeconds <= landedSeconds + KEEP_LONGER_TOLERANCE_SECONDS;
- onLog(
- `The store holds a landed ${pointer.file} (${landedSeconds} s); the download's container is ${newSeconds ?? "?"} s: ` +
- `${landedWins ? "the landed one stays and the download's is discarded" : "the download's is longer and replaces it"}.\n`,
- );
- await recordChallenge(videoDir, {
- at: (deps.now?.() ?? new Date()).toISOString(),
- by: "download",
- what: "container",
- newSeconds,
- landedSeconds,
- kept: landedWins ? "landed" : "download",
- });
- return landedWins;
-}
diff --git a/common/ytdlp/savedAlternates.test.ts b/common/ytdlp/savedAlternates.test.ts
@@ -0,0 +1,320 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import type { SavedVideoPointer } from "../lib/savedVideo";
+import { savedAlternatesLine } from "../lib/savedVideo";
+import {
+ dropSavedVideo,
+ loadSavedVideo,
+ persistSourceVideo,
+ resolveSavedVideo,
+ unpersistSavedVideo,
+} from "../lib/savedVideo-server";
+import { findSourceMedia, isSourceMediaFile } from "../lib/mediaFiles";
+import { wholeContainersOf } from "../lib/evidenceClip.mjs";
+import { isDoNotClean, setDoNotClean } from "../lib/doNotClean-server";
+import { mediaImportSidecar } from "../lib/mediaImport-server";
+import { listSavedAlternates, savedVideoTotals } from "../controller/savedVideoInventory";
+import { pruneSavedVideos } from "../controller/pruneSavedVideos";
+import { finalizeAppExtraction } from "./finalizeAppExtraction";
+import { alternateName, persistOverExisting, planSavedContainer, type SavedAlternatesDeps } from "./savedAlternates";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/savedAlternates.test.ts
+//
+// A download over a container already in the saved-video store keeps BOTH
+// (ytdlp/savedAlternates.ts): which is active, what the pointer flags, that no
+// reader takes the alternate for a source, and that nothing deletes one
+// silently. A temp corpus; a "container" is a text file whose content names
+// its length and height, read by injected measure/height deps.
+
+const CONFIG = { handling: "transcribe", platform: "rumble", url: "https://rumble.com/c/Synth" } as ChannelConfig;
+const SLUG = "synth-rumble";
+const NOW = new Date("2026-10-23T17:23:12.000Z");
+
+async function withCorpus(fn: (paths: Paths) => Promise<void>): Promise<void> {
+ const dir = await mkdtemp(path.join(tmpdir(), "saved-alternates-"));
+ const paths = {
+ transcriptsDir: dir,
+ channelsDir: path.join(dir, "channels"),
+ savedVideosDir: path.join(dir, "saved-videos"),
+ ffprobeBin: "/nonexistent/ffprobe",
+ ffmpegBin: "/nonexistent/ffmpeg",
+ } as Paths;
+ try {
+ await fn(paths);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+}
+
+function fakeMedia(tag: string, seconds: number, height: number): string {
+ return `${tag};seconds=${seconds};height=${height}`;
+}
+const deps: SavedAlternatesDeps = {
+ measure: async (f) => {
+ const m = /seconds=([\d.]+)/.exec(await readFile(f, "utf8").catch(() => ""));
+ return m ? Number(m[1]) : null;
+ },
+ height: async (f) => {
+ const m = /height=(\d+)/.exec(await readFile(f, "utf8").catch(() => ""));
+ return m ? Number(m[1]) : null;
+ },
+ now: () => NOW,
+};
+
+function videoDirOf(paths: Paths, id: string): string {
+ return path.join(paths.channelsDir, SLUG, "data", id);
+}
+
+// A video whose container is already in the store: landed (import-media, a
+// pin, with media-import.json) or an ordinary download.
+async function seed(
+ paths: Paths,
+ id: string,
+ opts: { landed?: boolean; seconds?: number; height?: number; keepReason?: "pin" | "keep-latest"; requestedBy?: string } = {},
+): Promise<string> {
+ const dir = videoDirOf(paths, id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("old", opts.seconds ?? 4696.629777, opts.height ?? 360));
+ await persistSourceVideo({
+ videoDir: dir,
+ sourceFilename: "source-media.mp4",
+ storeDir: path.join(paths.savedVideosDir, SLUG, id),
+ keepReason: opts.keepReason ?? (opts.landed ? "pin" : "keep-latest"),
+ ...(opts.landed
+ ? { origin: { requestedBy: "import-media", kind: "local-archive" as const, archive: "/x/cap.zip", entry: "cap.mp4" } }
+ : opts.requestedBy
+ ? { origin: { requestedBy: opts.requestedBy } }
+ : {}),
+ ...(opts.landed ? {} : { format: { preset: "original" as const, height: opts.height ?? 360 } }),
+ });
+ if (opts.landed) {
+ await mediaImportSidecar.write(dir, {
+ entries: [
+ {
+ at: "2026-10-22T00:00:00.000Z",
+ via: "import-media",
+ source: { path: "/x/cap.mp4", name: "cap.mp4", bytes: 10 },
+ finalized: "copied",
+ container: { file: "source-media.mp4", seconds: 4696.629777, bytes: 10 },
+ kept: "new",
+ audio: "skipped",
+ },
+ ],
+ });
+ }
+ return dir;
+}
+
+// The download's container, as yt-dlp leaves it in data/<id>/, finalized as a
+// forced persist over a transcript (no audio extracted).
+async function download(
+ paths: Paths,
+ dir: string,
+ opts: { explicit: boolean; seconds?: number; height?: number },
+): Promise<string> {
+ await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("new", opts.seconds ?? 4696.479777, opts.height ?? 720));
+ const log: string[] = [];
+ await finalizeAppExtraction({
+ paths,
+ channelSlug: SLUG,
+ channelConfig: CONFIG,
+ videoDir: dir,
+ videoId: path.basename(dir),
+ fmt: "mp3",
+ persist: true,
+ category: "override",
+ extractAudio: false,
+ format: { preset: "video_720", height: opts.height ?? 720, vcodec: "avc1" },
+ explicitPersist: opts.explicit,
+ alternatesDeps: deps,
+ onLog: (s) => void log.push(s),
+ signal: new AbortController().signal,
+ });
+ return log.join("");
+}
+
+const ALT_360 = "source-media.alt-360p-20261023172312.mp4";
+const ALT_720 = "source-media.alt-720p-20261023172312.mp4";
+
+async function storeFiles(p: SavedVideoPointer): Promise<string[]> {
+ return (await readdir(p.dir)).sort();
+}
+
+test("an explicit persist over a landed copy: both kept, the download active, the landed one flagged; the pin stays", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "v7h6xzw", { landed: true });
+ await setDoNotClean(dir, true, "keep");
+ const log = await download(paths, dir, { explicit: true });
+ assert.match(
+ log,
+ /Kept both copies: the download \(720p, 4696\.5 s\) is now the active source; the landed one \(360p, 4696\.6 s\) stays as source-media\.alt-360p-20261023172312\.mp4\. Flagged for a check\.\n/,
+ );
+ const p = (await loadSavedVideo(dir))!;
+ assert.equal(p.file, "source-media.mp4");
+ assert.match(await readFile(path.join(p.dir, p.file), "utf8"), /^new/);
+ assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]);
+ assert.match(await readFile(path.join(p.dir, ALT_360), "utf8"), /^old/);
+ // A pin stays a pin; the do-not-clean marker is untouched.
+ assert.equal(p.keepReason, "pin");
+ assert.ok(await isDoNotClean(dir));
+ // The landed provenance moved to the alternate; the active one is a download.
+ assert.equal(p.origin, undefined);
+ assert.equal(p.format?.height, 720);
+ assert.deepEqual(p.probed, { seconds: 4696.479777, height: 720 });
+ assert.equal(p.alternates?.length, 1);
+ const alt = p.alternates![0]!;
+ assert.equal(alt.file, ALT_360);
+ assert.equal(alt.height, 360);
+ assert.equal(alt.seconds, 4696.629777);
+ assert.equal(alt.origin?.requestedBy, "import-media");
+ assert.equal(alt.origin?.kind, "local-archive");
+ assert.equal(alt.setAsideAt, NOW.toISOString());
+ // The flag in the landing's own history.
+ const c = (await mediaImportSidecar.load(dir))?.challenges?.at(-1);
+ assert.equal(c?.kept, "download");
+ assert.equal(c?.alternate, ALT_360);
+ assert.equal(c?.explicit, true);
+ assert.equal(
+ savedAlternatesLine(p),
+ "2 saved copies: active 720p, 4696.5 s (download); alternate 360p, 4696.6 s (import-media, source-media.alt-360p-20261023172312.mp4)",
+ );
+ });
+});
+
+test("an explicit persist much shorter than the landed copy still becomes active; nothing is deleted", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vshort", { landed: true });
+ const log = await download(paths, dir, { explicit: true, seconds: 4696.629777 - 300 });
+ assert.match(log, /the download \(720p, 4396\.6 s\) is now the active source/);
+ const p = (await loadSavedVideo(dir))!;
+ assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]);
+ // A second one: the first download joins the alternates, which accumulate.
+ await download(paths, dir, { explicit: true, height: 1080 });
+ const p2 = (await loadSavedVideo(dir))!;
+ assert.deepEqual(p2.alternates?.map((a) => a.file), [ALT_360, ALT_720]);
+ assert.deepEqual(await storeFiles(p2), [ALT_360, ALT_720, "source-media.mp4"]);
+ assert.equal(p2.keepReason, "pin");
+ });
+});
+
+test("an automatic download over a landed copy of the same length: both kept, the landed one stays active", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vauto", { landed: true });
+ await setDoNotClean(dir, true);
+ const log = await download(paths, dir, { explicit: false });
+ assert.match(
+ log,
+ /Kept both copies: the landed one \(360p, 4696\.6 s\) stays the active source \(an automatic download takes over only when it is longer\); the download \(720p, 4696\.5 s\) is kept as source-media\.alt-720p-20261023172312\.mp4\. Flagged for a check\.\n/,
+ );
+ const p = (await loadSavedVideo(dir))!;
+ assert.equal(p.file, "source-media.mp4");
+ assert.match(await readFile(path.join(p.dir, p.file), "utf8"), /^old/);
+ assert.match(await readFile(path.join(p.dir, ALT_720), "utf8"), /^new/);
+ assert.equal(p.origin?.requestedBy, "import-media", "the active copy keeps its own provenance");
+ assert.equal(p.keepReason, "pin");
+ assert.ok(await isDoNotClean(dir));
+ assert.deepEqual(p.alternates?.map((a) => [a.file, a.height, a.preset, a.vcodec]), [[ALT_720, 720, "video_720", "avc1"]]);
+ assert.ok(!(await readdir(dir)).includes("source-media.mp4"), "the download left the data dir");
+ assert.equal((await mediaImportSidecar.load(dir))?.challenges?.at(-1)?.kept, "landed");
+ });
+});
+
+test("an automatic download longer than the copy in the store becomes active; the other is kept", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vlong", { requestedBy: "umtool" });
+ const log = await download(paths, dir, { explicit: false, seconds: 5000 });
+ assert.match(log, /the download \(720p, 5000\.0 s\) is now the active source \(it is longer\); the saved one \(360p, 4696\.6 s\) stays as source-media\.alt-360p-20261023172312\.mp4/);
+ const p = (await loadSavedVideo(dir))!;
+ // An ordinary copy's requester and keep-latest class carry over.
+ assert.equal(p.keepReason, "keep-latest");
+ assert.equal(p.origin?.requestedBy, "umtool");
+ assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]);
+ });
+});
+
+test("no copy in the store: an ordinary persist, no alternates", async () => {
+ await withCorpus(async (paths) => {
+ const dir = videoDirOf(paths, "vfresh");
+ await mkdir(dir, { recursive: true });
+ const log = await download(paths, dir, { explicit: true });
+ assert.doesNotMatch(log, /Kept both/);
+ const p = (await loadSavedVideo(dir))!;
+ assert.equal(p.alternates, undefined);
+ assert.equal(p.keepReason, "override");
+ });
+});
+
+test("readers never take an alternate for the source", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vread", { landed: true });
+ await download(paths, dir, { explicit: true });
+ const p = (await loadSavedVideo(dir))!;
+ assert.equal(await resolveSavedVideo(dir), path.join(p.dir, "source-media.mp4"));
+ for (const name of [ALT_360, "source-media.alt-20261023172312.webm", "source-media.alt-720p-20261023172312-2.mkv"]) {
+ assert.equal(isSourceMediaFile(name), false, name);
+ }
+ assert.equal(findSourceMedia([ALT_360]), null);
+ // Even in the data dir (where unpersist puts it back), the clip tier's
+ // whole-container list does not name it.
+ await writeFile(path.join(dir, ALT_360), "x");
+ assert.deepEqual((await wholeContainersOf(dir)).map((c) => c.name), ["source-media.mp4"]);
+ });
+});
+
+test("the inventory counts and lists alternates; the prune never removes one; drop and unpersist take them along", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vprune", { keepReason: "keep-latest" });
+ await download(paths, dir, { explicit: true });
+ const p = (await loadSavedVideo(dir))!;
+ assert.equal(p.keepReason, "keep-latest");
+ const totals = await savedVideoTotals({ paths, channelSlug: SLUG });
+ assert.equal(totals.bytes, p.bytes + p.alternates![0]!.bytes);
+ assert.deepEqual((await listSavedAlternates({ paths })).map((e) => e.videoId), ["vprune"]);
+ // Rolled out of a keep-latest window of 0: kept, with a line saying why.
+ await writeFile(path.join(paths.channelsDir, SLUG, "config.json"), JSON.stringify(CONFIG));
+ const lines: string[] = [];
+ const r = await pruneSavedVideos({ paths, channelSlug: SLUG, onLog: (l) => void lines.push(l) });
+ assert.equal(r.pruned, 0);
+ assert.match(lines.join("\n"), /Kept saved video vprune .* 1 alternate copy flagged for a check/);
+ assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]);
+ // Unpersist brings both back to the data dir.
+ assert.equal(await unpersistSavedVideo(dir), true);
+ const back = (await readdir(dir)).sort();
+ assert.ok(back.includes(ALT_360) && back.includes("source-media.mp4"));
+ // Drop (a deliberate whole-video delete) removes both and counts both.
+ const dir2 = await seed(paths, "vdrop", {});
+ await download(paths, dir2, { explicit: true });
+ const p2 = (await loadSavedVideo(dir2))!;
+ assert.equal(await dropSavedVideo(dir2), p2.bytes + p2.alternates![0]!.bytes);
+ assert.deepEqual(await readdir(p2.dir).catch(() => []), []);
+ });
+});
+
+test("a persist that fails after the rename puts the old name back", async () => {
+ await withCorpus(async (paths) => {
+ const dir = await seed(paths, "vfail", { landed: true });
+ await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("new", 4696, 720));
+ const plan = (await planSavedContainer({ videoDir: dir, newContainer: path.join(dir, "source-media.mp4"), explicit: true, deps }))!;
+ await rm(path.join(dir, "source-media.mp4"));
+ await assert.rejects(
+ persistOverExisting(plan, { sourceFilename: "source-media.mp4", deps, onLog: () => {} }),
+ );
+ const p = (await loadSavedVideo(dir))!;
+ assert.deepEqual(await storeFiles(p), ["source-media.mp4"]);
+ assert.equal(p.alternates, undefined);
+ });
+});
+
+test("alternate names: height when known, a numbered suffix on a clash", () => {
+ assert.equal(alternateName("source-media.webm", null, NOW), "source-media.alt-20261023172312.webm");
+ assert.equal(
+ alternateName("source-media.mp4", 720, NOW, [ALT_720]),
+ "source-media.alt-720p-20261023172312-2.mp4",
+ );
+});
diff --git a/common/ytdlp/savedAlternates.ts b/common/ytdlp/savedAlternates.ts
@@ -0,0 +1,274 @@
+// A DOWNLOAD OVER A CONTAINER ALREADY IN THE STORE KEEPS BOTH (operator ruling
+// 2026-10-23: "if you download a format that's different just keep both and
+// flag for a later diagnostic check").
+//
+// Until this, a landed recording (an import, a live recording, an attach — see
+// ytdlp/landedGuard.ts) as long or longer than a later download made the
+// download's container be DISCARDED, so an explicit 720p persist over a 360p
+// capture of the same stream could never land; and any other saved container
+// was overwritten by a re-download. Now finalizeAppExtraction asks here before
+// it extracts or persists, and neither copy is ever removed:
+//
+// which is ACTIVE an explicit persist (persist-videos, "Persist source
+// video", the whole-recording fetch) makes the download
+// active. Any other download keeps the copy in the store
+// active unless the download is longer
+// (KEEP_LONGER_TOLERANCE_SECONDS of slack, a tie keeps
+// what is there; an unmeasurable copy in the store loses).
+// the OTHER copy stays in the same store dir as
+// `source-media.alt-<h>p-<YYYYMMDDHHMMSS>.<ext>` — a name
+// no reader takes for a source (lib/mediaFiles.ts,
+// lib/evidenceClip.mjs anchor on `source-media.<ext>`) —
+// and is listed in the pointer's `alternates` with its
+// length, height and provenance: the flag a later check
+// reads (`pnpm ops get saved-alternates`, /saved-videos).
+// the pointer keeps its `keepReason` (a pin stays a pin) and the
+// do-not-clean marker is not touched. Its `origin` is the
+// download's requester, else the old one's — never a
+// landed copy's, which now describes the alternate.
+//
+// Audio is not part of this: the landed guard's audio half still keeps the
+// longer audio.<fmt> (a transcript was made from it), as before.
+
+import path from "node:path";
+import { readdir, rename, stat } from "node:fs/promises";
+import { KEEP_LONGER_TOLERANCE_SECONDS } from "../lib/mediaImport";
+import {
+ savedVideoPath,
+ type SavedVideoFormat,
+ type SavedVideoKeepReason,
+ type SavedVideoOrigin,
+ type SavedVideoPointer,
+ type SavedVideoProbe,
+} from "../lib/savedVideo";
+import {
+ loadSavedVideo,
+ moveFileCrossDevice,
+ persistSourceVideo,
+ writePointer,
+} from "../lib/savedVideo-server";
+import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore";
+import type { Paths } from "../lib/paths";
+import { LANDED_BY, recordChallenge } from "./landedGuard";
+
+export type SavedAlternatesDeps = {
+ // Seconds of a media file (null: not measurable).
+ measure: (file: string) => Promise<number | null>;
+ // Pixel height of its first video stream (null: none or not measurable).
+ height?: (file: string) => Promise<number | null>;
+ now?: () => Date;
+};
+
+export type SavedContainerPlan = {
+ videoDir: string;
+ existing: SavedVideoPointer;
+ landed: boolean;
+ explicit: boolean;
+ active: "download" | "existing";
+ newSeconds: number | null;
+ newHeight: number | null;
+ oldSeconds: number | null;
+ oldHeight: number | null;
+};
+
+async function exists(file: string): Promise<boolean> {
+ return stat(file).then(
+ () => true,
+ () => false,
+ );
+}
+
+// Before a downloaded container is extracted and persisted: is there a copy in
+// the store already, and which of the two will be active? Null when the store
+// holds none (no pointer, or its file is gone) — the persist is an ordinary one.
+export async function planSavedContainer(opts: {
+ videoDir: string;
+ newContainer: string;
+ // The download's height as yt-dlp reported it, when it did.
+ newHeight?: number;
+ explicit: boolean;
+ deps: SavedAlternatesDeps;
+}): Promise<SavedContainerPlan | null> {
+ const existing = await loadSavedVideo(opts.videoDir);
+ if (!existing) return null;
+ const oldFile = savedVideoPath(existing);
+ if (!(await exists(oldFile))) return null;
+ const { deps } = opts;
+ const newSeconds = await deps.measure(opts.newContainer);
+ const oldSeconds = await deps.measure(oldFile);
+ const newHeight = opts.newHeight ?? (await deps.height?.(opts.newContainer)) ?? null;
+ const oldHeight =
+ existing.format?.height ?? existing.probed?.height ?? (await deps.height?.(oldFile)) ?? null;
+ const longer =
+ newSeconds !== null &&
+ (oldSeconds === null || newSeconds > oldSeconds + KEEP_LONGER_TOLERANCE_SECONDS);
+ return {
+ videoDir: opts.videoDir,
+ existing,
+ landed: existing.origin?.requestedBy !== undefined && LANDED_BY.has(existing.origin.requestedBy),
+ explicit: opts.explicit,
+ active: opts.explicit || longer ? "download" : "existing",
+ newSeconds,
+ newHeight,
+ oldSeconds,
+ oldHeight,
+ };
+}
+
+function stampOf(at: Date): string {
+ return at.toISOString().replace(/\D/g, "").slice(0, 14);
+}
+
+// `source-media.alt-<h>p-<stamp>.<ext>`, unique in `taken`.
+export function alternateName(file: string, height: number | null, at: Date, taken: Iterable<string> = []): string {
+ const ext = path.extname(file);
+ const stem = `source-media.alt-${height ? `${height}p-` : ""}${stampOf(at)}`;
+ const names = new Set(taken);
+ let name = `${stem}${ext}`;
+ for (let n = 2; names.has(name); n++) name = `${stem}-${n}${ext}`;
+ return name;
+}
+
+function describe(height: number | null, seconds: number | null): string {
+ return `${height ? `${height}p` : "height unknown"}, ${seconds !== null ? `${seconds.toFixed(1)} s` : "length unknown"}`;
+}
+
+function probeOf(seconds: number | null, height: number | null): SavedVideoProbe | undefined {
+ const p: SavedVideoProbe = {};
+ if (seconds !== null) p.seconds = seconds;
+ if (height !== null) p.height = height;
+ return Object.keys(p).length ? p : undefined;
+}
+
+async function flag(plan: SavedContainerPlan, alternate: string, at: Date): Promise<void> {
+ if (!plan.landed) return;
+ await recordChallenge(plan.videoDir, {
+ at: at.toISOString(),
+ by: "download",
+ what: "container",
+ newSeconds: plan.newSeconds,
+ landedSeconds: plan.oldSeconds,
+ kept: plan.active === "download" ? "download" : "landed",
+ alternate,
+ ...(plan.explicit ? { explicit: true } : {}),
+ });
+}
+
+// The copy in the store stays active: the download's container moves into the
+// same store dir under an alternate name, and the pointer lists it.
+export async function keepDownloadAsAlternate(
+ plan: SavedContainerPlan,
+ opts: {
+ sourceFilename: string;
+ origin?: SavedVideoOrigin;
+ format?: SavedVideoFormat | null;
+ paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">;
+ deps: SavedAlternatesDeps;
+ onLog: (s: string) => void;
+ },
+): Promise<string> {
+ const { existing, videoDir } = plan;
+ if (opts.paths) await assertSavedVideosStoreWritable(opts.paths, existing.dir);
+ const at = opts.deps.now?.() ?? new Date();
+ const src = path.join(videoDir, opts.sourceFilename);
+ const alt = alternateName(opts.sourceFilename, plan.newHeight, at, await readdir(existing.dir).catch(() => []));
+ const { size } = await stat(src);
+ await moveFileCrossDevice(src, path.join(existing.dir, alt));
+ const probed = probeOf(plan.oldSeconds, plan.oldHeight);
+ await writePointer(videoDir, {
+ ...existing,
+ ...(probed ? { probed } : {}),
+ alternates: [
+ ...(existing.alternates ?? []),
+ {
+ file: alt,
+ bytes: size,
+ storedAt: at.toISOString(),
+ setAsideAt: at.toISOString(),
+ ...(plan.newSeconds !== null ? { seconds: plan.newSeconds } : {}),
+ ...(plan.newHeight !== null ? { height: plan.newHeight } : {}),
+ ...(opts.format?.vcodec ? { vcodec: opts.format.vcodec } : {}),
+ ...(opts.origin ? { origin: opts.origin } : {}),
+ ...(opts.format?.preset ? { preset: opts.format.preset } : {}),
+ },
+ ],
+ });
+ const which = plan.landed ? "landed" : "saved";
+ opts.onLog(
+ `Kept both copies: the ${which} one (${describe(plan.oldHeight, plan.oldSeconds)}) stays the active source ` +
+ `(an automatic download takes over only when it is longer); the download (${describe(plan.newHeight, plan.newSeconds)}) ` +
+ `is kept as ${alt}. Flagged for a check.\n`,
+ );
+ await flag(plan, alt, at);
+ return alt;
+}
+
+// The download becomes active: the copy in the store is renamed to an
+// alternate name in its own dir, the download is persisted beside it (same
+// dir, so the two stay together), and the pointer lists the old one. A persist
+// that fails puts the old name back, so the pointer never names a missing file.
+export async function persistOverExisting(
+ plan: SavedContainerPlan,
+ opts: {
+ sourceFilename: string;
+ keepReason?: SavedVideoKeepReason;
+ origin?: SavedVideoOrigin;
+ format?: SavedVideoFormat | null;
+ paths?: Pick<Paths, "transcriptsDir" | "savedVideosDir">;
+ deps: SavedAlternatesDeps;
+ onLog: (s: string) => void;
+ },
+): Promise<SavedVideoPointer> {
+ const { videoDir } = plan;
+ // Re-read: an extraction ran since the plan.
+ const old = (await loadSavedVideo(videoDir)) ?? plan.existing;
+ if (opts.paths) await assertSavedVideosStoreWritable(opts.paths, old.dir);
+ const at = opts.deps.now?.() ?? new Date();
+ const alt = alternateName(old.file, plan.oldHeight, at, await readdir(old.dir).catch(() => []));
+ await rename(path.join(old.dir, old.file), path.join(old.dir, alt));
+ const keptOrigin = old.origin && !LANDED_BY.has(old.origin.requestedBy) ? old.origin : undefined;
+ let pointer: SavedVideoPointer;
+ try {
+ pointer = await persistSourceVideo({
+ videoDir,
+ sourceFilename: opts.sourceFilename,
+ storeDir: old.dir,
+ // A pin stays a pin; a keep-latest container stays evictable.
+ keepReason: old.keepReason ?? opts.keepReason,
+ origin: opts.origin ?? keptOrigin,
+ ...(opts.format ? { format: opts.format } : {}),
+ ...(opts.paths ? { paths: opts.paths } : {}),
+ });
+ } catch (err) {
+ await rename(path.join(old.dir, alt), path.join(old.dir, old.file)).catch(() => {});
+ throw err;
+ }
+ const probed = probeOf(plan.newSeconds, plan.newHeight);
+ pointer = {
+ ...pointer,
+ ...(probed ? { probed } : {}),
+ alternates: [
+ ...(pointer.alternates ?? []),
+ {
+ file: alt,
+ bytes: old.bytes,
+ storedAt: old.storedAt,
+ setAsideAt: at.toISOString(),
+ ...(plan.oldSeconds !== null ? { seconds: plan.oldSeconds } : {}),
+ ...(plan.oldHeight !== null ? { height: plan.oldHeight } : {}),
+ ...(old.format?.vcodec ? { vcodec: old.format.vcodec } : {}),
+ ...(old.origin ? { origin: old.origin } : {}),
+ ...(old.format?.preset ? { preset: old.format.preset } : {}),
+ },
+ ],
+ };
+ await writePointer(videoDir, pointer);
+ const which = plan.landed ? "landed" : "saved";
+ const why = plan.explicit ? "" : " (it is longer)";
+ opts.onLog(
+ `Kept both copies: the download (${describe(plan.newHeight, plan.newSeconds)}) is now the active source${why}; ` +
+ `the ${which} one (${describe(plan.oldHeight, plan.oldSeconds)}) stays as ${alt}. Flagged for a check.\n`,
+ );
+ await flag(plan, alt, at);
+ return pointer;
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,7 @@
# Changelog
## [Unreleased]
+- **A download over a copy already saved keeps both, and flags them for a check.** An import, an attach or a live recording that was as long as a later download used to make that download be thrown away, so asking for a 720p copy of a stream already held as a 360p capture (`pnpm ops persist-videos` with `"format": "video_720"`) downloaded it and then discarded it. Now no copy is deleted. **Persist source video**, `persist-videos` and a whole-recording fetch make the download the copy everything uses; any other download keeps the saved copy in use unless it is longer. The other copy stays beside it in the saved-video store as `source-media.alt-<height>p-<date>.<ext>`, which no reader takes for the source, and the log says so: "Kept both copies: the download (720p, 4696.5 s) is now the active source; the landed one (360p, 4696.6 s) stays as source-media.alt-360p-20261023172312.mp4. Flagged for a check." A pinned video stays pinned, and `"replace": "above-height"` keeps the taller copy beside the new one rather than removing it. /saved-videos lists every video with two copies, with both copies' height, length and origin, and counts both in its sizes; `pnpm ops get saved-alternates [<slug>]` lists the same. The keep-latest prune leaves such a video alone. Needs a restart of the editor.
- **umtool's clip walk goes through the recordings in date order.** `p`/`n` and the Cut tab's walk used to follow the cut, which can open on a finale and end years earlier. The walk now goes by each clip's date (its on-screen date, else the recording's upload date), with a recording's clips together in the order they come in it, so what is left out between two clips, or split off into a clip of its own, comes up next. The cut's own order is unchanged.
- **A clip from a stream captured live can be trimmed again in umtool's clip editor.** Such a stream's record has no length, which umtool passed on as zero, so every drag of a clip's edge snapped back to the left with "that is the edge of what is cached". An unknown length is now treated as unknown.
- **umtool's clip editor opens a clip from a whole saved recording as a short excerpt.** When the only file holding a clip was the whole recording (hours long), the editor used all of it as its view: a waveform of the whole stream with the clip a sliver in it, and a video seeking hours into a large file. It now cuts the clip and 45 seconds either side from the recording once, on the umtool machine, and works on that; the cut starts when the clip is opened and is kept for the next time. The rendered video still cuts from the whole recording.
diff --git a/editor/app/api/ops/_read.test.ts b/editor/app/api/ops/_read.test.ts
@@ -46,7 +46,7 @@ const route = async (name: string) => (await import(`./${name}/route`)).GET as G
test.after(() => corpus.cleanup());
test("every read route is behind the token", async () => {
- for (const name of ["settings", "storage", "sites", "workers", "auto-queue", "scheduler"]) {
+ for (const name of ["settings", "storage", "sites", "workers", "auto-queue", "scheduler", "saved-alternates"]) {
const res = await callGet(await route(name), undefined, {}, {});
assert.equal(res.status, 401, name);
}
@@ -135,6 +135,18 @@ test("get workers, auto-queue, scheduler and storage answer their pages' payload
assert.equal(storage.status, 200, JSON.stringify(storage.body));
});
+test("get saved-alternates lists the saved videos holding two copies (none here); a bad slug is a 400", async () => {
+ const get = await route("saved-alternates");
+ const all = await callGet(get);
+ assert.equal(all.status, 200, JSON.stringify(all.body));
+ assert.equal(all.body.count, 0);
+ assert.deepEqual(all.body.videos, []);
+ const one = await callGet(get, "http://localhost/api/ops/saved-alternates?slug=test-youtube");
+ assert.equal(one.status, 200, JSON.stringify(one.body));
+ const bad = await callGet(get, "http://localhost/api/ops/saved-alternates?slug=../x");
+ assert.equal(bad.status, 400);
+});
+
test("/api/auto-queue/control is behind the ops token now", async () => {
const { POST } = await import("../auto-queue/control/route");
const anon = await callPost(POST, { kind: "download", action: "stop" }, {});
diff --git a/editor/app/api/ops/saved-alternates/route.ts b/editor/app/api/ops/saved-alternates/route.ts
@@ -0,0 +1,48 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { savedAlternatesLine } from "yt-dlp-transcript-common/lib/savedVideo";
+import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels";
+import { listSavedAlternates } from "yt-dlp-transcript-common/controller/savedVideoInventory";
+import { readRoute } from "../_read";
+import { opsFail } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// GET [?slug=<channel>]
+// -> { ok, count, videos: [{ slug, id, line, dir, active: { file, bytes,
+// height?, seconds?, origin?, storedAt }, alternates: [...] }],
+// notAnswering: [slug] }
+//
+// Every saved video that holds two copies (ytdlp/savedAlternates.ts): a
+// download over a container already in the store keeps both, one active and
+// the other flagged here for a check. The /saved-videos page lists the same.
+// Pointers only — no container is opened. Nothing is written.
+export async function GET(request: Request) {
+ return readRoute(request, ["slug"], async (q) => {
+ const slug = q.get("slug")?.trim() || undefined;
+ if (slug && !isValidChannelSlug(slug)) return opsFail(`"${slug}" is not a valid channel slug`);
+ const notAnswering: string[] = [];
+ const entries = await listSavedAlternates({ paths: getPaths(), channelSlug: slug, notAnswering });
+ return {
+ count: entries.length,
+ videos: entries.map((e) => ({
+ slug: e.slug,
+ id: e.videoId,
+ line: savedAlternatesLine(e.pointer),
+ dir: e.pointer.dir,
+ active: {
+ file: e.pointer.file,
+ bytes: e.pointer.bytes,
+ ...((e.pointer.format?.height ?? e.pointer.probed?.height)
+ ? { height: e.pointer.format?.height ?? e.pointer.probed?.height }
+ : {}),
+ ...(e.pointer.probed?.seconds ? { seconds: e.pointer.probed.seconds } : {}),
+ ...(e.pointer.keepReason ? { keepReason: e.pointer.keepReason } : {}),
+ ...(e.pointer.origin ? { origin: e.pointer.origin } : {}),
+ storedAt: e.pointer.storedAt,
+ },
+ alternates: e.pointer.alternates ?? [],
+ })),
+ notAnswering: notAnswering.sort(),
+ };
+ });
+}
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -531,6 +531,10 @@ async function archiveSourceVideo(
// skip it. Without this a youtube-handling video with a transcript
// got two subtitle passes and no file (release 10 slice N).
forceMedia: true,
+ // A person's click (or the tool's request for a whole recording):
+ // over a copy already saved, the download becomes the active one
+ // and the other is kept beside it (ytdlp/savedAlternates.ts).
+ explicitPersist: true,
persistOrigin,
persistFormatPreset,
});
diff --git a/editor/app/saved-videos/page.tsx b/editor/app/saved-videos/page.tsx
@@ -4,6 +4,10 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { formatBytes } from "yt-dlp-transcript-common/lib/format";
import { listSavedVideos } from "yt-dlp-transcript-common/controller/savedVideoInventory";
+import {
+ savedAlternatesLine,
+ savedVideoBytes,
+} from "yt-dlp-transcript-common/lib/savedVideo";
import { readSchedulerState } from "yt-dlp-transcript-common/jobs/syncSchedulerState";
import { SavedVideosControls } from "./components/SavedVideosControls";
import { PersistVideoListControl } from "./components/PersistVideoListControl";
@@ -38,14 +42,17 @@ export default async function SavedVideosPage() {
byChannel.get(e.slug) ??
{ slug: e.slug, count: 0, bytes: 0, verified: 0 };
row.count += 1;
- row.bytes += e.pointer.bytes;
+ row.bytes += savedVideoBytes(e.pointer);
if (e.pointer.sha256) {
row.verified += 1;
totalVerified += 1;
}
byChannel.set(e.slug, row);
- totalBytes += e.pointer.bytes;
+ totalBytes += savedVideoBytes(e.pointer);
}
+ // Two copies of one video, both kept (ytdlp/savedAlternates.ts): flagged
+ // for a check. Off the same pointer walk, so free.
+ const withAlternates = entries.filter((e) => (e.pointer.alternates?.length ?? 0) > 0);
const channels = [...byChannel.values()].sort((a, b) =>
a.slug.localeCompare(b.slug),
);
@@ -158,6 +165,30 @@ export default async function SavedVideosPage() {
)}
</section>
+ {withAlternates.length > 0 && (
+ <section aria-label="saved videos with two copies" className="flex flex-col gap-2">
+ <h2 className="text-base font-semibold">
+ Two saved copies ({withAlternates.length})
+ </h2>
+ <ul className="flex flex-col gap-1 text-sm">
+ {withAlternates.map((e) => (
+ <li key={`${e.slug}/${e.videoId}`} aria-label={`two copies ${e.slug}/${e.videoId}`}>
+ <Link
+ href={`/channels/${e.slug}/videos/${encodeURIComponent(e.videoId)}`}
+ className="underline hover:no-underline"
+ >
+ {e.slug}/{e.videoId}
+ </Link>
+ <span className="text-muted-foreground">
+ {" "}
+ — {savedAlternatesLine(e.pointer)}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+
<section aria-label="backups" className="flex flex-col gap-2">
<h2 className="text-base font-semibold">Backups</h2>
<SavedVideosControls
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -244,6 +244,10 @@ const GETTERS = {
key ? `/api/ops/settings?key=${encodeURIComponent(key)}` : "/api/ops/settings",
// The /storage page: each location, mounted or not, its free space and tiers.
storage: () => "/api/ops/storage",
+ // Saved videos holding two copies (a download over a container already in
+ // the store keeps both): each one's active copy and its flagged alternates.
+ "saved-alternates": (slug) =>
+ slug ? `/api/ops/saved-alternates?slug=${encodeURIComponent(slug)}` : "/api/ops/saved-alternates",
// Every site: id, title, siteUrl, Pages project, audience, policy, channels.
sites: () => "/api/ops/sites",
// The transcription workers and what each is running.
@@ -298,6 +302,7 @@ const GET_ARG_OPTIONAL = new Set([
"jobs",
"settings",
"storage",
+ "saved-alternates",
"sites",
"workers",
"auto-queue",
@@ -930,6 +935,7 @@ export function usage() {
" pnpm ops job wait <id>... [--wait-timeout <seconds>]",
" pnpm ops get settings [<key>]",
" pnpm ops get storage | sites | workers | auto-queue | scheduler",
+ " pnpm ops get saved-alternates [<slug>]",
" pnpm ops get services",
" pnpm ops get cleanup <slug>",
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
@@ -966,6 +972,13 @@ export function usage() {
"get settings [<key>] is settings.json as the editor reads it (migrated and",
" defaulted; a secret is \"<redacted>\"), or one top-level key of it.",
"get storage is /storage: each location, mounted or not, free space, tiers.",
+ "get saved-alternates [<slug>] lists every saved video holding two copies:",
+ " a download over a container already in the store keeps both — an",
+ " explicit persist (persist-videos, Persist source video, a whole-recording",
+ " fetch) makes the download active, any other keeps the saved one unless",
+ " the download is longer — and the other stays beside it as",
+ " source-media.alt-<h>p-<stamp>.<ext>, flagged for a check. Each video:",
+ " its line, the active copy, the alternates (height, seconds, origin).",
"get sites lists every site: id, title, siteUrl, Pages project, audience,",
" listed, search, publish policy, channels, citedChannels. (`get publish`",
" is the status.)",
@@ -1373,7 +1386,10 @@ export function usage() {
' "dryRun": true answers with the buckets (saved, wrongHeight, toFetch,',
' noUrl, unknown) and starts nothing. One job per channel, on its download',
" queue; a low disk or a rate limit stops it, and running the same body",
- " again resumes — saved videos are skipped.",
+ " again resumes — saved videos are skipped. Over a copy already in the",
+ " store (an import, an attach, a live recording or an earlier download) the",
+ " download becomes the active one and the old copy is kept beside it,",
+ " flagged for a check (`get saved-alternates`); nothing is deleted.",
"",
'import-archive-org imports archive.org media into a channel, as one job on',
' archive.org\'s queue: {"slug", "item", "files": [...] | "match": "<regex>"}',