// FETCH WINDOWS FROM UMTOOL (release 35 O1): a project's clip windows, asked of // the editor as ONE `fetch-windows` batch — the body the orchestrator used to // build by hand from the manifest, built here the same way, every time. // // {requestedBy: "umtool:", manifest: , // storedUrl: "fallback", // items: [{slug: clip.channel, id: clip.video, from, to, clipId, pad, reason}]} // // `from`/`to` are the build's own fetch span (build-video.mjs `fetchSpan`: // start − render.fetchPad … end + render.fetchPad, two decimals) — for a phrase // seed (fetchPad 0) exactly the clip's start and end. A clip with gaps is // asked for PER KEPT PIECE (gaps.mjs fetchPieces, the build's `fetchSpans`): // each piece padded at its own edges, pieces under a minute apart as one — // a gap-joined clip over 5385–21812 asks for its two moments, not 4½ hours. `pad` is provenance (the // seconds each side that are margin): the fetchPad, else 3. `reason` is // " montage" for a montage (clips carrying `montage`), else the title. // A montage clip the rulings leave out (cut / not-him / read-aloud) is not // asked for: nobody needs its seconds. // // IT WRITES NOTHING IN THE CORPUS. The editor fetches, paces (one job per // platform queue) and writes the windows; this asks and records what it asked: // `<project>/fetch-runs.json` {runs: [{at, bodyHash, dryRun, items, jobIds, // summary, jobs?: {<jobId>: {status, platform, failed: [...], at}}}]}, so the // stand-in step (standIns.mjs) can find the jobs and the windows they refused. // // A REFETCH (`umtool fetch --refetch <clipId>`) evicts first: each named clip's // fetch span — exactly the item this body asks for, pad included — goes to the // editor's `evict-clips` as `{slug, id, covering: [{from, to}]}`, one request // per video, which removes every cached window OVERLAPPING it (a wider window // the dedup would have served the span from included). Then the fetch runs as // usual and finds those seconds missing. The run records what was evicted // (`refetch` on its fetch-runs.json entry). // // The editor's URL and token are read where report-to-video/fetch-via-editor.mjs // reads them: ARCHILYZER_EDITOR_URL (default http://localhost:3001) and // WORKER_TOKEN (else the editor's own env files, lib/annotations/agentAuth.mjs). import { createHash } from "node:crypto"; import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; import { LEFT_OUT_VERDICTS, clipMomentKey, readMontageRulings } from "umtool-report-to-video/montage-rulings"; import { fetchPieces, renderGaps } from "umtool-report-to-video/gaps"; import { tallWindowCap } from "umtool-report-to-video/sources"; import { agentToken } from "../annotations/agentAuth.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const FETCH_RUNS_FILE = "fetch-runs.json"; export const MANIFEST_FILE = "video.manifest.json"; export const DEFAULT_EDITOR = "http://localhost:3001"; /** The provenance pad when the manifest fetches no margin of its own (a phrase seed's window already has it). */ export const DEFAULT_PROVENANCE_PAD = 3; /** Runs kept in fetch-runs.json (the newest). */ export const FETCH_RUNS_KEPT = 50; const REASON_LIMIT = 400; const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); const r2 = (x) => Number(Number(x).toFixed(2)); /** Does the manifest cut a montage (any clip carrying a `montage` object)? */ export const isMontage = (manifest) => (Array.isArray(manifest?.timeline) ? manifest.timeline : []).some((e) => isObj(e) && e.type === "clip" && isObj(e.montage)); /** * The editor's fetch-windows body for a manifest. Pure. * * @param {Record<string, any>} manifest * @param {{ manifestPath: string, project: string, rulings?: { rulings: Record<string, { verdict: string }> } | null, reason?: string | null }} opts * @returns {{ body: { requestedBy: string, manifest: string, storedUrl: "fallback", archive?: string, items: Record<string, any>[] }, skipped: { clipId: string, why: string }[] }} */ export function fetchWindowsBody(manifest, { manifestPath, project, rulings = null, reason = null }) { const montage = isMontage(manifest); const title = String(manifest?.title ?? "").trim() || project; const why = String(reason ?? "").trim() || (montage ? `${title} montage` : title); const fetchPad = Number(manifest?.render?.fetchPad ?? DEFAULT_PROVENANCE_PAD); const padOf = Number.isFinite(fetchPad) && fetchPad > 0 ? fetchPad : DEFAULT_PROVENANCE_PAD; const margin = Number.isFinite(fetchPad) && fetchPad > 0 ? fetchPad : 0; const left = new Set(LEFT_OUT_VERDICTS); const items = []; const skipped = []; for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { if (!isObj(e) || e.type !== "clip") continue; const slug = e.channel ?? manifest?.provenance?.channelSlug ?? null; if (!slug || !e.video) { skipped.push({ clipId: String(e.id ?? ""), why: "no channel or video (a src clip)" }); continue; } if (!Number.isFinite(Number(e.start)) || !Number.isFinite(Number(e.end))) { skipped.push({ clipId: String(e.id ?? ""), why: "no start and end" }); continue; } const key = clipMomentKey(e, manifest); const ruling = key ? rulings?.rulings?.[key] : null; if (ruling && left.has(ruling.verdict)) { skipped.push({ clipId: String(e.id), why: `ruled ${ruling.verdict}` }); continue; } // One item per kept piece (gaps.mjs fetchPieces, the build's fetchSpans): // a gap-joined clip asks for its moments, never the hours between them. for (const span of fetchPieces(Number(e.start), Number(e.end), renderGaps(e, manifest?.render ?? {}), { before: margin, after: margin })) { items.push({ slug, id: e.video, from: r2(span.from), to: r2(span.to), clipId: e.id, pad: padOf, reason: why.slice(0, REASON_LIMIT), }); } } // The archive the cut cites (demo epic D1): its provenance.siteOrigin. The // editor registers a channel it does not hold as remote-only only when that // origin is a CONNECTED archive; any other origin changes nothing. const site = typeof manifest?.provenance?.siteOrigin === "string" ? manifest.provenance.siteOrigin.trim().replace(/\/+$/, "") : ""; // A TALL PROJECT (`render.tallWindows`, sources.mjs tallWindowCap) asks for // its render.maxHeightSource: the editor holds it to its // clips.windowMaxHeight, keeps a taller window beside a 720 one and says // which clips stayed lower and why (`lower` in its answer). Any other // project sends no height, as before. const maxHeight = tallWindowCap(manifest?.render); return { body: { requestedBy: `umtool:${project}`, manifest: path.resolve(manifestPath), storedUrl: "fallback", ...(/^https?:\/\//.test(site) ? { archive: site } : {}), ...(maxHeight !== undefined ? { maxHeight } : {}), items, }, skipped, }; } // Twitch's record ids wear a `v` the directory does not: "v123" and "123" are one video. const sameVideo = (a, b) => String(a).replace(/^v(?=\d+$)/, "") === String(b).replace(/^v(?=\d+$)/, ""); /** * What a refetch evicts first: the named clips' fetch spans, and every span a * named video is asked for, as one evict-clips request per video. Pure. * * @param {{ items: Record<string, any>[] }} body the fetch-windows body (fetchWindowsBody) * @param {{ clipId: string, why: string }[]} skipped what the body left out, and why * @param {{ clipIds?: string[], videos?: string[] }} want clip ids; videos as "<slug>/<id>" * @returns {{ ok: true, requests: { slug: string, id: string, covering: { from: number, to: number }[], clipIds: string[] }[] } | { ok: false, error: string }} */ export function refetchEvictions(body, skipped, { clipIds = [], videos = [] }) { const items = Array.isArray(body?.items) ? body.items : []; /** @type {Map<string, { slug: string, id: string, covering: { from: number, to: number }[], clipIds: string[] }>} */ const byVideo = new Map(); const add = (it) => { const key = `${it.slug}/${it.id}`; const req = byVideo.get(key) ?? { slug: it.slug, id: it.id, covering: [], clipIds: [] }; // A clip fetched in pieces is one clip with several spans. if (req.covering.some((c) => c.from === it.from && c.to === it.to)) return; req.covering.push({ from: it.from, to: it.to }); if (!req.clipIds.includes(it.clipId)) req.clipIds.push(it.clipId); byVideo.set(key, req); }; for (const clipId of clipIds) { const its = items.filter((i) => i.clipId === clipId); if (!its.length) { const left = skipped.find((s) => s.clipId === clipId); return { ok: false, error: left ? `${clipId} is not fetched by this project (${left.why}), so there is nothing to refetch` : `no clip "${clipId}" in the manifest's timeline`, }; } for (const it of its) add(it); } for (const v of videos) { const at = String(v).indexOf("/"); const slug = at > 0 ? v.slice(0, at) : ""; const id = at > 0 ? v.slice(at + 1) : ""; if (!slug || !id || id.includes("/")) return { ok: false, error: `--refetch-video takes <slug>/<id>, not "${v}"` }; const its = items.filter((i) => i.slug === slug && sameVideo(i.id, id)); if (!its.length) return { ok: false, error: `this project asks for no window of ${slug}/${id}` }; for (const it of its) add(it); } return { ok: true, requests: [...byVideo.values()] }; } /** sha256 of the body with its keys sorted (key order never changes the hash). */ export function bodyHash(body) { const canon = (v) => Array.isArray(v) ? v.map(canon) : isObj(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, canon(v[k])])) : v; return createHash("sha256").update(JSON.stringify(canon(body))).digest("hex"); } /** * The body for a project on disk: its manifest, its rulings. * * `take` (`umtool fetch <p> --take <id>`): the TAKE's clips -- its manifest * as its walk reads it (takeManifest.mjs resolveTakeManifest: the project's * now, the style's patch, the take's), so a clip only the take has (in its * patch, not the cut) is asked for, and a DRAFT take needs no render first. * The body names takes/<id>/take.json as the manifest it came from. * * `localIds` (what is POSTED, never what a page shows): each item's id is the * DIRECTORY id the corpus keeps the recording under -- a Rumble embed id, which * the manifest cites, becomes its URL slug's directory (recording-ids.mjs) -- * and `mapped` lists the ids that changed. * * @param {{ id: string, dir: string }} project * @param {{ reason?: string | null, take?: string | null, localIds?: boolean }} [opts] */ export async function projectFetchBody(project, { reason = null, take = null, localIds = false } = {}) { let manifestPath = path.join(project.dir, MANIFEST_FILE); let manifest; if (take) { const [{ resolveTakeManifest }, { takesDirOf, TAKE_FILE }] = await Promise.all([import("./takeManifest.mjs"), import("./takes.mjs")]); manifest = (await resolveTakeManifest(project.dir, take)).manifest; manifestPath = path.join(takesDirOf(project.dir), take, TAKE_FILE); } else { manifest = JSON.parse(await readFile(manifestPath, "utf8")); } const rulings = await readMontageRulings(project.dir); const built = fetchWindowsBody(manifest, { manifestPath, project: project.id, rulings, reason }); if (!localIds) return { manifest, manifestPath, ...built, mapped: [] }; const { withLocalIds } = await import("umtool-report-to-video/recording-ids"); const local = await withLocalIds(built.body.items); return { manifest, manifestPath, ...built, body: { ...built.body, items: local.items }, mapped: local.mapped }; } // --------------------------------------------------------------------------- // The editor. // --------------------------------------------------------------------------- /** * Where the editor is and the token to ask it with. * @param {Record<string, string | undefined>} [env] */ export function editorConfig(env = process.env) { return { url: String(env.ARCHILYZER_EDITOR_URL ?? DEFAULT_EDITOR).replace(/\/+$/, ""), token: agentToken(env), }; } export class EditorError extends Error { /** @param {string} message @param {number} [status] */ constructor(message, status = 502) { super(message); this.status = status; } } /** * One request to the editor. Throws EditorError with the editor's own words. * @param {{ url: string, token: string, fetch?: typeof fetch }} cfg * @param {string} route * @param {{ method?: string, body?: unknown, auth?: boolean }} [opts] */ async function ask(cfg, route, { method = "GET", body, auth = true } = {}) { if (auth && !cfg.token) { throw new EditorError("WORKER_TOKEN is not set here, so the editor cannot be asked (set it to the editor's own value)", 503); } const f = cfg.fetch ?? fetch; let res; try { res = await f(`${cfg.url}${route}`, { method, headers: { ...(auth ? { authorization: `Bearer ${cfg.token}` } : {}), ...(body !== undefined ? { "content-type": "application/json" } : {}) }, ...(body !== undefined ? { body: JSON.stringify(body) } : {}), cache: "no-store", }); } catch (e) { throw new EditorError(`could not reach the editor at ${cfg.url}: ${e instanceof Error ? e.message : String(e)}`, 502); } const j = await res.json().catch(() => ({})); if (!res.ok || j?.ok === false) { throw new EditorError(`the editor refused (HTTP ${res.status}): ${j?.error ?? "no reason given"}`, res.status >= 400 && res.status < 500 ? res.status : 502); } return j; } /** * POST /api/ops/fetch-windows — the dry run or the start. * @param {{ url: string, token: string, fetch?: typeof fetch }} cfg * @param {Record<string, any>} body * @param {{ dryRun?: boolean }} [opts] */ export function postFetchWindows(cfg, body, { dryRun = false } = {}) { return ask(cfg, "/api/ops/fetch-windows", { method: "POST", body: dryRun ? { ...body, dryRun: true } : body }); } /** * POST /api/ops/evict-clips, targeted: `{slug, id, covering, tiers}` -> `{jobId}`. * `tiers` is "plain" or "tiered" (refetchTiers): a refetch removes only the * windows its project reads, never the other kind. * @param {{ url: string, token: string, fetch?: typeof fetch }} cfg * @param {{ slug: string, id: string, covering: { from: number, to: number }[], tiers?: "plain" | "tiered" }} req * @param {{ dryRun?: boolean }} [opts] */ export function postEvictClips(cfg, { slug, id, covering, tiers }, { dryRun = false } = {}) { return ask(cfg, "/api/ops/evict-clips", { method: "POST", body: { slug, id, covering, ...(tiers ? { tiers } : {}), ...(dryRun ? { dryRun: true } : {}) } }); } /** * Which windows a refetch evicts (the height tier): a TALL project's body asks * a height (`maxHeight`, tallWindowCap) and evicts only the taller tiered * windows of its spans — the plain 720 window a site's evidence reads stays; * any other project evicts the plain windows only, as before the tier. Pure. * @param {{ maxHeight?: number }} body * @returns {"plain" | "tiered"} */ export const refetchTiers = (body) => (body?.maxHeight !== undefined ? "tiered" : "plain"); /** * Mark the body's items a refetch evicts for (`refetch: true`, in place): the * items of each request's video whose span overlaps one it evicts. The editor * then does not answer them with a lower held window on a tall project. * @param {{ items: Record<string, any>[] }} body * @param {{ slug: string, id: string, covering: { from: number, to: number }[] }[]} requests */ export function markRefetched(body, requests) { for (const it of body.items) { const hit = requests.some( (r) => r.slug === it.slug && sameVideo(r.id, it.id) && r.covering.some((c) => c.from < it.to && it.from < c.to), ); if (hit) it.refetch = true; } return body; } // `evicting <slug>/<id>/<name> (…)` / `would evict …` — the line // common/controller/evictClipWindows.ts logs for each window. const EVICT_LINE = /^\s*(?:would evict|evicting) [^/\s]+\/[^/\s]+\/(\S+) /; const EVICT_SUMMARY = /^\s*((?:Would evict|Evicted) \d+ window.*)$/; /** * The windows an evict-clips job named (evicted, or would have), and its summary sentence. * @param {string} log */ export function parseEvictLog(log) { const windows = []; let summary = null; for (const line of String(log ?? "").split("\n")) { const m = EVICT_LINE.exec(line); if (m) windows.push(m[1]); const s = EVICT_SUMMARY.exec(line); if (s) summary = s[1].trim(); } return { windows, summary }; } /** GET /api/ops/job/<id>: `{job: {id, status, progress?, queue?}}`. */ export function jobStatus(cfg, jobId) { return ask(cfg, `/api/ops/job/${encodeURIComponent(jobId)}`); } /** The job's whole log (`GET /api/jobs/<id>/log`, the route every run panel reads). */ export async function jobLog(cfg, jobId) { const j = await ask(cfg, `/api/jobs/${encodeURIComponent(jobId)}/log?from=0`, { auth: false }); return String(j?.content ?? ""); } export const TERMINAL = new Set(["done", "failed", "cancelled", "interrupted"]); // ` ✗ <slug>/<id> <from>–<to> (<clipId>): <class> — <message>` — the line // common/controller/fetchWindows.ts logs for each window that failed. const FAILED_LINE = /^\s*✗ ([^/\s]+)\/(\S+) (\d+(?:\.\d+)?)–(\d+(?:\.\d+)?)(?: \(([^)]+)\))?: (\S+) — (.*)$/; /** * The windows a fetch-windows job failed, from its log. * @param {string} log * @returns {{ slug: string, id: string, from: number, to: number, clipId: string | null, class: string, message: string }[]} */ export function parseFailedWindows(log) { const out = []; for (const line of String(log ?? "").split("\n")) { const m = FAILED_LINE.exec(line); if (!m) continue; out.push({ slug: m[1], id: m[2], from: Number(m[3]), to: Number(m[4]), clipId: m[5] ?? null, class: m[6], message: m[7].trim() }); } return out; } /** * The editor's answer, said the way the panel and the CLI show it. * @param {Record<string, any>} a */ export function summarizeAnswer(a) { const label = (i) => i?.clipId ?? `${i?.slug}/${i?.id}`; return { dryRun: !!a?.dryRun, groups: (a?.groups ?? []).map((g) => ({ platform: g.platform, queueKey: g.queueKey ?? null, items: Array.isArray(g.items) ? g.items.length : Number(g.items ?? 0), ...(g.storedUrlItems !== undefined ? { storedUrlItems: Number(g.storedUrlItems) } : {}), })), cached: (a?.cached ?? []).map(label), inFlight: (a?.inFlight ?? []).map((f) => ({ clipId: label(f.item), jobId: f.jobId })), unresolved: (a?.unresolved ?? []).map((u) => ({ clipId: label(u.item), slug: u.item?.slug, id: u.item?.id, error: String(u.error ?? "") })), refused: (a?.refused ?? []).map((r) => ({ platform: r.platform, items: Number(r.items ?? 0), error: String(r.error ?? "") })), // Cached windows LOWER than the height asked, used as they are, and why. lower: (a?.lower ?? []).map((l) => ({ clipId: label(l.item), file: String(l.file ?? ""), height: Number.isFinite(Number(l.height)) && l.height !== null ? Number(l.height) : null, asked: Number(l.asked), why: String(l.why ?? ""), })), ...(Number.isFinite(Number(a?.clampedFrom)) ? { clampedFrom: Number(a.clampedFrom) } : {}), // THE RECORDING'S END (lane window-end): windows asked past the end of a // saved recording known whole, cut from it clamped at that end. atRecordingEnd: (a?.atRecordingEnd ?? []).map((e) => ({ clipId: label(e.item), askedTo: Number(e.askedTo), cutTo: Number(e.cutTo), why: String(e.why ?? ""), })), jobs: (a?.jobs ?? []).map((j) => ({ platform: j.platform, queueKey: j.queueKey ?? null, jobId: j.jobId, items: Number(j.items ?? 0) })), }; } // --------------------------------------------------------------------------- // fetch-runs.json — one writer, queued, tmp + rename. // --------------------------------------------------------------------------- let queue = Promise.resolve(); /** @template T @param {() => Promise<T>} fn @returns {Promise<T>} */ function withRunsLock(fn) { const run = queue.then(fn, fn); queue = run.then( () => undefined, () => undefined, ); return run; } /** `{runs: []}` when there is no file; throws on one that does not parse (never read as empty). */ export async function readFetchRuns(projectDir) { let text; try { text = await readFile(path.join(projectDir, FETCH_RUNS_FILE), "utf8"); } catch (e) { if (/** @type {NodeJS.ErrnoException} */ (e)?.code === "ENOENT") return { runs: [] }; throw e; } const doc = JSON.parse(text); if (!isObj(doc) || !Array.isArray(doc.runs)) throw new Error(`${FETCH_RUNS_FILE} is not {runs: [...]}`); return doc; } async function writeRuns(projectDir, doc) { const file = path.join(projectDir, FETCH_RUNS_FILE); await mkdir(projectDir, { recursive: true }); const tmp = tmpPathFor(file); await writeFile(tmp, JSON.stringify(doc, null, 1) + "\n", "utf8"); await rename(tmp, file); } /** * Record a run (the dry run or the start). * @param {string} projectDir * @param {{ body: Record<string, any>, answer: Record<string, any>, refetch?: Record<string, any>[] | null, take?: string | null, now?: Date }} r * `refetch`: what a `--refetch` evicted first (one entry per video). * `take`: the run asked for a take's clips (`umtool fetch --take`); recorded on the run. */ export function recordFetchRun(projectDir, { body, answer, refetch = null, take = null, now = new Date() }) { return withRunsLock(async () => { const doc = await readFetchRuns(projectDir); const summary = summarizeAnswer(answer); const run = { at: now.toISOString(), bodyHash: bodyHash(body), dryRun: summary.dryRun, items: (body.items ?? []).length, jobIds: summary.jobs.map((j) => j.jobId), summary, ...(refetch ? { refetch } : {}), ...(take ? { take } : {}), }; doc.runs.push(run); doc.runs = doc.runs.slice(-FETCH_RUNS_KEPT); await writeRuns(projectDir, doc); return run; }); } /** * Record how one job of a run ended, and the windows it failed. * @param {string} projectDir * @param {string} jobId * @param {{ status: string, platform?: string | null, failed: ReturnType<typeof parseFailedWindows>, now?: Date }} outcome */ export function recordJobOutcome(projectDir, jobId, { status, platform = null, failed, now = new Date() }) { return withRunsLock(async () => { const doc = await readFetchRuns(projectDir); const run = [...doc.runs].reverse().find((r) => Array.isArray(r.jobIds) && r.jobIds.includes(jobId)); if (!run) return null; run.jobs = { ...(run.jobs ?? {}), [jobId]: { status, platform: platform ?? run.summary?.jobs?.find((j) => j.jobId === jobId)?.platform ?? null, failed, at: now.toISOString() } }; await writeRuns(projectDir, doc); return run; }); } /** * The newest run that started jobs, or null: of the cut (no `take`), or of * that take -- a take's run is never read as the cut's last, nor the other way. */ export const lastStartedRun = (doc, { take = null } = {}) => [...(doc?.runs ?? [])].reverse().find((r) => !r.dryRun && r.jobIds?.length && (r.take ?? null) === (take ?? null)) ?? null; /** * Follow a run's jobs once: each job not yet recorded as ended is asked for its * status; one that has ended has its log read and its outcome recorded. Returns * every job's state (`progress` while it runs). * * @param {{ url: string, token: string, fetch?: typeof fetch }} cfg * @param {string} projectDir * @param {{ jobIds: string[], jobs?: Record<string, any>, summary?: any }} run */ export async function followRun(cfg, projectDir, run) { const states = []; for (const jobId of run.jobIds ?? []) { const known = run.jobs?.[jobId]; if (known && TERMINAL.has(known.status)) { states.push({ jobId, status: known.status, platform: known.platform ?? null, failed: known.failed ?? [] }); continue; } const j = await jobStatus(cfg, jobId); const status = String(j?.job?.status ?? "unknown"); const platform = run.summary?.jobs?.find((x) => x.jobId === jobId)?.platform ?? null; if (TERMINAL.has(status)) { const failed = parseFailedWindows(await jobLog(cfg, jobId).catch(() => "")); await recordJobOutcome(projectDir, jobId, { status, platform, failed }); states.push({ jobId, status, platform, failed }); } else { states.push({ jobId, status, platform, ...(j?.job?.progress ? { progress: j.job.progress } : {}), ...(j?.job?.queue ? { queue: j.job.queue } : {}) }); } } return states; } /** One request to the editor's ops (`ask` above): the ingredient rail's other editor actions (lib/ingredients/actions.mjs). */ export { ask as askEditorOps };