Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 416a90a723c02e9a72b84486d1e1e912998c7597
parent 908b3568ca357fb7f7cc9e369c8875648706d59a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 18 Oct 2026 22:54:14 -0400

umtool: Fetch windows from umtool -- `umtool fetch` and a button on the Cut tab and the clip deck (release 35 O1, slice 3)

The editor's fetch-windows body built from the manifest the way the
orchestrator built it by hand: {requestedBy: "umtool:<project>", manifest:
<abs path>, storedUrl: "fallback", items: [{slug, id, from, to, clipId, pad,
reason}]} -- the build's fetch span (start/end for a phrase seed), pad 3 as
provenance, reason "<title> montage" (or the title; --reason overrides).
Clips the montage rulings leave out are not asked for. `umtool fetch
<project> [--body | --dry-run | --wait | --status]`; the button runs the dry
run (groups per platform, cached, in flight, unresolved), Start (one paced job
per platform queue) and follows the jobs (`GET /api/ops/job/<id>`), naming the
windows a job failed (read from its log). Each run is recorded in
<project>/fetch-runs.json for the stand-in step. Checked: `umtool fetch
quartering-oopsie --body --reason "oopsie montage"` equals the hand-built
windows.json exactly; without --reason, everything but the reason.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Aumtool/app/api/report/fetch-windows/route.ts | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/bin/umtool.mjs | 7+++++++
Mumtool/components/projects/ClipDeckPage.tsx | 7+++++++
Mumtool/components/projects/report/CutTab.tsx | 11+++++++++++
Aumtool/components/projects/report/FetchWindowsPanel.tsx | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/ClipDeck.tsx | 4++++
Aumtool/lib/report/fetchCli.mjs | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/fetchWindows.mjs | 343+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/fetchWindows.test.mjs | 199+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
9 files changed, 1034 insertions(+), 0 deletions(-)

diff --git a/umtool/app/api/report/fetch-windows/route.ts b/umtool/app/api/report/fetch-windows/route.ts @@ -0,0 +1,79 @@ +import { projectRef } from "@/lib/projects"; +import { + EditorError, + editorConfig, + followRun, + lastStartedRun, + postFetchWindows, + projectFetchBody, + readFetchRuns, + recordFetchRun, + summarizeAnswer, +} from "@/lib/report/fetchWindows.mjs"; + +export const dynamic = "force-dynamic"; + +// FETCH WINDOWS (release 35 O1): the project's clip windows asked of the editor +// as ONE fetch-windows batch — the Cut tab's and the clip deck's button, and +// `umtool fetch` from a terminal (lib/report/fetchWindows.mjs builds the body +// for both). The editor fetches, paces and writes; this asks and records each +// run in <project>/fetch-runs.json. The token never reaches the browser. +// +// GET ?project=<id> the body's size, what is skipped, the +// last run, whether this umtool can ask +// POST { project, action: "dry-run" } the editor's plan: groups per platform, +// cached, in flight, unresolved +// POST { project, action: "start" } one paced job per platform queue +// POST { project, action: "follow" } the last started run's jobs, once: their +// status and progress; an ended job's +// refused windows read from its log +const headers = { "cache-control": "no-store" }; + +function fail(e: unknown) { + if (e instanceof EditorError) return Response.json({ error: e.message }, { status: e.status, headers }); + return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers }); +} + +export async function GET(request: Request) { + const url = new URL(request.url); + const project = await projectRef(url.searchParams.get("project") ?? ""); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + try { + const { body, skipped } = await projectFetchBody(project); + const runs = (await readFetchRuns(project.dir)).runs; + const cfg = editorConfig(); + return Response.json( + { project: project.id, configured: !!cfg.token, editor: cfg.url, items: body.items.length, skipped, lastRun: lastStartedRun({ runs }), runs: runs.length }, + { headers }, + ); + } catch (e) { + return fail(e); + } +} + +export async function POST(request: Request) { + const b = (await request.json().catch(() => null)) as Record<string, unknown> | null; + if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); + const project = await projectRef(String(b.project ?? "")); + if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + const action = String(b.action ?? ""); + const cfg = editorConfig(); + try { + if (action === "follow") { + const run = lastStartedRun(await readFetchRuns(project.dir)); + if (!run) return Response.json({ error: "no fetch run has started jobs yet" }, { status: 404, headers }); + const jobs = await followRun(cfg, project.dir, run); + return Response.json({ run: { at: run.at, jobIds: run.jobIds, summary: run.summary }, jobs }, { headers }); + } + if (action !== "dry-run" && action !== "start") { + return Response.json({ error: 'action must be "dry-run", "start" or "follow"' }, { status: 400, headers }); + } + const { body, skipped } = await projectFetchBody(project); + if (!body.items.length) return Response.json({ error: "no clip windows to fetch" }, { status: 400, headers }); + const answer = await postFetchWindows(cfg, body, { dryRun: action === "dry-run" }); + const run = await recordFetchRun(project.dir, { body, answer }); + return Response.json({ items: body.items.length, skipped, summary: summarizeAnswer(answer), run }, { headers }); + } catch (e) { + return fail(e); + } +} diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -52,6 +52,8 @@ // umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway] // umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>] // the clip deck's montage rulings (release 34) +// umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] the clip windows, asked of +// the editor as one fetch-windows batch (release 35) // umtool phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] // [--samples N] [--no-cache] [--json|--full] how often each was said, by year (one pass) // umtool voice-match <project> [--reference auto|rulings|recordings] [--instances F] [--dry] [--json] @@ -727,6 +729,9 @@ function usage() { " umtool takes make <project> [--recipe F | --all-styles] | styles | pick <project> <take> [--anyway]", " umtool rulings <project> [--json] | import [--dry-run] | set <clip> keep|cut|not-him|read-aloud [--reason R] [--match M] | clear <clip>", " the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out", + " umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] [--json]", + " the clip windows asked of the editor as one fetch-windows batch (one paced job per platform);", + " each run recorded in <project>/fetch-runs.json", " umtool phrases \"<phrase>\" [\"<phrase>\" …] --channels a,b [--prefer c] [--exclude RE] [--words|--regex] [--json]", " how often each phrase was said, by year, in one pass (the phrase finder's search)", " umtool voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …] [--instances F] [--dry] [--json]", @@ -769,6 +774,8 @@ const COMMANDS = { takes: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takesCommand(argv.slice(argv.indexOf("takes") + 1))), // The clip deck's rulings (release 34): lib/report/rulingsCli.mjs. rulings: async () => process.exit(await (await import("../lib/report/rulingsCli.mjs")).rulingsCommand(argv.slice(argv.indexOf("rulings") + 1))), + // Fetch windows and stand-ins (release 35 O1): lib/report/fetchCli.mjs, standInsCli.mjs. + fetch: async () => process.exit(await (await import("../lib/report/fetchCli.mjs")).fetchCommand(argv.slice(argv.indexOf("fetch") + 1))), // The phrase finder (release 34): lib/phrase-finder/cli.mjs. phrases: async () => process.exit(await (await import("../lib/phrase-finder/cli.mjs")).phrasesCommand(argv.slice(argv.indexOf("phrases") + 1))), // Who is speaking, per montage clip (release 34): lib/report/voiceMatch.mjs. diff --git a/umtool/components/projects/ClipDeckPage.tsx b/umtool/components/projects/ClipDeckPage.tsx @@ -6,6 +6,8 @@ import type { ProjectRef } from "@/lib/project-types"; import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; import ClipDeck from "./review/ClipDeck"; import VoiceMatchPanel from "./report/VoiceMatchPanel"; +import FetchWindowsPanel from "./report/FetchWindowsPanel"; +import { lastStartedRun, projectFetchBody, readFetchRuns } from "@/lib/report/fetchWindows.mjs"; import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; // `/projects/<project>/clips` -- THE CLIP DECK (release 34 N1): a montage's @@ -39,6 +41,10 @@ export default async function ClipDeckPage({ project, show }: { project: Project : view.cards.every((c) => view.rulings[c.key]) ? "all" : "unruled"; + // Fetch windows (release 35): every kept clip's window, asked of the editor. + const fetchBody = await projectFetchBody(project) + .then(async ({ body, skipped }) => ({ items: body.items.length, skipped: skipped.length, lastRun: lastStartedRun(await readFetchRuns(project.dir)) })) + .catch(() => null); return ( <BenchFrame kind="clips" top={top}> <ClipDeck @@ -48,6 +54,7 @@ export default async function ClipDeckPage({ project, show }: { project: Project back={back} takesHref={takesHref(project.id)} voicePanel={<VoiceMatchPanel project={project.id} summary={voiceMatchSummary(await readVoiceMatch(project.dir))} reload />} + fetchPanel={fetchBody ? <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} /> : null} /> </BenchFrame> ); diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx @@ -15,6 +15,8 @@ import { clipRecord, storedUrlOf } from "@/lib/clips/stored"; import { RowControls, RowNotes, TimelineList } from "../TimelineEditor"; import { Pill, TONE, hms, type ReportTabProps } from "./shared"; import VoiceMatchPanel from "./VoiceMatchPanel"; +import FetchWindowsPanel from "./FetchWindowsPanel"; +import { lastStartedRun, projectFetchBody, readFetchRuns } from "@/lib/report/fetchWindows.mjs"; import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs"; import { clipMomentKey } from "umtool-report-to-video/montage-rulings"; @@ -66,6 +68,14 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor return montage.filter((e) => !doc.rulings[keys.get(e.id) ?? ""]).length; }) : 0; + // Fetch windows (release 35): the body the button sends, sized here; a run + // still going is followed when the page opens. A rulings file that does not + // parse leaves the button out (the clip deck says what is wrong with it). + const fetchBody = clips.length + ? await projectFetchBody(project) + .then(async ({ body, skipped }) => ({ items: body.items.length, skipped: skipped.length, lastRun: lastStartedRun(await readFetchRuns(project.dir)) })) + .catch(() => null) + : null; // Who is speaking, per clip (release 34): voice-match.json, keyed by the // source moment (clipMomentKey, the rulings' key), so a re-seed keeps its scores. const voices = await readVoiceMatch(project.dir); @@ -173,6 +183,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor summary={voiceMatchSummary(voices)} /> )} + {fetchBody && <FetchWindowsPanel project={project.id} items={fetchBody.items} skipped={fetchBody.skipped} lastRun={fetchBody.lastRun} />} </div> {/* --- the timeline --------------------------------------------- */} diff --git a/umtool/components/projects/report/FetchWindowsPanel.tsx b/umtool/components/projects/report/FetchWindowsPanel.tsx @@ -0,0 +1,223 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; + +// --------------------------------------------------------------------------- +// "Fetch windows" (release 35 O1): every clip's window asked of the editor as +// ONE fetch-windows batch (lib/report/fetchWindows.mjs; `umtool fetch` is the +// same body from a terminal). The dry run first — the groups per platform, +// what is already on disk, what a job already fetches, what the editor cannot +// resolve — then Start: one paced job per platform queue, followed here until +// each ends, and the windows a job refused named. The editor does the fetching; +// this page never touches the network itself. +// --------------------------------------------------------------------------- + +type Summary = { + dryRun: boolean; + groups: { platform: string; queueKey: string | null; items: number; storedUrlItems?: number }[]; + cached: string[]; + inFlight: { clipId: string; jobId: string }[]; + unresolved: { clipId: string; error: string }[]; + refused: { platform: string; items: number; error: string }[]; + jobs: { platform: string; jobId: string; items: number }[]; +}; +type Failure = { clipId: string | null; slug: string; id: string; class: string; message: string }; +type JobState = { jobId: string; status: string; platform: string | null; progress?: { done?: number; total?: number }; queue?: { position?: number }; failed?: Failure[] }; +type LastRun = { at: string; jobIds: string[]; jobs?: Record<string, { status: string }> } | null; + +const ENDED = new Set(["done", "failed", "cancelled", "interrupted"]); + +export default function FetchWindowsPanel({ + project, + items, + skipped = 0, + lastRun = null, + onSettled, +}: { + project: string; + /** How many windows the body asks for. */ + items: number; + /** How many clips it leaves out (ruled out, no video). */ + skipped?: number; + /** The last run that started jobs (fetch-runs.json), to follow on load. */ + lastRun?: LastRun; + /** Called once every job has ended, with the windows they failed. */ + onSettled?: (failed: Failure[]) => void; +}) { + const [plan, setPlan] = useState<Summary | null>(null); + const [started, setStarted] = useState<Summary | null>(null); + const [jobs, setJobs] = useState<JobState[] | null>(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState<string | null>(null); + const alive = useRef(true); + useEffect(() => () => void (alive.current = false), []); + + const post = async (action: string) => { + const r = await fetch("/api/report/fetch-windows", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ project, action }), + cache: "no-store", + }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`); + return j; + }; + + const follow = useCallback(async () => { + for (;;) { + if (!alive.current) return; + let j: { jobs: JobState[] }; + try { + j = await post("follow"); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + return; + } + setJobs(j.jobs); + if (j.jobs.every((s) => ENDED.has(s.status))) { + onSettled?.(j.jobs.flatMap((s) => s.failed ?? [])); + return; + } + await new Promise((r) => setTimeout(r, 3000)); + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [project]); + + // A run still going when the page opened: follow it. + useEffect(() => { + if (lastRun && lastRun.jobIds.some((id) => !ENDED.has(lastRun.jobs?.[id]?.status ?? ""))) void follow(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + async function dryRun() { + setBusy(true); + setError(null); + setStarted(null); + try { + setPlan((await post("dry-run")).summary); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + } + + async function start() { + setBusy(true); + setError(null); + try { + const j = await post("start"); + setStarted(j.summary); + setPlan(null); + if (j.summary.jobs.length) void follow(); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusy(false); + } + } + + const running = !!jobs && !jobs.every((s) => ENDED.has(s.status)); + const failed = (jobs ?? []).flatMap((s) => s.failed ?? []); + return ( + <div data-fetch-windows="" className="flex flex-col items-start gap-1.5"> + <div className="flex flex-wrap items-center gap-2"> + <button + type="button" + data-action="fetch-windows" + disabled={busy || running || items === 0} + onClick={() => void dryRun()} + className={buttonVariants({ size: "sm" })} + title="ask the editor for every clip's window: a dry run first" + > + Fetch windows + </button> + <span data-fetch-items={items} className="num text-[11px] text-[var(--color-dim)]"> + {items} window{items === 1 ? "" : "s"} + {skipped ? ` · ${skipped} skipped` : ""} + </span> + </div> + {plan && ( + <div data-fetch-plan="" className="w-full max-w-[560px] space-y-1 rounded-[4px] border border-seam bg-panel px-3 py-2 text-[12px] text-text-2"> + <Lines s={plan} /> + <div className="flex gap-2 pt-1"> + <button + type="button" + data-action="fetch-start" + disabled={busy || plan.groups.length === 0} + onClick={() => void start()} + className={buttonVariants({ variant: "go", size: "sm" })} + > + Start {plan.groups.reduce((n, g) => n + g.items, 0)} window{plan.groups.reduce((n, g) => n + g.items, 0) === 1 ? "" : "s"} + </button> + <button type="button" data-action="fetch-dismiss" onClick={() => setPlan(null)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Not now + </button> + </div> + </div> + )} + {started && ( + <div data-fetch-started="" className="w-full max-w-[560px] space-y-1 text-[12px] text-text-2"> + <Lines s={started} /> + </div> + )} + {jobs && ( + <ul data-fetch-jobs="" className="grid gap-0.5 font-mono text-[11.5px] text-text-2"> + {jobs.map((s) => ( + <li key={s.jobId} data-fetch-job={s.jobId} data-fetch-job-status={s.status}> + {s.platform ?? "job"} · {s.jobId} · {s.status} + {s.progress && Number.isFinite(Number(s.progress.done)) ? ` · ${s.progress.done}/${s.progress.total ?? "?"}` : ""} + {s.queue && Number(s.queue.position) > 0 ? ` · queued, position ${s.queue.position}` : ""} + </li> + ))} + </ul> + )} + {failed.length > 0 && ( + <ul data-fetch-failed-list="" className="grid gap-0.5 text-[11.5px] text-reject-text"> + {failed.map((f) => ( + <li key={`${f.slug}/${f.id}/${f.clipId}`} data-fetch-failed={f.clipId ?? `${f.slug}/${f.id}`}> + {f.clipId ?? `${f.slug}/${f.id}`}: {f.class} — {f.message} + </li> + ))} + </ul> + )} + {error && ( + <span role="alert" data-fetch-error="" className="text-[12px] text-reject-text"> + {error} + </span> + )} + </div> + ); +} + +function Lines({ s }: { s: Summary }) { + return ( + <> + {s.groups.map((g) => ( + <p key={g.platform} className="m-0" data-fetch-group={g.platform}> + {g.platform}: {g.items} window{g.items === 1 ? "" : "s"} to fetch{g.storedUrlItems ? ` (${g.storedUrlItems} from a stored media URL)` : ""} + </p> + ))} + <p className="m-0" data-fetch-cached={s.cached.length}> + {s.cached.length} already on disk + </p> + {s.inFlight.length > 0 && ( + <p className="m-0" data-fetch-inflight={s.inFlight.length}> + {s.inFlight.length} already being fetched ({[...new Set(s.inFlight.map((f) => f.jobId))].join(", ")}) + </p> + )} + {s.unresolved.map((u) => ( + <p key={u.clipId} className="m-0 text-reject-text" data-fetch-unresolved={u.clipId}> + {u.clipId}: {u.error} + </p> + ))} + {s.refused.map((r) => ( + <p key={r.platform} className="m-0 text-reject-text" data-fetch-refused={r.platform}> + {r.platform}: {r.items} not started — {r.error} + </p> + ))} + </> + ); +} diff --git a/umtool/components/projects/review/ClipDeck.tsx b/umtool/components/projects/review/ClipDeck.tsx @@ -112,6 +112,7 @@ export default function ClipDeck({ back, takesHref, voicePanel = null, + fetchPanel = null, }: { project: string; view: ClipDeckView; @@ -120,6 +121,8 @@ export default function ClipDeck({ takesHref: string; /** Release 34 N2's "Score the voices" (VoiceMatchPanel), shown in the head. */ voicePanel?: React.ReactNode; + /** Release 35's "Fetch windows" and stand-ins (FetchWindowsPanel / StandInsPanel), shown in the head. */ + fetchPanel?: React.ReactNode; }) { const cards = view.cards; const byId = useMemo(() => new Map(cards.map((c) => [c.id, c])), [cards]); @@ -453,6 +456,7 @@ export default function ClipDeck({ </p> )} {voicePanel} + {fetchPanel} </div> ); diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs @@ -0,0 +1,161 @@ +// `umtool fetch` (release 35 O1): a project's clip windows asked of the editor +// as one fetch-windows batch (lib/report/fetchWindows.mjs) — the dry run, the +// start, and the wait — the same body the Cut tab's and the clip deck's +// "Fetch windows" button sends. +// +// umtool fetch <project> --body the body, printed; the editor is not asked +// umtool fetch <project> --dry-run [--json] the editor's plan: groups per platform, cached, in flight, unresolved +// umtool fetch <project> [--wait] [--json] start it: one job per platform queue; --wait follows them to the end +// umtool fetch <project> --status [--json] the last run's jobs, followed once (what --wait polls) +// … [--reason "…"] the provenance reason (default: "<title> montage", or the title) +import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; +import { + EditorError, + FETCH_RUNS_FILE, + TERMINAL, + editorConfig, + followRun, + lastStartedRun, + postFetchWindows, + projectFetchBody, + readFetchRuns, + recordFetchRun, + summarizeAnswer, +} from "./fetchWindows.mjs"; + +export const FETCH_USAGE = [ + "usage: umtool fetch <project> --body the editor's fetch-windows body for the manifest, printed", + " umtool fetch <project> --dry-run [--json] what the editor would do: groups per platform, cached, unresolved", + " umtool fetch <project> [--wait] [--json] start it (one paced job per platform); --wait follows the jobs", + " umtool fetch <project> --status [--json] the last run's jobs, and the windows they failed", + " … [--reason \"…\"] the provenance reason (default \"<title> montage\" for a montage, else the title)", + "", + `Every run is recorded in <project>/${FETCH_RUNS_FILE}; \`umtool fallback\` reads it for the refused windows.`, + "The editor: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN (else the editor's env files).", +].join("\n"); + +class CliError extends Error {} + +const POLL_MS = Number(process.env.UMTOOL_FETCH_POLL_MS) > 0 ? Number(process.env.UMTOOL_FETCH_POLL_MS) : 5000; +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +/** The answer's summary as lines. */ +export function summaryLines(s) { + const lines = []; + for (const g of s.groups) lines.push(` ${g.platform.padEnd(10)} ${g.items} window(s)${g.storedUrlItems ? ` (${g.storedUrlItems} with a stored media URL)` : ""}`); + lines.push(` cached ${s.cached.length}${s.cached.length ? ` ${s.cached.join(" ")}` : ""}`); + if (s.inFlight.length) lines.push(` in flight ${s.inFlight.length} ${s.inFlight.map((f) => `${f.clipId} (job ${f.jobId})`).join(" ")}`); + for (const u of s.unresolved) lines.push(` unresolved ${u.clipId}: ${u.error}`); + for (const r of s.refused) lines.push(` refused ${r.platform}: ${r.items} window(s) — ${r.error}`); + for (const j of s.jobs) lines.push(` job ${j.jobId} ${j.platform}, ${j.items} window(s)`); + return lines; +} + +const stateLine = (st) => + ` ${st.jobId} ${String(st.platform ?? "").padEnd(8)} ${st.status}` + + (st.progress && Number.isFinite(Number(st.progress.done)) ? ` ${st.progress.done}/${st.progress.total ?? "?"}` : "") + + (st.queue && Number(st.queue.position) > 0 ? ` queued, position ${st.queue.position}` : "") + + (st.failed?.length ? ` ${st.failed.length} window(s) failed` : ""); + +/** + * @param {string[]} args the words after `fetch` + * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, cfg?: ReturnType<typeof editorConfig> & { fetch?: typeof fetch }, pollMs?: number }} [opts] + * @returns {Promise<number>} the exit code + */ +export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), cfg = editorConfig(), pollMs = POLL_MS } = {}) { + const json = args.includes("--json"); + const words = []; + let reason = null; + for (let i = 0; i < args.length; i += 1) { + if (args[i] === "--reason") { + reason = args[i + 1] ?? ""; + i += 1; + } else if (!args[i].startsWith("--")) words.push(args[i]); + } + try { + const [projectArg] = words; + if (!projectArg || args.includes("--help")) { + err(FETCH_USAGE); + return 2; + } + const r = await resolveProject(projectArg, root); + if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); + if (!r.project) throw new CliError(`no project matches "${projectArg}"`); + const project = r.project; + + if (args.includes("--status")) { + const run = lastStartedRun(await readFetchRuns(project.dir)); + if (!run) throw new CliError(`${project.id} has no started fetch run in ${FETCH_RUNS_FILE}`); + const states = await followRun(cfg, project.dir, run); + if (json) out(JSON.stringify({ project: project.id, run: { at: run.at, jobIds: run.jobIds }, jobs: states }, null, 2)); + else { + out(`${project.id}: the run of ${run.at}`); + for (const st of states) out(stateLine(st)); + for (const st of states) for (const f of st.failed ?? []) out(` ✗ ${f.clipId ?? `${f.slug}/${f.id}`}: ${f.class} — ${f.message}`); + } + return 0; + } + + const { body, skipped } = await projectFetchBody(project, { reason }); + if (args.includes("--body")) { + out(JSON.stringify(body, null, 1)); + return 0; + } + if (!body.items.length) { + out(`${project.id}: no clip windows to fetch${skipped.length ? ` (${skipped.length} skipped)` : ""}`); + return 0; + } + const dryRun = args.includes("--dry-run"); + const answer = await postFetchWindows(cfg, body, { dryRun }); + const run = await recordFetchRun(project.dir, { body, answer }); + const summary = summarizeAnswer(answer); + if (!dryRun && !args.includes("--wait")) { + if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...summary }, null, 2)); + else { + out(`${project.id}: ${body.items.length} window(s) asked${skipped.length ? `, ${skipped.length} skipped` : ""}`); + for (const l of summaryLines(summary)) out(l); + } + return summary.refused.length && !summary.jobs.length ? 1 : 0; + } + if (dryRun) { + if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...summary }, null, 2)); + else { + out(`${project.id}: ${body.items.length} window(s) — the dry run${skipped.length ? ` (${skipped.length} skipped: ${skipped.map((s) => `${s.clipId} ${s.why}`).join(", ")})` : ""}`); + for (const l of summaryLines(summary)) out(l); + } + return 0; + } + // --wait: follow every job to its end. + if (!json) { + out(`${project.id}: ${body.items.length} window(s) asked`); + for (const l of summaryLines(summary)) out(l); + } + let states = []; + const said = new Map(); + for (;;) { + states = await followRun(cfg, project.dir, { ...run, jobs: (await readFetchRuns(project.dir)).runs.find((x) => x.at === run.at && x.bodyHash === run.bodyHash)?.jobs }); + if (!json) { + for (const st of states) { + const line = stateLine(st); + if (said.get(st.jobId) !== line) out(line); + said.set(st.jobId, line); + } + } + if (states.every((st) => TERMINAL.has(st.status))) break; + await sleep(pollMs); + } + const failed = states.flatMap((st) => st.failed ?? []); + if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...summary, jobsEnded: states }, null, 2)); + else { + for (const f of failed) out(` ✗ ${f.clipId ?? `${f.slug}/${f.id}`}: ${f.class} — ${f.message}`); + if (failed.length) out(`${failed.length} window(s) failed — \`umtool fallback ${project.id} --dry-run\` finds a stand-in for each refused one`); + } + return states.some((st) => st.status !== "done") || summary.refused.length ? 1 : 0; + } catch (e) { + if (e instanceof CliError || e instanceof EditorError) { + err(e.message); + return 1; + } + throw e; + } +} diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs @@ -0,0 +1,343 @@ +// 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:<project>", manifest: <abs path of video.manifest.json>, +// 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. `pad` is provenance (the +// seconds each side that are margin): the fetchPad, else 3. `reason` is +// "<title> 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. +// +// 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 { agentToken } from "../annotations/agentAuth.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", 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; + } + items.push({ + slug, + id: e.video, + from: r2(Math.max(0, Number(e.start) - margin)), + to: r2(Number(e.end) + margin), + clipId: e.id, + pad: padOf, + reason: why.slice(0, REASON_LIMIT), + }); + } + return { + body: { requestedBy: `umtool:${project}`, manifest: path.resolve(manifestPath), storedUrl: "fallback", items }, + skipped, + }; +} + +/** 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. + * @param {{ id: string, dir: string }} project + * @param {{ reason?: string | null }} [opts] + */ +export async function projectFetchBody(project, { reason = null } = {}) { + const manifestPath = path.join(project.dir, MANIFEST_FILE); + const manifest = JSON.parse(await readFile(manifestPath, "utf8")); + const rulings = await readMontageRulings(project.dir); + return { manifest, manifestPath, ...fetchWindowsBody(manifest, { manifestPath, project: project.id, rulings, reason }) }; +} + +// --------------------------------------------------------------------------- +// 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 }); +} + +/** 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 ?? "") })), + 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 = `${file}.${process.pid}.${Date.now()}.tmp`; + 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>, now?: Date }} r + */ +export function recordFetchRun(projectDir, { body, answer, 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, + }; + 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. */ +export const lastStartedRun = (doc) => [...(doc?.runs ?? [])].reverse().find((r) => !r.dryRun && r.jobIds?.length) ?? 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; +} diff --git a/umtool/lib/report/fetchWindows.test.mjs b/umtool/lib/report/fetchWindows.test.mjs @@ -0,0 +1,199 @@ +// Fetch windows from umtool (release 35 O1): the body is the one the +// orchestrator built by hand from the manifest; runs are recorded in +// fetch-runs.json; a job's refused windows are read from its log. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { + bodyHash, + fetchWindowsBody, + followRun, + lastStartedRun, + parseFailedWindows, + projectFetchBody, + readFetchRuns, + recordFetchRun, + summarizeAnswer, +} from "./fetchWindows.mjs"; +import { fetchCommand } from "./fetchCli.mjs"; + +// A phrase-seeded montage, as `umtool new --seed phrase` writes one (fetchPad 0). +const MANIFEST = { + schemaVersion: 1, + slug: "synth-oops", + title: "Oops reel", + provenance: { siteOrigin: "", channelSlug: "synth-rumble" }, + render: { fetchPad: 0, transition: 0 }, + timeline: [ + { type: "clip", id: "s01", channel: "synth-yt", video: "yt1", start: 55.81, end: 63.87, cutStart: 58.31, cutEnd: 61.37, montage: { n: 1, of: 3 } }, + { type: "clip", id: "s02", channel: "synth-rumble", video: "v2abc", start: 0, end: 7.5, cutStart: 2, cutEnd: 5, montage: { n: 2, of: 3 } }, + { type: "card", id: "t0", heading: "not a clip" }, + { type: "clip", id: "s03", video: "v2def", start: 100.256, end: 104.1, cutStart: 102.756, cutEnd: 101.6, montage: { n: 3, of: 3 } }, + ], +}; + +// The orchestrator's hand-built body (the python that made windows.json). +const handBuilt = (m, manifestPath, project, reason) => ({ + requestedBy: `umtool:${project}`, + manifest: manifestPath, + storedUrl: "fallback", + items: m.timeline + .filter((e) => e.type === "clip") + .map((e) => ({ slug: e.channel ?? m.provenance.channelSlug, id: e.video, from: Number(e.start.toFixed(2)), to: Number(e.end.toFixed(2)), clipId: e.id, pad: 3, reason })), +}); + +test("the body is the hand-built body: every clip's window, the project's provenance, key order and all", () => { + const manifestPath = "/x/reports/synth-oops/video.manifest.json"; + const { body, skipped } = fetchWindowsBody(MANIFEST, { manifestPath, project: "synth-oops" }); + assert.deepEqual(skipped, []); + const want = handBuilt(MANIFEST, manifestPath, "synth-oops", "Oops reel montage"); + assert.equal(JSON.stringify(body), JSON.stringify(want)); + // --reason overrides the provenance sentence and nothing else. + const own = fetchWindowsBody(MANIFEST, { manifestPath, project: "synth-oops", reason: "oops montage" }).body; + assert.equal(JSON.stringify(own), JSON.stringify(handBuilt(MANIFEST, manifestPath, "synth-oops", "oops montage"))); + // Key order never changes the hash. + const shuffled = { items: want.items.map((i) => Object.fromEntries(Object.entries(i).reverse())), storedUrl: "fallback", manifest: manifestPath, requestedBy: "umtool:synth-oops" }; + assert.equal(bodyHash(shuffled), bodyHash(want)); +}); + +test("a report video (no montage): the title as the reason, the build's own fetch pad; a src clip and a ruled-out clip are skipped", () => { + const m = { + title: "The ferret cut", + provenance: { channelSlug: "chan" }, + render: {}, + timeline: [ + { type: "clip", id: "a1", video: "v1", start: 1, end: 10 }, + { type: "clip", id: "a2", src: "local.mp4", start: 0, end: 3 }, + ], + }; + const { body, skipped } = fetchWindowsBody(m, { manifestPath: "/r/p/video.manifest.json", project: "p" }); + assert.deepEqual(body.items, [{ slug: "chan", id: "v1", from: 0, to: 13, clipId: "a1", pad: 3, reason: "The ferret cut" }]); + assert.deepEqual(skipped, [{ clipId: "a2", why: "no channel or video (a src clip)" }]); + const ruled = fetchWindowsBody(MANIFEST, { + manifestPath: "/r/p/video.manifest.json", + project: "p", + rulings: { rulings: { "synth-rumble/v2abc@2.00": { verdict: "not-him" }, "synth-yt/yt1@58.31": { verdict: "keep" } } }, + }); + assert.deepEqual(ruled.body.items.map((i) => i.clipId), ["s01", "s03"]); + assert.deepEqual(ruled.skipped, [{ clipId: "s02", why: "ruled not-him" }]); +}); + +test("a job's refused windows, from its log", () => { + const log = [ + "Fetch windows: 3 window(s) for umtool:synth-oops · /x/video.manifest.json", + " = synth-yt/yt1 55.81–63.87 (s01): cached in clips/55.81-63.87.mp4", + "Sleeping 121s before the next fetch...", + " ✗ synth-rumble/v2abc 0.00–7.50 (s02): network — HTTP Error 403: Forbidden (the embed lookup)", + " ✗ synth-rumble/v2def 100.26–104.10: unavailable — Video unavailable", + "Fetch windows: 0 fetched, 1 cached, 2 failed.", + ].join("\n"); + assert.deepEqual(parseFailedWindows(log), [ + { slug: "synth-rumble", id: "v2abc", from: 0, to: 7.5, clipId: "s02", class: "network", message: "HTTP Error 403: Forbidden (the embed lookup)" }, + { slug: "synth-rumble", id: "v2def", from: 100.26, to: 104.1, clipId: null, class: "unavailable", message: "Video unavailable" }, + ]); +}); + +/** A fake editor: routes -> answers, every request recorded. */ +function fakeEditor(routes) { + const seen = []; + const f = async (url, init = {}) => { + const u = new URL(url); + const key = `${init.method ?? "GET"} ${u.pathname}`; + seen.push({ key, body: init.body ? JSON.parse(init.body) : null, auth: init.headers?.authorization ?? null }); + const r = typeof routes[key] === "function" ? routes[key](init.body ? JSON.parse(init.body) : null) : routes[key]; + if (!r) return new Response(JSON.stringify({ ok: false, error: "not found" }), { status: 404 }); + return new Response(JSON.stringify(r), { status: 200, headers: { "content-type": "application/json" } }); + }; + return { fetch: f, seen }; +} + +test("umtool fetch: the dry run, the start, --wait to the end; each run in fetch-runs.json with its jobs' refused windows", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "umtool-fetch-")); + try { + const dir = path.join(root, "synth-oops"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2)); + let polls = 0; + const ed = fakeEditor({ + "POST /api/ops/fetch-windows": (b) => + b.dryRun + ? { ok: true, dryRun: true, groups: [{ platform: "youtube", queueKey: "clips:youtube", items: [b.items[0]] }, { platform: "rumble", queueKey: "clips:rumble", items: b.items.slice(1), storedUrlItems: 0 }], cached: [], inFlight: [], unresolved: [] } + : { ok: true, dryRun: false, groups: [], cached: [b.items[0]], inFlight: [], unresolved: [], refused: [], jobs: [{ platform: "rumble", queueKey: "clips:rumble", jobId: "J1", items: 2 }], jobIds: ["J1"], jobId: "J1" }, + "GET /api/ops/job/J1": () => ({ ok: true, job: { id: "J1", status: ++polls < 2 ? "running" : "failed", progress: { done: 1, total: 2 } } }), + "GET /api/jobs/J1/log": { content: " ✗ synth-rumble/v2abc 0.00–7.50 (s02): network — HTTP Error 403: Forbidden\n", nextOffset: 10, status: "archived" }, + }); + const cfg = { url: "http://editor.test", token: "tok", fetch: ed.fetch }; + const lines = []; + const run = (args) => fetchCommand(args, { root, out: (s) => lines.push(s), err: (s) => lines.push(s), cfg, pollMs: 1 }); + + assert.equal(await run(["synth-oops", "--body"]), 0); + const printed = JSON.parse(lines.join("\n")); + assert.equal(printed.items.length, 3); + assert.equal(printed.manifest, path.join(dir, "video.manifest.json")); + assert.equal(ed.seen.length, 0, "--body asks nobody"); + + lines.length = 0; + assert.equal(await run(["synth-oops", "--dry-run"]), 0); + assert.equal(ed.seen[0].body.dryRun, true); + assert.equal(ed.seen[0].auth, "Bearer tok"); + assert.match(lines.join("\n"), /youtube {4}1 window\(s\)/); + assert.match(lines.join("\n"), /rumble {5}2 window\(s\)/); + + lines.length = 0; + assert.equal(await run(["synth-oops", "--wait"]), 1, "a failed job is exit 1"); + assert.equal("dryRun" in ed.seen[1].body, false); + assert.match(lines.join("\n"), /✗ s02: network — HTTP Error 403: Forbidden/); + assert.match(lines.join("\n"), /umtool fallback synth-oops --dry-run/); + + const doc = await readFetchRuns(dir); + assert.equal(doc.runs.length, 2); + assert.equal(doc.runs[0].dryRun, true); + assert.deepEqual(doc.runs[0].jobIds, []); + assert.deepEqual(doc.runs[0].summary.groups, [{ platform: "youtube", queueKey: "clips:youtube", items: 1 }, { platform: "rumble", queueKey: "clips:rumble", items: 2, storedUrlItems: 0 }]); + assert.equal(doc.runs[0].bodyHash, doc.runs[1].bodyHash); + const started = lastStartedRun(doc); + assert.deepEqual(started.jobIds, ["J1"]); + assert.deepEqual(started.summary.cached, ["s01"]); + assert.equal(started.jobs.J1.status, "failed"); + assert.deepEqual(started.jobs.J1.failed.map((f) => [f.clipId, f.class]), [["s02", "network"]]); + + // An ended job is never asked again. + const before = ed.seen.length; + const states = await followRun(cfg, dir, started); + assert.equal(ed.seen.length, before); + assert.equal(states[0].status, "failed"); + + // No token: said in the editor's terms, nothing posted. + lines.length = 0; + assert.equal(await fetchCommand(["synth-oops", "--dry-run"], { root, out: (s) => lines.push(s), err: (s) => lines.push(s), cfg: { ...cfg, token: "" } }), 1); + assert.match(lines.join("\n"), /WORKER_TOKEN is not set here/); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test("projectFetchBody reads the rulings beside the manifest; summarizeAnswer names what the editor said", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "umtool-fetch-")); + try { + const dir = path.join(root, "p"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST)); + await writeFile(path.join(dir, "montage-rulings.json"), JSON.stringify({ version: 1, rulings: { "synth-yt/yt1@58.31": { verdict: "cut", reason: "", at: "2026-10-18T00:00:00.000Z" } } })); + const { body, skipped } = await projectFetchBody({ id: "p", dir }); + assert.deepEqual(body.items.map((i) => i.clipId), ["s02", "s03"]); + assert.deepEqual(skipped, [{ clipId: "s01", why: "ruled cut" }]); + const s = summarizeAnswer({ ok: true, dryRun: false, cached: [], inFlight: [{ item: body.items[0], jobId: "J0" }], unresolved: [{ item: body.items[1], error: "the recording is deleted" }], refused: [{ platform: "rumble", error: "held", items: 2 }], jobs: [] }); + assert.deepEqual(s.inFlight, [{ clipId: "s02", jobId: "J0" }]); + assert.deepEqual(s.unresolved, [{ clipId: "s03", slug: "synth-rumble", id: "v2def", error: "the recording is deleted" }]); + assert.deepEqual(s.refused, [{ platform: "rumble", items: 2, error: "held" }]); + // recordFetchRun keeps a bounded history. + for (let k = 0; k < 3; k++) await recordFetchRun(dir, { body, answer: { ok: true, dryRun: true }, now: new Date(Date.UTC(2026, 9, 18, 0, k)) }); + const doc = JSON.parse(await readFile(path.join(dir, "fetch-runs.json"), "utf8")); + assert.equal(doc.runs.length, 3); + assert.equal(doc.runs[2].at, "2026-10-18T00:02:00.000Z"); + } finally { + await rm(root, { recursive: true, force: true }); + } +});