commit cd321a4e58ac1ca1c5089bca3da6d846cc62e581 parent fb7c3588fbca56ed84a7411cdb086eb972a1d3db Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sun, 25 Oct 2026 00:51:15 -0400 umtool preflight: never probe what is held on disk, pace the rest per platform check-availability asks the build's own question first (fetchSpan + the local tiers): a source whose clips are all on disk is `held-locally` and costs no request. What still needs a probe is paced per platform at the clip-window floor (30 s, Rumble 120 s), now in common/ytdlp/platformArgs.mjs beside PLATFORM_MIN_GAP_SECONDS (fetchWindows re-exports it). A 403/429/bot check stops probing that platform and leaves its sources `unchecked` (ok: null), an info card in the inbox, never "can't be fetched". The driver budgets the preflight's timeout by source count x the widest gap. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
19 files changed, 512 insertions(+), 80 deletions(-)
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -55,6 +55,8 @@ import { configForVideoUrl, } from "../ytdlp/channelArgs"; import { + CLIP_WINDOW_MIN_GAP_SECONDS, + CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS, platformMinGapSeconds, staticSleepRequestsSeconds, } from "../ytdlp/platformArgs.mjs"; @@ -160,19 +162,12 @@ import { findVideoSourceUrl } from "./undownloadedVideos"; // item on a channel whose text is not readable fails as `unreachable` (its // clips/ directory lives in that text), and the rest carry on. -// The least a batch waits between two clip-window fetches on one platform. -// A window is a short request, which is exactly why a loop of them looks like -// a scraper: 20 s apart was enough for YouTube to answer 403 (2026-10-07). -export const CLIP_WINDOW_MIN_GAP_SECONDS = 30; - -// A platform whose windows must be further apart than that. Rumble's -// Cloudflare puts the whole IP behind a JS challenge ("Just a moment…", 403 to -// every rumble.com request, impersonated or not) after a handful of requests -// in a few minutes, and a window costs three (page, embed JSON, HLS manifest): -// on 2026-10-07 windows 30–45 s apart drew it within four, and it lifted again -// in about five minutes of quiet. -export const CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS: Readonly<Record<string, number>> = - Object.freeze({ rumble: 120 }); +// The least a batch waits between two clip-window fetches on one platform, and +// the platforms (Rumble) that must be further apart: the table lives beside +// PLATFORM_MIN_GAP_SECONDS in ytdlp/platformArgs.mjs, where umtool's +// availability probe reads it too. Re-exported for the callers that import it +// from here. +export { CLIP_WINDOW_MIN_GAP_SECONDS, CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS }; // TEST-ONLY: E2E_CLIP_WINDOW_GAP_MS replaces the batch gap above, so the e2e // suite sees the one owed pause without waiting 30–45 s for it diff --git a/common/ytdlp/platformArgs.mjs b/common/ytdlp/platformArgs.mjs @@ -94,6 +94,39 @@ export const PLATFORM_MIN_GAP_SECONDS = Object.freeze({ bitchute: 60, }); +// THE LEAST A RUN WAITS BETWEEN TWO CLIP-WINDOW REQUESTS on one platform, in +// seconds — a clip fetch (common/controller/fetchWindows.ts) and umtool's +// availability probe (report-to-video/check-availability.mjs) alike. A window +// is a short request, which is exactly why a loop of them looks like a +// scraper: 20 s apart was enough for YouTube to answer 403 (2026-10-07). +export const CLIP_WINDOW_MIN_GAP_SECONDS = 30; + +// A platform whose clip-window requests must be further apart than that. +// Rumble's Cloudflare puts the whole IP behind a JS challenge ("Just a +// moment…", 403 to every rumble.com request, impersonated or not) after a +// handful of requests in a few minutes, and a window costs three (page, embed +// JSON, HLS manifest): on 2026-10-07 windows 30–45 s apart drew it within four, +// and it lifted again in about five minutes of quiet. +/** @type {Readonly<Record<string, number>>} */ +export const CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS = Object.freeze({ rumble: 120 }); + +/** + * The floor between two clip-window requests on `platform`, in seconds: the + * larger of CLIP_WINDOW_MIN_GAP_SECONDS, the batch floor and the platform's + * own clip floor. + * @param {string | null | undefined} platform + * @returns {number} + */ +export function clipWindowMinGapSeconds(platform) { + /** @type {Record<string, number | undefined>} */ + const table = CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS; + return Math.max( + CLIP_WINDOW_MIN_GAP_SECONDS, + platformMinGapSeconds(platform), + platform ? table[platform] ?? 0 : 0, + ); +} + // THE FLOOR UNDER THE GAP BETWEEN TWO ONE-OFF IMPORTS on a platform, in // seconds, where it must be higher than the batch floor above. Each import is // its own job, so nothing else spaces them: Odysee's API answered HTTP 429 to diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **umtool's "check every source" step no longer asks for what is already on disk, and no longer bursts a platform.** A source whose clips are all held locally (the build's cache, the editor's window cache, a saved recording) is marked **held locally** and costs no request. The rest are probed one at a time per platform, at least 30 s apart (Rumble 120 s), the same floor the editor's clip fetches keep. When a platform refuses a probe (403, 429, a bot check) umtool stops asking it and marks its remaining sources **not checked**, an info card in the Inbox ("Re-check later"), never "can't be fetched", and it does not stop the build. Needs a restart of umtool. - **A report video can set a subject's own claims against the record on its timeline.** A count claim (`“less than ten” in a year`) draws a band over the dates it is about on the on-screen panel's timeline, dims the rest of the timeline, lights each clip that carries the counter's stamps in date order with its count under it, and counts up to the total under his words in the panel (`19 seizures on camera`). With a **per** (a day, a week, a month) it lights every span that holds that many or more instead (`12 in a day`, `4 in a week`). A goalpost (`“3–5 weeks”` → `“6–8 weeks”`) draws a hollow bracket over the dates each deadline implies; when he moves it, the old one stays dashed and a copy of it moves to the new dates, off the timeline's end with the dates written when they are past its last clip. The finale's large timeline shows every claim at the end. A stamp can be dated by the day the event happened rather than the clip's day (**happened** in the clip editor's Marks). In umtool: the On-screen section's **claim checks** (beside the markers), with **use the playhead** and the build's own checks shown as each field is typed. From a terminal: `umtool look <project> deck.claims='[…]'` and `umtool set <project> <clip> claim.eventDate=2026-09-22`. When the record does not contradict a claim the build prints a note. A video without claims builds exactly as before. Needs a restart of umtool and a rebuild of the video. - **umtool plays a whole report video, or one take of it, in the browser without rendering it, and takes timecoded notes as it plays.** The Cut tab's **Play the cut** (and **Play** beside each take on the takes page) opens `/projects/<project>/play`: every clip plays in order from its fetched window, with the on-screen panel, the tally, the stamps, the markers and the finale drawn over it as the live preview draws them, on one clock across the whole cut, the next clip loaded behind the one playing. A take plays the project's video as it is now with the take's changes, including a take with its own clip list and one a recipe names that was never rendered; **Blurred clips: uncensored** on a take plays its clips as recorded. Under the picture, the **reel strip** shows the whole cut at once: a cell per clip or card as wide as it plays, shaded by the recording's date, hatched when its media is not fetched, the sections' boundaries with their first date, the counter (the tally) drawn as a staircase with its total at the end and at the playhead, and each note as a pin; click or drag on it to move through the cut. Under the strip, **Now** shows what the clip on screen says with the spoken line lit, and which clip comes next. Space plays and pauses, J K L go back, pause and play (L again is faster, at the voice's own pitch), ← and → move 5 seconds, N and P move between clips, [ and ] between notes, and ? lists the keys. A line under the picture lists what it does not do: each crossfade is a hard cut at its middle, cards and teasers are placeholders with their heading, edges are not snapped to silence, and the sound is the recording's. A clip with nothing fetched says "No media for this clip — fetch it" and the video plays on. M (or **Note at 09:44**) saves a note at that second of the cut, naming the clip on screen, its second in the recording, the take, and what it asks for (Trim, Cut, Move, Fact, Look or Other); playback pauses while you write and goes on when it is saved (**Pause while I write**). The notes list in cut order (open, all or resolved), a timecode plays from there, `umtool notes <project>` prints each with where it was taken and what it asks for, and **Send to the assistant** on a note (or **Send N open notes to the assistant**) asks the video assistant, whose reply lands on the note and whose edits wait for **Apply all**. With no assistant configured the button says why. Needs a restart of umtool. - **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. diff --git a/umtool/app/api/report/build/route.ts b/umtool/app/api/report/build/route.ts @@ -6,6 +6,7 @@ import { clipsOf, readManifest } from "@/lib/projects/report.mjs"; import { projectRef } from "@/lib/projects"; import { recordBuildSnapshot } from "@/lib/report/snapshots.mjs"; import { renderSeconds } from "@/lib/report/onscreen.mjs"; +import { sourceCountOf } from "umtool-report-to-video/manifest-sources"; import { DEFAULT_VARIANT, VARIANTS, variantPaths } from "umtool-report-to-video/build-video"; import { refuseCaller } from "@/lib/report/caller"; @@ -137,7 +138,9 @@ export async function POST(request: Request) { } // A cut that renders its on-screen chrome is budgeted by its length too (driver.mjs buildTimeoutMs). const seconds = renderSeconds(manifest, options.variant ?? null); - const steps = buildSteps(project, { preset, only, skipFetch, clipCount, seconds, options }); + // The paced preflight is budgeted by how many sources it may probe (driver.mjs availabilityTimeoutMs). + const sources = sourceCountOf(manifest); + const steps = buildSteps(project, { preset, only, skipFetch, clipCount, sources, seconds, options }); const view = { project: project.id, preset, diff --git a/umtool/app/api/report/check-sources/route.ts b/umtool/app/api/report/check-sources/route.ts @@ -2,7 +2,8 @@ import { stat } from "node:fs/promises"; import path from "node:path"; import { runningJob, jobView, startJob } from "@/lib/jobs"; import { projectRef } from "@/lib/projects"; -import { MANIFEST_NAME } from "@/lib/projects/report.mjs"; +import { MANIFEST_NAME, readManifest } from "@/lib/projects/report.mjs"; +import { sourceCountOf } from "umtool-report-to-video/manifest-sources"; import { checkSourcesSteps } from "@/lib/report/driver.mjs"; export const dynamic = "force-dynamic"; @@ -29,7 +30,8 @@ export async function POST(request: Request) { if (!(await stat(path.join(p.dir, MANIFEST_NAME)).then((s) => s.isFile(), () => false))) { return Response.json({ error: `${id} has no ${MANIFEST_NAME} to check` }, { status: 400 }); } - refs.push(p); + // How many sources it cites budgets its paced preflight (driver.mjs availabilityTimeoutMs). + refs.push({ ...p, sources: sourceCountOf(await readManifest(p.dir)) }); } const steps = checkSourcesSteps(refs); diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -95,6 +95,7 @@ import { updateClip, updateStorage } from "../lib/report/manifest.mjs"; import { withEditNotes } from "../lib/report/edit-guard.mjs"; import { hms } from "umtool-report-to-video/attribution"; import { buildSteps, checkSourcesSteps, PRESETS } from "../lib/report/driver.mjs"; +import { sourceCountOf } from "umtool-report-to-video/manifest-sources"; import { runBuildOverHttp, umtoolBase } from "../lib/report/buildRun.mjs"; import { CHAIN_STEP_NAMES, chainStepsOf, planChain } from "../lib/report/chain.mjs"; import { spawn } from "node:child_process"; @@ -677,6 +678,8 @@ async function cmdCheckSources() { }); if (!refs.length) return console.log("every source was checked in the last 30 days"); } + // How many sources each cites budgets its paced preflight (driver.mjs availabilityTimeoutMs). + for (const r of refs) r.sources = sourceCountOf(await readManifest(r.dir)); const steps = checkSourcesSteps(refs); if (json) return out({ projects: refs.map((p) => p.id), steps }); console.log(`# re-check sources of ${refs.length} project(s)`); @@ -1030,6 +1033,7 @@ async function cmdBuild() { only: val("--only") ?? null, skipFetch: has("--skip-fetch"), clipCount, + sources: sourceCountOf(manifest), }); if (json && !has("--run")) return out({ project: p.id, preset, steps }); diff --git a/umtool/components/projects/report/SourcesTab.tsx b/umtool/components/projects/report/SourcesTab.tsx @@ -111,8 +111,13 @@ export default async function SourcesTab({ project, detail }: ReportTabProps) { </td> <td className="num px-1.5 py-1"> {a ? ( - <span className={a.ok ? "text-[var(--color-dim)]" : "text-[var(--color-bad)]"} title={a.error ?? undefined}> - {a.state} · {days(a.checkedAtMs)} d ago + <span + className={ + a.ok ? "text-[var(--color-dim)]" : a.ok === null ? "text-[var(--color-dirty)]" : "text-[var(--color-bad)]" + } + title={a.error ?? undefined} + > + {a.state === "held-locally" ? "held locally" : a.state === "unchecked" ? "not checked" : a.state} · {days(a.checkedAtMs)} d ago </span> ) : ( <span className="text-[var(--color-dim)]">never checked</span> diff --git a/umtool/docs/inbox.md b/umtool/docs/inbox.md @@ -62,6 +62,7 @@ on (`decisionTab`, `songTabOfSection`). | `manifest-invalid` | blocking | a `localhost`/private `siteOrigin`; a missing one only when a QR the cut draws is built from it (its count and first ids named — lint.mjs `originQrsOf`); missing `channelSlug`, duplicate ids, `section` out of range | Fix the manifest | | `clip-no-cues` | blocking | no `transcript.cues.json` — the build dies there | Fix the cue source | | `clip-unfetchable` | blocking | the last preflight says the source is gone | Replace the source | +| `clip-unchecked` | info | the last preflight could not ask: the platform refused a probe (403, 429, a bot check), so it and the platform's other sources were left `unchecked` | Re-check later | | `clip-mid-sentence` | open | the cut lands inside a cue that does not close a sentence, and `lockEnd` is unset | Trim to the sentence | | `window-overlap` | open/info | two clips from one source overlap | Fix the windows | | `no-punctuation` | info | a source's ASR has no terminators — one row per project | Check the windows | diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -120,6 +120,7 @@ const ACTION_LABEL = { "claim-incoherent": "Rule on the flag", "clip-no-cues": "Fix the cue source", "clip-unfetchable": "Replace the source", + "clip-unchecked": "Re-check later", "clip-mid-sentence": "Trim to the sentence", "clip-cue-gap": "Fix the window", "clip-cut-outside": "Fix the cut", diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -25,6 +25,7 @@ export const WHAT = { "claim-incoherent": "claims that don't hold together", "clip-no-cues": "clips with no cues", "clip-unfetchable": "clips can't be fetched", + "clip-unchecked": "sources not checked", "clip-mid-sentence": "clips end mid-sentence", "clip-cue-gap": "clips over a cue gap", "clip-cut-outside": "cuts outside the window", diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -710,7 +710,7 @@ const fmtDur = (s) => { * key: string, channel: string|null, video: string, clips: string[], * cues: "present"|"missing"|"no-punctuation", cueFile: string|null, * cuesEnd: number|null, latestClipEnd: number, coverageGap: null | { clip: string, needs: number, cuesEnd: number }, - * availability: null | { state: string, ok: boolean, checkedAtMs: number, title: string|null, url: string|null, error: string|null }, + * availability: null | { state: string, ok: boolean | null, checkedAtMs: number, title: string|null, url: string|null, error: string|null }, * cite: { derived: string, override: string|null, differs: boolean }, * title: string|null, * }>, checkedAtMs: number|null, channelsDir: string }>} @@ -765,7 +765,8 @@ export async function sourcesOf(dir, { manifest = null } = {}) { availability: a ? { state: a.state ?? (a.ok ? "ok" : "unknown"), - ok: !!a.ok, + // null: not checked (the platform refused the probe) -- no verdict. + ok: a.ok === null ? null : !!a.ok, checkedAtMs: Date.parse(a.checkedAt ?? "") || avail.checkedAtMs, title: a.title ?? null, url: a.url ?? null, @@ -805,7 +806,7 @@ export async function summariseReport(ctx) { // the record is cached in the index against the signature -- so the first // load of a project pays for its cue files once, and no page does again. const src = m ? await sourcesOf(dir, { manifest: m }) : { rows: [], checkedAtMs: null }; - const sourcesDead = src.rows.filter((r) => r.availability && !r.availability.ok && r.availability.state !== "no-cues").length; + const sourcesDead = src.rows.filter((r) => r.availability && r.availability.ok === false && r.availability.state !== "no-cues").length; const sourcesMissing = src.rows.filter((r) => r.cues === "missing").length; const cueGaps = src.rows.filter((r) => r.coverageGap).length; // The codes a missing or dead origin would break (deadOriginQrsOf): the @@ -905,6 +906,11 @@ export const REPORT_DECISION_KINDS = [ "manifest-invalid", "clip-no-cues", "clip-unfetchable", + // The preflight could not ask: the platform refused a probe (403, 429, a bot + // check) and the rest of its sources were left unprobed rather than burst. + // `info`: no verdict about the source, and the build's own fetches go + // through the editor's paced queue. + "clip-unchecked", "clip-mid-sentence", "window-overlap", "no-punctuation", @@ -1041,7 +1047,17 @@ export async function reportDecisions(ctx, summary) { ); if (avail) { for (const src of avail.sources ?? []) { + // `ok` and `held-locally` (every clip is on disk: never probed) are fine. if (src.ok) continue; + if (src.ok === null || src.state === "unchecked") { + add( + "clip-unchecked", + src.key, + `not checked — ${src.error ?? "the platform refused the probe"}. Re-check later; nothing says it is gone`, + "info", + ); + continue; + } // SEVERITY FOLLOWS THE CLIPS, not the source. // // The probe covers ledger sources as well as clip sources now, and most diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs @@ -11,6 +11,10 @@ import { existsSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { + CLIP_WINDOW_MIN_GAP_SECONDS, + CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS, +} from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs"; /** * This package's own root (umtool/): bin/ lives here, and so does @@ -111,24 +115,46 @@ export const buildTimeoutMs = (clipCount, xfade, seconds = 0) => * @typedef {{ variant?: string, xfade?: boolean, chaptersOnly?: boolean, chromeOnly?: boolean, preview?: { at: number, dur: number } | null, narrate?: boolean, podcast?: boolean }} BuildOptions */ -/** The step-1 preflight alone, reused by the check-sources job. */ -export function availabilityStep(project, env = {}) { +/** + * The preflight's timeout, for a manifest citing `sources` sources + * (report-to-video/manifest-sources.mjs sourceCountOf). The preflight paces + * its probes per platform (check-availability.mjs): up to the widest + * clip-window gap (Rumble's 120 s) plus half again between two, so a manifest + * whose sources are all on one slow platform takes n gaps. Budgeted for that + * worst case, plus a minute per probe; never under ten minutes. A source held + * on disk costs no probe, so this is a ceiling, not an estimate. + */ +export const PROBE_BUDGET_MS = 60_000; +export function availabilityTimeoutMs(sources = 0) { + const widestGapMs = Math.max(CLIP_WINDOW_MIN_GAP_SECONDS, ...Object.values(CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS)) * 1500; + const n = Number.isFinite(sources) && sources > 0 ? sources : 0; + return Math.max(10 * 60_000, Math.round(n * (widestGapMs + PROBE_BUDGET_MS))); +} + +/** + * The step-1 preflight alone, reused by the check-sources job. `sources` is + * how many sources the manifest cites (sourceCountOf), for the timeout; a + * project ref may carry it as `project.sources`. + */ +export function availabilityStep(project, env = {}, { sources = project.sources ?? 0 } = {}) { const manifest = path.join(project.dir, "video.manifest.json"); return { cwd: PIPELINE_DIR, env, label: `check every source of ${project.id} is still fetchable`, argv: ["node", script("check-availability.mjs"), manifest, "--out", path.join(project.dir, "out"), "--allow-missing"], - timeoutMs: 10 * 60_000, + timeoutMs: availabilityTimeoutMs(sources), }; } /** + * `sources` is how many sources the manifest cites (sourceCountOf), which + * budgets the paced preflight; absent, the clip count stands in for it. * @param {{ id: string, dir: string }} project - * @param {{ preset?: string, only?: string | null, skipFetch?: boolean, env?: Record<string,string>, clipCount?: number, seconds?: number, options?: BuildOptions }} [opts] + * @param {{ preset?: string, only?: string | null, skipFetch?: boolean, env?: Record<string,string>, clipCount?: number, sources?: number, seconds?: number, options?: BuildOptions }} [opts] * @returns {import("../trim").Step[]} */ -export function buildSteps(project, { preset = "fast", only = null, skipFetch = false, env = {}, clipCount = 20, seconds = 0, options = {} } = {}) { +export function buildSteps(project, { preset = "fast", only = null, skipFetch = false, env = {}, clipCount = 20, sources = clipCount, seconds = 0, options = {} } = {}) { const p = PRESETS[preset] ?? PRESETS.fast; const manifest = path.join(project.dir, "video.manifest.json"); const outDir = path.join(project.dir, "out"); @@ -149,7 +175,7 @@ export function buildSteps(project, { preset = "fast", only = null, skipFetch = ...base, label: "check every source is still fetchable", argv: ["node", script("check-availability.mjs"), manifest, "--out", outDir], - timeoutMs: 10 * 60_000, + timeoutMs: availabilityTimeoutMs(sources), }, { ...base, diff --git a/umtool/lib/report/driver.test.mjs b/umtool/lib/report/driver.test.mjs @@ -113,3 +113,15 @@ test("the pipeline is found from the module, whatever the cwd", async () => { rmSync(elsewhere, { recursive: true, force: true }); } }); + +test("the preflight's timeout allows for its pacing: n sources, n of the widest gap", async () => { + const { availabilityTimeoutMs, availabilityStep } = await import("./driver.mjs"); + assert.equal(availabilityTimeoutMs(0), 10 * 60_000); + assert.equal(availabilityTimeoutMs(2), 10 * 60_000, "a few sources keep the ten-minute floor"); + // 40 Rumble sources: 40 × (120 s × 1.5 + a minute) = 160 min. + assert.equal(availabilityTimeoutMs(40), 40 * (180_000 + 60_000)); + const pre = buildSteps(project, { preset: "fast", clipCount: 3, sources: 40 })[0]; + assert.match(pre.label, /check every source/); + assert.equal(pre.timeoutMs, availabilityTimeoutMs(40)); + assert.equal(availabilityStep({ ...project, sources: 40 }).timeoutMs, availabilityTimeoutMs(40)); +}); diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -30,10 +30,20 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // E2E_UMTOOL_CLIP_RENDER_SCRIPT set below on the app server: Render this // clip's renderer (the live preview; // lib/report/clipRender.mjs), stubbed +// E2E_AVAILABILITY_GAP_MS set below for the whole run (the app server and +// the CLIs specs spawn): the gap between two +// availability probes on one platform +// (report-to-video/check-availability.mjs), in +// place of the real 30–180 s, against the stub yt-dlp // The ports are common/lib/ports.mjs's (offset per worktree by // scripts/worktree.mjs), not test-only, and keep their names. const PORT = portFor("UMTOOL_E2E_PORT"); +// The preflight's per-platform pacing, against the fixture's stub yt-dlp: 50 ms, +// not the 30 s a real YouTube probe waits. On process.env, so the app server +// and every worker (and the CLIs they spawn) inherit it. +process.env.E2E_AVAILABILITY_GAP_MS ??= "50"; + // START MODE BY DEFAULT, as the editor suite (plans/e2e-speed.md, S1): `next // dev` compiles each route on first use and again after a change, and the // suite was 26.5 min under it in release 19's gate. The build is its OWN diff --git a/umtool/report-to-video/check-availability.mjs b/umtool/report-to-video/check-availability.mjs @@ -11,6 +11,22 @@ // resolves formats without downloading a byte: a few seconds for a whole // manifest against twenty-odd minutes for the build it protects. // +// WHAT IS ON DISK IS NEVER ASKED OF THE NETWORK. A source every one of whose +// clips the build can cut from a file already held -- the build's raw cache, +// the editor's window cache, a saved recording; build-video.mjs fetchSpan and +// planLocalSources, the build's own answer -- is `held-locally` (ok) and costs +// no request. Only what the build would have to fetch is probed. +// +// AND WHAT IS PROBED IS PACED, per platform, exactly as the editor paces a +// clip-window fetch: at least clipWindowMinGapSeconds(platform) between two +// probes on one platform (30 s; Rumble 120 s -- common/ytdlp/platformArgs.mjs), +// plus up to half again at random. Probes on different platforms interleave. +// A probe that draws a refusal (HTTP 403 / 429, Cloudflare's "Just a moment", +// YouTube's bot check) STOPS probing that platform: that source and the rest +// of the platform's are `unchecked` (ok: null) -- not a verdict about the +// source, and not a reason to refuse the build, whose fetches go through the +// editor's own paced queue. +// // On the CLI: // node umtool/report-to-video/check-availability.mjs <manifest.json> [--json] // @@ -22,7 +38,7 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; -import { readFile, writeFile } from "node:fs/promises"; +import { readFile, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { DEFAULT_CHANNELS_DIR } from "./cues.mjs"; @@ -30,7 +46,16 @@ import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mj import { ensureWriteDir } from "../lib/report/storage.mjs"; // The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table, // in common, plain JS so bare `node` can load it. -import { platformArgsForUrl } from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs"; +import { + clipWindowMinGapSeconds, + platformArgsForUrl, +} from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs"; +import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs"; +import { fetchSpan, localSources } from "./build-video.mjs"; +import { SHADOW_CHANNELS, audioUse, channelsDirFor } from "./sources.mjs"; +import { manifestSources } from "./manifest-sources.mjs"; + +export { manifestSources }; const execFileP = promisify(execFile); @@ -44,8 +69,19 @@ const CHANNELS_DIR = DEFAULT_CHANNELS_DIR; // blip needs a retry. Anything unrecognised stays `maybe_missing` rather than // being called deleted -- claiming a source is gone when it is not is the more // expensive mistake, because it invites deleting a citation. -function classify(stderr) { +// A REFUSAL is about us, not the source: the platform turned the probe away +// (rate limit, Cloudflare's JS challenge, YouTube's bot check). Asked first, +// because "Sign in to confirm you're not a bot" would otherwise read as an +// age restriction below. +export function isRefusal(stderr) { + return /HTTP Error 403|HTTP Error 429|Too Many Requests|Just a moment|cf-challenge|Cloudflare|not a bot|rate.?limit/i.test( + String(stderr ?? ""), + ); +} + +export function classify(stderr) { const t = String(stderr ?? ""); + if (isRefusal(t)) return "unchecked"; if (/Private video|private/i.test(t)) return "private"; if (/removed by the uploader|has been removed|no longer available|Video unavailable|does not exist|410/i.test(t)) return "deleted"; @@ -73,36 +109,71 @@ export async function cueMeta(videoId, channelSlug) { return { title: d.title, webpageUrl: d.webpageUrl, duration: d.duration }; } -export async function checkAvailability(manifestPath, { outDir, maxAgeDays = 0 } = {}) { +/** A source's verdict, as the inbox, the CLI and the build read it: true, false, or null (not checked). */ +const verdictOf = (state) => (state === "ok" || state === "held-locally" ? true : state === "unchecked" ? null : false); + +/** + * Can the build cut every clip of this source from disk? The build's own + * question (fetchSpan + the local tiers), asked with the network on: a clip + * that plays from its sound because it has no picture to fetch counts, a + * picture that would be fetched does not. A source with no clips (ledger only) + * has nothing on disk to answer for it. + */ +async function heldLocally(w, render, local) { + if (!w.entries.length) return false; + for (const entry of w.entries) { + const span = fetchSpan(entry, render, {}); + const audio = audioUse({ entry, render, network: true }) !== null; + if (!(await local.resolve(entry, span, { audio }))) return false; + } + return true; +} + +const realSleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +// TEST-ONLY: E2E_AVAILABILITY_GAP_MS replaces the gap between two probes on a +// platform, so the e2e suite (a stub yt-dlp) does not wait 30 s per source. +// Unset everywhere but the e2e run (umtool/playwright.config.ts). +function testGapMs() { + const raw = Number(process.env.E2E_AVAILABILITY_GAP_MS); + return Number.isFinite(raw) && raw > 0 ? raw : undefined; +} + +/** + * @param {string} manifestPath + * @param {{ outDir?: string, maxAgeDays?: number, channelsDir?: string, + * ytdlp?: string, now?: () => number, sleep?: (ms: number) => Promise<void>, + * random?: () => number, log?: (m: string) => void }} [opts] + * `now`, `sleep` and `random` are the clock the pacing runs on (tests pass a + * fake one); `channelsDir` is where held media is looked for (default: the + * tree the build reads, sources.mjs channelsDirFor). + */ +export async function checkAvailability(manifestPath, { + outDir, maxAgeDays = 0, channelsDir = null, ytdlp = YTDLP, + now = Date.now, sleep = realSleep, random = Math.random, log = () => {}, +} = {}) { const manifest = JSON.parse(await readFile(manifestPath, "utf8")); - const slug = manifest.provenance?.channelSlug; - const dir = outDir ?? path.join(path.dirname(path.resolve(manifestPath)), "out"); + const manifestDir = path.dirname(path.resolve(manifestPath)); + const dir = outDir ?? path.join(manifestDir, "out"); const file = path.join(dir, "availability.json"); + const iso = () => new Date(now()).toISOString(); // A clip may name its own channel: the same streamer's VODs are mirrored // across more than one archive, and the same id under a different slug is a // different file. So the unit of work is (channel, video), never video alone. - const wanted = new Map(); - const want = (channel, video) => { - const key = `${channel}/${video}`; - if (!wanted.has(key)) wanted.set(key, { key, channel, video, clips: [], claims: [] }); - return wanted.get(key); - }; - for (const e of manifest.timeline ?? []) { - // A clip with its own `src` is a file beside the manifest, on no platform: - // the build checks it is there. - if (e.type !== "clip" || e.src != null) continue; - want(e.channel ?? slug, e.video).clips.push(e.id); - } - // LEDGER SOURCES TOO, not just the clipped ones. A cut that stacks its - // unclipped claims onto cards has to say WHY each one is a line of text - // rather than footage, and "the upload is gone" and "we did not cut it" are - // different sentences. Guessing which is which is how a live source ends up - // labelled deleted on screen. - for (const c of manifest.ledger ?? []) { - if (!c.video) continue; - want(c.channel ?? slug, c.video).claims.push(c.id); - } + const wanted = manifestSources(manifest); + + // Where the build would find media on disk: the same raw cache and channels + // tree build-video.mjs reads (variantPaths' clips-raw, channelsDirFor). + const local = localSources({ + rawDir: path.join(dir, "clips-raw"), + channelsDir: channelsDir ?? channelsDirFor(manifestDir, manifest, { + shadowExists: await stat(path.join(manifestDir, SHADOW_CHANNELS)).then((st) => st.isDirectory(), () => false), + fallback: CHANNELS_DIR, + }), + channelSlug: manifest.provenance?.channelSlug ?? null, + }); + const render = manifest.render ?? {}; const prev = await readFile(file, "utf8").then( (s) => JSON.parse(s), @@ -111,11 +182,16 @@ export async function checkAvailability(manifestPath, { outDir, maxAgeDays = 0 } const prevBy = new Map((prev.sources ?? []).map((s) => [s.key, s])); const freshMs = maxAgeDays * 86400_000; - const sources = []; - for (const w of wanted.values()) { + // Each source's row, in manifest order; the probes are filled in below. + const rows = new Array(wanted.length); + const probes = []; + const strip = ({ entries: _entries, ...w }) => w; + for (const [i, wFull] of wanted.entries()) { + const w = strip(wFull); const was = prevBy.get(w.key); - if (freshMs > 0 && was?.checkedAt && Date.now() - Date.parse(was.checkedAt) < freshMs) { - sources.push({ ...was, clips: w.clips, claims: w.claims, reused: true }); + // An `unchecked` row is not a verdict, so it is never reused. + if (freshMs > 0 && was?.checkedAt && was.state !== "unchecked" && now() - Date.parse(was.checkedAt) < freshMs) { + rows[i] = { ...was, clips: w.clips, claims: w.claims, reused: true }; continue; } @@ -127,33 +203,69 @@ export async function checkAvailability(manifestPath, { outDir, maxAgeDays = 0 } // the Rumble two-ids trap produces: the manifest names the MCP video id // while the cues live under the URL slug. Build would die here too, so it // is reported here rather than discovered twenty minutes in. - sources.push({ - ...w, ok: false, state: "no-cues", checkedAt: new Date().toISOString(), + rows[i] = { + ...w, ok: false, state: "no-cues", checkedAt: iso(), error: `no transcript.cues.json under ${w.channel}/data/${w.video}`, - }); + }; + continue; + } + + if (await heldLocally(wFull, render, local)) { + rows[i] = { + ...w, ok: true, state: "held-locally", title: meta.title, url: meta.webpageUrl, + checkedAt: iso(), error: null, + }; continue; } + probes.push({ i, w, meta, platform: detectPlatform(meta.webpageUrl) ?? "other" }); + } + + // THE PACED PROBES. Each platform has its own clock: the next probe on it is + // due a gap after the last one ended. The probe made next is always the one due + // soonest, so two platforms interleave instead of one waiting on the other. + const testGap = testGapMs(); + const floorMs = (platform) => testGap ?? clipWindowMinGapSeconds(platform === "other" ? null : platform) * 1000; + const dueAt = new Map(); // platform -> when its next probe may start, in ms + const refused = new Map(); // platform -> the refusal that stopped it + const pending = [...probes]; + while (pending.length) { + let k = 0; + const due = (p) => dueAt.get(p.platform) ?? -Infinity; + for (let j = 1; j < pending.length; j++) if (due(pending[j]) < due(pending[k])) k = j; + const p = pending.splice(k, 1)[0]; + const { i, w, meta, platform } = p; + if (refused.has(platform)) { + rows[i] = { + ...w, ok: null, state: "unchecked", title: meta.title, url: meta.webpageUrl, checkedAt: iso(), + error: `not probed: ${platform} refused an earlier probe this run (${refused.get(platform)})`, + }; + continue; + } + + const wait = due(p) - now(); + if (wait > 0) { + log(`waiting ${Math.round(wait / 1000)} s before the next ${platform} probe`); + await sleep(wait); + } + const checkedAt = iso(); try { - await execFileP( - YTDLP, - simulateArgs(meta.webpageUrl), - { maxBuffer: 1 << 24 }, - ); - sources.push({ - ...w, ok: true, state: "ok", title: meta.title, url: meta.webpageUrl, - checkedAt: new Date().toISOString(), error: null, - }); + await execFileP(ytdlp, simulateArgs(meta.webpageUrl), { maxBuffer: 1 << 24 }); + rows[i] = { ...w, ok: true, state: "ok", title: meta.title, url: meta.webpageUrl, checkedAt, error: null }; } catch (err) { - const stderr = err?.stderr ?? err?.message ?? ""; - sources.push({ - ...w, ok: false, state: classify(stderr), title: meta.title, url: meta.webpageUrl, - checkedAt: new Date().toISOString(), error: String(stderr).trim().split("\n").slice(-3).join(" "), - }); + const stderr = err?.stderr || err?.message || ""; + const error = String(stderr).trim().split("\n").slice(-3).join(" "); + const state = classify(stderr); + if (state === "unchecked") refused.set(platform, error.slice(0, 160)); + rows[i] = { ...w, ok: verdictOf(state), state, title: meta.title, url: meta.webpageUrl, checkedAt, error }; } + // The gap runs from the END of a probe (a --simulate is several requests), + // the floor plus up to half again so a run never settles into a beat. + dueAt.set(platform, now() + (testGap ?? floorMs(platform) * (1 + 0.5 * random()))); } - const report = { manifest: path.resolve(manifestPath), checkedAt: new Date().toISOString(), sources }; + const sources = rows; + const report = { manifest: path.resolve(manifestPath), checkedAt: iso(), sources }; // ensureWriteDir, not mkdir: a project's out/ may belong on the media root. await ensureWriteDir(dir); await writeFile(file, JSON.stringify(report, null, 2) + "\n", "utf8"); @@ -174,24 +286,33 @@ async function main() { const report = await checkAvailability(manifestPath, { outDir: flag("--out"), maxAgeDays: Number(flag("--max-age") ?? 0), + log: (m) => console.error(m), }); if (argv.includes("--json")) { console.log(JSON.stringify(report, null, 2)); } else { for (const s of report.sources) { - const mark = s.ok ? "ok " : "GONE"; + const mark = s.ok ? "ok " : s.ok === null ? "?? " : "GONE"; console.log( `${mark} ${s.key.padEnd(40)} ${String(s.state).padEnd(14)} ` + `${s.clips.length} clip(s)${s.reused ? " (cached)" : ""}`, ); if (!s.ok && s.error) console.log(` ${s.error}`); } - const bad = report.sources.filter((s) => !s.ok).length; - console.log(`\n${report.sources.length} source(s), ${bad} unavailable -> ${report.file}`); + const bad = report.sources.filter((s) => s.ok === false).length; + const held = report.sources.filter((s) => s.state === "held-locally").length; + const unchecked = report.sources.filter((s) => s.ok === null).length; + console.log( + `\n${report.sources.length} source(s), ${bad} unavailable` + + (held ? `, ${held} held locally (not probed)` : "") + + (unchecked ? `, ${unchecked} not checked (the platform refused a probe)` : "") + + ` -> ${report.file}`, + ); } - if (report.sources.some((s) => !s.ok) && !argv.includes("--allow-missing")) process.exit(1); + // `unchecked` is no verdict: only a source known to be gone stops the chain. + if (report.sources.some((s) => s.ok === false) && !argv.includes("--allow-missing")) process.exit(1); } if (import.meta.url === `file://${process.argv[1]}`) { diff --git a/umtool/report-to-video/check-availability.test.mjs b/umtool/report-to-video/check-availability.test.mjs @@ -11,6 +11,8 @@ import path from "node:path"; const ROOT = await mkdtemp(path.join(os.tmpdir(), "check-availability-")); process.env.CHANNELS_DIR = ROOT; +// The real pacing is under test here, not the e2e stub gap. +delete process.env.E2E_AVAILABILITY_GAP_MS; const { cueMeta } = await import("./check-availability.mjs"); test.after(() => rm(ROOT, { recursive: true, force: true })); @@ -31,3 +33,155 @@ test("cueMeta reads a Twitch v<n> record from data/<n>/", async () => { await writeFile(path.join(ROOT, "example-twitch", "config.json"), JSON.stringify({ handling: "youtube", platform: "youtube" })); await assert.rejects(() => cueMeta(`v${n}`, "example-twitch"), /ENOENT/); }); + +// ---- the preflight never bursts a platform, and never asks for what is held ---- +// +// A fake yt-dlp records each invocation; the pacing runs on a fake clock (the +// injected `now`/`sleep`), so a 120 s Rumble gap costs the test nothing. + +const { checkAvailability, classify } = await import("./check-availability.mjs"); +const { rawWindowName } = await import("./sources.mjs"); +const { chmod, readFile } = await import("node:fs/promises"); +const { CLIP_WINDOW_MIN_GAP_SECONDS, CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS } = await import( + "yt-dlp-transcript-common/ytdlp/platformArgs.mjs" +); + +/** A fake yt-dlp: appends its last arg (the URL) to `log`; a URL with "blocked" draws a 403. */ +async function fakeYtdlp(dir) { + const bin = path.join(dir, "fake-yt-dlp.sh"); + const log = path.join(dir, "invocations.log"); + await writeFile( + bin, + `#!/bin/sh\nfor a; do last="$a"; done\necho "$last" >> "${log}"\n` + + `case "$last" in *blocked*) echo "ERROR: [Rumble] x: Unable to download webpage: HTTP Error 403: Forbidden" >&2; exit 1;; esac\nexit 0\n`, + ); + await chmod(bin, 0o755); + const calls = async () => (await readFile(log, "utf8").catch(() => "")).split("\n").filter(Boolean); + return { bin, calls }; +} + +/** A fake clock: `sleep` advances it and records what was asked. */ +function fakeClock(start = Date.parse("2026-10-25T00:00:00Z")) { + let t = start; + const sleeps = []; + return { + now: () => t, + sleep: async (ms) => { + sleeps.push(ms); + t += ms; + }, + random: () => 0, + sleeps, + }; +} + +/** A channel with one video's cue file, its page at `url`. */ +async function cueFile(slug, id, url) { + await mkdir(path.join(ROOT, slug, "data", id), { recursive: true }); + await writeFile(path.join(ROOT, slug, "config.json"), JSON.stringify({ handling: "youtube" })); + await writeFile( + path.join(ROOT, slug, "data", id, "transcript.cues.json"), + JSON.stringify({ id, title: `video ${id}`, webpageUrl: url, duration: 600, cues: [] }), + ); +} + +async function project(name, timeline, ledger = []) { + const dir = path.join(ROOT, "projects", name); + await mkdir(dir, { recursive: true }); + const manifest = path.join(dir, "video.manifest.json"); + await writeFile( + manifest, + JSON.stringify({ slug: name, provenance: { channelSlug: "chan" }, render: { fetchPad: 3 }, timeline, ledger }), + ); + return { dir, manifest, out: path.join(dir, "out") }; +} + +test("classify: a refusal is unchecked, never an age restriction or a death", () => { + assert.equal(classify("ERROR: HTTP Error 403: Forbidden"), "unchecked"); + assert.equal(classify("ERROR: HTTP Error 429: Too Many Requests"), "unchecked"); + assert.equal(classify("Sign in to confirm you're not a bot"), "unchecked"); + assert.equal(classify("Just a moment..."), "unchecked"); + assert.equal(classify("Sign in to confirm your age"), "restricted"); + assert.equal(classify("Video unavailable"), "deleted"); +}); + +test("every clip held on disk: held-locally, and yt-dlp is never run", async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), "ca-held-")); + const fake = await fakeYtdlp(tmp); + await cueFile("chan", "held1", "https://rumble.com/v111-held.html"); + await cueFile("chan", "held2", "https://www.youtube.com/watch?v=held2xxxxxx"); + const p = await project("all-local", [ + { id: "c1", type: "clip", video: "held1", start: 10, end: 20 }, + { id: "c2", type: "clip", video: "held2", start: 30, end: 40 }, + ]); + await mkdir(path.join(p.out, "clips-raw"), { recursive: true }); + // c1 in the build's raw cache (its exact padded span), c2 in the editor's window cache. + await writeFile(path.join(p.out, "clips-raw", rawWindowName("held1", 7, 23)), "x"); + await mkdir(path.join(ROOT, "chan", "data", "held2", "clips"), { recursive: true }); + await writeFile(path.join(ROOT, "chan", "data", "held2", "clips", "20-50.mp4"), "x"); + const clock = fakeClock(); + const report = await checkAvailability(p.manifest, { outDir: p.out, ytdlp: fake.bin, ...clock }); + assert.deepEqual(report.sources.map((s) => [s.key, s.state, s.ok]), [ + ["chan/held1", "held-locally", true], + ["chan/held2", "held-locally", true], + ]); + assert.deepEqual(await fake.calls(), [], "no probe at all"); + assert.deepEqual(clock.sleeps, []); +}); + +test("two Rumble sources: the second probe starts at least 120 s after the first ends", async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), "ca-paced-")); + const fake = await fakeYtdlp(tmp); + await cueFile("chan", "r1", "https://rumble.com/v201-one.html"); + await cueFile("chan", "r2", "https://rumble.com/v202-two.html"); + await cueFile("chan", "y1", "https://www.youtube.com/watch?v=y1xxxxxxxxx"); + const p = await project("paced", [ + { id: "c1", type: "clip", video: "r1", start: 10, end: 20 }, + { id: "c2", type: "clip", video: "r2", start: 10, end: 20 }, + { id: "c3", type: "clip", video: "y1", start: 10, end: 20 }, + ]); + const clock = fakeClock(); + const report = await checkAvailability(p.manifest, { outDir: p.out, ytdlp: fake.bin, ...clock }); + assert.equal(CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS.rumble, 120); + const at = Object.fromEntries(report.sources.map((s) => [s.video, Date.parse(s.checkedAt)])); + assert.ok(at.r2 - at.r1 >= 120_000, `rumble probes ${at.r2 - at.r1} ms apart`); + // The YouTube probe does not wait behind Rumble's gap: it interleaves. + assert.ok(at.y1 < at.r2, "youtube probed inside rumble's gap"); + assert.deepEqual(clock.sleeps, [120_000]); + assert.equal((await fake.calls()).length, 3); + assert.ok(report.sources.every((s) => s.state === "ok")); + assert.ok(CLIP_WINDOW_MIN_GAP_SECONDS >= 30); +}); + +test("a 403 stops that platform: its remaining sources are unchecked, never unavailable", async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), "ca-refused-")); + const fake = await fakeYtdlp(tmp); + await cueFile("chan", "b1", "https://rumble.com/v301-blocked.html"); + await cueFile("chan", "b2", "https://rumble.com/v302-next.html"); + await cueFile("chan", "b3", "https://rumble.com/v303-later.html"); + await cueFile("chan", "y2", "https://www.youtube.com/watch?v=y2xxxxxxxxx"); + const p = await project( + "refused", + [ + { id: "c1", type: "clip", video: "b1", start: 10, end: 20 }, + { id: "c2", type: "clip", video: "b2", start: 10, end: 20 }, + { id: "c4", type: "clip", video: "y2", start: 10, end: 20 }, + ], + [{ id: "k1", video: "b3" }], + ); + const clock = fakeClock(); + const report = await checkAvailability(p.manifest, { outDir: p.out, ytdlp: fake.bin, ...clock }); + const by = Object.fromEntries(report.sources.map((s) => [s.video, s])); + assert.equal(by.b1.state, "unchecked"); + assert.equal(by.b1.ok, null); + assert.equal(by.b2.state, "unchecked"); + assert.equal(by.b3.state, "unchecked"); + assert.match(by.b2.error, /rumble refused an earlier probe/); + assert.equal(by.y2.state, "ok", "another platform is still probed"); + const calls = await fake.calls(); + assert.equal(calls.filter((u) => u.includes("rumble.com")).length, 1, "one Rumble request, then none"); + assert.equal(calls.length, 2); + // On disk too: what the inbox reads. + const disk = JSON.parse(await readFile(path.join(p.out, "availability.json"), "utf8")); + assert.ok(disk.sources.every((s) => s.ok !== false), JSON.stringify(disk.sources.map((s) => s.state))); +}); diff --git a/umtool/report-to-video/manifest-sources.mjs b/umtool/report-to-video/manifest-sources.mjs @@ -0,0 +1,43 @@ +// manifest-sources.mjs — the (channel, video) sources a manifest cites, as the +// availability preflight counts them. A LEAF (no imports), so the preflight, +// the driver that budgets its timeout, and the routes that build its step all +// count the same thing without pulling the build into a request handler. + +/** + * Every clip without its own `src` (a `src` clip is a file beside the + * manifest, on no platform: the build checks it is there), and every ledger + * claim with a video. A clip may name its own channel: the same id under a + * different slug is a different file, so the unit is (channel, video). + * + * LEDGER SOURCES TOO, not just the clipped ones. A cut that stacks its + * unclipped claims onto cards has to say WHY each one is a line of text rather + * than footage, and "the upload is gone" and "we did not cut it" are different + * sentences. Guessing which is which is how a live source ends up labelled + * deleted on screen. + * + * @param {any} manifest + * @returns {{ key: string, channel: string, video: string, clips: string[], claims: string[], entries: any[] }[]} + */ +export function manifestSources(manifest) { + const slug = manifest?.provenance?.channelSlug; + const wanted = new Map(); + const want = (channel, video) => { + const key = `${channel}/${video}`; + if (!wanted.has(key)) wanted.set(key, { key, channel, video, clips: [], claims: [], entries: [] }); + return wanted.get(key); + }; + for (const e of manifest?.timeline ?? []) { + if (e?.type !== "clip" || e.src != null) continue; + const w = want(e.channel ?? slug, e.video); + w.clips.push(e.id); + w.entries.push(e); + } + for (const c of manifest?.ledger ?? []) { + if (!c?.video) continue; + want(c.channel ?? slug, c.video).claims.push(c.id); + } + return [...wanted.values()]; +} + +/** How many sources the preflight may have to probe. */ +export const sourceCountOf = (manifest) => manifestSources(manifest).length; diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -39,6 +39,7 @@ "./montage-styles": "./montage-styles.mjs", "./montage-rulings": "./montage-rulings.mjs", "./lint": "./lint.mjs", + "./manifest-sources": "./manifest-sources.mjs", "./local-media": "./local-media.mjs", "./join-preview": "./join-preview.mjs", "./look": "./look.mjs", diff --git a/umtool/report-to-video/render-cards.mjs b/umtool/report-to-video/render-cards.mjs @@ -1008,6 +1008,9 @@ export const ledgerSeconds = (n) => LEDGER_LEAD + LEDGER_STEP * n + LEDGER_TAIL */ export const SOURCE_TAG = { ok: "not clipped", + "held-locally": "not clipped", + // Not checked is no verdict: the card never says a source is gone unasked. + unchecked: "not clipped", deleted: "source deleted", private: "source private", "members-only": "members only",