// 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, parseEvictLog, parseFailedWindows, projectFetchBody, readFetchRuns, recordFetchRun, refetchEvictions, 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 }); } }); test("refetchEvictions: a clip resolves to the very span the body fetches (pad included), grouped per video", () => { const padded = { ...MANIFEST, render: { fetchPad: 2, transition: 0 }, timeline: [...MANIFEST.timeline, { type: "clip", id: "s04", channel: "synth-yt", video: "yt1", start: 200, end: 210 }] }; const { body, skipped } = fetchWindowsBody(padded, { manifestPath: "/x/m.json", project: "p" }); const r = refetchEvictions(body, skipped, { clipIds: ["s01", "s04", "s02"] }); assert.ok(r.ok); assert.deepEqual(r.requests, [ { slug: "synth-yt", id: "yt1", covering: [{ from: 53.81, to: 65.87 }, { from: 198, to: 212 }], clipIds: ["s01", "s04"] }, { slug: "synth-rumble", id: "v2abc", covering: [{ from: 0, to: 9.5 }], clipIds: ["s02"] }, ]); // --refetch-video: every span the project asks of that video, once. const v = refetchEvictions(body, skipped, { clipIds: ["s01"], videos: ["synth-yt/yt1"] }); assert.ok(v.ok); assert.deepEqual(v.requests.map((q) => q.clipIds), [["s01", "s04"]]); // A Twitch record id and its directory id are one video. const tw = fetchWindowsBody({ timeline: [{ type: "clip", id: "z01", channel: "tw", video: "2912435200", start: 10, end: 20 }], render: { fetchPad: 0 } }, { manifestPath: "/x/m.json", project: "p" }); assert.ok(refetchEvictions(tw.body, tw.skipped, { videos: ["tw/v2912435200"] }).ok); // Refusals say why. assert.match(refetchEvictions(body, skipped, { clipIds: ["nope"] }).error, /no clip "nope"/); assert.match(refetchEvictions(body, [{ clipId: "s09", why: "ruled cut" }], { clipIds: ["s09"] }).error, /not fetched by this project \(ruled cut\)/); assert.match(refetchEvictions(body, skipped, { videos: ["synth-yt"] }).error, /takes \//); assert.match(refetchEvictions(body, skipped, { videos: ["synth-yt/other"] }).error, /asks for no window of synth-yt\/other/); }); test("umtool fetch --refetch: evict-clips {slug, id, covering} first, waited for; then the fetch; the run records what went", 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 evictPolls = 0; const ed = fakeEditor({ "POST /api/ops/evict-clips": (b) => ({ ok: true, jobId: b.dryRun ? "E0" : "E1" }), "GET /api/ops/job/E0": { ok: true, job: { id: "E0", status: "done" } }, "GET /api/ops/job/E1": () => ({ ok: true, job: { id: "E1", status: ++evictPolls < 2 ? "running" : "done" } }), "GET /api/jobs/E0/log": { content: "would evict synth-rumble/v2abc/0.00-9.00.mp4 (1 KB, last touched 2026-10-28)\nWould evict 1 window(s), 1 KB across 1 video(s) in 1 channel(s); 0 other window(s) (0 B) left alone.\n" }, "GET /api/jobs/E1/log": { content: "evicting synth-rumble/v2abc/0.00-9.00.mp4 (1 KB, last touched 2026-10-28)\nEvicted 1 window(s), 1 KB across 1 video(s) in 1 channel(s); 0 other window(s) (0 B) left alone.\n" }, "POST /api/ops/fetch-windows": (b) => ({ ok: true, dryRun: !!b.dryRun, groups: [], cached: [], inFlight: [], unresolved: [], refused: [], jobs: b.dryRun ? [] : [{ platform: "rumble", jobId: "J1", items: 1 }] }), "GET /api/ops/job/J1": { ok: true, job: { id: "J1", status: "done" } }, "GET /api/jobs/J1/log": { content: "" }, }); 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", "--refetch", "s02", "--dry-run"]), 0); assert.deepEqual(ed.seen[0], { key: "POST /api/ops/evict-clips", body: { slug: "synth-rumble", id: "v2abc", covering: [{ from: 0, to: 7.5 }], tiers: "plain", dryRun: true }, auth: "Bearer tok" }); assert.equal(ed.seen.at(-1).key, "POST /api/ops/fetch-windows"); assert.equal(ed.seen.at(-1).body.dryRun, true); assert.match(lines.join("\n"), /would evict for s02 \(synth-rumble\/v2abc, job E0\): 0\.00-9\.00\.mp4/); ed.seen.length = 0; lines.length = 0; assert.equal(await run(["synth-oops", "--refetch", "s02", "--wait"]), 0); const keys = ed.seen.map((x) => x.key); // The fetch is asked only after the eviction job has ended. assert.equal(keys.indexOf("POST /api/ops/fetch-windows") > keys.lastIndexOf("GET /api/ops/job/E1"), true); assert.equal("dryRun" in ed.seen[0].body, false); const doc = await readFetchRuns(dir); const last = doc.runs.at(-1); assert.deepEqual(last.refetch, [{ slug: "synth-rumble", id: "v2abc", clipIds: ["s02"], covering: [{ from: 0, to: 7.5 }], dryRun: false, jobId: "E1", status: "done", windows: ["0.00-9.00.mp4"] }]); assert.deepEqual(last.jobIds, ["J1"]); // An unknown clip is refused before the editor is asked. ed.seen.length = 0; lines.length = 0; assert.equal(await run(["synth-oops", "--refetch", "zz9"]), 1); assert.equal(ed.seen.length, 0); assert.match(lines.join("\n"), /no clip "zz9"/); assert.deepEqual(parseEvictLog("evicting a/b/1.00-2.00.desynced.mp4 (x)\n").windows, ["1.00-2.00.desynced.mp4"]); } finally { await rm(root, { recursive: true, force: true }); } }); test("a gap-joined clip is fetched per kept piece, each padded at its own edges -- never the hours between", () => { // Two moments of one stream joined by a gap: 5385–5400 and 21800–21812. const joined = { type: "clip", id: "j01", channel: "synth-tw", video: "2468013579", start: 5385, end: 21812, gaps: [{ from: 5400, to: 21800 }] }; const short = { type: "clip", id: "j02", channel: "synth-tw", video: "2468013579", start: 100, end: 130, gaps: [{ from: 110, to: 112.5 }] }; const m = { title: "Pieces", render: { fetchPad: 3, transition: 0 }, timeline: [joined, short] }; const { body } = fetchWindowsBody(m, { manifestPath: "/r/p/video.manifest.json", project: "p" }); assert.deepEqual( body.items.map((i) => [i.clipId, i.from, i.to]), [ ["j01", 5382, 5403], ["j01", 21797, 21815], // A short gap: one span, the padded extent, as before. ["j02", 97, 133], ], ); const asked = body.items.filter((i) => i.clipId === "j01").reduce((s, i) => s + (i.to - i.from), 0); assert.ok(asked < 60, `the joined clip asks for ${asked}s, not ${21815 - 5382}s`); // A refetch of the clip evicts both of its pieces. const r = refetchEvictions(body, [], { clipIds: ["j01"] }); assert.ok(r.ok); assert.deepEqual(r.requests, [{ slug: "synth-tw", id: "2468013579", covering: [{ from: 5382, to: 5403 }, { from: 21797, to: 21815 }], clipIds: ["j01"] }]); // A montage cuts every clip to its phrase, so applies no gaps: the whole extent. const montage = fetchWindowsBody({ ...m, render: { ...m.render, montage: {} }, timeline: [joined] }, { manifestPath: "/r/p/video.manifest.json", project: "p" }); assert.deepEqual(montage.body.items.map((i) => [i.from, i.to]), [[5382, 21815]]); }); // THE HEIGHT TIER: the body asks for the height the cut renders from, and the // editor's answer says which clips stayed lower and why -- printed by `umtool fetch`. test("a tall project's body carries its maxHeightSource as maxHeight; the answer's lower clips are summarized and printed", async () => { const { summaryLines } = await import("./fetchCli.mjs"); const tall = { ...MANIFEST, render: { ...MANIFEST.render, tallWindows: true, maxHeightSource: 1080 } }; const { body } = fetchWindowsBody(tall, { manifestPath: "/x/m.json", project: "p" }); assert.equal(body.maxHeight, 1080); // Without the knob, no height, whatever maxHeightSource says. assert.equal(fetchWindowsBody({ ...MANIFEST, render: { maxHeightSource: 1080 } }, { manifestPath: "/x/m.json", project: "p" }).body.maxHeight, undefined); assert.equal(fetchWindowsBody({ ...MANIFEST, render: { tallWindows: true, maxHeightSource: 99 } }, { manifestPath: "/x/m.json", project: "p" }).body.maxHeight, undefined); const s = summarizeAnswer({ cached: [{ slug: "synth-yt", id: "yt1", clipId: "s01" }], lower: [{ item: { slug: "synth-yt", id: "yt1", clipId: "s01" }, file: "55.81-63.87.mp4", height: 720, asked: 1080, why: "no saved copy of the recording to cut a taller one from" }], clampedFrom: 2160, }); assert.deepEqual(s.lower, [{ clipId: "s01", file: "55.81-63.87.mp4", height: 720, asked: 1080, why: "no saved copy of the recording to cut a taller one from" }]); assert.equal(s.clampedFrom, 2160); const lines = summaryLines(s); assert.ok(lines.includes(" lower s01: 720p (asked 1080p) in 55.81-63.87.mp4 — no saved copy of the recording to cut a taller one from")); assert.ok(lines.some((l) => /2160p asked; the editor's clips\.windowMaxHeight/.test(l))); assert.deepEqual(summarizeAnswer({}).lower, []); }); // THE RECORDING'S END (lane window-end): the editor plans the last clip's // window on the saved-video queue, clamped at the recording's end, and the dry // run says so in those words. test("umtool fetch --dry-run: a window past a whole saved recording's end reads 'saved-video, clamped at the recording's end'", 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)); const ed = fakeEditor({ "POST /api/ops/fetch-windows": (b) => ({ ok: true, dryRun: true, groups: [{ platform: "saved-video", queueKey: "clips:saved-video", items: [b.items[1]] }], cached: [], inFlight: [], unresolved: [], atRecordingEnd: [{ item: b.items[1], askedTo: 7.5, cutTo: 6.96, why: "the saved recording ends at 6.96 s, the whole recording (its record's duration is 7 s, within 2 s)" }], }), }); const cfg = { url: "http://editor.test", token: "tok", fetch: ed.fetch }; const lines = []; assert.equal(await fetchCommand(["synth-oops", "--dry-run"], { root, out: (s) => lines.push(s), err: (s) => lines.push(s), cfg, pollMs: 1 }), 0); const text = lines.join("\n"); assert.match(text, /saved-video 1 window\(s\)/); assert.match(text, /at end {5}s02: saved-video, clamped at the recording's end \(asked to 7\.50, cut to 6\.96\) — the saved recording ends at 6\.96 s/); const doc = await readFetchRuns(dir); assert.deepEqual(doc.runs[0].summary.atRecordingEnd, [{ clipId: "s02", askedTo: 7.5, cutTo: 6.96, why: "the saved recording ends at 6.96 s, the whole recording (its record's duration is 7 s, within 2 s)" }]); assert.deepEqual(summarizeAnswer({}).atRecordingEnd, []); } finally { await rm(root, { recursive: true, force: true }); } });