import path from "node:path"; import { readdir } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import { CLIPS_DIR_NAME } from "../lib/clipWindow"; import { listClipWindows } from "../lib/clipWindow-server"; import { windowSyncLagText } from "../lib/clipWindowSync"; import { ffprobeWindowProbe, judgeClipWindow, setAsideDesyncedWindow, type WindowStreamProbe, } from "../lib/clipWindowSync-server"; import { inspectChannelMedia } from "../lib/channelMedia"; import { channelConfigPlatform } from "../lib/videoId"; import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; import { readChannelConfig } from "./channels"; // CHECK THE WINDOWS ALREADY ON DISK (lib/clipWindowSync.ts). // // A fetch judges the windows IT considers (controller/fetchWindows.ts): the one // it just fetched, and the held ones it would have answered a span with. The // windows fetched before the check existed — 26 of the 318 Rumble windows on // the corpus on 2026-10-23 had their picture 1–4 s off their sound — are judged // only when something asks for their span again. This is the sweep that does // not wait: every window in one video, one channel or the corpus is probed, // and a desynced one is SET ASIDE (`-.desynced.`, never deleted) // so a report video stops cutting from it today, not on its next fetch. // // The walk is evictClipWindows' (the same text guard, the same skip of a // channel whose text cannot be read), and the probe is one ffprobe of the // stream headers per window. A window whose sidecar already records a good // verdict for its current size is not probed again — that verdict came from // this same probe of these same bytes — and a good verdict found here is // recorded the same way, so the second sweep of a corpus costs a readdir. export type CheckClipWindowsOptions = { paths: Paths; // One channel, or every channel when absent. slug?: string; // One video of `slug` (a record id; a Twitch v resolves to its dir). video?: string; // List what is desynced; rename nothing, record nothing. dryRun?: boolean; onLog?: (message: string) => void; signal?: AbortSignal; // Tests inject one; absent = ffprobe at `paths.ffprobeBin`. probe?: WindowStreamProbe; }; export type CheckedDesyncedWindow = { slug: string; id: string; file: string; lagS: number; reason?: string; // The name it was set aside as; null on a dry run. setAsideAs: string | null; }; export type CheckClipWindowsResult = { dryRun: boolean; channels: number; // Video dirs that held at least one window. videos: number; checked: number; // Of `checked`: answered by a verdict the sidecar already recorded. fromRecord: number; // Of `checked`: ffprobe could not read them — kept, not judged. unreadable: number; desynced: CheckedDesyncedWindow[]; setAside: number; // `: ` for every channel the walk refused to touch. skipped: string[]; }; async function checkVideo( opts: CheckClipWindowsOptions, probe: WindowStreamProbe, slug: string, id: string, out: CheckClipWindowsResult, ): Promise { const videoDir = path.join(opts.paths.channelsDir, slug, "data", id); // The taller (tiered) windows too: a remote seek at any height can run off its sound. const windows = await listClipWindows(videoDir, { tiers: true }); if (windows.length === 0) return; out.videos += 1; for (const w of windows) { if (opts.signal?.aborted) return; out.checked += 1; const { sync, fromRecord } = await judgeClipWindow(w, { probe, record: !opts.dryRun }); if (fromRecord) out.fromRecord += 1; if (!sync) { out.unreadable += 1; opts.onLog?.(`could not probe ${slug}/${id}/${CLIPS_DIR_NAME}/${w.file} — kept, not judged`); continue; } if (sync.ok) continue; let setAsideAs: string | null = null; if (!opts.dryRun) { try { setAsideAs = (await setAsideDesyncedWindow(w, sync)).file; out.setAside += 1; } catch (e) { // Counted desynced and not set aside; the summary's two numbers differ. opts.onLog?.(`could not set ${slug}/${id}/${CLIPS_DIR_NAME}/${w.file} aside: ${(e as Error).message}`); } } out.desynced.push({ slug, id, file: w.file, lagS: sync.lagS, ...(sync.reason ? { reason: sync.reason } : {}), setAsideAs, }); opts.onLog?.( `desynced ${slug}/${id}/${CLIPS_DIR_NAME}/${w.file}: ${windowSyncLagText(sync)}` + `${sync.reason ? ` (${sync.reason})` : ""} — ` + (setAsideAs ? `set aside as ${setAsideAs}` : opts.dryRun ? "would be set aside" : "NOT set aside"), ); } } async function checkChannel( opts: CheckClipWindowsOptions, probe: WindowStreamProbe, slug: string, out: CheckClipWindowsResult, ): Promise { // THE TEXT GUARD, as evictClipWindows: `clips/` is on the corpus disk and // never tiered, so a channel whose MEDIA is away is checked as usual; one // whose text cannot be read (a `legacy` channel, a tier migration) would // read as "no windows", and is skipped saying so instead. const media = await inspectChannelMedia(opts.paths, slug, undefined, { fresh: true }); if (!media.text.readable) { out.skipped.push( `${slug}: media ${media.status}${media.detail ? ` (${media.detail})` : ""} — nothing was touched`, ); return; } out.channels += 1; if (opts.video) { const config = await readChannelConfig(opts.paths, slug).catch(() => null); const id = await resolveVideoDirId(opts.paths.channelsDir, slug, opts.video, { ...(config ? { platform: channelConfigPlatform(config) } : {}), }); await checkVideo(opts, probe, slug, id, out); return; } const ids = await readdir(path.join(opts.paths.channelsDir, slug, "data")).catch(() => [] as string[]); for (const id of ids.sort()) { if (opts.signal?.aborted) return; await checkVideo(opts, probe, slug, id, out); } } export async function checkClipWindows( opts: CheckClipWindowsOptions, ): Promise { if (opts.video && !opts.slug) throw new Error("a video is named within a channel: give its slug too"); const out: CheckClipWindowsResult = { dryRun: Boolean(opts.dryRun), channels: 0, videos: 0, checked: 0, fromRecord: 0, unreadable: 0, desynced: [], setAside: 0, skipped: [], }; const probe = opts.probe ?? ffprobeWindowProbe(opts.paths.ffprobeBin); let slugs: string[]; if (opts.slug) { slugs = [opts.slug]; } else { // `isDirectory()` for the reason channel listing does it: a symlinked // `/` is not a channel (AGENTS.md). const entries = await readdir(opts.paths.channelsDir, { withFileTypes: true }).catch(() => []); slugs = entries .filter((e) => e.isDirectory()) .map((e) => e.name) .sort(); } for (const slug of slugs) { if (opts.signal?.aborted) break; await checkChannel(opts, probe, slug, out); } return out; } // The one sentence every surface ends a run with. export function checkClipWindowsSummary(r: CheckClipWindowsResult): string { return ( `Checked ${r.checked} window(s) in ${r.videos} video(s) across ${r.channels} channel(s)` + (r.fromRecord ? ` (${r.fromRecord} by a recorded verdict)` : "") + `: ${r.desynced.length} desynced, ${r.setAside} set aside` + (r.dryRun && r.desynced.length ? " (dry run: nothing renamed)" : "") + (r.unreadable ? `; ${r.unreadable} could not be probed` : "") + "." + (r.skipped.length ? ` Skipped: ${r.skipped.join("; ")}` : "") ); }