commit 5846ae957f7a78918f2fedcc21c758eaaeaf1201
parent d21d923c1569f5aacce8894a072f63dd7c18b1d9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 18 Oct 2026 23:38:13 -0400
Merge r35/montage-ops slices 1–3: phrase-scan alternates, the phrase seed's cap (--max N), Fetch windows from umtool (umtool fetch + button)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
19 files changed, 1998 insertions(+), 21 deletions(-)
diff --git a/common/lib/montage/fixtures/phraseScan.r34.json b/common/lib/montage/fixtures/phraseScan.r34.json
@@ -0,0 +1,600 @@
+[
+ {
+ "instances": [
+ {
+ "slug": "yt",
+ "videoId": "yt3",
+ "platform": "youtube",
+ "source": null,
+ "date": "20190502",
+ "title": "t yt3",
+ "duration": 900,
+ "start": 2,
+ "end": 5,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news week",
+ "context": ">> it must be a slow news week Well well-well, here we go",
+ "speakerCheck": true,
+ "availability": "public"
+ },
+ {
+ "slug": "other",
+ "videoId": "o1",
+ "platform": "youtube",
+ "source": null,
+ "date": "20220303",
+ "title": "t o1",
+ "duration": 300,
+ "start": 4,
+ "end": 10,
+ "cueFirst": 1,
+ "cueLast": 2,
+ "match": "slow news day",
+ "context": "nobody asked for this slow news day",
+ "speakerCheck": false,
+ "availability": "unlisted"
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r1",
+ "platform": "rumble",
+ "source": null,
+ "date": "20230102",
+ "title": "t r1",
+ "duration": 1000,
+ "start": 100,
+ "end": 103,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news day",
+ "context": "kind of a slow news day today folks well well well look at this",
+ "speakerCheck": false,
+ "alsoIn": [
+ {
+ "slug": "rumble",
+ "videoId": "r3",
+ "start": 5
+ }
+ ],
+ "availability": null
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r2",
+ "platform": "rumble",
+ "source": null,
+ "date": "20230301",
+ "title": "t r2",
+ "duration": 2000,
+ "start": 500,
+ "end": 506,
+ "cueFirst": 1,
+ "cueLast": 1,
+ "match": "slow news day",
+ "context": "so the admin tweeted a statement must be a really slow news day and no one asked for it",
+ "via": {
+ "slug": "yt",
+ "videoId": "yt2",
+ "start": 523,
+ "score": 0.86
+ },
+ "speakerCheck": false,
+ "availability": null
+ },
+ {
+ "slug": "yt",
+ "videoId": "yt4",
+ "platform": "youtube",
+ "source": null,
+ "date": "20260507",
+ "title": "t yt4",
+ "duration": 810,
+ "start": 769,
+ "end": 772,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news cycle",
+ "context": "don't get sucked into this it's uh slow news cycle panic",
+ "speakerCheck": false,
+ "availability": null
+ }
+ ],
+ "dropped": [
+ {
+ "slug": "rumble",
+ "videoId": "r4",
+ "platform": "rumble",
+ "source": null,
+ "date": "20240101",
+ "title": "t r4",
+ "duration": 900,
+ "start": 9,
+ "end": 12,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news week",
+ "context": "slow news week Jeremy says chat well, well, well",
+ "why": "matches the exclude pattern"
+ }
+ ]
+ },
+ {
+ "instances": [
+ {
+ "slug": "other",
+ "videoId": "o1",
+ "platform": "youtube",
+ "source": null,
+ "date": "20220303",
+ "title": "t o1",
+ "duration": 300,
+ "start": 1,
+ "end": 4,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "nobody asked",
+ "context": "nobody asked for this slow",
+ "speakerCheck": false,
+ "availability": "unlisted"
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r2",
+ "platform": "rumble",
+ "source": null,
+ "date": "20230301",
+ "title": "t r2",
+ "duration": 2000,
+ "start": 506,
+ "end": 509,
+ "cueFirst": 2,
+ "cueLast": 2,
+ "match": "nobody asked",
+ "context": "must be a really slow new state and nobody asked for it",
+ "speakerCheck": false,
+ "availability": null
+ }
+ ],
+ "dropped": []
+ },
+ {
+ "instances": [
+ {
+ "slug": "yt",
+ "videoId": "yt3",
+ "platform": "youtube",
+ "source": null,
+ "date": "20190502",
+ "title": "t yt3",
+ "duration": 900,
+ "start": 30,
+ "end": 33,
+ "cueFirst": 1,
+ "cueLast": 1,
+ "match": "Well well-well",
+ "context": ">> it must be a slow news week Well well-well, here we go",
+ "speakerCheck": true,
+ "availability": "public"
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r1",
+ "platform": "rumble",
+ "source": null,
+ "date": "20230102",
+ "title": "t r1",
+ "duration": 1000,
+ "start": 103,
+ "end": 106,
+ "cueFirst": 1,
+ "cueLast": 1,
+ "match": "well well well",
+ "context": "kind of a slow news day today folks well well well look at this",
+ "speakerCheck": false,
+ "availability": null
+ }
+ ],
+ "dropped": [
+ {
+ "slug": "rumble",
+ "videoId": "r4",
+ "platform": "rumble",
+ "source": null,
+ "date": "20240101",
+ "title": "t r4",
+ "duration": 900,
+ "start": 40,
+ "end": 40,
+ "cueFirst": 1,
+ "cueLast": 1,
+ "match": "well, well, well",
+ "context": "slow news week Jeremy says chat well, well, well",
+ "why": "matches the exclude pattern"
+ }
+ ]
+ },
+ {
+ "instances": [],
+ "dropped": []
+ },
+ {
+ "instances": [
+ {
+ "slug": "yt",
+ "videoId": "yt3",
+ "platform": "youtube",
+ "source": null,
+ "date": "20190502",
+ "title": "t yt3",
+ "duration": 900,
+ "start": 2,
+ "end": 5,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news week",
+ "context": ">> it must be a slow news week Well well-well, here we go",
+ "speakerCheck": true,
+ "availability": "public"
+ },
+ {
+ "slug": "other",
+ "videoId": "o1",
+ "platform": "youtube",
+ "source": null,
+ "date": "20220303",
+ "title": "t o1",
+ "duration": 300,
+ "start": 4,
+ "end": 10,
+ "cueFirst": 1,
+ "cueLast": 2,
+ "match": "slow news day",
+ "context": "nobody asked for this slow news day",
+ "speakerCheck": false,
+ "availability": "unlisted"
+ },
+ {
+ "slug": "yt",
+ "videoId": "yt1",
+ "platform": "youtube",
+ "source": null,
+ "date": "20230101",
+ "title": "t yt1",
+ "duration": 1010,
+ "start": 110,
+ "end": 113,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news day",
+ "context": "kind of a slow news day today folks",
+ "speakerCheck": false,
+ "alsoIn": [
+ {
+ "slug": "rumble",
+ "videoId": "r1",
+ "start": 100
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r3",
+ "start": 5
+ }
+ ],
+ "availability": null
+ },
+ {
+ "slug": "yt",
+ "videoId": "yt2",
+ "platform": "youtube",
+ "source": null,
+ "date": "20230301",
+ "title": "t yt2",
+ "duration": 2010,
+ "start": 523,
+ "end": 526,
+ "cueFirst": 1,
+ "cueLast": 1,
+ "match": "slow news day",
+ "context": "so the admin tweeted a statement must be a really slow news day and no one asked for it",
+ "speakerCheck": false,
+ "availability": null
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r4",
+ "platform": "rumble",
+ "source": null,
+ "date": "20240101",
+ "title": "t r4",
+ "duration": 900,
+ "start": 9,
+ "end": 12,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news week",
+ "context": "slow news week Jeremy says chat well, well, well",
+ "speakerCheck": false,
+ "availability": null
+ },
+ {
+ "slug": "yt",
+ "videoId": "yt4",
+ "platform": "youtube",
+ "source": null,
+ "date": "20260507",
+ "title": "t yt4",
+ "duration": 810,
+ "start": 769,
+ "end": 772,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news cycle",
+ "context": "don't get sucked into this it's uh slow news cycle panic",
+ "speakerCheck": false,
+ "availability": null
+ }
+ ],
+ "dropped": []
+ },
+ {
+ "instances": [
+ {
+ "slug": "other",
+ "videoId": "o1",
+ "platform": "youtube",
+ "source": null,
+ "date": "20220303",
+ "title": "t o1",
+ "duration": 300,
+ "start": 1,
+ "end": 4,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "nobody asked",
+ "context": "nobody asked for this slow",
+ "speakerCheck": false,
+ "availability": "unlisted"
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r2",
+ "platform": "rumble",
+ "source": null,
+ "date": "20230301",
+ "title": "t r2",
+ "duration": 2000,
+ "start": 506,
+ "end": 509,
+ "cueFirst": 2,
+ "cueLast": 2,
+ "match": "nobody asked",
+ "context": "must be a really slow new state and nobody asked for it",
+ "speakerCheck": false,
+ "alsoIn": [
+ {
+ "slug": "yt",
+ "videoId": "yt2",
+ "start": 526
+ }
+ ],
+ "availability": null
+ }
+ ],
+ "dropped": []
+ },
+ {
+ "instances": [
+ {
+ "slug": "yt",
+ "videoId": "yt3",
+ "platform": "youtube",
+ "source": null,
+ "date": "20190502",
+ "title": "t yt3",
+ "duration": 900,
+ "start": 30,
+ "end": 33,
+ "cueFirst": 1,
+ "cueLast": 1,
+ "match": "Well well-well",
+ "context": ">> it must be a slow news week Well well-well, here we go",
+ "speakerCheck": true,
+ "availability": "public"
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r1",
+ "platform": "rumble",
+ "source": null,
+ "date": "20230102",
+ "title": "t r1",
+ "duration": 1000,
+ "start": 103,
+ "end": 106,
+ "cueFirst": 1,
+ "cueLast": 1,
+ "match": "well well well",
+ "context": "kind of a slow news day today folks well well well look at this",
+ "speakerCheck": false,
+ "availability": null
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r4",
+ "platform": "rumble",
+ "source": null,
+ "date": "20240101",
+ "title": "t r4",
+ "duration": 900,
+ "start": 40,
+ "end": 40,
+ "cueFirst": 1,
+ "cueLast": 1,
+ "match": "well, well, well",
+ "context": "slow news week Jeremy says chat well, well, well",
+ "speakerCheck": false,
+ "availability": null
+ }
+ ],
+ "dropped": []
+ },
+ {
+ "instances": [],
+ "dropped": []
+ },
+ {
+ "instances": [
+ {
+ "slug": "other",
+ "videoId": "o1",
+ "platform": "youtube",
+ "source": null,
+ "date": "20220303",
+ "title": "t o1",
+ "duration": 300,
+ "start": 4,
+ "end": 10,
+ "cueFirst": 1,
+ "cueLast": 2,
+ "match": "slow news day",
+ "context": "nobody asked for this slow news day",
+ "speakerCheck": false,
+ "availability": "unlisted"
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r4",
+ "platform": "rumble",
+ "source": null,
+ "date": "20240101",
+ "title": "t r4",
+ "duration": 900,
+ "start": 9,
+ "end": 12,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news week",
+ "context": "slow news week Jeremy says chat well, well, well",
+ "speakerCheck": false,
+ "availability": null
+ }
+ ],
+ "dropped": [
+ {
+ "slug": "rumble",
+ "videoId": "r1",
+ "platform": "rumble",
+ "source": null,
+ "date": "20230102",
+ "title": "t r1",
+ "duration": 1000,
+ "start": 100,
+ "end": 103,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news day",
+ "context": "kind of a slow news day today folks well well well look at this",
+ "why": "matches the exclude pattern"
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r3",
+ "platform": "rumble",
+ "source": null,
+ "date": "20230104",
+ "title": "t r3",
+ "duration": 60,
+ "start": 5,
+ "end": 8,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "slow news day",
+ "context": "kind of a slow news day today folks",
+ "why": "matches the exclude pattern"
+ }
+ ]
+ },
+ {
+ "instances": [
+ {
+ "slug": "other",
+ "videoId": "o1",
+ "platform": "youtube",
+ "source": null,
+ "date": "20220303",
+ "title": "t o1",
+ "duration": 300,
+ "start": 1,
+ "end": 4,
+ "cueFirst": 0,
+ "cueLast": 0,
+ "match": "nobody asked",
+ "context": "nobody asked for this slow",
+ "speakerCheck": false,
+ "availability": "unlisted"
+ },
+ {
+ "slug": "rumble",
+ "videoId": "r2",
+ "platform": "rumble",
+ "source": null,
+ "date": "20230301",
+ "title": "t r2",
+ "duration": 2000,
+ "start": 506,
+ "end": 509,
+ "cueFirst": 2,
+ "cueLast": 2,
+ "match": "nobody asked",
+ "context": "must be a really slow new state and nobody asked for it",
+ "speakerCheck": false,
+ "availability": null
+ }
+ ],
+ "dropped": []
+ },
+ {
+ "instances": [
+ {
+ "slug": "rumble",
+ "videoId": "r4",
+ "platform": "rumble",
+ "source": null,
+ "date": "20240101",
+ "title": "t r4",
+ "duration": 900,
+ "start": 40,
+ "end": 40,
+ "cueFirst": 1,
+ "cueLast": 1,
+ "match": "well, well, well",
+ "context": "slow news week Jeremy says chat well, well, well",
+ "speakerCheck": false,
+ "availability": null
+ }
+ ],
+ "dropped": [
+ {
+ "slug": "rumble",
+ "videoId": "r1",
+ "platform": "rumble",
+ "source": null,
+ "date": "20230102",
+ "title": "t r1",
+ "duration": 1000,
+ "start": 103,
+ "end": 106,
+ "cueFirst": 1,
+ "cueLast": 1,
+ "match": "well well well",
+ "context": "kind of a slow news day today folks well well well look at this",
+ "why": "matches the exclude pattern"
+ }
+ ]
+ },
+ {
+ "instances": [],
+ "dropped": []
+ }
+]
diff --git a/common/lib/montage/phraseScan.d.mts b/common/lib/montage/phraseScan.d.mts
@@ -22,6 +22,17 @@ export type PhraseInstance = CueHit & {
availability?: string | null;
via?: { slug: string; videoId: string; start: number; score: number };
alsoIn?: { slug: string; videoId: string; start: number }[];
+ // Release 35: the other-channel hits folded into this instance, each its own
+ // moment on its own recording (an instance in `instances` always has the list).
+ alternates?: PhraseAlternate[];
+};
+export type PhraseAlternate = {
+ slug: string;
+ videoId: string;
+ start: number;
+ end: number;
+ platform: string | null;
+ availability: string | null;
};
export type PhraseScanResult = {
instances: PhraseInstance[];
@@ -60,6 +71,10 @@ export function phraseScanMany(opts: {
}): Promise<PhraseScanManyResult[]>;
export { phraseSourceOf, phraseWords, wordsPhraseSource } from "./phraseSource.mjs";
export function niceDate(s: unknown): string;
+export function capInstances<T extends { date?: string | null; speakerCheck?: boolean }>(
+ instances: T[],
+ max: number | null | undefined,
+): { kept: T[]; skipped: T[] };
export function instancesAsClips(
instances: PhraseInstance[],
opts?: { pad?: number; idPrefix?: string },
diff --git a/common/lib/montage/phraseScan.mjs b/common/lib/montage/phraseScan.mjs
@@ -259,7 +259,19 @@ async function foldHits({ hits, prefer, preferred, recordOf, ex, availability })
preferredHits.get(h.videoId).push(h);
}
- const placed = hits.filter((h) => h.slug === prefer).map((h) => ({ ...h }));
+ // The other-channel hits each instance stands for (release 35): a twin's hit
+ // its preferred copy already has, the hit a placed instance came from, and
+ // every hit folded into it — the copies a stand-in can be cut from.
+ const altsOf = new Map(); // placed entry -> its alternates
+ const placedOf = new Map(); // a preferred hit -> its placed copy
+ const placed = hits
+ .filter((h) => h.slug === prefer)
+ .map((h) => {
+ const c = { ...h };
+ placedOf.set(h, c);
+ altsOf.set(c, []);
+ return c;
+ });
for (const h of hits) {
if (h.slug === prefer) continue;
const day = dayNumber(h.date);
@@ -277,10 +289,15 @@ async function foldHits({ hits, prefer, preferred, recordOf, ex, availability })
}
const ctx = words(h.context);
// Its twin already has the hit: nothing to add.
- const covered = twins.some((id) =>
- (preferredHits.get(id) ?? []).some((p) => locateInCues([{ text: p.context }], ctx).score >= SAME_HIT_MIN_SCORE),
- );
- if (covered) continue;
+ let covered = null;
+ for (const id of twins) {
+ covered = (preferredHits.get(id) ?? []).find((p) => locateInCues([{ text: p.context }], ctx).score >= SAME_HIT_MIN_SCORE) ?? null;
+ if (covered) break;
+ }
+ if (covered) {
+ altsOf.get(placedOf.get(covered))?.push(alternateOf(h));
+ continue;
+ }
// Its twin's transcript says it in other words (a different track): place it there.
let moved = null;
const placeable = new Set(content(ctx)).size >= PLACE_MIN_WORDS;
@@ -305,7 +322,9 @@ async function foldHits({ hits, prefer, preferred, recordOf, ex, availability })
break;
}
}
- placed.push(moved ?? { ...h });
+ const entry = moved ?? { ...h };
+ altsOf.set(entry, moved ? [alternateOf(h)] : []);
+ placed.push(entry);
}
placed.sort((a, b) => String(a.date ?? "").localeCompare(String(b.date ?? "")) || (a.slug === prefer ? 0 : 1) - (b.slug === prefer ? 0 : 1) || a.start - b.start);
@@ -319,20 +338,117 @@ async function foldHits({ hits, prefer, preferred, recordOf, ex, availability })
});
if (twin) {
(twin.alsoIn ??= []).push({ slug: i.slug, videoId: i.videoId, start: i.start });
+ altsOf.get(twin.ref).push(alternateOf(i), ...altsOf.get(i));
continue;
}
if (ex?.test(i.context)) {
dropped.push({ ...i, why: "matches the exclude pattern" });
continue;
}
- instances.push({ ...i, speakerCheck: i.context.includes(">>") });
+ const inst = { ...i, speakerCheck: i.context.includes(">>") };
+ // Non-enumerable: never copied into the answer.
+ Object.defineProperty(inst, "ref", { value: i, enumerable: false });
+ instances.push(inst);
}
+ const availabilityFor = (slug, id) => (slug === prefer ? null : availability(slug, id));
for (const i of instances) {
- i.availability = i.slug === prefer ? null : await availability(i.slug, i.videoId);
+ i.availability = await availabilityFor(i.slug, i.videoId);
+ const seen = new Set();
+ const alternates = [];
+ for (const a of altsOf.get(i.ref) ?? []) {
+ const k = `${a.slug}/${a.videoId}`;
+ if ((a.slug === i.slug && a.videoId === i.videoId) || seen.has(k)) continue;
+ seen.add(k);
+ alternates.push({ ...a, availability: await availabilityFor(a.slug, a.videoId) });
+ }
+ i.alternates = alternates;
}
return { instances, dropped };
}
+/** An other-channel hit as an instance's alternate: its own moment on its own recording. */
+function alternateOf(h) {
+ return { slug: h.slug, videoId: h.videoId, start: h.start, end: h.end, platform: h.platform ?? null };
+}
+
+/**
+ * The cap (release 35, `max`): N of the instances, spread across the years in
+ * proportion to each year's count — at least one for every year that has any
+ * (largest-remainder rounding), or, when N is fewer than the years, one each
+ * for N years spread across them. Within a year the instances without a
+ * `speakerCheck` come first, picked evenly through the year (not its first
+ * few). `kept` and `skipped` are both chronological (the order given); an
+ * instance with no date is its own year, last. `max` absent, not a positive
+ * whole number, or ≥ the count → everything kept.
+ *
+ * @template T
+ * @param {T[]} instances chronological
+ * @param {number | null | undefined} max
+ * @returns {{ kept: T[], skipped: T[] }}
+ */
+export function capInstances(instances, max) {
+ const list = Array.isArray(instances) ? instances : [];
+ if (!(Number.isInteger(max) && max > 0) || max >= list.length) return { kept: [...list], skipped: [] };
+ const yearOf = (i) => /^(\d{4})/.exec(String(i?.date ?? ""))?.[1] ?? "~";
+ const byYear = new Map();
+ list.forEach((inst, k) => {
+ const y = yearOf(inst);
+ if (!byYear.has(y)) byYear.set(y, []);
+ byYear.get(y).push(k);
+ });
+ const years = [...byYear.keys()].sort();
+ const alloc = new Map(years.map((y) => [y, 0]));
+ if (max < years.length) {
+ for (const k of spreadIndices(years.length, max)) alloc.set(years[k], 1);
+ } else {
+ const quota = new Map(years.map((y) => [y, (max * byYear.get(y).length) / list.length]));
+ for (const y of years) alloc.set(y, Math.min(byYear.get(y).length, Math.max(1, Math.floor(quota.get(y)))));
+ let sum = years.reduce((n, y) => n + alloc.get(y), 0);
+ // How far a year is under its quota: at its floor, the remainder.
+ const under = (y) => quota.get(y) - alloc.get(y);
+ while (sum < max) {
+ // The largest remainder first (ties: the bigger year, then the earlier).
+ const y = years
+ .filter((y) => alloc.get(y) < byYear.get(y).length)
+ .sort((a, b) => under(b) - under(a) || byYear.get(b).length - byYear.get(a).length || a.localeCompare(b))[0];
+ alloc.set(y, alloc.get(y) + 1);
+ sum++;
+ }
+ while (sum > max) {
+ // The ≥ 1 floor overshot: take back from the most over-allotted year that keeps one.
+ const y = years
+ .filter((y) => alloc.get(y) > 1)
+ .sort((a, b) => under(a) - under(b) || byYear.get(b).length - byYear.get(a).length || b.localeCompare(a))[0];
+ alloc.set(y, alloc.get(y) - 1);
+ sum--;
+ }
+ }
+ const keep = new Set();
+ for (const y of years) {
+ const n = alloc.get(y);
+ if (!n) continue;
+ const ks = byYear.get(y);
+ const clean = ks.filter((k) => !list[k]?.speakerCheck);
+ const checked = ks.filter((k) => list[k]?.speakerCheck);
+ if (n <= clean.length) for (const j of spreadIndices(clean.length, n)) keep.add(clean[j]);
+ else {
+ for (const k of clean) keep.add(k);
+ for (const j of spreadIndices(checked.length, n - clean.length)) keep.add(checked[j]);
+ }
+ }
+ const kept = [];
+ const skipped = [];
+ list.forEach((inst, k) => (keep.has(k) ? kept : skipped).push(inst));
+ return { kept, skipped };
+}
+
+/** `n` of `0..len-1`, evenly spread (the middle of each of n equal stretches). */
+function spreadIndices(len, n) {
+ const out = [];
+ for (let j = 0; j < n; j++) out.push(Math.min(len - 1, Math.floor(((j + 0.5) * len) / n)));
+ return out;
+}
+
/**
* Many phrases in ONE pass over the transcripts (release 34): each cue file is
* read and parsed once, its text joined once, and every phrase matched in it.
diff --git a/common/lib/montage/phraseScan.test.ts b/common/lib/montage/phraseScan.test.ts
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import test from "node:test";
-import { dayNumber, hitsInCues, instancesAsClips, niceDate, phraseRegExp, phraseScan } from "./phraseScan.mjs";
+import { capInstances, dayNumber, hitsInCues, instancesAsClips, niceDate, phraseRegExp, phraseScan } from "./phraseScan.mjs";
const PHRASE = String.raw`\bslow[\s,.\-]+news\b(?:[\s,.\-]+(?:day|week|cycle))?`;
@@ -110,3 +110,63 @@ test("dates and the phrase", () => {
assert.equal(dayNumber("nope"), null);
assert.throws(() => phraseRegExp(" "), /phrase is required/);
});
+
+// Release 35: the cap. N instances spread across years in proportion to each
+// year's count (≥ 1 per year that has any; largest remainder), chronological,
+// the ones without a speakerCheck first within a year, spread through it.
+type I = { id: string; date: string | null; speakerCheck?: boolean };
+const inst = (spec: Record<string, number>, checked: string[] = []): I[] => {
+ const out: I[] = [];
+ for (const [year, n] of Object.entries(spec)) {
+ for (let k = 0; k < n; k++) {
+ const id = `${year}-${String(k).padStart(2, "0")}`;
+ out.push({ id, date: year === "none" ? null : `${year}${String(1 + (k % 12)).padStart(2, "0")}15`, speakerCheck: checked.includes(id) });
+ }
+ }
+ return out.sort((a, b) => String(a.date ?? "~").localeCompare(String(b.date ?? "~")) || a.id.localeCompare(b.id));
+};
+const years = (l: I[]) => l.reduce<Record<string, number>>((m, i) => ((m[i.id.slice(0, 4)] = (m[i.id.slice(0, 4)] ?? 0) + 1), m), {});
+
+test("capInstances: proportional to each year, at least one each, largest remainder, chronological", () => {
+ const all = inst({ 2019: 2, 2020: 30, 2021: 10, 2022: 1, 2023: 7 });
+ const { kept, skipped } = capInstances(all, 10);
+ assert.equal(kept.length, 10);
+ assert.equal(skipped.length, all.length - 10);
+ // 50 instances, 10 kept: quotas 0.4, 6, 2, 0.2, 1.4 -> floors with a floor of one 1, 6, 2, 1, 1 = 11 -> one back
+ // from a year above one at its quota (2020 and 2021 tie at 0; the bigger year gives it up).
+ assert.deepEqual(years(kept), { 2019: 1, 2020: 5, 2021: 2, 2022: 1, 2023: 1 });
+ const order = all.map((i) => i.id);
+ const pos = (l: I[]) => l.map((i) => order.indexOf(i.id));
+ assert.deepEqual(pos(kept), [...pos(kept)].sort((a, b) => a - b), "kept is chronological");
+ assert.deepEqual(pos(skipped), [...pos(skipped)].sort((a, b) => a - b), "skipped is chronological");
+ assert.deepEqual(new Set([...kept, ...skipped].map((i) => i.id)), new Set(order));
+ // Largest remainder: 20 of the same 50 -> 0.8, 12, 4, 0.4, 2.8 -> 1, 12, 4, 1, 2 = 20.
+ assert.deepEqual(years(capInstances(all, 20).kept), { 2019: 1, 2020: 12, 2021: 4, 2022: 1, 2023: 2 });
+ // 24 -> 0.96, 14.4, 4.8, 0.48, 3.36 -> 1, 14, 4, 1, 3 = 23, +1 to 2021 (.8 under).
+ assert.deepEqual(years(capInstances(all, 24).kept), { 2019: 1, 2020: 14, 2021: 5, 2022: 1, 2023: 3 });
+});
+
+test("capInstances: spread through the year, not its first few; the speaker-checked last", () => {
+ const all = inst({ 2020: 12 }, ["2020-00", "2020-06"]);
+ const { kept } = capInstances(all, 3);
+ // Ten clean ones, three spread through them (the middle of each third): clean #1, #5, #8.
+ assert.deepEqual(kept.map((i) => i.id), ["2020-02", "2020-07", "2020-10"]);
+ assert.ok(kept.every((i) => !i.speakerCheck));
+ // More asked than clean: every clean one, then the checked.
+ const few = inst({ 2021: 4 }, ["2021-00", "2021-01", "2021-02"]);
+ // The one clean (03) and the middle of the three checked (01), chronological.
+ assert.deepEqual(capInstances(few, 2).kept.map((i) => i.id), ["2021-01", "2021-03"]);
+});
+
+test("capInstances: fewer than the years -> one each for years spread across them; no cap -> all", () => {
+ const all = inst({ 2016: 3, 2017: 3, 2018: 3, 2019: 3, 2020: 3, 2021: 3 });
+ assert.deepEqual(Object.keys(years(capInstances(all, 3).kept)), ["2017", "2019", "2021"]);
+ for (const max of [undefined, null, 0, -1, 2.5, 18, 100]) {
+ const r = capInstances(all, max as number);
+ assert.equal(r.kept.length, 18);
+ assert.deepEqual(r.skipped, []);
+ }
+ // A dateless instance is its own year, last.
+ const mixed = [...inst({ 2020: 4 }), { id: "none-00", date: null }];
+ assert.ok(capInstances(mixed, 2).kept.some((i) => i.id === "none-00"));
+});
diff --git a/common/lib/montage/phraseScanMany.test.ts b/common/lib/montage/phraseScanMany.test.ts
@@ -179,3 +179,61 @@ test("plain words become a tolerant whole-word pattern", () => {
assert.throws(() => phraseSourceOf("slow (news"), /not a regular expression/);
assert.throws(() => wordsPhraseSource("!!"), /phrase is required/);
});
+
+// Release 35: every instance records its alternates — the other-channel hits
+// folded into it. Everything else is what release 34 answered: the snapshot
+// fixtures/phraseScan.r34.json was made by release 34's phraseScan over this
+// same corpus, and the new answer minus `alternates` equals it.
+test("alternates: the old answer is the new one minus alternates (every option set, every phrase, both scanners)", async () => {
+ const dir = corpus(VIDEOS);
+ const want = JSON.parse(readFileSync(path.join(import.meta.dirname, "fixtures", "phraseScan.r34.json"), "utf8"));
+ const strip = (r: { instances: Record<string, unknown>[]; dropped: unknown[] }) => ({
+ instances: r.instances.map(({ alternates, ...rest }) => {
+ assert.ok(Array.isArray(alternates), "every instance carries its alternates");
+ return rest;
+ }),
+ dropped: r.dropped,
+ });
+ try {
+ let k = 0;
+ for (const opts of [
+ { channels: ["yt", "other"], prefer: "rumble", exclude: String.raw`slow news \w+,? jeremy` },
+ { channels: ["yt", "other", "rumble"], prefer: null, exclude: null },
+ { channels: ["other"], prefer: "rumble", exclude: "today" },
+ ]) {
+ const many = await phraseScanMany({ channelsDir: dir, ...opts, phrases: PHRASES });
+ for (const [j, p] of PHRASES.entries()) {
+ const alone = await phraseScan({ channelsDir: dir, ...opts, phrase: p.phrase });
+ assert.deepEqual(strip(alone), want[k], `${p.id} with ${JSON.stringify(opts)}`);
+ assert.deepEqual(strip(many[j]), want[k], `${p.id} (many) with ${JSON.stringify(opts)}`);
+ k++;
+ }
+ }
+ assert.equal(k, want.length);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test("alternates: a twin's covered hit, the hit a placed instance came from, a folded upload — each with its own moment", async () => {
+ const dir = corpus(VIDEOS);
+ try {
+ const r = await phraseScan({ channelsDir: dir, channels: ["yt", "other"], prefer: "rumble", phrase: SLOW });
+ const by = (id: string) => r.instances.find((i) => i.videoId === id)!;
+ // r1 has the hit itself: yt1 (its twin) is covered, r3 (a clip upload) folds in.
+ assert.deepEqual(by("r1").alternates, [
+ { slug: "yt", videoId: "yt1", start: 110, end: 113, platform: "youtube", availability: null },
+ { slug: "rumble", videoId: "r3", start: 5, end: 8, platform: "rumble", availability: null },
+ ]);
+ // r2 was placed from yt2's hit: yt2 is the alternate, at yt2's own moment.
+ assert.equal(by("r2").via?.videoId, "yt2");
+ assert.deepEqual(by("r2").alternates, [{ slug: "yt", videoId: "yt2", start: 523, end: 526, platform: "youtube", availability: null }]);
+ // No twin, nothing folded: none.
+ assert.deepEqual(by("yt3").alternates, []);
+ // Availability is read for an alternate as for an instance.
+ const o = await phraseScan({ channelsDir: dir, channels: ["other", "yt"], prefer: null, phrase: String.raw`\b(?:no ?one|nobody) (?:asked|was asking)\b` });
+ assert.ok(o.instances.every((i) => Array.isArray(i.alternates)));
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
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]
@@ -707,7 +709,8 @@ function usage() {
" --seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>]: every time",
" the phrase was said in those channels' transcripts, chronological, cut from the --prefer",
" channel's copy where it has one (a twin by date and duration); a context matching --exclude",
- " is left out; the scan beside the manifest as phrase-scan.json",
+ " is left out; the scan beside the manifest as phrase-scan.json; --max N keeps N instances",
+ " spread across the years in proportion (the rest: phrase-scan.json \"skippedByCap\")",
" [--brand archilyzer-media] render.brand: the report-to-video brand preset",
" umtool doctor [--json] exit 1 if the report pipeline is missing a tool",
" or the media root is set and not there; the roots, and a leftover old cache",
@@ -726,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]",
@@ -768,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.
@@ -1122,7 +1130,7 @@ async function cmdNew() {
"usage: umtool new <slug> [--kind report-video] [--title T]\n" +
" [--from <sweep-report.md> | <share URL> | <channel>/<videoId>]\n" +
" [--site-origin <url>] [--seed chapters|frames [--target <seconds>]] [--brand archilyzer-media]\n" +
- " [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>]]",
+ " [--seed phrase --phrase <regex> --channels a,b [--prefer <slug>] [--exclude <regex>] [--max N]]",
);
}
const kind = val("--kind") ?? "report-video";
@@ -1147,6 +1155,7 @@ async function cmdNew() {
exclude: val("--exclude") ?? null,
}
: {}),
+ ...(val("--max") != null ? { max: Number(val("--max")) } : {}),
});
} catch (e) {
die(e?.message ?? String(e));
diff --git a/umtool/components/NewProjectMenu.tsx b/umtool/components/NewProjectMenu.tsx
@@ -32,6 +32,7 @@ import { useHydrated } from "@/components/ui/use-hydrated";
// the frames seed's length budget is [data-new-target], seconds.
// Release 33: with no source, [data-new-seed] offers "a phrase across channels"
// ([data-new-phrase], [data-new-channels], [data-new-prefer], [data-new-exclude]).
+// Release 35: [data-new-max] caps the reel at N instances spread across the years.
type Brand = { id: string; label: string };
type Kind = { id: string; label: string; scaffold?: { fields: string[]; brands?: Brand[] } | null };
@@ -46,6 +47,7 @@ const FIELD_HINT: Record<string, string> = {
channels: "the channel slugs to scan, separated by commas",
prefer: "the channel to cut from where it holds a copy of the same stream (optional)",
exclude: "leave out a hit whose surrounding words match this regular expression (optional)",
+ max: "keep at most this many instances, spread across the years in proportion (optional)",
brand: "a report-to-video preset: its palette and faces, the title lockup, the header mark, an end card",
};
@@ -92,6 +94,7 @@ export default function NewProjectMenu({
const [channels, setChannels] = useState("");
const [prefer, setPrefer] = useState("");
const [exclude, setExclude] = useState("");
+ const [max, setMax] = useState("");
const [target, setTarget] = useState("240");
// What the video can be seeded from (null: not asked yet, or not a video).
const [seeds, setSeeds] = useState<{ chapters: boolean; frames: boolean } | null>(null);
@@ -136,6 +139,7 @@ export default function NewProjectMenu({
if (fields.includes("siteOrigin") && origin.trim()) body.siteOrigin = origin.trim();
if (asksPhrase && seed === "phrase") {
Object.assign(body, { seed, phrase, channels, prefer, exclude });
+ if (max.trim()) body.max = Number(max.trim());
} else if (fields.includes("seed") && seed && seed !== "phrase" && looksLikeVideo) {
body.seed = seed;
if (seed === "frames") body.target = Number(target);
@@ -312,6 +316,9 @@ export default function NewProjectMenu({
<Field label="Exclude">
<Input value={exclude} onChange={(e) => setExclude(e.target.value)} placeholder="optional" aria-label={`exclude — ${FIELD_HINT.exclude}`} title={FIELD_HINT.exclude} data-new-exclude className="w-44" />
</Field>
+ <Field label="Max">
+ <Input value={max} onChange={(e) => setMax(e.target.value)} inputMode="numeric" placeholder="all" aria-label={`max — ${FIELD_HINT.max}`} title={FIELD_HINT.max} data-new-max className="w-20" />
+ </Field>
</>
)}
{asksSeed && seed === "frames" && (
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/components/tools/PhraseFinder.tsx b/umtool/components/tools/PhraseFinder.tsx
@@ -526,6 +526,8 @@ function Sample({ s, names }: { s: PhraseSample; names: Map<string, string> }) {
function CreateMontage({ scan, row }: { scan: PhraseScanView; row: PhraseScanRowView }) {
const router = useRouter();
const [slug, setSlug] = useState(() => montageSlug(row.label ?? row.text));
+ // The cap (release 35): N instances spread across the years; empty = all.
+ const [max, setMax] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const empty = row.summary.instances === 0;
@@ -547,6 +549,7 @@ function CreateMontage({ scan, row }: { scan: PhraseScanView; row: PhraseScanRow
prefer: scan.spec.prefer,
exclude: scan.spec.exclude,
scan: { id: scan.id, row: row.id },
+ ...(max.trim() ? { max: Number(max.trim()) } : {}),
}),
});
const j = await r.json();
@@ -569,7 +572,19 @@ function CreateMontage({ scan, row }: { scan: PhraseScanView; row: PhraseScanRow
<Field label="Montage project">
<Input value={slug} onChange={(e) => setSlug(e.target.value)} aria-label="montage project slug" className="w-72" data-phrase-slug="" />
</Field>
- <Button type="submit" disabled={busy || empty || !slug.trim()} title={empty ? "nothing to cut" : `${row.summary.instances} clips, chronological`} data-phrase-create="">
+ <Field label="Max clips">
+ <Input
+ value={max}
+ onChange={(e) => setMax(e.target.value)}
+ inputMode="numeric"
+ placeholder="all"
+ aria-label="max clips — at most this many, spread across the years in proportion"
+ title="at most this many, spread across the years in proportion (empty: all)"
+ className="w-20"
+ data-phrase-max=""
+ />
+ </Field>
+ <Button type="submit" disabled={busy || empty || !slug.trim()} title={empty ? "nothing to cut" : `${max.trim() && Number(max) < row.summary.instances ? `${Number(max)} of ${row.summary.instances}` : row.summary.instances} clips, chronological`} data-phrase-create="">
{busy ? "Creating…" : "Create montage"}
</Button>
{error && (
diff --git a/umtool/lib/projects/scaffold.mjs b/umtool/lib/projects/scaffold.mjs
@@ -7,7 +7,7 @@ import { mkdir, readFile, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { BRAND_IDS } from "umtool-report-to-video/brand-ids";
import { FRAMES_CUT_DEFAULTS, framesCut } from "umtool-report-to-video/frames-cut";
-import { instancesAsClips, phraseScan } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs";
+import { capInstances, instancesAsClips, phraseScan } from "yt-dlp-transcript-common/lib/montage/phraseScan.mjs";
import { GLOBAL_CHANNELS_DIR, MANIFEST_NAME } from "./report.mjs";
export const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
@@ -211,6 +211,15 @@ export async function framesAsClips({ channelsDir, channel, video, profile = "po
return framesCut(scan, { channel, video, cues, stats, ...(target !== undefined ? { target } : {}) });
}
+// The most clips a phrase seed's cap (`--max`) can ask for.
+export const MAX_PHRASE_CAP = 10000;
+
+/** The cap, said once for the README and the scaffold's notes. */
+const capNote = (max, kept, found) =>
+ kept < found
+ ? `Capped at ${max} (--max): ${kept} of ${found} instance(s) kept, spread across the years in proportion; the other ${found - kept} are in phrase-scan.json ("skippedByCap")`
+ : `Capped at ${max} (--max): all ${found} instance(s) kept`;
+
/**
* Write the project. Refuses an existing directory and a slug that will not
* route; everything else it cannot know is written EMPTY so `check` blocks.
@@ -228,10 +237,13 @@ export async function framesAsClips({ channelsDir, channel, video, profile = "po
* 34) is that answer already made — the phrase finder's search with these
* same settings (phraseScanMany answers each phrase as phraseScan does) — so a
* project is seeded from what the page showed without reading the corpus again.
+ * `max` (release 35) caps the reel at N instances spread across the years
+ * (common/lib/montage/phraseScan.mjs `capInstances`); the rest are listed in
+ * phrase-scan.json as `skippedByCap`. No `max`: the output is what it was.
*
- * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null }} args
+ * @param {{ root: string, slug: string, title?: string, from?: string | null, siteOrigin?: string | null, seed?: string | null, brand?: string | null, channelsDir?: string, timeline?: Record<string, unknown>[] | null, timelineFrom?: string | null, target?: number, phrase?: string | null, channels?: string[] | null, prefer?: string | null, exclude?: string | null, scan?: { instances: any[], hits: any[], dropped: any[], scanned: number } | null, max?: number | null }} args
*/
-export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null }) {
+export async function scaffoldReportVideo({ root, slug, title, from = null, siteOrigin = null, seed = null, brand = null, channelsDir = GLOBAL_CHANNELS_DIR(), timeline = null, timelineFrom = null, target = undefined, phrase = null, channels = null, prefer = null, exclude = null, scan: given = null, max = null }) {
if (!SLUG_RE.test(String(slug ?? ""))) {
throw new Error(`"${slug}" will not route — use lower-case letters, digits and dashes`);
}
@@ -262,9 +274,13 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
if (!list.length) throw new Error("--seed phrase needs --channels (and optionally --prefer)");
for (const c of list) if (!CHANNEL_SLUG_RE.test(c)) throw new Error(`"${c}" is not a channel slug`);
if (given && !(Array.isArray(given.instances) && Array.isArray(given.hits) && Array.isArray(given.dropped))) throw new Error("a phrase scan is { instances, hits, dropped, scanned }");
- } else if (phrase || channels?.length || prefer || exclude || given) {
- throw new Error("--phrase, --channels, --prefer and --exclude go with --seed phrase");
+ } else if (phrase || channels?.length || prefer || exclude || given || (max !== null && max !== undefined)) {
+ throw new Error("--phrase, --channels, --prefer, --exclude and --max go with --seed phrase");
+ }
+ if (max !== null && max !== undefined && !(Number.isInteger(max) && max >= 1 && max <= MAX_PHRASE_CAP)) {
+ throw new Error(`--max must be a whole number of clips from 1 to ${MAX_PHRASE_CAP}`);
}
+ const capped = max !== null && max !== undefined;
if (timeline && (seed || src)) throw new Error("a board's timeline is the whole timeline: give it without --from or --seed");
if (target !== undefined && seed !== "frames") throw new Error("--target is the frames seed's length budget: give it with --seed frames");
if (target !== undefined && !(Number.isFinite(target) && target >= 10 && target <= 3600)) {
@@ -329,7 +345,9 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
let phraseSeeded = null;
if (seed === "phrase") {
const chans = (channels ?? []).map((c) => String(c).trim()).filter(Boolean);
- const scan = given ?? (await phraseScan({ channelsDir, channels: chans, prefer: prefer ? String(prefer).trim() : null, phrase: String(phrase), exclude: exclude || null }));
+ const found = given ?? (await phraseScan({ channelsDir, channels: chans, prefer: prefer ? String(prefer).trim() : null, phrase: String(phrase), exclude: exclude || null }));
+ const { kept, skipped } = capInstances(found.instances, capped ? max : null);
+ const scan = capped ? { ...found, instances: kept, skippedByCap: skipped, found: found.instances.length } : found;
doc.timeline = instancesAsClips(scan.instances);
doc.render.transition = 0;
// The window already carries its margin (2.5 s each side), and the editor
@@ -340,7 +358,8 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
else if (chans.length === 1) doc.provenance.channelSlug = chans[0];
seeded = doc.timeline.length;
phraseSeeded = scan;
- notes.push(`${scan.scanned} transcript(s) read, ${scan.hits.length} hit(s), ${scan.instances.length} instance(s)`);
+ notes.push(`${scan.scanned} transcript(s) read, ${scan.hits.length} hit(s), ${capped ? found.instances.length : scan.instances.length} instance(s)`);
+ if (capped) notes.push(capNote(max, scan.instances.length, found.instances.length));
const placed = scan.instances.filter((i) => i.via).length;
if (placed) notes.push(`${placed} hit(s) from another channel placed in the ${prefer} copy by their words — check the cut lands on the phrase`);
if (scan.dropped.length) notes.push(`${scan.dropped.length} left out by --exclude (phrase-scan.json, "dropped")`);
@@ -360,8 +379,10 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(doc, null, 2) + "\n", "utf8");
if (reportText !== null) await writeFile(path.join(dir, "sweep-report.md"), reportText, "utf8");
if (phraseSeeded) {
- const { instances, dropped, hits, scanned } = phraseSeeded;
- const scanDoc = { phrase: String(phrase), channels, prefer: prefer ?? null, exclude: exclude ?? null, scanned, hits: hits.length, instances, dropped };
+ const { instances, dropped, hits, scanned, skippedByCap } = phraseSeeded;
+ const scanDoc = capped
+ ? { phrase: String(phrase), channels, prefer: prefer ?? null, exclude: exclude ?? null, max, scanned, hits: hits.length, instances, skippedByCap, dropped }
+ : { phrase: String(phrase), channels, prefer: prefer ?? null, exclude: exclude ?? null, scanned, hits: hits.length, instances, dropped };
await writeFile(path.join(dir, "phrase-scan.json"), JSON.stringify(scanDoc, null, 1) + "\n", "utf8");
}
@@ -390,6 +411,7 @@ export async function scaffoldReportVideo({ root, slug, title, from = null, site
"Every window below is a place the transcripts say the phrase: the cues it was",
"said in, chronological. A transcript can mishear and a line can be someone",
"else's (a co-host, chat read out): listen to each in the bench before you keep it.",
+ ...(capped ? ["", `${capNote(max, phraseSeeded.instances.length, phraseSeeded.found)}.`] : []),
"",
...doc.timeline.map((c) => `- [ ] ${c.id} ${c.onscreen?.subtitle ?? ""} ${c.channel}/${c.video} ${c.cutStart}–${c.cutEnd} "${c.onscreen?.title ?? ""}"${c.note ? ` (${c.note})` : ""}`),
);
diff --git a/umtool/lib/projects/scaffold.ts b/umtool/lib/projects/scaffold.ts
@@ -28,6 +28,8 @@ export type NewProjectBody = {
// The phrase finder's search these settings came from (release 34): the
// project is seeded from its answer, not from a second read of the corpus.
scan?: { id?: string; row?: string } | null;
+ // The phrase seed's cap (release 35): N instances spread across the years.
+ max?: number | string | null;
};
/**
@@ -77,6 +79,7 @@ export async function scaffoldProject(body: NewProjectBody): Promise<{ href: str
prefer: body.prefer || null,
exclude: body.exclude || null,
...(scan ? { scan } : {}),
+ ...(body.max !== undefined && body.max !== null && body.max !== "" ? { max: Number(body.max) } : {}),
}
: {}),
...(body.seed === "frames" && body.target !== undefined && body.target !== null && body.target !== "" ? { target: Number(body.target) } : {}),
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 });
+ }
+});
diff --git a/umtool/lib/scaffold-phrase.test.mjs b/umtool/lib/scaffold-phrase.test.mjs
@@ -87,3 +87,48 @@ test("--seed phrase with a finished scan (release 34, the phrase finder): the sa
await rm(tmp, { recursive: true, force: true });
}
});
+
+test("--seed phrase --max N (release 35): N instances spread across the years, the rest as skippedByCap, the cap in the README", async () => {
+ const tmp = await mkdtemp(path.join(os.tmpdir(), "umtool-phrase-seed-"));
+ try {
+ const channelsDir = path.join(tmp, "channels");
+ // 2019: 1, 2020: 6, 2021: 3 — ten instances, each its own video.
+ const plan = [["2019", 1], ["2020", 6], ["2021", 3]];
+ for (const [year, n] of plan) {
+ for (let k = 0; k < n; k++) {
+ await video(channelsDir, "synth-yt", `y${year}${k}`, { uploadDate: `${year}${String(k + 1).padStart(2, "0")}10`, duration: 600, platform: "youtube", cues: [{ start: 10, end: 13, text: k === 0 && year === "2020" ? ">> a slow news day" : "a slow news day" }] });
+ }
+ }
+ const base = { root: path.join(tmp, "reports"), seed: "phrase", phrase: String.raw`slow[\s,]+news`, channels: ["synth-yt"], channelsDir };
+ const capped = await scaffoldReportVideo({ ...base, slug: "capped", max: 5 });
+ assert.equal(capped.seeded, 5);
+ const doc = JSON.parse(await readFile(path.join(capped.dir, "video.manifest.json"), "utf8"));
+ // 5 of 10: quotas 0.5, 3, 1.5 -> 1, 3, 1 = 5. The 2020 speaker-checked instance is passed over.
+ assert.deepEqual(doc.timeline.map((c) => c.video), ["y20190", "y20201", "y20203", "y20205", "y20211"]);
+ assert.deepEqual(doc.timeline.map((c) => [c.id, c.montage.n, c.montage.of]), [["s01", 1, 5], ["s02", 2, 5], ["s03", 3, 5], ["s04", 4, 5], ["s05", 5, 5]]);
+ const scan = JSON.parse(await readFile(path.join(capped.dir, "phrase-scan.json"), "utf8"));
+ assert.equal(scan.max, 5);
+ assert.equal(scan.instances.length, 5);
+ assert.deepEqual(scan.skippedByCap.map((i) => i.videoId), ["y20200", "y20202", "y20204", "y20210", "y20212"]);
+ assert.ok(scan.instances.every((i) => Array.isArray(i.alternates)), "the instance shape, alternates and all");
+ const readme = await readFile(path.join(capped.dir, "README.md"), "utf8");
+ assert.match(readme, /Capped at 5 \(--max\): 5 of 10 instance\(s\) kept, spread across the years in proportion; the other 5 are in phrase-scan.json \("skippedByCap"\)\./);
+ assert.ok(capped.notes.some((n) => /Capped at 5/.test(n)));
+
+ // No cap and a cap above the count: the same manifest; only a cap writes max / skippedByCap.
+ const plain = await scaffoldReportVideo({ ...base, slug: "plain" });
+ const roomy = await scaffoldReportVideo({ ...base, slug: "roomy", max: 50 });
+ const text = async (r, f) => (await readFile(path.join(r.dir, f), "utf8")).replaceAll(path.basename(r.dir), "X");
+ assert.equal(await text(roomy, "video.manifest.json"), await text(plain, "video.manifest.json"));
+ const plainScan = JSON.parse(await readFile(path.join(plain.dir, "phrase-scan.json"), "utf8"));
+ assert.equal("max" in plainScan || "skippedByCap" in plainScan, false);
+ assert.doesNotMatch(await text(plain, "README.md"), /Capped/);
+ assert.match(await text(roomy, "README.md"), /Capped at 50 \(--max\): all 10 instance\(s\) kept/);
+
+ await assert.rejects(scaffoldReportVideo({ ...base, slug: "bad", max: 0 }), /--max must be a whole number/);
+ await assert.rejects(scaffoldReportVideo({ ...base, slug: "bad", max: 2.5 }), /--max must be a whole number/);
+ await assert.rejects(scaffoldReportVideo({ root: base.root, slug: "bad", channelsDir, max: 3 }), /go with --seed phrase/);
+ } finally {
+ await rm(tmp, { recursive: true, force: true });
+ }
+});