// 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-p-.` — a name // no reader takes for a source (lib/mediaFiles.ts, // lib/evidenceClip.mjs anchor on `source-media.`) — // 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. // a PROXY `oldCopyAsProxy` (persist-videos "below-height" only): // when the download is measured TALLER than the copy it // replaces, the old copy's entry carries `keptAs: "proxy"` // — kept on purpose, not for a check — in the same pointer // write as the rest. Not taller, or either height unknown: // no mark, flagged for a check as any other. // // DROPPING ONE after the check (2026-10-29): `dropSavedAlternate` // (lib/savedVideo-server.ts) — `pnpm ops drop-saved-alternate`, or the video // page's "Drop this alternate" — deletes one listed alternate and its pointer // entry, never the active copy. Nothing else deletes one but `dropSavedVideo` // (the whole video) and `unpersistSavedVideo` (which brings them back). // An ORIGINAL (`keptAs: "original"`, the source of a compacted copy — // controller/compactSavedVideos.ts) goes only by a confirmed // dropSavedAlternate: dropSavedVideo refuses a video that keeps one. // // Audio is not part of this: the landed guard's audio half still keeps the // longer audio. (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 { SavedPointerChangedError, alternateName, assertNotCompacting, loadSavedVideo, moveFileCrossDevice, persistSourceVideoUnlocked, samePointerCopy, withPointerLock, 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; // Pixel height of its first video stream (null: none or not measurable). height?: (file: string) => Promise; 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 { 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 { 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, }; } // `source-media.alt-p-.`, unique in `taken` (lib/savedVideo-server.ts: // persistSourceVideo moves an alternate aside under the same kind of name). export { alternateName }; 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 { 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; deps: SavedAlternatesDeps; onLog: (s: string) => void; }, ): Promise { // UNDER THE POINTER'S LOCK, ON THE POINTER AS IT IS NOW: the plan was made // before the extraction (minutes), and a compaction or another persist may // have swapped the active copy since. Then this refuses rather than write // the plan's older pointer back over the new one. return withPointerLock(plan.videoDir, () => keepDownloadAsAlternateLocked(plan, opts)); } async function currentFor(plan: SavedContainerPlan, what: string): Promise { const now = await loadSavedVideo(plan.videoDir); if (!now || !samePointerCopy(now, plan.existing)) { throw new SavedPointerChangedError( `${what} refused: the saved copy changed since this download was planned ` + `(${plan.existing.file} then, ${now ? now.file : "no pointer"} now). The download stays in the data dir; run it again.`, ); } await assertNotCompacting(now.dir, what); return now; } async function keepDownloadAsAlternateLocked( plan: SavedContainerPlan, opts: Parameters[1], ): Promise { const { videoDir } = plan; const existing = await currentFor(plan, "Keeping the download as an alternate"); 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; // Mark the old copy as the proxy when the download is taller (see top). oldCopyAsProxy?: boolean; // An explicit persist (SavedVideoPointer.explicit). explicit?: boolean; paths?: Pick; deps: SavedAlternatesDeps; onLog: (s: string) => void; }, ): Promise { return withPointerLock(plan.videoDir, () => persistOverExistingLocked(plan, opts)); } async function persistOverExistingLocked( plan: SavedContainerPlan, opts: Parameters[1], ): Promise { const { videoDir } = plan; // Re-read under the lock: an extraction ran since the plan, and the active // copy must still be the one the plan measured. const old = await currentFor(plan, "Persisting the download over the saved copy"); 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 persistSourceVideoUnlocked({ 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.explicit || old.explicit ? { explicit: true } : {}), ...(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); const proxy = opts.oldCopyAsProxy === true && plan.newHeight !== null && plan.oldHeight !== null && plan.newHeight > plan.oldHeight; 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 } : {}), ...(proxy ? { keptAs: "proxy" as const } : {}), // The copy set aside was itself a re-encode (a compacted active copy): // it says so wherever it is listed. ...(old.compacted ? { compactedFrom: old.compacted.source.sha256, ...(old.sha256 ? { sha256: old.sha256 } : {}) } : {}), }, ], }; 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}. ` + (proxy ? "Kept on purpose as the lower-quality proxy.\n" : opts.oldCopyAsProxy ? "Not marked as a proxy (the download is not measured taller); flagged for a check.\n" : "Flagged for a check.\n"), ); await flag(plan, alt, at); return pointer; }