commit 20139882a2894620ee72fb84de0db1dfc6977d5e
parent 93357f00ff7c463c4a3ad1b2a03753afa001d257
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 18 Oct 2026 17:44:25 -0400
Merge main (lane N1, the clip deck) into r34/voice-match: voice-match.json keys come from N1's clipMomentKey; Score the voices sits on the deck's head too
Conflicts kept both sides (the changelog, umtool.mjs's usage and dispatch, the Cut tab, cli.md,
report-video.md). Adapted: planClips and the Cut tab key by clipMomentKey (umtool-report-to-
video/montage-rulings); voiceMatchSummary (common) says a run's counts and reference in words,
counted from the rows when a file carries no counts (the deck fixture's does not); the deck page
passes VoiceMatchPanel to ClipDeck as `voicePanel` (reloads when the run ends); the panel's handle
is data-voice-match-panel (the deck's own data-voice-match line keeps its name).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
34 files changed, 2974 insertions(+), 37 deletions(-)
diff --git a/common/lib/montage/voiceMatch.d.mts b/common/lib/montage/voiceMatch.d.mts
@@ -118,3 +118,8 @@ export function runVoiceMatch(o: {
export function readVoiceMatch(dir: string): Promise<VoiceMatchDoc | null>;
export function writeVoiceMatch(dir: string, doc: VoiceMatchDoc): Promise<string>;
+export function voiceMatchSummary(doc: VoiceMatchDoc | null): {
+ madeAt: string;
+ counts: VoiceMatchDoc["counts"];
+ reference: string;
+} | null;
diff --git a/common/lib/montage/voiceMatch.mjs b/common/lib/montage/voiceMatch.mjs
@@ -596,6 +596,32 @@ export async function readVoiceMatch(dir) {
}
}
+/**
+ * What a page says about a run: when, the counts, and the reference in words
+ * ("3 clips ruled keep", "8 solo recordings").
+ */
+export function voiceMatchSummary(doc) {
+ if (!doc) return null;
+ const ref = doc.reference && typeof doc.reference === "object" ? doc.reference : {};
+ const reference =
+ ref.kind === "rulings"
+ ? `${Number(ref.kept) || 0} clip${ref.kept === 1 ? "" : "s"} ruled keep`
+ : `${Array.isArray(ref.recordings) ? ref.recordings.length : 0} solo recording${Array.isArray(ref.recordings) && ref.recordings.length === 1 ? "" : "s"}`;
+ // Counted from the rows when the file does not carry them (a hand-made or
+ // older file): a page never trusts a field to be there.
+ const rows = Object.values(doc.clips ?? {});
+ const n = (label) => rows.filter((r) => r && r.label === label).length;
+ const c = doc.counts && typeof doc.counts === "object" ? doc.counts : {};
+ const counts = {
+ clips: Number.isFinite(c.clips) ? c.clips : rows.length,
+ scored: Number.isFinite(c.scored) ? c.scored : rows.filter((r) => r && Number.isFinite(r.score)).length,
+ likely: Number.isFinite(c.likely) ? c.likely : n("likely"),
+ unsure: Number.isFinite(c.unsure) ? c.unsure : n("unsure"),
+ unlikely: Number.isFinite(c.unlikely) ? c.unlikely : n("unlikely"),
+ };
+ return { madeAt: typeof doc.madeAt === "string" ? doc.madeAt : "", counts, reference };
+}
+
/** Written whole: tmp + rename. */
export async function writeVoiceMatch(dir, doc) {
const file = path.join(dir, VOICE_MATCH_FILE);
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -2,6 +2,7 @@
## [Unreleased]
- **umtool scores who is speaking in each montage clip.** A report video's Cut tab has **Score the voices**: each clip's phrase (and a second either side, its speech only) is compared with the host's voice, and every row then reads `voice 0.43 · unsure` — likely, unsure or unlikely him. The host's voice is the clips you ruled keep in the audition deck once there are three, or before that solo uploads of the channel found on disk (captioned, no speaker change in the captions, not a stream, no guest in the title, spread over the years); the picker beside the button chooses. It runs on this machine with the speaker model the diarization lane already uses — no network, no AI model — and takes about half a minute for 73 clips. It sorts and flags; whether it is him is still decided by ear. The scores are kept in `voice-match.json` beside the manifest, by the source moment, so a re-seeded montage keeps them. The same from a terminal: `umtool voice-match <project>`. Needs a restart of umtool.
+- **Rule a montage's clips by ear, and the render leaves out the ones that aren't him.** A report video made of one phrase said many times has a clip deck (the Cut tab's **Clips — n to rule**, at `/projects/<id>/clips`): one card per instance, its cut playing from the cached window (**Wider** plays the whole clip), the quote with the phrase marked, the date and source, the clip's note, and — when a speaker score is beside the manifest — that score. Swipe or press → **Keep**, ← **Cut**, ↓ **Not him** (a co-host, a guest, a clip played), ↑ **Read aloud** (a post or a quote read out); **e** keeps it with a wider phrase, **s** skips, space replays, **z** undoes; a reason chip or a few words go with the ruling. The deck walks the unruled clips, the doubtful ones first, the ruled ones, or all, and works at phone width with the buttons under the thumb. The rulings are `montage-rulings.json` beside the manifest, kept by the moment in the source rather than the clip's number, so seeding the montage again keeps them. A render, and a take, leaves out every clip ruled cut, not him or read aloud (of the cut and of the wall), cuts a clip to its wider phrase, and numbers the kept clips 1 to N; the build log names each clip left out and why. Without a rulings file a render is exactly as before; `--no-rulings` builds every clip. The end of the deck counts the rulings, shows the next render's clips, and **Re-render the take** makes the picked take (or the one whole-cut take) again. A seed's `edits.json` is offered once as **Import earlier rulings**. From a terminal: `umtool rulings <project>` (show, `import`, `set`, `clear`). Nothing calls a model. Needs a restart of umtool.
- **Report videos cut clips from Rumble windows on the right second.** Some downloaded windows (Rumble's) keep their source's clock, so their picture starts a second or two in, and every cut from one landed that much late — in the slow-news montage, one clip's "slow news week" fell into the pause after it. The build now reads where such a window's picture starts and cuts on its own clock (and says so in the build log). In a montage with even loudness, a clip or wall tile that measures near-silent is taken for a phrase looked for in the wrong place: it is found again by the sound — the speech nearest where it was expected — recorded, said in the log, and never boosted from silence.
- **Montages are level, and their walls don't repeat themselves side by side.** With `render.montage.loudness` (every montage style has it, at −16 LUFS), each clip and each wall tile is measured and brought to the same loudness, with a limiter so a quiet clip raised up cannot clip — an old upload and a recent stream no longer jump in level at the cut. `wall.spread: "stream"` keeps two clips of one stream, or a stream and its mirror on another platform, from touching in the wall's grid, and `wall.distinct` takes one clip per stream when there are enough. `wall.label` puts each tile's year, its number or both in its corner. Build to the wall uses all three. Manifests without them render exactly as before.
- **A montage can build to its wall.** The closing wall can fill in groups of 1, 1, 2, 4, 8 … tiles, each group sliding in on a beat that comes a little sooner than the last; a group says the phrase together, with every tile's first syllable placed on the beat (from whisper's word timings, or from the captions checked against the sound), and at the end every tile says it on the same frame. The wall can take the latest clips instead of a spread (`wall.clips: "tail"`) and take them out of the run before it (`wall.exclusive`), so it condenses the repetition instead of repeating it; the count before it then stops where the wall begins. A ramp can end at the wall's first beat (`ramp.into: "wall"`), so the cuts speed straight into it. A seventh style, **Build to the wall**, puts these together: whip cuts getting shorter, tally marks, then the latest twenty-five in synced groups. Manifests without the new keys render exactly as before.
diff --git a/plans/FACTS.md b/plans/FACTS.md
@@ -10493,3 +10493,36 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri
estimate; tuned on s38/s70) → recut; records `montage.loudness.relocated {from, to, why}` and `montage.found: "sound"`; a wall-only tile:
`montageWall.sync[].relocated`. `loudnessGain` is 0 under −40 LUFS. Consensus shifts failing `shiftAllowed` (−10 dB)
keep the estimate (`by: "estimate"`, `held`).
+
+## Release 34 lane N1: the clip deck and montage rulings (verified 2026-10-18, branch `r34/clip-deck`)
+
+- **`<project>/montage-rulings.json`** `{version: 1, rulings: {"<channel>/<video>@<cutStart.toFixed(2)>": {verdict:
+ "keep"|"cut"|"not-him"|"read-aloud", reason, match?, at}}}`. The key rule is ONE function,
+ `umtool/report-to-video/montage-rulings.mjs` `clipMomentKey(entry, manifest)`: the clip's `channel`, else
+ `provenance.channelSlug`; `cutStart`, else `start`; a `src` clip (no video) has no key. voice-match.json (N2) uses the
+ same key. Exported as `umtool-report-to-video/montage-rulings`.
+- **Applied at render** by `applyMontageRulings(manifest, doc, {keep})` → `{manifest, left, matched, renumbered}`:
+ cut / not-him / read-aloud clips dropped from the timeline (so from the wall: `montageSplit` takes tiles from it);
+ `match` replaces `montage.match`; when anything was dropped, every kept clip's `montage.n` / `montage.of` (where
+ present) become 1…N of N in timeline order. Nothing changed → the SAME object (byte-identical render, tested by md5).
+ build-video applies it to the variant view only (`selectVariant(applied)`): `whole` (validators, posts, a bench
+ `--fetch-only`) is the manifest as written; `--only <id>` keeps that id. `verify-build` applies the same file.
+ `--no-rulings` on both. A file that does not parse refuses the build (`readMontageRulings` throws; null = no file).
+- **The take maker** applies the rulings to the patched manifest BEFORE windowing (windowEntries still times entries
+ on the base manifest); the render manifest beside the project is re-applied by build-video as a no-op (nothing left
+ to drop, so no renumber). `takes/<id>/video.manifest.json` (what a pick copies) is the manifest as written.
+- **The one writer**: `umtool/lib/report/montageRulings.mjs` (in-process queue, tmp + rename, sorted keys, an
+ unparseable file never overwritten). `setMontageRuling(dir, key, ruling|null)`; `resolveRulingKey(manifest, id|key)`
+ refuses a key no clip has (the route and `umtool rulings set`); the import writes keys the manifest may not have.
+- **Import of a seed's edits.json** (`{exclude: [{videoId, near, why}], match: [{videoId, near, match, why}]}`, `near` =
+ the instance's start): the clip with that `video` whose cutStart (else start) is nearest and < 30 s away; else the
+ seed's `instances.json` (`{slug, videoId, start}`, key at `round(start, 2)`); an exclude's verdict from its words
+ (`verdictFromWhy`: another speaker / co-host / guest → not-him; read out / tweet / post / chat → read-aloud; else
+ cut). Offered while some mapped key is unruled (no extra state). On the slow-news project the two excludes are no
+ longer in the manifest (the seed dropped them) and map through instances.json.
+- **Surfaces**: `/projects/<id>/clips` (`clipDeckHref(p, {show})`, `show` = all|unruled|doubtful|ruled; the Cut tab's
+ `[data-clip-deck-link]`), `GET/POST /api/report/montage-rulings` (`{project, clip, ruling|null}` | `{project, import:
+ true, dryRun?}`; GET returns `plan` = `renderPlan` = the kept clips as the build numbers them), `umtool rulings
+ <project> [--json] | import [--dry-run] | set <clip|key> <verdict> [--reason] [--match] | clear <clip|key>`.
+ "Re-render the take" = `POST /api/report/takes/make {project, rebuild}` on the single picked take, else the single
+ full-window maker take (`baseHash`), else a link to the Takes page.
diff --git a/plans/release-34/clip-deck.md b/plans/release-34/clip-deck.md
@@ -0,0 +1,137 @@
+# Release 34 lane N1 — `r34/clip-deck`: the montage clip audition deck (as shipped)
+
+The operator rules montage clips by ear ("#4 is another speaker, #6 is him reading a tweet, #58 only makes sense if
+she's refuting his claim"), and until now the orchestrator hand-edited the seed's `edits.json`. This lane is the app
+surface for it: one card per instance, swiped keep / cut / not him / read aloud, persisted through the app, applied at
+render. Rulings followed: audits get an app-like UI, one decision per item, persisted; the UI works with no model
+(nothing here calls one); no cards in the video; plain words; synthetic fixtures only.
+
+## What
+
+1. **The rulings store** — `<project>/montage-rulings.json` `{version: 1, rulings: {"<channel>/<video>@<cutStart to 2
+ decimals>": {verdict, reason, match?, at}}}`, keyed by the source moment so a re-seed keeps every ruling.
+ - The key rule, the shape check and the render application are `umtool/report-to-video/montage-rulings.mjs`
+ (exported as `umtool-report-to-video/montage-rulings`); `clipMomentKey(entry, manifest)` is the one key function
+ (the clip's `channel`, else `provenance.channelSlug`; `cutStart`, else `start`).
+ - The one writer is `umtool/lib/report/montageRulings.mjs`: an in-process queue, tmp + rename, keys sorted, a file
+ that does not parse never overwritten (and never read as empty).
+ - **Import**: a seed's `edits.json` maps to moments — the clip with that video whose cutStart is nearest and within
+ 30 s, else the seed's `instances.json` (a moment the seed already left out). An exclude's verdict comes from its
+ words; a match keeps the clip with the wider phrase. Offered while some mapped moment is unruled, so once imported
+ it is not offered again (no extra state).
+2. **Applied at render** — `applyMontageRulings` in build-video (on the variant view; `whole` stays as written for the
+ validators and a bench `--fetch-only`; `--only <id>` keeps that clip) and verify-build: cut / not-him / read-aloud
+ clips are left out of the cut and the wall; `match` replaces `montage.match`; when anything was left out the kept
+ clips' `montage.n` / `montage.of` are numbered 1…N of N. No file, or nothing that changes anything, returns the same
+ object: today's render byte for byte. The build log names each clip left out and why. `--no-rulings` on both. A file
+ that does not parse refuses the build. The take maker applies the rulings BEFORE windowing, so a window counts over
+ the whole kept cut; the take's own manifest (what a pick copies) stays as written.
+3. **The deck** at `/projects/<id>/clips` (`clipDeckHref`; the Cut tab's **Clips — n of N to rule** on a cut whose clips
+ carry `montage`): built on R1's AuditionDeck patterns (swipe threshold and flick, stamps, the decided card flying out,
+ the next card underneath with its media loading, the card after warmed, 20-deep undo, the bar under the thumb).
+ - A card: the counter's number, the phrase, the cut playing from the project's cached window (the cited clip;
+ **Wider**/`w` plays the clip's whole extent), the quote with the phrase marked, date · platform · channel · video,
+ the clip's note (the seed's voice check, a stand-in upload), and voice-match.json's label and score when present.
+ - Keys: → / `k` keep, ← / `x` cut, ↓ / `n` not him, ↑ / `r` read aloud, `e` keep with an edited phrase (Enter), `s`
+ skip, `w` wider, space replay, `z` / Backspace undo, `?` keys. Reason chips (co-host, guest, a clip played, a post
+ read out, chat read out, wrong moment, says something else) or a few words ride with the next ruling.
+ - Filters: Unruled, Doubtful first (voice unlikely by score, unsure, a voice check in the note, then the rest),
+ Ruled, All; `?show=` keeps it. One counter row: `n / N · k kept · c cut · h not him · r read aloud`, and `R of N
+ ruled`.
+ - End card: the counts, the clips left out with their reasons, **the next render** (GET's `plan`: the build's own
+ application, the kept clips as it numbers them) and **Re-render the take** (the take maker's Rebuild job on the
+ single picked take, else the single whole-cut maker take; otherwise a link to the Takes page), with how many
+ rulings were made since that take was built.
+ - Phone width: one column, the five rulings in a fixed bar under the thumb, no sideways scroll.
+4. **`umtool rulings <project>`** — show (`--json`: each clip, its key and ruling, the plan), `import [--dry-run]`,
+ `set <clip|key> <verdict> [--reason] [--match]`, `clear <clip|key>`: the same writer.
+5. **The route** `GET/POST /api/report/montage-rulings` (`{project, clip, ruling|null}`; `{project, import: true}`); a
+ ruling must name a clip the manifest has.
+
+## Files
+
+report-to-video: `montage-rulings.mjs` (new), `montage-rulings.test.mjs` (new, 9 tests: 6 pure, 3 real renders),
+`build-video.mjs` (apply on the variant view, the log lines, `--no-rulings`), `verify-build.mjs` (same file,
+`noRulings`), `package.json` (export), `README.md` (module row, "`montage-rulings.json`" section).
+umtool: `lib/report/montageRulings.mjs` (new), `montageRulings.test.mjs` (new, 8), `lib/report/rulingsCli.mjs` (new),
+`lib/report/clipDeck.ts` (new: the page data, voice-match.json read leniently), `lib/report/takeMaker.mjs` (+ test 1),
+`lib/hrefs.ts` (`clipDeckHref`, `CLIP_DECK_SHOWS`; + test 1), `app/api/report/montage-rulings/route.ts` (new),
+`components/projects/ClipDeckPage.tsx` (new), `components/projects/review/ClipDeck.tsx` (new),
+`components/projects/ProjectView.tsx` (the `clips` view), `components/projects/report/CutTab.tsx` (the link),
+`bin/umtool.mjs` (one dispatch + usage block), `docs/report-video.md` ("Ruling the clips"), `docs/cli.md` (one row),
+`e2e/clip-deck.spec.ts` (new, 2), `e2e/fixtures/clip-deck-fixture.mjs` (new) + `make-fixture.mjs` (registered),
+`e2e/visual-audit.spec.ts` (+ `bench-clips`). `editor/CHANGELOG.md`, `plans/FACTS.md` ("Release 34 lane N1").
+
+| Commit | What |
+| --- | --- |
+| `1a0b5a69` | report-to-video montage-rulings.mjs; build-video, verify-build, the take maker apply it; umtool's writer + import; tests |
+| `91735315` | the clip deck page, route, `umtool rulings`, Cut tab link, e2e fixture + clip-deck.spec |
+| `b1dbc15a` | docs, the visual audit's page and one filled action, synthetic test ids, FACTS, CHANGELOG |
+| (this commit) | this record |
+
+## Interfaces
+
+- `umtool-report-to-video/montage-rulings`: `MONTAGE_RULINGS_FILE`, `RULING_VERDICTS`, `LEFT_OUT_VERDICTS`,
+ `VERDICT_WORDS`, `momentKey({channel, video, at})`, `clipMomentKey(entry, manifest?)`, `isMomentKey`,
+ `parseMomentKey`, `parseMontageRulings(raw)`, `readMontageRulings(dir)` (null | doc | throws),
+ `applyMontageRulings(manifest, doc, {keep?})` → `{manifest, left: [{id, key, verdict, reason}], matched: [{id, key,
+ match, was}], renumbered}`, `rulingsLines(applied)`, `leftOutWords`.
+- `umtool/lib/report/montageRulings.mjs`: `readRulingsState(dir)` → `{exists, doc, error}`, `setMontageRuling(dir, key,
+ ruling|null, {now})`, `setMontageRulings(dir, entries, {overwrite})`, `normaliseRuling`, `montageClipsOf`,
+ `hasMontageClips`, `momentKeysOf`, `resolveRulingKey`, `verdictFromWhy`, `mapEarlierRulings(manifest, edits,
+ instances)`, `earlierRulingsOffer(dir, manifest, doc?)`, `importEarlierRulings(dir, manifest, {dryRun})`,
+ `renderPlan(manifest, doc)` → `{kept: [{id, n, of, match}], left, matched, lines}`.
+- `lib/report/clipDeck.ts`: `clipDeckView(project)`, `readVoiceMatch(dir)` (reads N2's `clips[key].{score, label,
+ speechSeconds}`; a row not that shape is skipped; no file = null), `doubtOf`.
+- `clipDeckHref(project, {show?, note?})`; `GET /api/report/montage-rulings?project=` → `{rulings, error, plan, offer}`.
+
+## Gates (all through the shared lock, from the worktree root)
+
+- tsc (all packages): clean before each code commit and at the end.
+- test:scripts: **1141 (1137 pass, 4 skipped) at `main` `9d5df831` → 1160 (1156 pass, 0 fail, 4 skipped)**: +9
+ montage-rulings, +8 montageRulings (store, import, CLI), +1 takeMaker, +1 hrefs.
+- umtool `test`: 45/45 before and after (no tests of mine in its globs).
+- Byte-identical: in-suite, the same four-clip montage rendered with no rulings file and with a file whose rulings
+ change nothing (a keep, a moment the cut does not have) — identical md5 for the final and two segments; a ruled cut's
+ kept clip #2 of 2 is md5-identical to a hand-numbered two-clip manifest's (the counter is drawn from the renumbered
+ values); a ruled-out clip is not a wall tile; `--no-rulings` builds all four and verify-build agrees.
+- `archilyzer docs cli --check`, `docs files --check`: clean (no generated doc changes; `umtool` rows are cli.md's).
+- e2e umtool, single specs: `clip-deck.spec.ts` 2/2 (12.1 s, after one fix of the spec's reload step); `clip-deck` +
+ visual-audit's `bench-clips` 3/3 (15.1 s, screenshots at 1366/1440 × dark/light and 390 px); `takes.spec.ts` +
+ `visual-audit.spec.ts` 73/73 (1.5 min).
+- No editor, export, homepage or common code touched; their suites not run.
+
+## Smoke (the project read only; its manifest, edits.json and instances.json copied to scratch)
+
+- `umtool rulings slow-news import --dry-run` → three: two excludes (no longer in the manifest) through instances.json
+ as not-him and read-aloud, and the widened phrase on s56 as keep; `import` wrote them; the show reads "1 of 73
+ ruled; the next render: 73 clip(s)" (the seed had already applied all three).
+- `set s04 not-him` → the plan: 72 clips, s05 numbered #4 of 72.
+- A quick window take (straight, 0/20 s, `--skip-fetch`, the corpus read-only): the log names s04 left out; segments
+ s01–s03, s05, s06 and no s04; s05's chip reads "#4". 12.9 s.
+
+## Decisions
+
+- Keys on the deck: ↓ / `n` is not him and ↑ / `r` read aloud (R1's ↓ skip and ↑ edit moved to `s` and `e`), as the
+ brief asked; `x`/`k` keep R1's cut/keep.
+- `e` saves as **keep** with the phrase (editing the phrase is a decision to keep it wider), as R1's edit decides its
+ card. A ruling keeps a phrase it already had when it is changed by a swipe.
+- A reason applies to whichever ruling comes next (keep included), not only cuts.
+- Renumbering happens only when a clip was left out, so applying twice (the take maker, then the build over the render
+ manifest) changes nothing, and a window keeps the whole cut's numbers. Only `n`/`of` a clip already carries are
+ rewritten; a clip with none is numbered by its place (planMontage) as before.
+- The rulings apply whether or not `render.montage` is set: the slow-news project's own manifest has no montage key (the
+ takes add it), and a ruled-out clip is out of any cut.
+- The import offer has no "done" flag (the prelude's shape is exact): it offers what maps to a moment not yet ruled.
+- The deck's Start overlay and the Import button are outlines and the Cut tab's Clips link an outline, so a page keeps
+ one filled action (the visual audit's rule).
+- No take is re-rendered by the deck when the choice is ambiguous (several picked, or none picked and several
+ whole-cut takes): it links the Takes page.
+
+## Found and left
+
+- The slow-news project's two excluded moments are not in its manifest (the seed dropped them), so their rulings only
+ matter if the seed is run again without `edits.json`'s excludes. `seed-manifest.py` still reads `edits.json`; whether
+ it should read `montage-rulings.json` instead is the orchestrator's call.
+- kbd hints in the deck's bar show at phone width (the same `hidden md:inline` classes R1's deck uses lose to kbd's own
+ display rule); left as R1 has it.
diff --git a/umtool/app/api/report/montage-rulings/route.ts b/umtool/app/api/report/montage-rulings/route.ts
@@ -0,0 +1,79 @@
+import { projectRef } from "@/lib/projects";
+import { readManifest } from "@/lib/projects/report.mjs";
+import {
+ earlierRulingsOffer,
+ hasMontageClips,
+ importEarlierRulings,
+ readRulingsState,
+ renderPlan,
+ resolveRulingKey,
+ setMontageRuling,
+} from "@/lib/report/montageRulings.mjs";
+
+export const dynamic = "force-dynamic";
+
+// THE CLIP DECK's rulings (release 34 N1): <project>/montage-rulings.json,
+// written by lib/report/montageRulings.mjs (the one writer) and applied at
+// render by report-to-video/montage-rulings.mjs.
+//
+// GET ?project=<id> the rulings, the next render's plan
+// (the kept clips numbered, the left out),
+// and the earlier rulings edits.json offers
+// POST { project, clip, ruling } set one clip's ruling: `clip` its id or
+// its moment key; `ruling` { verdict:
+// "keep"|"cut"|"not-him"|"read-aloud",
+// reason?, match? }, or null to clear it
+// POST { project, import: true, dryRun? } write the earlier rulings in edits.json
+//
+// A ruling names a clip the manifest has: one on a moment the cut does not
+// carry would be a decision nobody made.
+const headers = { "cache-control": "no-store" };
+
+async function montageProject(id: unknown) {
+ const project = await projectRef(String(id ?? ""));
+ if (!project) return { error: Response.json({ error: "no such project" }, { status: 404 }) };
+ const manifest = await readManifest(project.dir);
+ if (!manifest) return { error: Response.json({ error: "no manifest" }, { status: 400 }) };
+ if (!hasMontageClips(manifest)) return { error: Response.json({ error: "this cut has no montage clips" }, { status: 400 }) };
+ return { project, manifest };
+}
+
+export async function GET(request: Request) {
+ const url = new URL(request.url);
+ const r = await montageProject(url.searchParams.get("project"));
+ if ("error" in r) return r.error;
+ const state = await readRulingsState(r.project.dir);
+ const offer = await earlierRulingsOffer(r.project.dir, r.manifest, state.doc);
+ return Response.json(
+ {
+ rulings: state.doc.rulings,
+ error: state.error,
+ plan: state.error ? null : renderPlan(r.manifest, state.doc),
+ offer: { count: offer.rulings.length, rulings: offer.rulings, unmapped: offer.unmapped },
+ },
+ { headers },
+ );
+}
+
+export async function POST(request: Request) {
+ const body = (await request.json().catch(() => null)) as Record<string, unknown> | null;
+ if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400 });
+ const r = await montageProject(body.project);
+ if ("error" in r) return r.error;
+ try {
+ if (body.import === true) {
+ const done = await importEarlierRulings(r.project.dir, r.manifest, { dryRun: body.dryRun === true });
+ const state = await readRulingsState(r.project.dir);
+ return Response.json({ ok: true, written: done.written, offered: done.rulings.length, unmapped: done.unmapped, rulings: state.doc.rulings }, { headers });
+ }
+ const key = typeof body.clip === "string" ? resolveRulingKey(r.manifest, body.clip) : null;
+ if (!key) return Response.json({ error: "no such montage clip" }, { status: 404 });
+ if (body.ruling !== null && (typeof body.ruling !== "object" || Array.isArray(body.ruling))) {
+ return Response.json({ error: "ruling is { verdict, reason?, match? } or null" }, { status: 400 });
+ }
+ const out = await setMontageRuling(r.project.dir, key, body.ruling as null | { verdict: string; reason?: string; match?: string });
+ return Response.json({ ok: true, key, ruling: out.ruling, rulings: out.doc.rulings }, { headers });
+ } catch (e) {
+ return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
+ }
+}
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -50,6 +50,8 @@
// umtool take <project> --id <id> --label L [--group G] [--style S] [--patch F | --set p=v …]
// [--at S --dur S | --full] [--force] | --id <id> --rebuild make one take
// 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 voice-match <project> [--reference auto|rulings|recordings] [--instances F] [--dry] [--json]
// a speaker-similarity score per montage clip -> <project>/voice-match.json
import process from "node:process";
@@ -720,6 +722,8 @@ function usage() {
" umtool take <project> --id <id> --label L [--style S] [--patch F | --set p=v …] [--at S --dur S | --full]",
" one take: the manifest with a style's patch, rendered into takes/<id>/ (--rebuild, --force)",
" 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 voice-match <project> [--reference auto|rulings|recordings] [--reference-video <channel>/<id> …] [--instances F] [--dry] [--json]",
" a local speaker-similarity score per montage clip (TitaNet-small) -> <project>/voice-match.json",
" umtool refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]",
@@ -758,6 +762,8 @@ const COMMANDS = {
// The take maker (release 33): lib/report/takeCli.mjs.
take: async () => process.exit(await (await import("../lib/report/takeCli.mjs")).takeCommand(argv.slice(argv.indexOf("take") + 1))),
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))),
// Who is speaking, per montage clip (release 34): lib/report/voiceMatch.mjs.
"voice-match": async () => process.exit(await (await import("../lib/report/voiceMatch.mjs")).voiceMatchCommand(argv.slice(argv.indexOf("voice-match") + 1))),
inbox: cmdInbox,
diff --git a/umtool/components/projects/ClipDeckPage.tsx b/umtool/components/projects/ClipDeckPage.tsx
@@ -0,0 +1,54 @@
+import Link from "next/link";
+import { CLIP_DECK_SHOWS, type ClipDeckShow, projectsHref, takesHref } from "@/lib/hrefs";
+import { clipDeckView } from "@/lib/report/clipDeck";
+import { pieceHrefOfProject } from "@/lib/pieces/article";
+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 { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+
+// `/projects/<project>/clips` -- THE CLIP DECK (release 34 N1): a montage's
+// every instance, one card at a time, its cut playing, ruled by ear: keep, cut,
+// not him (another speaker), read aloud (a post or a quote read out). The
+// rulings are <project>/montage-rulings.json (lib/report/montageRulings.mjs)
+// and a render applies them (report-to-video/montage-rulings.mjs). Nothing
+// here calls a model; release 34 N2's voice-match.json, when it is there,
+// only orders the doubtful first and shows its score.
+
+export default async function ClipDeckPage({ project, show }: { project: ProjectRef; show?: string }) {
+ const view = await clipDeckView(project);
+ const back = await pieceHrefOfProject(project.id, { tab: "cut" });
+ const top = <BenchTop trail={[{ href: projectsHref(), label: "Projects" }]} back={{ href: back, label: project.id }} kind="Clip deck" here="clips" />;
+ if (!view || !view.cards.length) {
+ return (
+ <BenchFrame kind="clips" top={top}>
+ <BenchBody workClassName="space-y-3">
+ <p data-clip-deck-empty="" className="text-[12px] text-[var(--color-dim)]">
+ No montage clips in this cut.{" "}
+ <Link href={back} className="ink-link">
+ back to {project.id}
+ </Link>
+ </p>
+ </BenchBody>
+ </BenchFrame>
+ );
+ }
+ const initialShow: ClipDeckShow = (CLIP_DECK_SHOWS as readonly string[]).includes(show ?? "")
+ ? (show as ClipDeckShow)
+ : view.cards.every((c) => view.rulings[c.key])
+ ? "all"
+ : "unruled";
+ return (
+ <BenchFrame kind="clips" top={top}>
+ <ClipDeck
+ project={project.id}
+ view={view}
+ initialShow={initialShow}
+ back={back}
+ takesHref={takesHref(project.id)}
+ voicePanel={<VoiceMatchPanel project={project.id} summary={voiceMatchSummary(await readVoiceMatch(project.dir))} reload />}
+ />
+ </BenchFrame>
+ );
+}
diff --git a/umtool/components/projects/ProjectView.tsx b/umtool/components/projects/ProjectView.tsx
@@ -9,6 +9,7 @@ import SweepProject from "./SweepProject";
import TakesPage from "./TakesPage";
import NarrationPage from "./NarrationPage";
import ReviewPage from "./ReviewPage";
+import ClipDeckPage from "./ClipDeckPage";
// ---------------------------------------------------------------------------
// The one place a kind id is matched against a component.
@@ -62,6 +63,9 @@ export default async function ProjectView({
// `/browse/<project>/review` -- every drafted field, approved / rejected
// before a final build, and the alternatives a draft task kept.
if (rest.length === 1 && rest[0] === "review") return <ReviewPage project={project} view={search.view} />;
+ // `/projects/<project>/clips` -- the montage's instances, ruled by ear
+ // keep / cut / not him / read aloud (release 34), applied at render.
+ if (rest.length === 1 && rest[0] === "clips") return <ClipDeckPage project={project} show={search.show} />;
return notFound();
}
case "sweep-report": {
diff --git a/umtool/components/projects/report/CutTab.tsx b/umtool/components/projects/report/CutTab.tsx
@@ -8,13 +8,15 @@ import {
} from "@/lib/projects/report.mjs";
import { listTakes } from "@/lib/report/takes.mjs";
import { buttonVariants } from "@/components/ui/button";
-import { clipBenchHref, mixHref as toolsMixHref, projectHref, takesHref } from "@/lib/hrefs";
+import { clipBenchHref, clipDeckHref, mixHref as toolsMixHref, projectHref, takesHref } from "@/lib/hrefs";
+import { montageClipsOf, momentKeysOf, readRulingsState } from "@/lib/report/montageRulings.mjs";
import FetchUnfetchedButton from "../FetchUnfetchedButton";
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 { readVoiceMatch, voiceMatchKey } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+import { readVoiceMatch, voiceMatchSummary } from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
+import { clipMomentKey } from "umtool-report-to-video/montage-rulings";
// The Cut tab: the timeline, read back -- the walk into it, its takes, every
// entry with what is wrong with it, and the corrections the walk collected.
@@ -55,11 +57,22 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
const walkStart = (readiness.readyIds[0] as string | undefined) ?? clips[0]?.id;
const showAll = search.all === "1";
const takes = await listTakes(project.dir);
+ // A montage (clips carrying `montage`) is ruled on the clip deck (release 34):
+ // how many of its instances have no ruling yet.
+ const montage = montageClipsOf(m) as { id: string }[];
+ const unruled = montage.length
+ ? await readRulingsState(project.dir).then(({ doc }) => {
+ const keys = momentKeysOf(m) as Map<string, string>;
+ return montage.filter((e) => !doc.rulings[keys.get(e.id) ?? ""]).length;
+ })
+ : 0;
// Who is speaking, per clip (release 34): voice-match.json, keyed by the
- // source moment (channel/video@cutStart), so a re-seed keeps its scores.
+ // source moment (clipMomentKey, the rulings' key), so a re-seed keeps its scores.
const voices = await readVoiceMatch(project.dir);
- const voiceOf = (e: { channel?: string | null; video?: string; cutStart?: number; start: number }) =>
- voices && e.channel && e.video ? voices.clips[voiceMatchKey(e.channel, e.video, e.cutStart ?? e.start)] ?? null : null;
+ const voiceOf = (e: Record<string, unknown>) => {
+ const key = voices ? (clipMomentKey({ ...e, type: "clip" }, m) as string | null) : null;
+ return key ? voices!.clips[key] ?? null : null;
+ };
// ---- what a clip's "mix" link opens ---------------------------------------
//
@@ -129,6 +142,16 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
</span>
</div>
)}
+ {/* A montage's instances, ruled by ear before a render (release 34). */}
+ {montage.length > 0 && (
+ <Link
+ href={clipDeckHref(project.id)}
+ data-clip-deck-link={unruled}
+ className={buttonVariants({ size: "lg" })}
+ >
+ Clips — {unruled ? `${unruled} of ${montage.length} to rule` : `${montage.length} ruled`}
+ </Link>
+ )}
{/* Alternative renders of part of the cut, judged on their own page --
where the first one is made, too (release 33's take maker). */}
{takes.exists ? (
@@ -147,18 +170,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
{clips.length > 0 && (
<VoiceMatchPanel
project={project.id}
- summary={
- voices
- ? {
- madeAt: voices.madeAt,
- counts: voices.counts,
- reference:
- voices.reference.kind === "rulings"
- ? `${voices.reference.kept} clips ruled keep`
- : `${(voices.reference.recordings as unknown[] | undefined)?.length ?? 0} solo recordings`,
- }
- : null
- }
+ summary={voiceMatchSummary(voices)}
/>
)}
</div>
@@ -254,7 +266,7 @@ export default async function CutTab({ project, detail, search, tabHref }: Repor
return (
<span data-voice={v.label ?? "unscored"} data-voice-score={v.score ?? ""}>
<Pill tone={v.label === "unlikely" ? TONE.blocking : v.label === "unsure" ? TONE.open : TONE.info}>
- {v.score == null ? `voice: ${v.why ?? "not scored"}` : `voice ${v.score.toFixed(2)} · ${v.label}`}
+ {typeof v.score !== "number" ? `voice: ${v.why ?? "not scored"}` : `voice ${v.score.toFixed(2)} · ${v.label}`}
</Pill>
</span>
);
diff --git a/umtool/components/projects/report/VoiceMatchPanel.tsx b/umtool/components/projects/report/VoiceMatchPanel.tsx
@@ -32,7 +32,16 @@ const REFERENCES = [
["recordings", "solo recordings on disk"],
] as const;
-export default function VoiceMatchPanel({ project, summary }: { project: string; summary: VoiceMatchSummary | null }) {
+export default function VoiceMatchPanel({
+ project,
+ summary,
+ reload = false,
+}: {
+ project: string;
+ summary: VoiceMatchSummary | null;
+ /** Reload the page when the run is done (the clip deck keeps its cards in state). */
+ reload?: boolean;
+}) {
const router = useRouter();
const [reference, setReference] = useState<string>("auto");
const [job, setJob] = useState<JobView | null>(null);
@@ -52,7 +61,10 @@ export default function VoiceMatchPanel({ project, summary }: { project: string;
}
setJob(j);
if (j.state !== "running") {
- if (j.state === "done") router.refresh();
+ if (j.state === "done") {
+ if (reload) window.location.reload();
+ else router.refresh();
+ }
return;
}
}
@@ -78,7 +90,7 @@ export default function VoiceMatchPanel({ project, summary }: { project: string;
const running = job?.state === "running";
const last = [...(job?.events ?? [])].reverse().find((e) => e.ev === "voice-match") as { phase?: string; n?: number; of?: number } | undefined;
return (
- <div data-voice-match="" className="flex flex-col items-start gap-1">
+ <div data-voice-match-panel="" className="flex flex-col items-start gap-1">
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
@@ -110,7 +122,8 @@ export default function VoiceMatchPanel({ project, summary }: { project: string;
{summary && (
<span data-voice-summary="" className="num text-[11px] text-[var(--color-dim)]">
voices: {summary.counts.likely} likely · {summary.counts.unsure} unsure · {summary.counts.unlikely} unlikely of{" "}
- {summary.counts.scored} scored · against {summary.reference} · {summary.madeAt.slice(0, 16).replace("T", " ")}
+ {summary.counts.scored} scored · against {summary.reference}
+ {summary.madeAt ? ` · ${summary.madeAt.slice(0, 16).replace("T", " ")}` : ""}
</span>
)}
{job && (
diff --git a/umtool/components/projects/review/ClipDeck.tsx b/umtool/components/projects/review/ClipDeck.tsx
@@ -0,0 +1,947 @@
+"use client";
+
+import Link from "next/link";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import CitedClip, { warmCited, type CitedClipHandle } from "@/components/clips/CitedClip";
+import { buttonVariants } from "@/components/ui/button";
+import type { ClipDeckShow } from "@/lib/hrefs";
+import type { ClipCard, ClipDeckView, ClipRuling } from "@/lib/report/clipDeck";
+import { cn } from "@/lib/utils";
+import { startTakeJob } from "../NewTakePanel";
+
+// ---------------------------------------------------------------------------
+// THE CLIP DECK (release 34 N1): a montage's instances, ruled by ear -- the
+// co-host hazard is the point: a co-host's or a guest's line, or a post read
+// out, credited to the host. One card per instance, its cut playing; the
+// decision is one gesture, the next card is underneath. Built on the drafts
+// review's audition deck (AuditionDeck.tsx, release 32 R1): the same swipe,
+// stamps, undo and bar under the thumb; its own verdicts.
+//
+// swipe → / → k KEEP it is him, saying it
+// swipe ← / ← x CUT out of the montage (a reason chip or a few words, never required)
+// swipe ↓ / ↓ n NOT HIM another speaker: a co-host, a guest, a clip played
+// swipe ↑ / ↑ r READ ALOUD him reading a post, a tweet, a quote out
+// e EDIT the phrase the cut is cut to (Enter keeps it, wider)
+// s SKIP to the back
+// w WIDER: play the clip's whole extent, not just the phrase
+// tap the video / space replay
+// z / Backspace UNDO the last ruling or skip (20 deep)
+//
+// Rulings write through /api/report/montage-rulings (montage-rulings.json,
+// keyed by the moment, so a re-seed keeps them); a render leaves out every
+// clip ruled cut, not him or read aloud, and numbers the kept ones 1…N.
+// ---------------------------------------------------------------------------
+
+type Verdict = ClipRuling["verdict"];
+type Dir = "right" | "left" | "down" | "up";
+type Undo = { id: string; kind: "rule" | "skip"; prev: ClipRuling | null };
+type Plan = { kept: { id: string; n: number | null; of: number | null; match: string | null }[]; left: { id: string; verdict: Verdict; reason: string }[]; lines: string[] };
+
+const VERDICT_OF: Record<Dir, Verdict> = { right: "keep", left: "cut", down: "not-him", up: "read-aloud" };
+const STAMP: Record<Verdict, string> = { keep: "KEEP", cut: "CUT", "not-him": "NOT HIM", "read-aloud": "READ ALOUD" };
+const WORDS: Record<Verdict, string> = { keep: "kept", cut: "cut", "not-him": "not him", "read-aloud": "read aloud" };
+const REASONS = ["co-host", "guest", "a clip played", "a post read out", "chat read out", "wrong moment", "says something else"];
+const SHOWS: { show: ClipDeckShow; label: string }[] = [
+ { show: "unruled", label: "Unruled" },
+ { show: "doubtful", label: "Doubtful first" },
+ { show: "ruled", label: "Ruled" },
+ { show: "all", label: "All" },
+];
+const THRESHOLD = 0.3;
+const FLICK = 0.6;
+const UNDO_DEPTH = 20;
+const DECK_CSS = `@keyframes deck-rise { from { transform: scale(0.97) translateY(4px); } to { transform: none; } }
+.deck-rise { animation: deck-rise 120ms ease-out; }
+@keyframes deck-out-right { from { transform: translate(var(--dx), var(--dy)) rotate(var(--r)); } to { transform: translate(120%, 0) rotate(8deg); opacity: 0.6; } }
+@keyframes deck-out-left { from { transform: translate(var(--dx), var(--dy)) rotate(var(--r)); } to { transform: translate(-120%, 0) rotate(-8deg); opacity: 0.6; } }
+@keyframes deck-out-down { from { transform: translate(var(--dx), var(--dy)); } to { transform: translate(0, 110%); opacity: 0; } }
+@keyframes deck-out-up { from { transform: translate(var(--dx), var(--dy)); } to { transform: translate(0, -110%); opacity: 0; } }
+@keyframes deck-fade { from { opacity: 1; } to { opacity: 0; } }
+.deck-out-right { animation: deck-out-right 160ms ease-in forwards; }
+.deck-out-left { animation: deck-out-left 160ms ease-in forwards; }
+.deck-out-down { animation: deck-out-down 160ms ease-in forwards; }
+.deck-out-up { animation: deck-out-up 160ms ease-in forwards; }
+.deck-fade { animation: deck-fade 80ms linear forwards; }
+@media (prefers-reduced-motion: reduce) { .deck-rise { animation: none; } }`;
+const TYPING = "input, textarea, select, [contenteditable=''], [contenteditable='true']";
+
+const stampClass = (v: Verdict) =>
+ cn(
+ "pointer-events-none absolute top-24 z-10 rotate-[-8deg] rounded-[4px] border-[3px] px-2.5 py-0.5 font-display text-[24px] font-bold uppercase tracking-wide",
+ v === "keep" ? "left-4 border-signal text-signal" : v === "cut" ? "right-4 border-muted text-muted line-through" : "right-4 border-seam-2 text-text-2",
+ );
+
+const doubt = (c: ClipCard) => (c.voice?.label === "unlikely" ? 0 : c.voice?.label === "unsure" ? 1 : c.voiceCheck ? 2 : 3);
+
+/** The cards a filter walks, in the order it walks them. */
+function queueOf(cards: ClipCard[], rulings: Record<string, ClipRuling>, show: ClipDeckShow): string[] {
+ const ruled = (c: ClipCard) => !!rulings[c.key];
+ if (show === "all") return cards.map((c) => c.id);
+ if (show === "ruled") return cards.filter(ruled).map((c) => c.id);
+ const open = cards.filter((c) => !ruled(c));
+ if (show === "unruled") return open.map((c) => c.id);
+ // Doubtful first: the voice match's unlikely (lowest score first), then its
+ // unsure, then a voice check in the clip's note, then the rest in order.
+ return open
+ .map((c, i) => ({ c, i }))
+ .sort((a, b) => doubt(a.c) - doubt(b.c) || (a.c.voice && b.c.voice ? a.c.voice.score - b.c.voice.score : 0) || a.i - b.i)
+ .map(({ c }) => c.id);
+}
+
+/** The quote, its phrase marked (case and punctuation aside). */
+function Quote({ quote, phrase }: { quote: string; phrase: string }) {
+ const words = phrase.toLowerCase().match(/[\p{L}\p{N}']+/gu) ?? [];
+ const re = words.length ? new RegExp(words.map((w) => w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[^\\p{L}\\p{N}']+"), "iu") : null;
+ const m = re ? re.exec(quote) : null;
+ if (!m) return <>“{quote}”</>;
+ return (
+ <>
+ “{quote.slice(0, m.index)}
+ <mark data-phrase="" className="rounded-[2px] bg-transparent px-0 text-text underline decoration-signal decoration-2 underline-offset-[5px]">
+ {m[0]}
+ </mark>
+ {quote.slice(m.index + m[0].length)}”
+ </>
+ );
+}
+
+export default function ClipDeck({
+ project,
+ view,
+ initialShow,
+ back,
+ takesHref,
+ voicePanel = null,
+}: {
+ project: string;
+ view: ClipDeckView;
+ initialShow: ClipDeckShow;
+ back: string;
+ takesHref: string;
+ /** Release 34 N2's "Score the voices" (VoiceMatchPanel), shown in the head. */
+ voicePanel?: React.ReactNode;
+}) {
+ const cards = view.cards;
+ const byId = useMemo(() => new Map(cards.map((c) => [c.id, c])), [cards]);
+ const [rulings, setRulings] = useState<Record<string, ClipRuling>>(view.rulings);
+ const [show, setShow] = useState<ClipDeckShow>(initialShow);
+ const [queue, setQueue] = useState<string[]>(() => queueOf(cards, view.rulings, initialShow));
+ const [total, setTotal] = useState(queue.length);
+ const [walked, setWalked] = useState(0);
+ const [skipped, setSkipped] = useState<Set<string>>(new Set());
+ const [undos, setUndos] = useState<Undo[]>([]);
+ const [started, setStarted] = useState(false);
+ const [wide, setWide] = useState(false);
+ const [editing, setEditing] = useState(false);
+ const [matchText, setMatchText] = useState("");
+ const [reason, setReason] = useState("");
+ const [error, setError] = useState<string | null>(view.rulingsError);
+ const [busy, setBusy] = useState(false);
+ const [offer, setOffer] = useState(view.offer);
+ const [imported, setImported] = useState<number | null>(null);
+ const [drag, setDrag] = useState<{ dx: number; dy: number } | null>(null);
+ const [ghost, setGhost] = useState<null | { id: string; dir: Dir; dx: number; dy: number; at: number }>(null);
+ const [reduced, setReduced] = useState(false);
+ const [hints, setHints] = useState(false);
+ const clip = useRef<CitedClipHandle | null>(null);
+ const cardEl = useRef<HTMLDivElement | null>(null);
+ const start = useRef<{ x: number; y: number; t: number; id: number } | null>(null);
+ const writable = !view.rulingsError;
+
+ useEffect(() => {
+ const m = window.matchMedia("(prefers-reduced-motion: reduce)");
+ setReduced(m.matches);
+ const on = () => setReduced(m.matches);
+ m.addEventListener("change", on);
+ return () => m.removeEventListener("change", on);
+ }, []);
+
+ const live = queue.filter((id) => !skipped.has(id));
+ const topId = live[0] ?? null;
+ const top = topId ? (byId.get(topId) ?? null) : null;
+ const under = live[1] ? (byId.get(live[1]) ?? null) : null;
+ const counts = useMemo(() => {
+ const c: Record<Verdict, number> = { keep: 0, cut: 0, "not-him": 0, "read-aloud": 0 };
+ for (const card of cards) {
+ const r = rulings[card.key];
+ if (r) c[r.verdict] += 1;
+ }
+ return c;
+ }, [cards, rulings]);
+ const ruledCount = counts.keep + counts.cut + counts["not-him"] + counts["read-aloud"];
+ const at = Math.min(walked + skipped.size + 1, total);
+ const hintShown = hints || walked + skipped.size < 3;
+
+ // The card after the next: ask what plays it before it is shown.
+ useEffect(() => {
+ const after = live[2] ? byId.get(live[2]) : null;
+ if (after?.cut) warmCited(after.cut);
+ }, [live, byId]);
+
+ const walk = useCallback(
+ (s: ClipDeckShow, from: Record<string, ClipRuling> = rulings) => {
+ const q = queueOf(cards, from, s);
+ setShow(s);
+ setQueue(q);
+ setTotal(q.length);
+ setWalked(0);
+ setSkipped(new Set());
+ setEditing(false);
+ try {
+ const u = new URL(window.location.href);
+ u.searchParams.set("show", s);
+ window.history.replaceState(null, "", u);
+ } catch {}
+ },
+ [cards, rulings],
+ );
+
+ const post = async (body: Record<string, unknown>) => {
+ const r = await fetch("/api/report/montage-rulings", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ project, ...body }),
+ cache: "no-store",
+ });
+ const j = (await r.json().catch(() => ({}))) as { error?: string; rulings?: Record<string, ClipRuling>; written?: string[] };
+ if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
+ if (j.rulings) setRulings(j.rulings);
+ return j;
+ };
+
+ const remember = (u: Undo) => setUndos((s) => [...s.slice(-(UNDO_DEPTH - 1)), u]);
+
+ const rule = useCallback(
+ async (id: string, verdict: Verdict, extra: { match?: string } = {}) => {
+ const c = byId.get(id);
+ if (!c || !writable) return;
+ const prev = rulings[c.key] ?? null;
+ setError(null);
+ setQueue((q) => q.filter((x) => x !== id));
+ setWalked((n) => n + 1);
+ remember({ id, kind: "rule", prev });
+ const ruling: Record<string, string> = { verdict, reason };
+ // A ruling keeps a phrase it had unless this one sets it.
+ const match = extra.match ?? prev?.match;
+ if (match && match !== c.phrase) ruling.match = match;
+ setRulings((r) => ({ ...r, [c.key]: { verdict, reason, ...(ruling.match ? { match: ruling.match } : {}), at: new Date().toISOString() } }));
+ try {
+ await post({ clip: id, ruling });
+ setReason("");
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ setQueue((q) => [id, ...q.filter((x) => x !== id)]);
+ setWalked((n) => Math.max(0, n - 1));
+ setUndos((s) => s.slice(0, -1));
+ setRulings((r) => {
+ const n = { ...r };
+ if (prev) n[c.key] = prev;
+ else delete n[c.key];
+ return n;
+ });
+ }
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [byId, rulings, reason, writable],
+ );
+
+ const decide = useCallback(
+ (dir: Dir | "skip") => {
+ if (!topId || busy || editing) return;
+ setStarted(true);
+ const id = topId;
+ const at_ = Date.now();
+ const gdir: Dir = dir === "skip" ? "down" : dir;
+ setGhost({ id, dir: gdir, dx: drag?.dx ?? 0, dy: drag?.dy ?? 0, at: at_ });
+ setDrag(null);
+ setWide(false);
+ window.setTimeout(() => setGhost((g) => (g?.at === at_ ? null : g)), reduced ? 80 : 160);
+ if (dir === "skip") {
+ setSkipped((s) => new Set(s).add(id));
+ setQueue((q) => [...q.filter((x) => x !== id), id]);
+ remember({ id, kind: "skip", prev: null });
+ return;
+ }
+ void rule(id, VERDICT_OF[dir]);
+ },
+ [topId, busy, editing, drag, reduced, rule],
+ );
+
+ const undo = useCallback(async () => {
+ const u = undos[undos.length - 1];
+ if (!u || busy) return;
+ setUndos((s) => s.slice(0, -1));
+ setError(null);
+ setEditing(false);
+ if (u.kind === "skip") {
+ setSkipped((s) => {
+ const n = new Set(s);
+ n.delete(u.id);
+ return n;
+ });
+ setQueue((q) => [u.id, ...q.filter((x) => x !== u.id)]);
+ return;
+ }
+ const c = byId.get(u.id);
+ if (!c) return;
+ setBusy(true);
+ try {
+ await post({ clip: u.id, ruling: u.prev ? { verdict: u.prev.verdict, reason: u.prev.reason, ...(u.prev.match ? { match: u.prev.match } : {}) } : null });
+ setWalked((n) => Math.max(0, n - 1));
+ setQueue((q) => [u.id, ...q.filter((x) => x !== u.id)]);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [undos, busy, byId]);
+
+ const openEdit = useCallback(() => {
+ if (!top || busy) return;
+ setStarted(true);
+ setEditing(true);
+ setMatchText(rulings[top.key]?.match ?? top.phrase);
+ }, [top, busy, rulings]);
+
+ const saveEdit = () => {
+ if (!top) return;
+ const m = matchText.trim().replace(/\s+/g, " ");
+ setEditing(false);
+ void rule(top.id, "keep", { match: m && m !== top.phrase ? m : undefined });
+ };
+
+ const importEarlier = async () => {
+ setBusy(true);
+ setError(null);
+ try {
+ const j = await post({ import: true });
+ const n = j.written?.length ?? 0;
+ setImported(n);
+ setOffer({ count: 0, left: 0, matched: 0, unmapped: offer.unmapped });
+ if (j.rulings) walk(show, j.rulings);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ // The keys. Typing (the phrase, the few words) keeps its own.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;
+ const t = e.target as HTMLElement | null;
+ if (editing) {
+ if (e.key === "Escape") {
+ e.preventDefault();
+ setEditing(false);
+ }
+ return;
+ }
+ if (t?.closest?.(TYPING)) return;
+ const k = e.key;
+ const act = (fn: () => void) => {
+ e.preventDefault();
+ fn();
+ };
+ if (k === "ArrowRight" || k === "k") act(() => decide("right"));
+ else if (k === "ArrowLeft" || k === "x") act(() => decide("left"));
+ else if (k === "ArrowDown" || k === "n") act(() => decide("down"));
+ else if (k === "ArrowUp" || k === "r") act(() => decide("up"));
+ else if (k === "s") act(() => decide("skip"));
+ else if (k === "e") act(openEdit);
+ else if (k === "w")
+ act(() => {
+ setStarted(true);
+ setWide((w) => !w);
+ });
+ else if (k === "z" || k === "Backspace") act(() => void undo());
+ else if (k === " ")
+ act(() => {
+ setStarted(true);
+ clip.current?.playSpan();
+ });
+ else if (k === "?") act(() => setHints((h) => !h));
+ else if (k === "Escape") (document.activeElement as HTMLElement | null)?.blur?.();
+ };
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [decide, undo, editing, openEdit]);
+
+ // The drag: past 30 % of the card's width, or a flick, decides; below it springs back.
+ const onPointerDown = (e: React.PointerEvent) => {
+ if (editing || e.button !== 0) return;
+ if ((e.target as HTMLElement).closest("button, a, input, textarea, select")) return;
+ start.current = { x: e.clientX, y: e.clientY, t: performance.now(), id: e.pointerId };
+ };
+ const onPointerMove = (e: React.PointerEvent) => {
+ const s = start.current;
+ if (!s || s.id !== e.pointerId) return;
+ const dx = e.clientX - s.x;
+ const dy = e.clientY - s.y;
+ if (!drag && Math.hypot(dx, dy) < 6) return;
+ if (!drag) (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
+ setDrag({ dx, dy });
+ };
+ const onPointerUp = () => {
+ const s = start.current;
+ start.current = null;
+ if (!s || !drag) return;
+ const w = cardEl.current?.offsetWidth ?? 400;
+ const dt = Math.max(1, performance.now() - s.t);
+ const { dx, dy } = drag;
+ const horizontal = Math.abs(dx) >= Math.abs(dy);
+ const d = horizontal ? dx : dy;
+ if (Math.abs(d) > THRESHOLD * w || Math.abs(d) / dt > FLICK) decide(horizontal ? (dx > 0 ? "right" : "left") : dy < 0 ? "up" : "down");
+ else setDrag(null);
+ };
+ const width = cardEl.current?.offsetWidth ?? 400;
+ const stamp: { v: Verdict; o: number } | null = drag
+ ? Math.abs(drag.dx) >= Math.abs(drag.dy)
+ ? { v: drag.dx > 0 ? "keep" : "cut", o: Math.min(1, Math.abs(drag.dx) / (width * THRESHOLD)) }
+ : { v: drag.dy < 0 ? "read-aloud" : "not-him", o: Math.min(1, Math.abs(drag.dy) / (width * THRESHOLD)) }
+ : null;
+
+ const counter = (
+ <span data-deck-count="" className="font-mono text-[11.5px] text-muted">
+ {total ? `${at} / ${total}` : "0 / 0"} · {counts.keep} kept · {counts.cut} cut · {counts["not-him"]} not him · {counts["read-aloud"]} read aloud
+ {skipped.size ? ` · ${skipped.size} skipped` : ""}
+ </span>
+ );
+ const head = (
+ <div className="space-y-2">
+ <div className="flex flex-wrap items-center gap-1.5 text-[12px]" role="group" aria-label="Which clips">
+ {SHOWS.map((s) => (
+ <button
+ key={s.show}
+ type="button"
+ data-deck-show={s.show}
+ aria-pressed={show === s.show}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => walk(s.show)}
+ className={buttonVariants({ variant: show === s.show ? "pressed" : "outline", size: "sm" })}
+ >
+ {s.label}
+ </button>
+ ))}
+ <span data-deck-ruled={ruledCount} className="ml-auto font-mono text-[11.5px] text-muted">
+ {ruledCount} of {cards.length} ruled
+ </span>
+ </div>
+ {counter}
+ {offer.count > 0 && (
+ <div data-import-offer={offer.count} className="flex flex-wrap items-center gap-2 rounded-[4px] border border-seam bg-panel px-3 py-2 text-[12px] text-text-2">
+ <span>
+ edits.json has {offer.count} earlier ruling{offer.count === 1 ? "" : "s"}
+ {offer.left ? ` · ${offer.left} left out` : ""}
+ {offer.matched ? ` · ${offer.matched} phrase${offer.matched === 1 ? "" : "s"} widened` : ""}
+ </span>
+ <button type="button" data-import-rulings="" disabled={busy || !writable} onClick={() => void importEarlier()} className={buttonVariants({ variant: "outline", size: "sm" })}>
+ Import {offer.count} earlier ruling{offer.count === 1 ? "" : "s"}
+ </button>
+ </div>
+ )}
+ {imported !== null && (
+ <p data-imported={imported} className="m-0 text-[12px] text-text-2">
+ Imported {imported} earlier ruling{imported === 1 ? "" : "s"}.
+ </p>
+ )}
+ {view.voiceMatch && (
+ <p data-voice-match={view.voiceMatch.count} className="m-0 font-mono text-[11px] text-muted">
+ voice match: {view.voiceMatch.count} clips scored{view.voiceMatch.model ? ` · ${view.voiceMatch.model}` : ""}
+ </p>
+ )}
+ {voicePanel}
+ </div>
+ );
+
+ if (!top) {
+ return (
+ <main data-deck="" data-clip-deck="" className="deck-main flex-1 p-4">
+ <div className="mx-auto max-w-[560px] space-y-4">
+ {head}
+ <EndCard
+ project={project}
+ cards={cards}
+ rulings={rulings}
+ counts={counts}
+ skipped={[...skipped]}
+ total={total}
+ onWalk={walk}
+ onSkipped={() => setSkipped(new Set())}
+ rerender={view.rerender}
+ takes={view.takes}
+ takesHref={takesHref}
+ back={back}
+ />
+ {error && (
+ <p role="alert" data-deck-error="" className="m-0 text-[12px] text-reject-text">
+ {error}
+ </p>
+ )}
+ </div>
+ </main>
+ );
+ }
+
+ const target = wide ? (top.extent ?? top.cut) : top.cut;
+ const peeks = Math.min(3, live.length - 1);
+ const ghostCard = ghost ? byId.get(ghost.id) : null;
+ return (
+ <main data-deck="" data-clip-deck="" className="deck-main flex min-h-0 flex-1 flex-col p-3 pb-24 sm:p-4 md:pb-4">
+ <div className="mx-auto flex w-full max-w-[560px] flex-col gap-3">
+ {head}
+ <style>{DECK_CSS}</style>
+ <div className="relative">
+ {under && (
+ <div aria-hidden data-card-under={under.id} className="pointer-events-none absolute inset-0 z-[1] origin-top scale-[0.97] overflow-hidden rounded-[8px] border border-seam bg-panel">
+ <Card card={under} ruling={rulings[under.key] ?? null} target={under.cut} preload />
+ </div>
+ )}
+ <div
+ ref={cardEl}
+ key={top.id}
+ role="region"
+ aria-label={`${top.id}: ${top.phrase}`}
+ tabIndex={-1}
+ data-card={top.id}
+ data-card-key={top.key}
+ data-card-top=""
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={() => {
+ start.current = null;
+ setDrag(null);
+ }}
+ className="deck-card deck-rise relative z-[2] touch-pan-y select-none rounded-[8px] border border-seam-2 bg-panel shadow-sm outline-none focus-visible:ring-2 focus-visible:ring-signal"
+ style={{
+ transform: drag ? `translate(${drag.dx}px, ${drag.dy}px) rotate(${drag.dx * 0.04}deg)` : undefined,
+ transition: drag ? "none" : "transform 120ms ease-out",
+ }}
+ >
+ {stamp && stamp.o > 0.05 && (
+ <span data-stamp={stamp.v} aria-hidden className={stampClass(stamp.v)} style={{ opacity: stamp.o }}>
+ {STAMP[stamp.v]}
+ </span>
+ )}
+ <Card
+ card={top}
+ ruling={rulings[top.key] ?? null}
+ target={target}
+ wide={wide}
+ playing={started}
+ clipRef={clip}
+ project={project}
+ editing={editing}
+ matchText={matchText}
+ onMatchText={setMatchText}
+ onSaveEdit={saveEdit}
+ onCancelEdit={() => setEditing(false)}
+ />
+ {!started && (
+ <div className="absolute inset-0 z-20 flex items-center justify-center rounded-[8px] bg-[color-mix(in_srgb,var(--ground)_55%,transparent)]">
+ <button
+ type="button"
+ data-deck-start=""
+ className={cn(buttonVariants({ variant: "outline", size: "lg" }), "bg-panel")}
+ onClick={() => {
+ setStarted(true);
+ clip.current?.playSpan();
+ }}
+ >
+ Start listening
+ </button>
+ </div>
+ )}
+ </div>
+ {ghost && ghostCard && (
+ <div
+ key={ghost.at}
+ aria-hidden
+ data-card-ghost={ghost.dir}
+ className={cn("pointer-events-none absolute inset-x-0 top-0 z-[3] overflow-hidden rounded-[8px] border border-seam-2 bg-panel shadow-sm", reduced ? "deck-fade" : `deck-out-${ghost.dir}`)}
+ style={{ "--dx": `${ghost.dx}px`, "--dy": `${ghost.dy}px`, "--r": `${ghost.dx * 0.04}deg` } as React.CSSProperties}
+ >
+ <div className="space-y-2 p-4 sm:p-5">
+ <span className="micro">{ghostCard.id}</span>
+ <p className="m-0 font-display text-[22px] font-semibold leading-[1.2] text-text">{ghostCard.phrase}</p>
+ </div>
+ </div>
+ )}
+ </div>
+ {peeks > 0 && (
+ <div aria-hidden data-deck-peeks={peeks} className="-mt-3 flex flex-col items-center">
+ {Array.from({ length: peeks }, (_, i) => (
+ <div key={i} className="h-[5px] rounded-b-[6px] border border-t-0 border-seam bg-panel-2" style={{ width: `${96 - i * 4}%` }} />
+ ))}
+ </div>
+ )}
+ {/* Why: optional, one tap, said with the next ruling. */}
+ <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label="Why">
+ {REASONS.map((r) => (
+ <button
+ key={r}
+ type="button"
+ data-reason={r}
+ aria-pressed={reason === r}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => setReason(reason === r ? "" : r)}
+ className={cn("rounded-full border px-2 py-[2px] text-[11.5px]", reason === r ? "border-muted bg-panel-2 text-text" : "border-seam-2 text-muted-2 hover:text-text")}
+ >
+ {r}
+ </button>
+ ))}
+ <input
+ value={REASONS.includes(reason) ? "" : reason}
+ onChange={(e) => setReason(e.target.value)}
+ placeholder="or why, in a few words"
+ aria-label="Why, in a few words"
+ data-reason-note=""
+ maxLength={300}
+ className="min-w-[10rem] flex-1 rounded-[3px] border border-seam-2 bg-ground px-1.5 py-[2px] text-[11.5px] text-text outline-none focus:border-signal"
+ />
+ </div>
+ <div className="flex flex-wrap items-center gap-1.5">
+ <QuietButton action="wider" pressed={wide} label={wide ? "Just the phrase" : "Wider"} k="w" onClick={() => { setStarted(true); setWide((w) => !w); }} />
+ <QuietButton action="edit-match" label="Edit the phrase" k="e" onClick={openEdit} disabled={busy || !writable} />
+ <QuietButton action="skip" label="Skip" k="s" onClick={() => decide("skip")} disabled={busy} />
+ </div>
+ {error && (
+ <p role="alert" data-deck-error="" className="m-0 text-[12px] text-reject-text">
+ {error}
+ </p>
+ )}
+ {/* Every gesture is a button too: a bar under the thumb on a phone. */}
+ <nav aria-label="Rule" className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 gap-1.5 border-t border-seam bg-ground p-2 md:static md:z-auto md:border-0 md:bg-transparent md:p-0">
+ <DeckButton action="undo" label="Undo" k="z" disabled={!undos.length || busy} onClick={() => void undo()} />
+ <DeckButton action="cut" label="Cut" k="←" disabled={busy || !writable} onClick={() => decide("left")} />
+ <DeckButton action="not-him" label="Not him" k="↓" disabled={busy || !writable} onClick={() => decide("down")} />
+ <DeckButton action="read-aloud" label="Read aloud" k="↑" disabled={busy || !writable} onClick={() => decide("up")} />
+ <DeckButton action="keep" label="Keep" k="→" go disabled={busy || !writable} onClick={() => decide("right")} />
+ </nav>
+ <p
+ data-deck-hint={hintShown ? "shown" : "hidden"}
+ aria-hidden={!hintShown}
+ className={cn("m-0 hidden text-center font-mono text-[11px] text-muted transition-opacity duration-500 md:block", hintShown ? "opacity-100" : "opacity-0")}
+ >
+ ← cut · ↓ not him · ↑ read aloud · keep → · e phrase · w wider · s skip · space replays · z undoes · ? keys
+ </p>
+ </div>
+ </main>
+ );
+}
+
+function DeckButton({ action, label, k, go = false, disabled, onClick }: { action: string; label: string; k: string; go?: boolean; disabled?: boolean; onClick: () => void }) {
+ return (
+ <button
+ type="button"
+ data-deck-action={action}
+ disabled={disabled}
+ aria-label={`${label} (${k})`}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={onClick}
+ className={cn(buttonVariants({ variant: go ? "go" : "outline", size: "lg" }), "flex-col gap-0 px-1 py-2 text-[12.5px] leading-tight md:flex-row md:gap-1.5 md:text-[13px]")}
+ >
+ <span>{label}</span>
+ <kbd className="hidden md:inline">{k}</kbd>
+ </button>
+ );
+}
+
+function QuietButton({ action, label, k, pressed, disabled, onClick }: { action: string; label: string; k: string; pressed?: boolean; disabled?: boolean; onClick: () => void }) {
+ return (
+ <button
+ type="button"
+ data-deck-action={action}
+ aria-pressed={pressed}
+ disabled={disabled}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={onClick}
+ className={buttonVariants({ variant: pressed ? "pressed" : "quiet", size: "sm" })}
+ >
+ {label} <kbd className="hidden md:inline">{k}</kbd>
+ </button>
+ );
+}
+
+/** One instance: the phrase, its cut playing, the quote, where and when, the note, the voice match. */
+function Card({
+ card,
+ ruling,
+ target,
+ wide = false,
+ preload = false,
+ playing = false,
+ clipRef,
+ project,
+ editing = false,
+ matchText = "",
+ onMatchText,
+ onSaveEdit,
+ onCancelEdit,
+}: {
+ card: ClipCard;
+ ruling: ClipRuling | null;
+ target: ClipCard["cut"];
+ wide?: boolean;
+ preload?: boolean;
+ playing?: boolean;
+ clipRef?: React.Ref<CitedClipHandle>;
+ project?: string;
+ editing?: boolean;
+ matchText?: string;
+ onMatchText?: (s: string) => void;
+ onSaveEdit?: () => void;
+ onCancelEdit?: () => void;
+}) {
+ const phrase = ruling?.match ?? card.phrase;
+ return (
+ <div className="flex flex-col gap-3 p-4 sm:p-5" data-card-body={card.id}>
+ <div className="flex flex-wrap items-baseline gap-2">
+ <span className="micro">{card.n !== null ? `#${card.n}${card.of ? ` of ${card.of}` : ""}` : card.id}</span>
+ <span className="font-mono text-[11px] text-muted">{card.id}</span>
+ {ruling && (
+ <span data-card-ruling={ruling.verdict} className="rounded-full border border-seam-2 px-2 py-[1px] text-[11px] text-text-2">
+ {WORDS[ruling.verdict]}
+ {ruling.reason ? ` · ${ruling.reason}` : ""}
+ </span>
+ )}
+ {card.voice && (
+ <span
+ data-card-voice={card.voice.label}
+ title={card.voice.speechSeconds !== null ? `${card.voice.speechSeconds.toFixed(1)} s of speech` : undefined}
+ className={cn("ml-auto rounded-full border px-2 py-[1px] font-mono text-[11px]", card.voice.label === "likely" ? "border-seam-2 text-text-2" : "border-muted text-text")}
+ >
+ voice {card.voice.label} · {card.voice.score.toFixed(2)}
+ </span>
+ )}
+ </div>
+ {editing ? (
+ <div className="space-y-1.5">
+ <input
+ autoFocus
+ data-card-match=""
+ aria-label="The phrase the cut is cut to"
+ value={matchText}
+ onChange={(e) => onMatchText?.(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ onSaveEdit?.();
+ }
+ }}
+ className="w-full rounded-[3px] border border-signal bg-ground px-2 py-1.5 font-display text-[20px] leading-snug text-text outline-none"
+ />
+ <div className="flex flex-wrap items-center gap-2 text-[11.5px] text-muted">
+ <button type="button" data-card-save="" onClick={onSaveEdit} className={buttonVariants({ variant: "go", size: "sm" })}>
+ Keep with this phrase <kbd>Enter</kbd>
+ </button>
+ <button type="button" onClick={onCancelEdit} className={buttonVariants({ variant: "ghost", size: "sm" })}>
+ Cancel <kbd>Esc</kbd>
+ </button>
+ <span>The cut widens to the phrase.</span>
+ </div>
+ </div>
+ ) : (
+ <p data-card-phrase="" className="m-0 font-display text-[24px] font-semibold leading-[1.2] text-text sm:text-[28px]">
+ {phrase}
+ </p>
+ )}
+ {target ? (
+ <CitedClip
+ key={`${card.id}|${target.from}|${target.to}`}
+ ref={clipRef}
+ target={target}
+ face="card"
+ preload={preload}
+ autoPlay={playing && !preload}
+ reason={`umtool clip deck ${project ?? ""} ${card.id}`.trim()}
+ report={project}
+ />
+ ) : (
+ <p className="m-0 text-[12px] text-muted">No span to play.</p>
+ )}
+ {wide && <p data-card-wide="" className="m-0 font-mono text-[11px] text-muted">playing the whole clip, not just the phrase</p>}
+ {card.quote && (
+ <p data-card-quote="" className="m-0 font-serif text-[16px] leading-[1.45] text-text-2">
+ <Quote quote={card.quote} phrase={phrase} />
+ </p>
+ )}
+ <div className="space-y-0.5 text-[12px] text-muted">
+ <div className="font-mono text-[11px]" data-card-source="">
+ {[card.date, card.platform, card.channel, card.video].filter(Boolean).join(" · ")}
+ </div>
+ {card.note && (
+ <div data-card-note="" className={card.voiceCheck ? "text-text-2" : undefined}>
+ {card.note}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** The end of a walk: the counts, what the next render makes, and the take made again. */
+function EndCard({
+ project,
+ cards,
+ rulings,
+ counts,
+ skipped,
+ total,
+ onWalk,
+ onSkipped,
+ rerender,
+ takes,
+ takesHref,
+ back,
+}: {
+ project: string;
+ cards: ClipCard[];
+ rulings: Record<string, ClipRuling>;
+ counts: Record<Verdict, number>;
+ skipped: string[];
+ total: number;
+ onWalk: (s: ClipDeckShow) => void;
+ onSkipped: () => void;
+ rerender: ClipDeckView["rerender"];
+ takes: number;
+ takesHref: string;
+ back: string;
+}) {
+ const [plan, setPlan] = useState<Plan | null>(null);
+ const [planError, setPlanError] = useState<string | null>(null);
+ const [job, setJob] = useState<{ id: string; state: string; error: string | null } | null>(null);
+ const [jobError, setJobError] = useState<string | null>(null);
+ const open = cards.filter((c) => !rulings[c.key]).length;
+ const since = rerender?.builtAt ? Object.values(rulings).filter((r) => r.at > (rerender.builtAt as string)).length : null;
+
+ // What the next render makes: the very rules a build applies, asked of the server.
+ useEffect(() => {
+ let gone = false;
+ void fetch(`/api/report/montage-rulings?project=${encodeURIComponent(project)}`, { cache: "no-store" })
+ .then(async (r) => {
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error ?? `HTTP ${r.status}`);
+ if (!gone) setPlan(j.plan as Plan);
+ })
+ .catch((e) => !gone && setPlanError(e instanceof Error ? e.message : String(e)));
+ return () => {
+ gone = true;
+ };
+ }, [project, rulings]);
+
+ useEffect(() => {
+ if (!job || job.state !== "running") return;
+ const t = setInterval(async () => {
+ const r = await fetch(`/api/report/takes/make?job=${job.id}`, { cache: "no-store" }).catch(() => null);
+ if (!r?.ok) return;
+ const j = (await r.json()) as { id: string; state: string; error: string | null };
+ setJob({ id: j.id, state: j.state, error: j.error });
+ }, 1500);
+ return () => clearInterval(t);
+ }, [job]);
+
+ const remake = async () => {
+ if (!rerender) return;
+ setJobError(null);
+ const r = await startTakeJob({ project, rebuild: rerender.take });
+ if (r.error || !r.job) setJobError(r.error ?? "the take did not start");
+ else setJob({ id: r.job.id, state: r.job.state, error: r.job.error });
+ };
+
+ const leftOut = cards.filter((c) => rulings[c.key] && rulings[c.key].verdict !== "keep");
+ return (
+ <section data-deck-summary="" className="space-y-3 rounded-[6px] border border-seam bg-panel p-5">
+ <h2 className="m-0 font-display text-[22px] font-semibold leading-tight text-text">
+ {counts.keep} kept · {counts.cut} cut · {counts["not-him"]} not him · {counts["read-aloud"]} read aloud
+ </h2>
+ <p className="m-0 text-[12.5px] text-text-2" data-deck-open={open}>
+ {total ? `${total} walked` : "Nothing to walk here"}
+ {open ? ` · ${open} still unruled` : " · every clip is ruled"}
+ {skipped.length ? ` · ${skipped.length} skipped` : ""}
+ </p>
+ {leftOut.length > 0 && (
+ <div>
+ <div className="micro">Left out of the render</div>
+ <ul className="m-0 mt-1 list-none space-y-1 p-0">
+ {leftOut.map((c) => (
+ <li key={c.id} data-left-out={c.id} className="text-[12.5px] text-text-2">
+ <span className="font-mono text-[11.5px] text-muted">{c.id}</span> {c.phrase} — {WORDS[rulings[c.key].verdict]}
+ {rulings[c.key].reason ? `: ${rulings[c.key].reason}` : ""}
+ <span className="text-muted"> · {c.date}</span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ <div data-render-plan={plan ? plan.kept.length : ""}>
+ <div className="micro">The next render</div>
+ {plan ? (
+ <p className="m-0 mt-1 text-[12.5px] text-text-2">
+ {plan.kept.length} clip{plan.kept.length === 1 ? "" : "s"}, numbered 1–{plan.kept.length}:{" "}
+ <span data-plan-kept={plan.kept.map((k) => k.id).join(" ")} className="font-mono text-[11.5px] text-muted">
+ {plan.kept.map((k) => k.id).join(" ")}
+ </span>
+ </p>
+ ) : (
+ <p className="m-0 mt-1 text-[12px] text-muted">{planError ?? "…"}</p>
+ )}
+ </div>
+ <div className="flex flex-wrap items-center gap-2 pt-1">
+ {rerender ? (
+ <button
+ type="button"
+ data-rerender-take={rerender.take}
+ disabled={job?.state === "running"}
+ onClick={() => void remake()}
+ className={buttonVariants({ variant: "go", size: "md" })}
+ >
+ Re-render the take — {rerender.label}
+ </button>
+ ) : (
+ <Link href={takesHref} prefetch={false} data-takes-choose="" className={buttonVariants({ variant: "go", size: "md" })}>
+ {takes ? "Choose a take to render again" : "Make a take"}
+ </Link>
+ )}
+ {skipped.length > 0 && (
+ <button type="button" className={buttonVariants({ variant: "outline", size: "md" })} onClick={onSkipped} data-deck-again="skipped">
+ The skipped ones
+ </button>
+ )}
+ {open > 0 && (
+ <button type="button" className={buttonVariants({ variant: "outline", size: "md" })} onClick={() => onWalk("unruled")} data-deck-again="unruled">
+ The unruled ones
+ </button>
+ )}
+ <button type="button" className={buttonVariants({ variant: "outline", size: "md" })} onClick={() => onWalk("ruled")} data-deck-again="ruled">
+ Walk the ruled ones again
+ </button>
+ <Link href={back} prefetch={false} data-deck-back="" className={buttonVariants({ variant: "quiet", size: "md" })}>
+ Back to the cut
+ </Link>
+ </div>
+ {rerender && (
+ <p className="m-0 text-[11.5px] text-muted" data-rerender-why={rerender.why}>
+ {rerender.why === "picked" ? "The picked take" : "The whole-cut take"}
+ {since !== null ? ` · ${since} ruling${since === 1 ? "" : "s"} since it was made` : ""}
+ </p>
+ )}
+ {job && (
+ <p data-rerender-job={job.state} className="m-0 text-[12px] text-text-2">
+ {job.state === "running" ? "Rendering" : job.state === "done" ? "Rendered" : `Failed${job.error ? `: ${job.error}` : ""}`} —{" "}
+ <Link href={takesHref} prefetch={false} className="ink-link">
+ the Takes page
+ </Link>
+ </p>
+ )}
+ {jobError && (
+ <p role="alert" data-rerender-error="" className="m-0 text-[12px] text-reject-text">
+ {jobError}
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -42,6 +42,7 @@ Inbox cannot disagree about what is wrong with one.
| `take <project> --id <id> --label L [--group G] [--kind similar\|different] [--summary S] [--style NAME] [--patch FILE \| --patch-json JSON \| --set path=value …] [--at S --dur S \| --full] [--quick] [--force] [--progress ndjson]` | one **take**: the manifest with a montage style's patch, then the take's own, rendered into `takes/<id>/` (the Takes page's New take); `--id <id> --rebuild` makes one again from its own `take.json` ([report-video.md](report-video.md#making-takes)) |
| `takes make <project> [--recipe FILE] [--only ID,ID] [--force]` · `takes make <project> --all-styles [--group G] [--at S --dur S \| --full]` | a recipe's takes, one at a time (default `takes/recipe.json`); every montage style, one take each (Make all styles); **exit 1** if any failed |
| `takes styles [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` |
+| `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) |
| `voice-match <project> [--reference auto\|rulings\|recordings] [--reference-video <channel>/<id> …] [--reference-channel <slug> …] [--instances FILE] [--span phrase\|cut] [--pad S] [--likely X --unlikely Y] [--out FILE] [--dry] [--json] [--progress ndjson]` | who is speaking, per montage clip: a local speaker-similarity score (TitaNet-small) against the host's voice → `<project>/voice-match.json` (the Cut tab's **Score the voices**); `--instances` also scores a phrase scan's instances not in the manifest; `--dry` prints the plan ([report-video.md](report-video.md#who-is-speaking-the-voice-match)) |
A project argument is an exact id, a directory, or a **unique** basename. Two
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -819,6 +819,47 @@ into a wall of the latest 25: they are taken out of the run (`wall.exclusive`,
beats, each group saying it in unison with its onsets synced to the beat, then
all 25 at once.
+### Ruling the clips
+
+A montage made from a transcript search hears every instance of the phrase,
+whoever said it: a co-host, a guest, a clip played on stream, a post read out.
+The **clip deck** (`/projects/<id>/clips`, the **Clips** button on the Cut tab
+of a cut whose clips carry `montage`) is where they are ruled by ear, one card
+at a time, the clip's cut playing from its cached window:
+
+| Gesture | Key | Ruling |
+| --- | --- | --- |
+| swipe → | → or `k` | **keep** |
+| swipe ← | ← or `x` | **cut** |
+| swipe ↓ | ↓ or `n` | **not him**: another speaker |
+| swipe ↑ | ↑ or `r` | **read aloud**: a post, a tweet, a quote read out |
+| | `e` | keep, with a wider phrase (the cut widens to it) |
+| | `s` · `w` · space · `z` | skip · play the clip's whole extent · replay · undo |
+
+A reason chip or a few words ride with the next ruling. The filters walk the
+unruled clips, the **doubtful first** (a voice match's `unlikely`, then
+`unsure`, then a clip whose note asks for a voice check), the ruled ones, or
+all. When `voice-match.json` (release 34's speaker score) is beside the
+manifest, each card shows its score; without it the deck works the same.
+
+The rulings are `montage-rulings.json` beside the manifest, keyed by the source
+moment (`<channel>/<video>@<cutStart>`), never the clip id — so a seed run again,
+which numbers its clips afresh, keeps every ruling. **A render applies them**:
+a clip ruled cut, not him or read aloud is left out of the cut and of the wall;
+a ruled phrase replaces `montage.match`; and the counter numbers the kept clips
+1…N, so it never skips a number. The build log names each clip left out and
+why; `verify-build` counts the clips that were built. With no rulings file the
+render is exactly what it was. `--no-rulings` builds every clip anyway. A take
+applies the rulings before it windows the cut, so a window still counts over the
+whole kept cut; a take's own manifest (what **Use this take** copies) stays as
+written.
+
+The end of a walk counts the rulings, lists the clips left out, shows the next
+render's clips as the build will number them, and **Re-render the take** makes
+the picked take (or the one whole-cut take) again with them. A seed's
+`edits.json` (its `exclude` and `match` lists) is offered once as **Import
+earlier rulings**. The same writer is `umtool rulings` ([cli.md](cli.md)).
+
### Who is speaking: the voice match
A montage of one phrase is also a montage of everyone who said it near the host:
diff --git a/umtool/e2e/clip-deck.spec.ts b/umtool/e2e/clip-deck.spec.ts
@@ -0,0 +1,160 @@
+import { test, expect, type Page } from "@playwright/test";
+import { existsSync, readFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import * as urls from "./urls";
+
+// ---------------------------------------------------------------------------
+// The montage clip deck (release 34 N1): every instance ruled by ear. The
+// earlier rulings in the seed's edits.json are imported once; "Doubtful first"
+// opens on the voice match's unlikely clip; a swipe keeps, ← cuts and z undoes
+// it, ↓ is not him, ↑ read aloud, e keeps with a wider phrase; the rulings are
+// montage-rulings.json, keyed by the moment, and survive a reload; the end
+// card's next render leaves out the ruled-out clips and numbers the kept. And
+// it fits a phone. Fixture: e2e/fixtures/clip-deck-fixture.mjs.
+// ---------------------------------------------------------------------------
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const FIXTURE = path.join(HERE, "..", ".e2e-song");
+const PROJECT = "reports/clip-deck-fixture";
+const DIR = path.join(FIXTURE, "reports", "clip-deck-fixture");
+const key = (at: string) => `testchan/vid1@${at}`;
+
+type Ruling = { verdict: string; reason: string; match?: string; at: string };
+const rulings = (): Record<string, Ruling> => {
+ const f = path.join(DIR, "montage-rulings.json");
+ if (!existsSync(f)) return {};
+ return (JSON.parse(readFileSync(f, "utf8")) as { rulings: Record<string, Ruling> }).rulings;
+};
+const verdictOf = (at: string) => rulings()[key(at)]?.verdict ?? null;
+
+/** Drag the top card by (dx, dy) with the mouse: a swipe. */
+async function swipe(page: Page, dx: number, dy: number) {
+ const box = (await page.locator("[data-card-top] [data-card-phrase]").boundingBox())!;
+ const x = box.x + box.width / 2;
+ const y = box.y + box.height / 2;
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ for (let i = 1; i <= 8; i += 1) await page.mouse.move(x + (dx * i) / 8, y + (dy * i) / 8);
+ await page.mouse.up();
+}
+
+test("the clip deck: import, doubtful first, swipe keep, cut + undo, not him, read aloud, a wider phrase; persisted; the next render", async ({ page, request }) => {
+ test.setTimeout(120_000);
+ await page.setViewportSize({ width: 1366, height: 900 });
+
+ // The Cut tab says the montage has clips to rule and links the deck.
+ await page.goto(urls.section(PROJECT, "cut"));
+ const link = page.locator("[data-clip-deck-link]");
+ await expect(link).toHaveAttribute("data-clip-deck-link", "6");
+ await expect(link).toHaveAttribute("href", urls.clipDeckHref(PROJECT));
+ await link.click();
+ await expect(page).toHaveURL(new RegExp(`${urls.clipDeckHref(PROJECT).replace(/\//g, "\\/")}$`));
+
+ const card = page.locator("[data-card-top]");
+ await expect(card).toHaveAttribute("data-card", "s01");
+ await expect(card.locator("[data-card-phrase]")).toHaveText("slow news day");
+ await expect(card.locator("[data-phrase]")).toHaveText("slow news day");
+ await expect(card.locator("[data-card-source]")).toContainText("1 May 2020 · youtube · testchan · vid1");
+ await expect(card.locator("[data-card-voice]")).toHaveText("voice likely · 0.86");
+ await expect(page.locator("[data-voice-match]")).toContainText("2 clips scored · titanet-small");
+ // Video first: the project's cached window.
+ await expect(card.locator("[data-play]")).toHaveAttribute("data-play", "window", { timeout: 15_000 });
+ await expect(card.locator("video[data-player]")).toHaveAttribute("src", /\/api\/report\/raw\?.*file=vid1_0\.00-9\.00\.mp4/);
+
+ // The seed's two earlier rulings, offered once.
+ await expect(page.locator("[data-import-offer]")).toContainText("edits.json has 2 earlier rulings · 1 left out · 1 phrase widened");
+ await page.locator("[data-import-rulings]").click();
+ await expect(page.locator("[data-imported]")).toHaveText("Imported 2 earlier rulings.");
+ await expect(page.locator("[data-import-offer]")).toHaveCount(0);
+ expect(rulings()[key("1.50")]).toMatchObject({ verdict: "not-him", reason: "another speaker" });
+ expect(rulings()[key("2.50")]).toMatchObject({ verdict: "keep", match: "it must be a slow news day" });
+ await expect(page.locator("[data-deck-ruled]")).toHaveText("2 of 6 ruled");
+
+ // Doubtful first: the voice match's unlikely, then the voice check in a note.
+ await page.locator('[data-deck-show="doubtful"]').click();
+ await expect(card).toHaveAttribute("data-card", "s06");
+ await expect(card.locator("[data-card-voice]")).toHaveText("voice unlikely · 0.21");
+ await expect(page.locator(`[data-card-under="s04"]`)).toHaveCount(1);
+ await page.locator('[data-deck-show="unruled"]').click();
+ await expect(card).toHaveAttribute("data-card", "s01");
+ await expect(page.locator("[data-deck-count]")).toContainText("1 / 4 · 1 kept · 0 cut · 1 not him · 0 read aloud");
+
+ // A swipe right keeps s01.
+ await page.locator("[data-deck-start]").click();
+ await swipe(page, 420, 0);
+ await expect.poll(() => verdictOf("0.50")).toBe("keep");
+
+ // s04: ← cuts, with a reason chip; z undoes it (the file has no ruling again); ↓ not him.
+ await expect(card).toHaveAttribute("data-card", "s04");
+ await expect(card.locator("[data-card-note]")).toHaveText("voice check: co-host show");
+ await page.locator('[data-reason="co-host"]').click();
+ await page.keyboard.press("ArrowLeft");
+ await expect.poll(() => rulings()[key("3.50")]).toMatchObject({ verdict: "cut", reason: "co-host" });
+ await page.keyboard.press("z");
+ await expect.poll(() => verdictOf("3.50")).toBeNull();
+ await expect(card).toHaveAttribute("data-card", "s04");
+ await page.keyboard.press("ArrowDown");
+ await expect.poll(() => verdictOf("3.50")).toBe("not-him");
+
+ // s05: ↑ read aloud.
+ await expect(card).toHaveAttribute("data-card", "s05");
+ await page.keyboard.press("ArrowUp");
+ await expect.poll(() => verdictOf("4.50")).toBe("read-aloud");
+
+ // s06: e edits the phrase; Enter keeps it, cut to the wider phrase.
+ await expect(card).toHaveAttribute("data-card", "s06");
+ await page.keyboard.press("e");
+ const input = card.locator("[data-card-match]");
+ await expect(input).toHaveValue("slow news day");
+ await input.fill("a slow news day number 6");
+ await input.press("Enter");
+ await expect.poll(() => rulings()[key("5.50")]).toMatchObject({ verdict: "keep", match: "a slow news day number 6" });
+
+ // The end: the counts, the left out, and the next render -- the kept, numbered.
+ const end = page.locator("[data-deck-summary]");
+ await expect(end).toContainText("3 kept · 0 cut · 2 not him · 1 read aloud");
+ await expect(end.locator("[data-left-out]")).toHaveCount(3);
+ await expect(end.locator("[data-plan-kept]")).toHaveAttribute("data-plan-kept", "s01 s03 s06");
+ await expect(end.locator("[data-render-plan]")).toContainText("3 clips, numbered 1–3");
+ // No take yet: the Takes page makes one.
+ await expect(end.locator("[data-takes-choose]")).toHaveAttribute("href", urls.takesHref(PROJECT));
+
+ // The route says the same: the very rules a build applies.
+ const plan = (await (await request.get(`/api/report/montage-rulings?project=${encodeURIComponent(PROJECT)}`)).json()) as {
+ plan: { kept: { id: string; n: number; of: number; match: string }[]; left: { id: string; verdict: string }[] };
+ };
+ expect(plan.plan.kept.map((k) => [k.id, k.n, k.of])).toEqual([["s01", 1, 3], ["s03", 2, 3], ["s06", 3, 3]]);
+ expect(plan.plan.kept[2].match).toBe("a slow news day number 6");
+ expect(plan.plan.left.map((l) => [l.id, l.verdict])).toEqual([["s02", "not-him"], ["s04", "not-him"], ["s05", "read-aloud"]]);
+
+ // Reload (the address keeps the filter, ?show=unruled): every ruling is the file's, nothing is left to rule.
+ await page.reload();
+ await expect(page.locator("[data-deck-ruled]")).toHaveText("6 of 6 ruled");
+ await expect(page.locator("[data-deck-open]")).toContainText("every clip is ruled");
+ // The deck's own address opens on all six, each wearing its ruling.
+ await page.goto(urls.clipDeckHref(PROJECT));
+ await expect(page.locator('[data-deck-show="all"]')).toHaveAttribute("aria-pressed", "true");
+ await expect(card).toHaveAttribute("data-card", "s01");
+ await expect(card.locator("[data-card-ruling]")).toHaveText("kept");
+ await expect(page.locator("[data-import-offer]")).toHaveCount(0);
+ expect(Object.keys(rulings()).sort()).toEqual(["0.50", "1.50", "2.50", "3.50", "4.50", "5.50"].map(key).sort());
+
+ // The Cut tab counts them ruled.
+ await page.goto(urls.section(PROJECT, "cut"));
+ await expect(page.locator("[data-clip-deck-link]")).toHaveText("Clips — 6 ruled");
+});
+
+test("the clip deck at phone width: one column, the bar under the thumb, no sideways scroll", async ({ page }) => {
+ await page.setViewportSize({ width: 390, height: 844 });
+ await page.goto(urls.clipDeckHref(PROJECT, { show: "all" }));
+ await expect(page.locator("[data-card-top]")).toBeVisible();
+ const bar = page.locator('nav[aria-label="Rule"]');
+ await expect(bar).toBeVisible();
+ for (const a of ["undo", "cut", "not-him", "read-aloud", "keep"]) await expect(bar.locator(`[data-deck-action="${a}"]`)).toBeVisible();
+ const box = (await bar.boundingBox())!;
+ expect(box.y + box.height).toBeLessThanOrEqual(844 + 1);
+ const wide = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
+ expect(wide).toBeLessThanOrEqual(0);
+ if (process.env.P6B_SHOTS) await page.screenshot({ path: path.join(process.env.P6B_SHOTS, "clip-deck-390x844.png"), fullPage: true });
+});
diff --git a/umtool/e2e/fixtures/clip-deck-fixture.mjs b/umtool/e2e/fixtures/clip-deck-fixture.mjs
@@ -0,0 +1,60 @@
+// What clip-deck.spec.ts walks (release 34 N1): a six-clip montage of one
+// synthetic source (vid1, its cues the fixture corpus's), every clip's window
+// cached in the project's out/clips-raw (a copy of vid1's 0-9 s), the seed's
+// edits.json with two earlier rulings (an exclude and a wider phrase), and a
+// voice-match.json in release 34 N2's shape scoring two clips. Its own project:
+// the spec writes montage-rulings.json beside its manifest.
+//
+// s01 0.5 s02 1.5 (edits: another speaker) s03 2.5 (edits: a wider phrase)
+// s04 3.5 (a voice check in its note) s05 4.5 s06 5.5 (voice: unlikely)
+//
+// Synthetic, like every fixture.
+import { copyFileSync, mkdirSync, writeFileSync } from "node:fs";
+import path from "node:path";
+
+const write = (dir, name, doc) => {
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, name), JSON.stringify(doc, null, 2) + "\n");
+};
+
+/**
+ * @param {{ reports: string, manifest: Function, cachedWindow: string }} o
+ */
+export function makeClipDeckFixture({ reports, manifest, cachedWindow }) {
+ const dir = path.join(reports, "clip-deck-fixture");
+ const clip = (n, at, extra = {}) => ({
+ type: "clip", id: `s0${n}`, video: "vid1", start: at - 0.5, end: at + 2.5, cutStart: at, cutEnd: at + 2, cite: at, section: 0, lock: true,
+ quote: `and it must be a slow news day number ${n} again`,
+ onscreen: { title: "slow news day", subtitle: `${n} May 2020` },
+ note: "",
+ montage: { n, of: 6, date: `2020050${n}`, platform: "youtube", match: "slow news day", speakerCheck: false },
+ ...extra,
+ });
+ // fetchPad 0, as a montage seed writes it: the cached window holds every clip's extent exactly.
+ const doc = manifest("clip-deck-fixture", "The Clip Deck Fixture", { siteOrigin: "https://archive.example" }, [
+ clip(1, 0.5),
+ clip(2, 1.5),
+ clip(3, 2.5),
+ clip(4, 3.5, { note: "voice check: co-host show", montage: { n: 4, of: 6, date: "20200504", platform: "youtube", match: "slow news day", speakerCheck: true } }),
+ clip(5, 4.5),
+ clip(6, 5.5),
+ ]);
+ doc.render.fetchPad = 0;
+ write(dir, "video.manifest.json", doc);
+ write(dir, "edits.json", {
+ exclude: [{ videoId: "vid1", near: 1.5, why: "another speaker" }],
+ match: [{ videoId: "vid1", near: 2.5, match: "it must be a slow news day", why: "the whole line" }],
+ });
+ write(dir, "voice-match.json", {
+ version: 1,
+ model: "titanet-small",
+ reference: { clips: ["testchan/vid1@0.50"] },
+ clips: {
+ "testchan/vid1@0.50": { score: 0.86, label: "likely", speechSeconds: 2 },
+ "testchan/vid1@5.50": { score: 0.21, label: "unlikely", speechSeconds: 1.8 },
+ },
+ });
+ mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true });
+ copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", "vid1_0.00-9.00.mp4"));
+ return { dir };
+}
diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs
@@ -29,6 +29,7 @@ import { makeMediaSurfacesFixture } from "./media-surfaces-fixture.mjs";
import { makeDeleteFixture } from "./delete-fixture.mjs";
import { makeDraftReviewFixture } from "./draft-review-fixture.mjs";
import { makeReviewPlayerFixture } from "./review-player-fixture.mjs";
+import { makeClipDeckFixture } from "./clip-deck-fixture.mjs";
import { makeBenchShellFixture } from "./bench-shell-fixture.mjs";
import { makeYoutubeFixture } from "./youtube-fixture.mjs";
import { makeBoardFixture, makeResearchFixture } from "./research-fixture.mjs";
@@ -1801,6 +1802,8 @@ for (const dir of [BENCH, BUILD, ONSCREEN, ONSCREEN_BUILD, ONSCREEN_POSTS, ONSCR
makeDraftReviewFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 32 R1: the audition deck, one window on disk and one fetched (review-player.spec.ts).
makeReviewPlayerFixture({ reports, channels: CHANNELS, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
+// Release 34 N1: the montage clip deck, six instances ruled by ear (clip-deck.spec.ts).
+makeClipDeckFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// P4b: the bench shell's own clips, and the Media tab's fields with their draft files.
makeBenchShellFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4") });
// Release 28 M6: the YouTube text, previewed and built (media-draft-e.spec.ts).
@@ -2136,6 +2139,7 @@ console.log(` onscreen-feed-fixture (writable, posts feed, built by t
console.log(` deliver-stop-fixture (writable: six confirmed clips to cut, for Stop and resume)`);
console.log(` takes-fixture (writable: takes/ with 4 takes over 2 groups, 1 skipped)`);
console.log(` takes-make-fixture (writable: one clip, its window cached, no takes/ -- the take maker's)`);
+console.log(` clip-deck-fixture (writable: six montage clips, windows cached, edits.json + voice-match.json -- the clip deck's)`);
console.log(` narration-fixture (writable: a narrated card, voiced by the editor stub's tone)`);
console.log(` narration-review-fixture (writable: two narrated cards, nothing judged)`);
console.log(` draft-review-fixture (writable: drafted on-screen, narration, teaser; an alternative), draft-review-build-fixture`);
diff --git a/umtool/e2e/visual-audit.spec.ts b/umtool/e2e/visual-audit.spec.ts
@@ -53,6 +53,7 @@ const PAGES: [string, string][] = [
["bench-narration", urls.narrationHref("reports/narration-review-fixture")],
["bench-takes", urls.takesHref("reports/takes-fixture")],
["bench-review", urls.reviewHref("reports/media-review-fixture", { view: "list" })],
+ ["bench-clips", urls.clipDeckHref("reports/clip-deck-fixture", { show: "all" })],
["create", urls.createHref()],
...(["research", "article", "article-board", "recurring", "video-article", "video-board", "video-recording", "video-report", "song"] as const).map(
(make) => [`create-${make}`, urls.createHref({ make })] as [string, string],
diff --git a/umtool/e2e/voice-match.spec.ts b/umtool/e2e/voice-match.spec.ts
@@ -21,7 +21,7 @@ const FILE = path.join(HERE, "..", ".e2e-song", "reports", "voice-fixture", "voi
test("Score the voices: a job writes voice-match.json and each clip row shows its score", async ({ page }) => {
await page.goto(urls.section(PROJECT, "cut"));
- const panel = page.locator("[data-voice-match]");
+ const panel = page.locator("[data-voice-match-panel]");
await expect(panel).toBeVisible();
await expect(page.locator("[data-voice-summary]")).toHaveCount(0);
await expect(page.locator("[data-entry] [data-voice]")).toHaveCount(0);
@@ -51,6 +51,17 @@ test("Score the voices: a job writes voice-match.json and each clip row shows it
await expect(panel.getByRole("button", { name: "Score the voices again" })).toBeVisible();
});
+test("the clip deck carries Score the voices, and its cards show the scores voice-match.json holds", async ({ page }) => {
+ // After the test above: voice-match.json is there.
+ await page.goto(urls.clipDeckHref(PROJECT, { show: "all" }));
+ const panel = page.locator("[data-voice-match-panel]");
+ await expect(panel).toBeVisible();
+ await expect(panel.locator("[data-voice-summary]")).toContainText("1 unlikely of 5 scored");
+ await expect(panel.getByRole("button", { name: "Score the voices again" })).toBeVisible();
+ // The deck puts the doubtful clip first, with its score (lane N1 reads the file).
+ await expect(page.locator("[data-card-voice]").first()).toHaveAttribute("data-card-voice", "unlikely");
+});
+
test("the route refuses what is not a report video, and a project that does not exist", async ({ request }) => {
expect((await request.post("/api/report/voice-match", { data: { project: "reports/no-such-project" } })).status()).toBe(404);
expect((await request.post("/api/report/voice-match", { data: "nope", headers: { "content-type": "application/json" } })).status()).toBe(400);
diff --git a/umtool/lib/hrefs.test.mjs b/umtool/lib/hrefs.test.mjs
@@ -13,6 +13,7 @@ test("note is always the last parameter", () => {
H.clipBenchHref("p", "c04", { note: "n" }),
H.claimBenchHref("p", "k1", { note: "n" }),
H.takesHref("p", { note: "n" }),
+ H.clipDeckHref("p", { show: "doubtful", note: "n" }),
H.narrationHref("p", { note: "n" }),
H.reviewHref("p", { note: "n" }),
H.projectAtHref("tools/x", { note: "n" }),
@@ -22,6 +23,11 @@ test("note is always the last parameter", () => {
}
});
+test("the clip deck: /projects/<p>/clips, its filter in `show`", () => {
+ assert.equal(H.clipDeckHref("a/b"), "/projects/a/b/clips");
+ assert.equal(H.clipDeckHref("a/b", { show: "unruled" }), "/projects/a/b/clips?show=unruled");
+});
+
test("withNote re-points an href and keeps note last, and the fragment after it", () => {
assert.equal(H.withNote("/articles/x?note=old&tab=source", "new"), "/articles/x?tab=source¬e=new");
assert.equal(H.withNote("/projects/p", "n"), "/projects/p?note=n");
diff --git a/umtool/lib/hrefs.ts b/umtool/lib/hrefs.ts
@@ -278,6 +278,15 @@ export function takesHref(project: string, q: NoteOpt = {}): string {
return withQuery(`/projects/${encodePath(project)}/takes`, {}, q.note);
}
+/** What the clip deck (release 34) walks: every instance, the unruled, the doubtful first, the ruled. */
+export const CLIP_DECK_SHOWS = ["all", "unruled", "doubtful", "ruled"] as const;
+export type ClipDeckShow = (typeof CLIP_DECK_SHOWS)[number];
+
+/** The montage clip deck: every instance ruled keep / cut / not him / read aloud (release 34). */
+export function clipDeckHref(project: string, q: NoteOpt & { show?: ClipDeckShow } = {}): string {
+ return withQuery(`/projects/${encodePath(project)}/clips`, q.show ? { show: q.show } : {}, q.note);
+}
+
/** The narration script, card by card. */
export function narrationHref(project: string, q: NoteOpt = {}): string {
return withQuery(`/projects/${encodePath(project)}/narration`, {}, q.note);
diff --git a/umtool/lib/report/clipDeck.ts b/umtool/lib/report/clipDeck.ts
@@ -0,0 +1,163 @@
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+import { channelFor, readManifest } from "@/lib/projects/report.mjs";
+import { listTakes, readVerdicts } from "@/lib/report/takes.mjs";
+import { clipMomentKey } from "umtool-report-to-video/montage-rulings";
+import { earlierRulingsOffer, montageClipsOf, readRulingsState } from "@/lib/report/montageRulings.mjs";
+import type { CitedTarget } from "@/lib/clips/types";
+
+// ---------------------------------------------------------------------------
+// THE CLIP DECK's page data (release 34 N1): one card per montage instance --
+// a clip carrying a `montage` object -- with what the deck needs to rule it by
+// ear: the cut and the clip's whole extent to play (the project's cached
+// windows first, through the cited clip), the quote with its phrase, the date
+// and source, the clip's note (the seed's "voice check", a stand-in upload),
+// and, when release 34 N2's voice-match.json is beside the manifest, its score.
+// Nothing here calls a model; voice-match.json is read if it is there.
+// ---------------------------------------------------------------------------
+
+export type ClipRuling = { verdict: "keep" | "cut" | "not-him" | "read-aloud"; reason: string; match?: string; at: string };
+export type VoiceMatch = { score: number; label: "likely" | "unsure" | "unlikely"; speechSeconds: number | null };
+
+export type ClipCard = {
+ id: string;
+ key: string;
+ /** The counter as the manifest has it (the render numbers the kept ones again). */
+ n: number | null;
+ of: number | null;
+ /** The phrase the cut is cut to: the manifest's `montage.match`, else its on-screen title. */
+ phrase: string;
+ quote: string | null;
+ /** "2 May 2019". */
+ date: string | null;
+ year: number | null;
+ platform: string | null;
+ channel: string;
+ video: string;
+ note: string;
+ /** The seed's voice check (a co-host show), or a note that says so. */
+ voiceCheck: boolean;
+ voice: VoiceMatch | null;
+ cut: CitedTarget | null;
+ extent: CitedTarget | null;
+};
+
+export type RerenderTarget = { take: string; label: string; builtAt: string | null; why: "picked" | "whole cut" };
+
+export type ClipDeckView = {
+ cards: ClipCard[];
+ rulings: Record<string, ClipRuling>;
+ rulingsError: string | null;
+ voiceMatch: { model: string | null; count: number } | null;
+ offer: { count: number; left: number; matched: number; unmapped: number };
+ /** The take "Re-render the take" makes again, or null (the Takes page chooses). */
+ rerender: RerenderTarget | null;
+ takes: number;
+};
+
+const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+const niceDate = (d: unknown) => {
+ const s = String(d ?? "");
+ if (!/^\d{8}$/.test(s)) return null;
+ return `${Number(s.slice(6, 8))} ${MONTHS[Number(s.slice(4, 6)) - 1] ?? "?"} ${s.slice(0, 4)}`;
+};
+const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
+
+/** release 34 N2's `<project>/voice-match.json`, read leniently: a row is used only when it is the shape. */
+export async function readVoiceMatch(dir: string): Promise<{ model: string | null; clips: Map<string, VoiceMatch> } | null> {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(await readFile(path.join(/* turbopackIgnore: true */ dir, "voice-match.json"), "utf8"));
+ } catch {
+ return null;
+ }
+ if (!raw || typeof raw !== "object") return null;
+ const r = raw as { model?: unknown; clips?: Record<string, unknown> };
+ const clips = new Map<string, VoiceMatch>();
+ for (const [k, v] of Object.entries(r.clips && typeof r.clips === "object" ? r.clips : {})) {
+ const row = v as { score?: unknown; label?: unknown; speechSeconds?: unknown };
+ const score = num(row?.score);
+ if (score === null || !["likely", "unsure", "unlikely"].includes(String(row?.label))) continue;
+ clips.set(k, { score, label: row.label as VoiceMatch["label"], speechSeconds: num(row.speechSeconds) });
+ }
+ return { model: typeof r.model === "string" ? r.model : null, clips };
+}
+
+/** How doubtful a card is: 0 voice unlikely, 1 voice unsure, 2 a voice check in its note, 3 nothing says so. */
+export const doubtOf = (c: Pick<ClipCard, "voice" | "voiceCheck">) =>
+ c.voice?.label === "unlikely" ? 0 : c.voice?.label === "unsure" ? 1 : c.voiceCheck ? 2 : 3;
+
+type Entry = Record<string, unknown> & {
+ id: string;
+ video?: string;
+ start?: number;
+ end?: number;
+ cutStart?: number;
+ cutEnd?: number;
+ quote?: string;
+ note?: string;
+ onscreen?: { title?: string };
+ montage?: { n?: number; of?: number; match?: string; date?: string; platform?: string; speakerCheck?: boolean };
+};
+
+export async function clipDeckView(project: { id: string; dir: string }): Promise<ClipDeckView | null> {
+ const manifest = await readManifest(project.dir);
+ if (!manifest) return null;
+ const [state, voice, listing, verdicts] = await Promise.all([
+ readRulingsState(project.dir),
+ readVoiceMatch(project.dir),
+ listTakes(project.dir),
+ readVerdicts(project.dir),
+ ]);
+ const offer = await earlierRulingsOffer(project.dir, manifest, state.doc);
+ const cards: ClipCard[] = [];
+ for (const e of montageClipsOf(manifest) as Entry[]) {
+ const key = clipMomentKey(e, manifest) as string | null;
+ const channel = channelFor(manifest, e) as string | null;
+ if (!key || !channel || !e.video) continue;
+ const m = e.montage ?? {};
+ const span = (from: unknown, to: unknown): CitedTarget | null => {
+ const f = num(from);
+ const t = num(to);
+ return f !== null && t !== null && f < t ? { channel, video: e.video as string, from: f, to: t, project: project.id, clip: e.id } : null;
+ };
+ const note = typeof e.note === "string" ? e.note.replace(/^[;\s]+/, "").trim() : "";
+ cards.push({
+ id: e.id,
+ key,
+ n: num(m.n),
+ of: num(m.of),
+ phrase: (typeof m.match === "string" && m.match) || e.onscreen?.title || "",
+ quote: typeof e.quote === "string" ? e.quote : null,
+ date: niceDate(m.date),
+ year: /^\d{8}$/.test(String(m.date ?? "")) ? Number(String(m.date).slice(0, 4)) : null,
+ platform: typeof m.platform === "string" ? m.platform : null,
+ channel,
+ video: e.video,
+ note,
+ voiceCheck: m.speakerCheck === true || /voice check/i.test(note),
+ voice: voice?.clips.get(key) ?? null,
+ cut: span(e.cutStart, e.cutEnd) ?? span(e.start, e.end),
+ extent: span(e.start, e.end),
+ });
+ }
+
+ // The take "Re-render the take" makes again: the one picked, else the one
+ // whole-cut take; anything else is a choice the Takes page makes.
+ type T = { id: string; label: string; builtAt: string | null; window?: unknown; baseHash?: string | null };
+ const made = (listing.takes as T[]).filter((t) => t.baseHash);
+ const picked = made.filter((t) => (verdicts as Record<string, { picked?: true }>)[t.id]?.picked);
+ const whole = made.filter((t) => t.window === "full");
+ const target = picked.length === 1 ? { t: picked[0], why: "picked" as const } : picked.length === 0 && whole.length === 1 ? { t: whole[0], why: "whole cut" as const } : null;
+
+ const left = offer.rulings.filter((r: { ruling: { verdict: string } }) => r.ruling.verdict !== "keep").length;
+ return {
+ cards,
+ rulings: state.doc.rulings as Record<string, ClipRuling>,
+ rulingsError: state.error,
+ voiceMatch: voice ? { model: voice.model, count: voice.clips.size } : null,
+ offer: { count: offer.rulings.length, left, matched: offer.rulings.length - left, unmapped: offer.unmapped.length },
+ rerender: target ? { take: target.t.id, label: target.t.label, builtAt: target.t.builtAt, why: target.why } : null,
+ takes: listing.takes.length,
+ };
+}
diff --git a/umtool/lib/report/montageRulings.mjs b/umtool/lib/report/montageRulings.mjs
@@ -0,0 +1,334 @@
+// THE CLIP DECK'S STORE (release 34 N1): `<project>/montage-rulings.json`, the
+// operator's verdict on each montage instance, written by ear on the clip deck
+// (`/projects/<id>/clips`) or `umtool rulings`. The shape, the key rule and how a
+// render applies it are report-to-video/montage-rulings.mjs; this is the ONE
+// writer.
+//
+// - every write is queued in-process, read-modify-write, tmp + rename;
+// - a file that does not parse (or is not the shape) is an ERROR: never
+// overwritten, never read as empty;
+// - a ruling is set whole ({verdict, reason, match?}, `at` stamped here) or
+// removed (null) -- the deck's undo is "set it back as it was".
+//
+// IMPORT. Before the deck, the operator ruled in chat and the rulings went into
+// the seed's `edits.json` beside the manifest ({exclude: [{videoId, near, why}],
+// match: [{videoId, near, match, why}]}, `near` the instance's start). Those map
+// to moments: the clip whose video matches and whose cutStart (else start) is
+// within 30 s; a moment the seed already left out of the manifest is found in
+// the seed's `instances.json` ({slug, videoId, start}) when there is one. An
+// exclude becomes not-him / read-aloud / cut by its words; a match keeps the
+// clip with the wider phrase. Moments already ruled are left as they are, so
+// the offer counts only what is new -- once imported, it is not offered again.
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import path from "node:path";
+import {
+ MONTAGE_RULINGS_FILE,
+ RULINGS_VERSION,
+ RULING_MATCH_LIMIT,
+ RULING_REASON_LIMIT,
+ RULING_VERDICTS,
+ applyMontageRulings,
+ clipMomentKey,
+ isMomentKey,
+ momentKey,
+ montageRulingsFileOf,
+ parseMontageRulings,
+ rulingsLines,
+} from "umtool-report-to-video/montage-rulings";
+
+export const EDITS_FILE = "edits.json";
+export const INSTANCES_FILE = "instances.json";
+/** How far an earlier ruling's `near` may be from the clip's cut start. */
+export const IMPORT_NEAR_SECONDS = 30;
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+
+let queue = Promise.resolve();
+/** @template T @param {() => Promise<T>} fn @returns {Promise<T>} */
+function withRulingsLock(fn) {
+ const run = queue.then(fn, fn);
+ queue = run.then(
+ () => undefined,
+ () => undefined,
+ );
+ return run;
+}
+
+/**
+ * The rulings as the page reads them: `{ exists, doc, error }`. A bad file is
+ * `error` (the page says so and refuses to write), never an empty doc.
+ * @param {string} projectDir
+ * @returns {Promise<{ exists: boolean, doc: { version: 1, rulings: Record<string, { verdict: string, reason: string, match?: string, at: string }> }, error: string | null }>}
+ */
+export async function readRulingsState(projectDir) {
+ let text = null;
+ try {
+ text = await readFile(montageRulingsFileOf(projectDir), "utf8");
+ } catch (err) {
+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT") return { exists: true, doc: emptyDoc(), error: String(err) };
+ }
+ if (text === null) return { exists: false, doc: emptyDoc(), error: null };
+ try {
+ return { exists: true, doc: parseMontageRulings(JSON.parse(text)), error: null };
+ } catch (e) {
+ return { exists: true, doc: emptyDoc(), error: `${MONTAGE_RULINGS_FILE} does not parse or is not the shape: ${e instanceof Error ? e.message : String(e)}` };
+ }
+}
+
+/** @returns {{ version: 1, rulings: Record<string, { verdict: string, reason: string, match?: string, at: string }> }} */
+const emptyDoc = () => ({ version: /** @type {1} */ (RULINGS_VERSION), rulings: {} });
+
+async function readForWrite(file) {
+ let text = null;
+ try {
+ text = await readFile(file, "utf8");
+ } catch (err) {
+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT") throw err;
+ }
+ if (text === null) return emptyDoc();
+ try {
+ return parseMontageRulings(JSON.parse(text));
+ } catch {
+ throw new Error(`${MONTAGE_RULINGS_FILE} does not parse or is not the shape; not overwriting it`);
+ }
+}
+
+async function writeDoc(file, doc) {
+ await mkdir(path.dirname(file), { recursive: true });
+ // Keys in order, so the file diffs as the deck walks.
+ const rulings = Object.fromEntries(Object.entries(doc.rulings).sort(([a], [b]) => a.localeCompare(b)));
+ const tmp = `${file}.tmp-${process.pid}-${Math.random().toString(36).slice(2, 8)}`;
+ await writeFile(tmp, JSON.stringify({ version: RULINGS_VERSION, rulings }, null, 2) + "\n", "utf8");
+ await rename(tmp, file);
+}
+
+/**
+ * One ruling, checked and normalised: `{verdict, reason, match?, at}`. Throws a
+ * sentence.
+ * @param {unknown} input
+ * @param {Date} now
+ */
+export function normaliseRuling(input, now = new Date()) {
+ if (!isObj(input)) throw new Error("a ruling is { verdict, reason?, match? }");
+ const verdict = input.verdict;
+ if (!RULING_VERDICTS.includes(/** @type {any} */ (verdict))) throw new Error(`verdict must be one of ${RULING_VERDICTS.join(", ")}`);
+ const reason = input.reason === undefined || input.reason === null ? "" : input.reason;
+ if (typeof reason !== "string") throw new Error("reason must be a string");
+ /** @type {{ verdict: string, reason: string, match?: string, at: string }} */
+ const out = { verdict: /** @type {string} */ (verdict), reason: reason.trim().slice(0, RULING_REASON_LIMIT), at: now.toISOString() };
+ if (input.match !== undefined && input.match !== null && input.match !== "") {
+ if (typeof input.match !== "string" || !input.match.trim()) throw new Error("match must be a phrase");
+ const m = input.match.trim().replace(/\s+/g, " ");
+ if (m.length > RULING_MATCH_LIMIT) throw new Error(`match is over ${RULING_MATCH_LIMIT} characters`);
+ out.match = m;
+ }
+ return out;
+}
+
+/**
+ * Set one moment's ruling (or remove it with `null`). Returns the whole doc.
+ * @param {string} projectDir
+ * @param {string} key
+ * @param {null | { verdict: string, reason?: string, match?: string | null }} ruling
+ * @param {{ now?: Date }} [opts]
+ */
+export async function setMontageRuling(projectDir, key, ruling, { now = new Date() } = {}) {
+ if (!isMomentKey(key)) throw new Error("not a moment key (<channel>/<video>@<seconds>)");
+ const next = ruling === null ? null : normaliseRuling(ruling, now);
+ const file = montageRulingsFileOf(projectDir);
+ return withRulingsLock(async () => {
+ const doc = await readForWrite(file);
+ if (next === null) delete doc.rulings[key];
+ else doc.rulings[key] = next;
+ await writeDoc(file, doc);
+ return { ruling: doc.rulings[key] ?? null, doc };
+ });
+}
+
+/** Many rulings in one write (the import). Keys already ruled are skipped unless `overwrite`. */
+export async function setMontageRulings(projectDir, entries, { now = new Date(), overwrite = false } = {}) {
+ const checked = entries.map(({ key, ruling }) => {
+ if (!isMomentKey(key)) throw new Error(`not a moment key: ${key}`);
+ return { key, ruling: normaliseRuling(ruling, now) };
+ });
+ const file = montageRulingsFileOf(projectDir);
+ return withRulingsLock(async () => {
+ const doc = await readForWrite(file);
+ const written = [];
+ for (const { key, ruling } of checked) {
+ if (doc.rulings[key] && !overwrite) continue;
+ doc.rulings[key] = ruling;
+ written.push(key);
+ }
+ if (written.length) await writeDoc(file, doc);
+ return { written, doc };
+ });
+}
+
+// ---------------------------------------------------------------------------
+// The montage clips, and their keys.
+// ---------------------------------------------------------------------------
+
+/** The clips a montage is made of: clips carrying a `montage` object, in order. */
+export const montageClipsOf = (manifest) =>
+ (Array.isArray(manifest?.timeline) ? manifest.timeline : []).filter((e) => isObj(e) && e.type === "clip" && isObj(e.montage));
+
+/** Does the manifest have a montage to rule (any clip with a `montage` object)? */
+export const hasMontageClips = (manifest) => montageClipsOf(manifest).length > 0;
+
+/** clip id → moment key, for every clip that has one. */
+export function momentKeysOf(manifest) {
+ const out = new Map();
+ for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) {
+ const k = clipMomentKey(e, manifest);
+ if (k) out.set(e.id, k);
+ }
+ return out;
+}
+
+/**
+ * Resolve a clip id or a key against the manifest to the key a ruling is
+ * written under. A key that is no clip's is refused: a ruling on a moment the
+ * cut does not have is a decision nobody made.
+ */
+export function resolveRulingKey(manifest, idOrKey) {
+ const keys = momentKeysOf(manifest);
+ if (keys.has(idOrKey)) return keys.get(idOrKey);
+ if ([...keys.values()].includes(idOrKey)) return idOrKey;
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// The import of the seed's edits.json.
+// ---------------------------------------------------------------------------
+
+/** An exclude's words → its verdict. */
+export function verdictFromWhy(why) {
+ const w = String(why ?? "").toLowerCase();
+ if (/\b(another|other|different) speaker|not (him|her|them)|co-?host|guest|caller|someone else/.test(w)) return "not-him";
+ if (/read (out|aloud)|reading|tweet|post\b|chat|quote[sd]? (out|aloud)|message/.test(w)) return "read-aloud";
+ return "cut";
+}
+
+const readJsonIf = async (file) => {
+ try {
+ return JSON.parse(await readFile(file, "utf8"));
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * The earlier rulings in the seed's edits.json, mapped to moments. Pure over
+ * what it is given.
+ *
+ * @param {Record<string, any>} manifest
+ * @param {unknown} edits edits.json's contents
+ * @param {unknown} [instances] instances.json's contents (the seed's)
+ * @returns {{ rulings: { key: string, clip: string | null, ruling: { verdict: string, reason: string, match?: string } }[], unmapped: { videoId: string, near: number, why: string }[] }}
+ */
+export function mapEarlierRulings(manifest, edits, instances = null) {
+ const out = { rulings: [], unmapped: [] };
+ if (!isObj(edits)) return out;
+ const clips = (manifest?.timeline ?? []).filter((e) => isObj(e) && e.type === "clip");
+ const inst = Array.isArray(instances) ? instances.filter(isObj) : [];
+ const at = (e) => (Number.isFinite(e.cutStart) ? e.cutStart : e.start);
+ const find = (videoId, near) => {
+ const near_ = Number(near);
+ const c = clips
+ .filter((e) => e.video === videoId && Number.isFinite(at(e)) && Math.abs(at(e) - near_) < IMPORT_NEAR_SECONDS)
+ .sort((a, b) => Math.abs(at(a) - near_) - Math.abs(at(b) - near_))[0];
+ if (c) {
+ const key = clipMomentKey(c, manifest);
+ if (key) return { key, clip: c.id };
+ }
+ const i = inst
+ .filter((x) => x.videoId === videoId && typeof x.slug === "string" && Number.isFinite(x.start) && Math.abs(x.start - near_) < IMPORT_NEAR_SECONDS)
+ .sort((a, b) => Math.abs(a.start - near_) - Math.abs(b.start - near_))[0];
+ if (i) {
+ const key = momentKey({ channel: i.slug, video: i.videoId, at: Math.round(i.start * 100) / 100 });
+ if (isMomentKey(key)) return { key, clip: null };
+ }
+ return null;
+ };
+ const take = (e, ruling) => {
+ if (!isObj(e) || typeof e.videoId !== "string" || !Number.isFinite(Number(e.near))) return;
+ const hit = find(e.videoId, e.near);
+ if (!hit) {
+ out.unmapped.push({ videoId: e.videoId, near: Number(e.near), why: String(e.why ?? "") });
+ return;
+ }
+ out.rulings.push({ ...hit, ruling });
+ };
+ for (const e of Array.isArray(edits.exclude) ? edits.exclude : []) {
+ take(e, { verdict: verdictFromWhy(e?.why), reason: String(e?.why ?? "").slice(0, RULING_REASON_LIMIT) });
+ }
+ for (const e of Array.isArray(edits.match) ? edits.match : []) {
+ if (typeof e?.match !== "string" || !e.match.trim()) continue;
+ take(e, { verdict: "keep", reason: String(e?.why ?? "").slice(0, RULING_REASON_LIMIT), match: e.match });
+ }
+ return out;
+}
+
+/**
+ * What the import would write now: the mapped earlier rulings whose moment is
+ * not ruled yet. `{ exists }` false when the project has no edits.json.
+ * @param {string} projectDir
+ * @param {Record<string, any>} manifest
+ * @param {{ rulings: Record<string, unknown> }} [doc] the current rulings (read when absent)
+ */
+export async function earlierRulingsOffer(projectDir, manifest, doc) {
+ const edits = await readJsonIf(path.join(/* turbopackIgnore: true */ projectDir, EDITS_FILE));
+ if (!edits) return { exists: false, rulings: [], unmapped: [] };
+ const instances = await readJsonIf(path.join(/* turbopackIgnore: true */ projectDir, INSTANCES_FILE));
+ const current = doc ?? (await readRulingsState(projectDir)).doc;
+ const mapped = mapEarlierRulings(manifest, edits, instances);
+ const seen = new Set();
+ const rulings = mapped.rulings.filter((r) => {
+ if (current.rulings[r.key] || seen.has(r.key)) return false;
+ seen.add(r.key);
+ return true;
+ });
+ return { exists: true, rulings, unmapped: mapped.unmapped };
+}
+
+/**
+ * Write the offer. Returns what was written and what could not be mapped.
+ * @param {string} projectDir
+ * @param {Record<string, any>} manifest
+ * @param {{ now?: Date, dryRun?: boolean }} [opts]
+ */
+export async function importEarlierRulings(projectDir, manifest, { now = new Date(), dryRun = false } = {}) {
+ const offer = await earlierRulingsOffer(projectDir, manifest);
+ if (dryRun || !offer.rulings.length) return { ...offer, written: [] };
+ const { written } = await setMontageRulings(projectDir, offer.rulings.map(({ key, ruling }) => ({ key, ruling })), { now });
+ return { ...offer, written };
+}
+
+// ---------------------------------------------------------------------------
+// What the next render makes of the rulings.
+// ---------------------------------------------------------------------------
+
+/**
+ * The next render's clips as the rulings have them -- the very function a
+ * build applies (report-to-video's applyMontageRulings): the kept clips in
+ * order with the counter's numbers and phrase, and the clips left out.
+ *
+ * @param {Record<string, any>} manifest
+ * @param {{ rulings: Record<string, any> } | null} doc
+ */
+export function renderPlan(manifest, doc) {
+ const applied = applyMontageRulings(manifest, doc);
+ const clips = (applied.manifest.timeline ?? []).filter((e) => isObj(e) && e.type === "clip");
+ return {
+ kept: clips.map((e) => ({
+ id: String(e.id),
+ n: Number.isFinite(e.montage?.n) ? e.montage.n : null,
+ of: Number.isFinite(e.montage?.of) ? e.montage.of : null,
+ match: typeof e.montage?.match === "string" ? e.montage.match : null,
+ })),
+ left: applied.left,
+ matched: applied.matched,
+ lines: rulingsLines(applied),
+ };
+}
diff --git a/umtool/lib/report/montageRulings.test.mjs b/umtool/lib/report/montageRulings.test.mjs
@@ -0,0 +1,168 @@
+// The clip deck's store (release 34 N1): one writer, a queue, tmp + rename, a
+// bad file never overwritten; the import of the seed's edits.json mapped to
+// moments (the clip within 30 s, else the seed's instances.json), offered once.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ earlierRulingsOffer, hasMontageClips, importEarlierRulings, mapEarlierRulings, momentKeysOf, normaliseRuling,
+ readRulingsState, resolveRulingKey, setMontageRuling, verdictFromWhy,
+} from "./montageRulings.mjs";
+
+const NOW = new Date("2026-10-18T12:00:00.000Z");
+const clip = (id, channel, video, cutStart) => ({
+ type: "clip", id, channel, video, start: cutStart - 2.5, end: cutStart + 5, cutStart, cutEnd: cutStart + 2, montage: { n: 1, of: 3, match: "slow news day" },
+});
+const MANIFEST = {
+ provenance: { channelSlug: "chan" },
+ timeline: [clip("s01", "chan", "aaa", 100), clip("s02", "chan-rumble", "v1a2b3c", 3597.6), clip("s03", "chan", "bbb", 12.25), { type: "card", id: "k1" }],
+};
+
+const tmp = () => mkdtemp(path.join(os.tmpdir(), "umtool-rulings-"));
+const file = (dir) => path.join(dir, "montage-rulings.json");
+
+test("keys: every clip's moment; a clip id or a key resolves, anything else is refused", () => {
+ assert.deepEqual([...momentKeysOf(MANIFEST)], [["s01", "chan/aaa@100.00"], ["s02", "chan-rumble/v1a2b3c@3597.60"], ["s03", "chan/bbb@12.25"]]);
+ assert.equal(resolveRulingKey(MANIFEST, "s02"), "chan-rumble/v1a2b3c@3597.60");
+ assert.equal(resolveRulingKey(MANIFEST, "chan/bbb@12.25"), "chan/bbb@12.25");
+ assert.equal(resolveRulingKey(MANIFEST, "chan/zzz@1.00"), null);
+ assert.equal(hasMontageClips(MANIFEST), true);
+ assert.equal(hasMontageClips({ timeline: [{ type: "clip", id: "c", video: "v", start: 1, end: 2 }] }), false);
+});
+
+test("normaliseRuling: checked, trimmed, stamped; a bad one is a sentence", () => {
+ assert.deepEqual(normaliseRuling({ verdict: "not-him", reason: " guest " }, NOW), { verdict: "not-him", reason: "guest", at: NOW.toISOString() });
+ assert.deepEqual(normaliseRuling({ verdict: "keep", match: " it's not that " }, NOW), { verdict: "keep", reason: "", match: "it's not that", at: NOW.toISOString() });
+ assert.throws(() => normaliseRuling({ verdict: "maybe" }), /verdict must be one of/);
+ assert.throws(() => normaliseRuling({ verdict: "cut", reason: 3 }), /reason must be a string/);
+ assert.throws(() => normaliseRuling(null), /a ruling is/);
+});
+
+test("setMontageRuling: set, replace, remove; writes queue; no temp file is left; the shape on disk", async () => {
+ const dir = await tmp();
+ try {
+ assert.deepEqual(await readRulingsState(dir), { exists: false, doc: { version: 1, rulings: {} }, error: null });
+ await Promise.all([
+ setMontageRuling(dir, "chan/aaa@100.00", { verdict: "cut", reason: "wrong moment" }, { now: NOW }),
+ setMontageRuling(dir, "chan/bbb@12.25", { verdict: "read-aloud" }, { now: NOW }),
+ setMontageRuling(dir, "chan-rumble/v1a2b3c@3597.60", { verdict: "keep", match: "it's not that it's a slow news cycle" }, { now: NOW }),
+ ]);
+ let disk = JSON.parse(await readFile(file(dir), "utf8"));
+ assert.equal(disk.version, 1);
+ assert.deepEqual(Object.keys(disk.rulings), ["chan-rumble/v1a2b3c@3597.60", "chan/aaa@100.00", "chan/bbb@12.25"]);
+ assert.deepEqual(disk.rulings["chan/aaa@100.00"], { verdict: "cut", reason: "wrong moment", at: NOW.toISOString() });
+ await setMontageRuling(dir, "chan/aaa@100.00", { verdict: "not-him" }, { now: NOW });
+ await setMontageRuling(dir, "chan/bbb@12.25", null);
+ disk = JSON.parse(await readFile(file(dir), "utf8"));
+ assert.equal(disk.rulings["chan/aaa@100.00"].verdict, "not-him");
+ assert.equal(disk.rulings["chan/bbb@12.25"], undefined);
+ assert.deepEqual((await readdir(dir)).sort(), ["montage-rulings.json"]);
+ await assert.rejects(setMontageRuling(dir, "s01", { verdict: "cut" }), /not a moment key/);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("a file that does not parse is an error: read as such, never overwritten", async () => {
+ const dir = await tmp();
+ try {
+ await writeFile(file(dir), "{ broken");
+ const st = await readRulingsState(dir);
+ assert.equal(st.exists, true);
+ assert.match(st.error, /does not parse/);
+ await assert.rejects(setMontageRuling(dir, "chan/aaa@100.00", { verdict: "cut" }), /not overwriting it/);
+ assert.equal(await readFile(file(dir), "utf8"), "{ broken");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("verdictFromWhy: an exclude's words", () => {
+ assert.equal(verdictFromWhy("another speaker"), "not-him");
+ assert.equal(verdictFromWhy("the co-host says it"), "not-him");
+ assert.equal(verdictFromWhy("a tweet read out, not his own line"), "read-aloud");
+ assert.equal(verdictFromWhy("reading chat"), "read-aloud");
+ assert.equal(verdictFromWhy("too long"), "cut");
+ assert.equal(verdictFromWhy(undefined), "cut");
+});
+
+const EDITS = {
+ exclude: [
+ { videoId: "aaa", near: 112, why: "another speaker" },
+ { videoId: "gone", near: 454, why: "a tweet read out, not his own line" },
+ { videoId: "nowhere", near: 1, why: "x" },
+ ],
+ match: [{ videoId: "v1a2b3c", near: 3597, match: "it's not that it's a slow news cycle", why: "the rebuttal" }],
+};
+const INSTANCES = [{ slug: "chan", videoId: "gone", start: 454.259 }, { slug: "chan", videoId: "aaa", start: 100 }];
+
+test("mapEarlierRulings: the clip whose video matches within 30 s; a moment the seed left out, from instances.json; the rest unmapped", () => {
+ const m = mapEarlierRulings(MANIFEST, EDITS, INSTANCES);
+ assert.deepEqual(m.rulings, [
+ { key: "chan/aaa@100.00", clip: "s01", ruling: { verdict: "not-him", reason: "another speaker" } },
+ { key: "chan/gone@454.26", clip: null, ruling: { verdict: "read-aloud", reason: "a tweet read out, not his own line" } },
+ { key: "chan-rumble/v1a2b3c@3597.60", clip: "s02", ruling: { verdict: "keep", reason: "the rebuttal", match: "it's not that it's a slow news cycle" } },
+ ]);
+ assert.deepEqual(m.unmapped, [{ videoId: "nowhere", near: 1, why: "x" }]);
+ // 30 s is the edge.
+ assert.equal(mapEarlierRulings(MANIFEST, { exclude: [{ videoId: "aaa", near: 130.1, why: "" }] }).rulings.length, 0);
+ assert.deepEqual(mapEarlierRulings(MANIFEST, null), { rulings: [], unmapped: [] });
+});
+
+test("the import: offered while something is new, written once, then not offered again; a ruled moment is left as it is", async () => {
+ const dir = await tmp();
+ try {
+ assert.deepEqual(await earlierRulingsOffer(dir, MANIFEST), { exists: false, rulings: [], unmapped: [] });
+ await writeFile(path.join(dir, "edits.json"), JSON.stringify(EDITS));
+ await writeFile(path.join(dir, "instances.json"), JSON.stringify(INSTANCES));
+ await setMontageRuling(dir, "chan/aaa@100.00", { verdict: "keep" }, { now: NOW });
+ const offer = await earlierRulingsOffer(dir, MANIFEST);
+ assert.deepEqual(offer.rulings.map((r) => r.key), ["chan/gone@454.26", "chan-rumble/v1a2b3c@3597.60"]);
+ const dry = await importEarlierRulings(dir, MANIFEST, { dryRun: true });
+ assert.deepEqual(dry.written, []);
+ const done = await importEarlierRulings(dir, MANIFEST, { now: NOW });
+ assert.deepEqual(done.written, ["chan/gone@454.26", "chan-rumble/v1a2b3c@3597.60"]);
+ const disk = (await readRulingsState(dir)).doc.rulings;
+ assert.equal(disk["chan/aaa@100.00"].verdict, "keep", "the deck's ruling stands");
+ assert.equal(disk["chan-rumble/v1a2b3c@3597.60"].match, "it's not that it's a slow news cycle");
+ assert.equal((await earlierRulingsOffer(dir, MANIFEST)).rulings.length, 0);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("umtool rulings: show, set, clear, import -- the same writer", async () => {
+ const { rulingsCommand } = await import("./rulingsCli.mjs");
+ const { mkdir } = await import("node:fs/promises");
+ const root = await tmp();
+ const dir = path.join(root, "slow");
+ try {
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ schemaVersion: 1, slug: "slow", title: "Slow", render: {}, ...MANIFEST }));
+ const lines = [];
+ const run = (...args) => rulingsCommand(args, { root, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`), now: NOW });
+ assert.equal(await run("slow", "set", "s01", "not-him", "--reason", "guest"), 0);
+ assert.equal(await run("slow", "set", "s02", "keep", "--match", "it's not that"), 0);
+ assert.equal(await run("slow", "set", "s09", "cut"), 1);
+ assert.match(lines.at(-1), /no montage clip "s09"/);
+ lines.length = 0;
+ assert.equal(await run("slow", "--json"), 0);
+ const shown = JSON.parse(lines.join("\n"));
+ assert.deepEqual(shown.plan.kept.map((k) => [k.id, k.n, k.match]), [["s02", 1, "it's not that"], ["s03", 2, "slow news day"]]);
+ assert.equal(await run("slow", "clear", "s01"), 0);
+ assert.equal((await readRulingsState(dir)).doc.rulings["chan/aaa@100.00"], undefined);
+ await writeFile(path.join(dir, "edits.json"), JSON.stringify(EDITS));
+ lines.length = 0;
+ assert.equal(await run("slow", "import", "--dry-run"), 0);
+ assert.match(lines.at(-1), /would import 1 earlier ruling/);
+ assert.equal(await run("slow", "import"), 0);
+ assert.equal((await readRulingsState(dir)).doc.rulings["chan/aaa@100.00"].verdict, "not-him");
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/report/rulingsCli.mjs b/umtool/lib/report/rulingsCli.mjs
@@ -0,0 +1,112 @@
+// `umtool rulings` (release 34 N1): the clip deck's rulings from a terminal --
+// the same writer the deck's buttons use (lib/report/montageRulings.mjs), so a
+// ruling typed here and one swiped there are the same file.
+//
+// umtool rulings <project> [--json] every montage clip, its ruling; the next render
+// umtool rulings <project> import [--dry-run] [--json] the earlier rulings in the seed's edits.json
+// umtool rulings <project> set <clip|key> <verdict> [--reason "…"] [--match "…"]
+// umtool rulings <project> clear <clip|key>
+import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
+import { readManifest } from "../projects/report.mjs";
+import {
+ hasMontageClips,
+ importEarlierRulings,
+ momentKeysOf,
+ montageClipsOf,
+ readRulingsState,
+ renderPlan,
+ resolveRulingKey,
+ setMontageRuling,
+} from "./montageRulings.mjs";
+
+export const RULINGS_USAGE = [
+ "usage: umtool rulings <project> [--json] each montage clip and its ruling; the next render",
+ " umtool rulings <project> import [--dry-run] [--json] the earlier rulings in the seed's edits.json",
+ " umtool rulings <project> set <clip|key> keep|cut|not-him|read-aloud [--reason \"…\"] [--match \"…\"]",
+ " umtool rulings <project> clear <clip|key>",
+ "",
+ "The clip deck's rulings (<project>/montage-rulings.json, keyed by the source moment): a render leaves",
+ "out every clip ruled cut, not-him or read-aloud, cuts to a ruled --match, and numbers the kept 1…N.",
+].join("\n");
+
+class CliError extends Error {}
+
+/**
+ * @param {string[]} args the words after `rulings`
+ * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void, now?: Date }} [opts]
+ * @returns {Promise<number>} the exit code
+ */
+export async function rulingsCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s), now = new Date() } = {}) {
+ const json = args.includes("--json");
+ const dryRun = args.includes("--dry-run");
+ const valued = new Set(["--reason", "--match"]);
+ const flags = new Map();
+ const words = [];
+ for (let i = 0; i < args.length; i += 1) {
+ const a = args[i];
+ if (valued.has(a)) {
+ flags.set(a, args[i + 1] ?? "");
+ i += 1;
+ } else if (!a.startsWith("--")) words.push(a);
+ }
+ try {
+ const [projectArg, verb = "show", target, verdict] = words;
+ if (!projectArg || args.includes("--help")) {
+ err(RULINGS_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;
+ const manifest = await readManifest(project.dir);
+ if (!manifest) throw new CliError(`${project.id} has no manifest`);
+ if (!hasMontageClips(manifest)) throw new CliError(`${project.id} has no montage clips (clips carrying \`montage\`)`);
+
+ if (verb === "show") {
+ const state = await readRulingsState(project.dir);
+ if (state.error) throw new CliError(state.error);
+ const keys = momentKeysOf(manifest);
+ const rows = montageClipsOf(manifest).map((e) => ({ id: e.id, key: keys.get(e.id) ?? null, ruling: state.doc.rulings[keys.get(e.id) ?? ""] ?? null }));
+ const plan = renderPlan(manifest, state.doc);
+ if (json) out(JSON.stringify({ project: project.id, clips: rows, plan }, null, 2));
+ else {
+ for (const row of rows) {
+ const v = row.ruling;
+ out(`${row.id.padEnd(5)} ${(v?.verdict ?? "—").padEnd(10)} ${row.key ?? "(no moment)"}${v?.match ? ` match "${v.match}"` : ""}${v?.reason ? ` — ${v.reason}` : ""}`);
+ }
+ out(`${rows.filter((x) => x.ruling).length} of ${rows.length} ruled; the next render: ${plan.kept.length} clip(s)`);
+ for (const line of plan.lines) out(line);
+ }
+ return 0;
+ }
+ if (verb === "import") {
+ const done = await importEarlierRulings(project.dir, manifest, { now, dryRun });
+ if (json) out(JSON.stringify({ project: project.id, dryRun, offered: done.rulings, written: done.written, unmapped: done.unmapped }, null, 2));
+ else {
+ if (!done.exists) out(`${project.id}: no edits.json — nothing to import`);
+ for (const x of done.rulings) {
+ out(`${dryRun ? "would write" : done.written.includes(x.key) ? "wrote" : "kept"} ${x.key}${x.clip ? ` (${x.clip})` : " (not in the manifest)"}: ${x.ruling.verdict}${x.ruling.match ? ` match "${x.ruling.match}"` : ""}${x.ruling.reason ? ` — ${x.ruling.reason}` : ""}`);
+ }
+ for (const u of done.unmapped) out(`no moment for ${u.videoId} near ${u.near}${u.why ? ` (${u.why})` : ""}`);
+ out(`${dryRun ? "would import" : "imported"} ${dryRun ? done.rulings.length : done.written.length} earlier ruling(s)`);
+ }
+ return 0;
+ }
+ if (verb === "set" || verb === "clear") {
+ if (!target) throw new CliError(`${verb} needs a clip id or a moment key`);
+ const key = resolveRulingKey(manifest, target);
+ if (!key) throw new CliError(`no montage clip "${target}" in ${project.id}`);
+ if (verb === "set" && !verdict) throw new CliError("set needs a verdict: keep, cut, not-him or read-aloud");
+ const ruling = verb === "clear" ? null : { verdict, reason: flags.get("--reason") ?? "", ...(flags.has("--match") ? { match: flags.get("--match") } : {}) };
+ const done = await setMontageRuling(project.dir, key, ruling, { now });
+ if (json) out(JSON.stringify({ key, ruling: done.ruling }, null, 2));
+ else out(done.ruling ? `${key}: ${done.ruling.verdict}${done.ruling.match ? ` match "${done.ruling.match}"` : ""}` : `${key}: cleared`);
+ return 0;
+ }
+ throw new CliError(`unknown: rulings ${verb} — show, import, set or clear`);
+ } catch (e) {
+ err(e instanceof CliError ? `umtool rulings: ${e.message}` : e instanceof Error ? `umtool rulings: ${e.message}` : String(e));
+ return 1;
+ }
+}
diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs
@@ -42,6 +42,7 @@ import { lstat, mkdir, readFile, rename, rm, stat, symlink, writeFile } from "no
import path from "node:path";
import { pathToFileURL } from "node:url";
import { mergePatch } from "umtool-report-to-video/montage-styles";
+import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-report-to-video/montage-rulings";
import { PIPELINE_DIR, UMTOOL_DIR } from "./driver.mjs";
import { replaceManifest } from "./manifest.mjs";
import { withEditNotes } from "./edit-guard.mjs";
@@ -419,18 +420,26 @@ export async function makeTake(projectDir, rawSpec, opts = {}) {
const changes = changeLines(base, manifest, patches);
const kind = changes.length === 0 ? "reference" : (spec.kind ?? "different");
+ // The clip deck's rulings (report-to-video/montage-rulings.mjs), applied to
+ // the WHOLE cut before it is windowed: a ruled-out clip leaves the window,
+ // and the counter is numbered over every kept clip, so a window still counts
+ // #31 of 70. The build applies them again over the render manifest beside
+ // the project's, where they change nothing more. The take's own manifest
+ // (what a pick copies) stays the manifest as written.
+ const ruled = applyMontageRulings(manifest, await readMontageRulings(projectDir));
+ for (const line of rulingsLines(ruled)) log(`${spec.id}: ${line}`);
// The render: the window's entries (timed against the project's, so every
// take of a group covers the same ones), or the whole cut.
- let renderDoc = manifest;
+ let renderDoc = ruled.manifest;
/** @type {null | { ids: string[], basis: string, total: number }} */
let covered = null;
if (spec.window !== "full") {
const schedule = await readJson(path.join(projectDir, "out", "sourced", "schedule.json"));
covered = windowEntries(base.timeline, spec.window, schedule);
- const present = new Set(sourcedEntries(manifest.timeline).map((e) => e.id));
+ const present = new Set(sourcedEntries(ruled.manifest.timeline).map((e) => e.id));
const ids = covered.ids.filter((id) => present.has(id));
- if (!ids.length) throw new Error(`${spec.id}: the patch removed every entry the window covers (${covered.ids.join(", ")})`);
- renderDoc = windowManifest(manifest, ids);
+ if (!ids.length) throw new Error(`${spec.id}: the patch or the clip rulings removed every entry the window covers (${covered.ids.join(", ")})`);
+ renderDoc = windowManifest(ruled.manifest, ids);
}
if (spec.quick) renderDoc = /** @type {Record<string, any>} */ (mergePatch(renderDoc, QUICK_RENDER));
diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs
@@ -179,6 +179,32 @@ test("makeTake: the style's patch then the take's, rendered from beside the proj
}
});
+test("makeTake: the clip deck's rulings leave their clips out of the render, numbered over the whole cut; the take's own manifest is as written", async () => {
+ // Five montage clips; s02 ruled not-him, s04 cut. A window over s03–s05.
+ const m = (id, start, n) => clip(id, start, start + 4, { channel: "chan", cutStart: start + 1, cutEnd: start + 3, montage: { n, of: 5, match: "slow news" } });
+ const manifest = { ...MANIFEST, timeline: [m("s01", 0, 1), m("s02", 10, 2), m("s03", 20, 3), m("s04", 30, 4), m("s05", 40, 5)] };
+ const { root, dir } = await project(manifest);
+ const r = stubRender();
+ const logs = [];
+ try {
+ await writeFile(path.join(dir, "montage-rulings.json"), JSON.stringify({ version: 1, rulings: {
+ "chan/v-s02@11.00": { verdict: "not-him", reason: "guest", at: "2026-10-18T00:00:00Z" },
+ "chan/v-s04@31.00": { verdict: "cut", reason: "", at: "2026-10-18T00:00:00Z" },
+ "chan/v-s05@41.00": { verdict: "keep", reason: "", match: "a slow news week", at: "2026-10-18T00:00:00Z" },
+ } }));
+ await makeTake(dir, { id: "win", label: "Window", window: { at: 4.5, dur: 5 } }, opts(r, { log: (l) => logs.push(l) }));
+ assert.deepEqual(r.calls[0].doc.timeline.map((e) => [e.id, e.montage.n, e.montage.of]), [["s03", 2, 3], ["s05", 3, 3]]);
+ assert.equal(r.calls[0].doc.timeline[1].montage.match, "a slow news week");
+ assert.ok(logs.some((l) => /win: montage rulings: 2 clip\(s\) left out — s02 \(not him: guest\), s04 \(cut\)/.test(l)), logs.join("\n"));
+ const take = JSON.parse(await readFile(path.join(dir, "takes", "win", "video.manifest.json"), "utf8"));
+ assert.equal(take.timeline.length, 5, "a pick copies the manifest as written; the rulings stay beside it");
+ await makeTake(dir, { id: "whole", label: "Whole", window: "full" }, opts(r));
+ assert.deepEqual(r.calls[1].doc.timeline.map((e) => e.id), ["s01", "s03", "s05"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
test("makeTake: no change is the reference; a transition turns crossfades on; full renders the whole cut", async () => {
const { root, dir } = await project();
const r = stubRender();
diff --git a/umtool/lib/report/voiceMatch.mjs b/umtool/lib/report/voiceMatch.mjs
@@ -35,12 +35,12 @@ import {
resolveEngine,
runVoiceMatch,
soloRecordingWhy,
- voiceMatchKey,
writeVoiceMatch,
} from "yt-dlp-transcript-common/lib/montage/voiceMatch.mjs";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
import { ffprobeSource, resolveLocalSource } from "umtool-report-to-video/sources";
import { clipPhrase, locatePhrase, whisperWords } from "umtool-report-to-video/montage";
+import { clipMomentKey } from "umtool-report-to-video/montage-rulings";
import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs";
import { kindMakesTakes } from "../projects/kinds.mjs";
import { channelsDirFor, hasShadowChannels, readManifest } from "../projects/report.mjs";
@@ -141,7 +141,7 @@ export async function clipSpan(entry, slug, transcripts, { span = "phrase", pad
/** A clip-like entry for one phrase-scan instance (umtool's seed shape). */
const instanceEntry = (i) => ({
- channel: i.slug, video: i.videoId, start: Math.max(0, i.start - 2.5), end: i.end + 2.5,
+ type: "clip", channel: i.slug, video: i.videoId, start: Math.max(0, i.start - 2.5), end: i.end + 2.5,
cutStart: Math.round(i.start * 100) / 100, cutEnd: Math.round(i.end * 100) / 100, montage: { match: i.match },
});
@@ -156,9 +156,10 @@ export async function planClips(dir, manifest, { channelsDir, rawDir = path.join
const seen = new Set();
const add = async (entry, id) => {
const slug = entry.channel ?? prov.channelSlug;
- if (!slug || !entry.video) return;
- const cutStart = num(entry.cutStart) ? entry.cutStart : entry.start;
- const key = voiceMatchKey(slug, entry.video, cutStart);
+ // The clip deck's key (lane N1's clipMomentKey): the source moment, so the
+ // deck finds each score under the key it files its rulings by.
+ const key = clipMomentKey(entry, manifest);
+ if (!slug || !entry.video || !key) return;
if (seen.has(key)) return;
seen.add(key);
const s = await clipSpan(entry, slug, transcripts, { span, pad });
diff --git a/umtool/report-to-video/README.md b/umtool/report-to-video/README.md
@@ -13,6 +13,7 @@ Two scripts and a manifest:
| `resolve-windows.mjs` | stable | widens clip windows from cue spans to whole sentences. Run once after authoring a manifest. |
| `brand.mjs`, `brand-cards.mjs` | stable | the opt-in brand preset (`render.brand`); see [its section](#the-archilyzer-media-preset-renderbrand). |
| `montage.mjs`, `montage-styles.mjs` | stable | montage editing (`render.montage`) and its named styles; see [its section](#rendermontage--montage-editing-release-33). |
+| `montage-rulings.mjs` | stable | the clip deck's rulings (`montage-rulings.json` beside the manifest), applied at render; see [its section](#montage-rulingsjson--the-clip-decks-rulings-release-34). |
| `<report>/video.manifest.json` | per report | the edit decision list. **This is the regeneration source of truth**, not the report. |
```
@@ -810,6 +811,32 @@ node umtool/report-to-video/montage-styles.mjs list
node umtool/report-to-video/montage-styles.mjs apply flash-count video.manifest.json --out takes/flash/video.manifest.json
```
+### `montage-rulings.json` — the clip deck's rulings (release 34)
+
+Beside the manifest, written by umtool's clip deck (`/projects/<id>/clips`) and
+`umtool rulings`, read here by `build-video` and `verify-build`:
+
+```json
+{ "version": 1,
+ "rulings": { "a-channel/abc123xyz@3127.54": { "verdict": "not-him", "reason": "another speaker", "at": "…" },
+ "a-channel-rumble/v1a2b3c@3597.60": { "verdict": "keep", "reason": "", "match": "it's not that it's a slow news day", "at": "…" } } }
+```
+
+- The key is the source moment, `<channel>/<video>@<cutStart to 2 decimals>`
+ (`clipMomentKey`: the clip's `channel`, else `provenance.channelSlug`;
+ `cutStart`, else `start`) — never the clip id, so a re-seed keeps it.
+- `verdict` `cut`, `not-him` or `read-aloud` leaves the clip out of the cut and
+ the wall; `keep` keeps it. `match` replaces the clip's `montage.match`.
+- When a clip is left out, every kept clip's `montage.n` / `montage.of` are
+ numbered again 1…N of N, in order. Nothing left out: the numbers stand (a
+ take's window of an already-ruled manifest keeps the whole cut's).
+- No file, or no ruling that changes anything: the same manifest, the same
+ render, byte for byte. A file that does not parse refuses the build.
+- The build log: `montage rulings: 2 clip(s) left out — s04 (not him: another
+ speaker), …`. `--no-rulings` (build-video and verify-build) builds every clip.
+- On the cut only: the validators and a bench `--fetch-only` read the manifest
+ as written, and `--only <id>` builds a ruled-out clip's segment anyway.
+
### `publish.youtube` — the upload's text (`out/youtube.txt`)
```jsonc
diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs
@@ -54,6 +54,9 @@
// after its validators and before it renders anything: an
// error refuses it, a warning is a note.
// --no-lint Build without the lint (an old manifest it refuses)
+// --no-rulings Build as if there were no montage-rulings.json beside the
+// manifest (montage-rulings.mjs: the clip deck's rulings,
+// which otherwise leave cut / not-him / read-aloud clips out)
// --narration-unreviewed Build narrated cards the narration review has not
// approved (unreviewed, or edited since); a rejected one
// still refuses. Without a review file nothing is held.
@@ -156,6 +159,7 @@ import {
} from "./narration.mjs";
import { narrationDir, narrationWavPath, readCutDisclosure, readNarrationRecords } from "./narration-store.mjs";
import { readDraftsReview } from "./drafts-review.mjs";
+import { applyMontageRulings, readMontageRulings, rulingsLines } from "./montage-rulings.mjs";
import { validateDrafted, validatePublish } from "yt-dlp-transcript-common/lib/report/drafted.mjs";
// The lint a build runs before it renders, and the prune after its final mux.
import { lintManifest, lintManifestFile, narrationLengthErrors } from "./lint.mjs";
@@ -4683,12 +4687,21 @@ export async function prepareLocalMedia(timeline, manifestDir, render = {}) {
export async function buildVideo({ manifestPath, opts = {}, out, only, fetchOnly } = {}) {
const variant = opts.variant ?? "sourced";
const whole = JSON.parse(await readFile(manifestPath, "utf8"));
- const manifest = selectVariant(whole, variant);
- const { render, provenance } = manifest;
// An `image` entry's `src` is relative to the MANIFEST, which is checked in
// beside the pictures it cites -- not to the cwd the build was started from.
// So is a clip's.
const manifestDir = path.dirname(path.resolve(manifestPath));
+ // The clip deck's rulings (montage-rulings.mjs), beside the manifest: a clip
+ // ruled cut / not-him / read-aloud is left out of this cut (and the wall),
+ // a ruled `match` widens its phrase, and the counter numbers the kept clips.
+ // On the cut only: `whole` (the validators, a bench `--fetch-only`) is the
+ // manifest as written. No file: the same object, today's render.
+ const ruled = opts.noRulings
+ ? { manifest: whole, left: [], matched: [], renumbered: false }
+ : applyMontageRulings(whole, await readMontageRulings(manifestDir), { keep: only ? [only] : [] });
+ const manifest = selectVariant(ruled.manifest, variant);
+ for (const message of rulingsLines(ruled)) EMIT("note", { message });
+ const { render, provenance } = manifest;
// A `src` clip's file and cues, checked and measured before anything else.
await prepareLocalMedia(manifest.timeline, manifestDir, render);
// A `render.chrome` that cannot be built is refused here, before a single
@@ -5500,6 +5513,7 @@ async function main() {
" [--no-rail] [--rail-only] [--preview <start> <dur>]\n" +
" [--chrome-only] [--no-chrome] [--chrome-preview <at> <dur>] [--keep-frames] (render.chrome, the deck)\n" +
" [--lint] [--no-lint] (lint the manifest and stop / build without the lint)\n" +
+ " [--no-rulings] (build as if there were no montage-rulings.json beside the manifest)\n" +
" [--narration-unreviewed] (build narrated cards the review has not approved; never a rejected one)\n" +
" [--final] [--drafts-unreviewed] (the deliverable: drafted fields must be approved / build the unapproved anyway)\n" +
" [--site-origin <url>] [--resolve-site-ids] [--cue-source auto|local|http]\n" +
@@ -5537,6 +5551,7 @@ async function main() {
thumbnailOnly: argv.includes("--thumbnail"),
keepFrames: argv.includes("--keep-frames"),
noLint: argv.includes("--no-lint"),
+ noRulings: argv.includes("--no-rulings"),
narrationUnreviewed: argv.includes("--narration-unreviewed"),
final: argv.includes("--final"),
draftsUnreviewed: argv.includes("--drafts-unreviewed"),
diff --git a/umtool/report-to-video/montage-rulings.mjs b/umtool/report-to-video/montage-rulings.mjs
@@ -0,0 +1,223 @@
+// MONTAGE RULINGS — the operator's word on each instance of a montage
+// (release 34 N1): keep it, cut it, not him (another speaker), read aloud (a
+// post or a quote read out, not his own line). Ruled by ear on umtool's clip
+// deck (`/projects/<id>/clips`), applied here at render.
+//
+// <project>/montage-rulings.json beside video.manifest.json
+// { "version": 1,
+// "rulings": { "<channel>/<video>@<cutStart, 2 decimals>":
+// { "verdict": "keep" | "cut" | "not-him" | "read-aloud",
+// "reason": string, "match"?: string, "at": ISO } } }
+//
+// KEYED BY THE SOURCE MOMENT, never the clip id: a montage's manifest is
+// derived (a seed script numbers its clips s01…), and a re-seed renumbers every
+// id while the moment stays where it is. `clipMomentKey` is the one key rule;
+// voice-match.json (release 34 N2) uses the same one. A clip with no `channel`
+// of its own takes the manifest's `provenance.channelSlug`, as every reader of
+// a clip does; its moment is `cutStart`, else `start`.
+//
+// AT RENDER (`applyMontageRulings`, build-video and verify-build, and the take
+// maker before it windows):
+// - a clip ruled cut / not-him / read-aloud is left out of the cut — and so of
+// the wall, which takes its tiles from the timeline;
+// - a ruling's `match` replaces the clip's `montage.match` (the phrase a
+// tightened cut is cut to, widened: "it's not that it's a slow news cycle");
+// - when anything was left out, every kept clip's `montage.n` / `montage.of`
+// are numbered again over the kept clips, in order, so the counter never
+// gaps (#1 … #N of N). Nothing left out: the numbers stay as they are, so a
+// take's window of an already-ruled manifest keeps its #31 of 70.
+// - NO FILE (or no ruling that changes anything): the very same manifest
+// object comes back, and the render is today's, byte for byte.
+// A file that does not parse refuses the build: a ruling silently ignored is a
+// clip the operator cut appearing in the video.
+//
+// Pure but for the file's read. Its one writer is umtool's
+// lib/report/montageRulings.mjs.
+import { readFile } from "node:fs/promises";
+import path from "node:path";
+
+export const MONTAGE_RULINGS_FILE = "montage-rulings.json";
+export const RULINGS_VERSION = 1;
+export const RULING_VERDICTS = Object.freeze(["keep", "cut", "not-him", "read-aloud"]);
+/** The verdicts that leave a clip out of the cut. */
+export const LEFT_OUT_VERDICTS = Object.freeze(["cut", "not-him", "read-aloud"]);
+/** A verdict in plain words. */
+export const VERDICT_WORDS = Object.freeze({ keep: "kept", cut: "cut", "not-him": "not him", "read-aloud": "read aloud" });
+export const RULING_REASON_LIMIT = 500;
+export const RULING_MATCH_LIMIT = 300;
+
+/** `<manifest's directory>/montage-rulings.json`. */
+export const montageRulingsFileOf = (dir) => path.join(/* turbopackIgnore: true */ dir, MONTAGE_RULINGS_FILE);
+
+const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
+const finite = (v) => typeof v === "number" && Number.isFinite(v);
+
+/** A moment's key: `<channel>/<video>@<at, 2 decimals>`. */
+export const momentKey = ({ channel, video, at }) => `${channel}/${video}@${Number(at).toFixed(2)}`;
+
+/** `<channel>/<video>@<seconds>` — no slash in a channel, no space anywhere, two decimals. */
+const KEY_RE = /^[^/\s@]+\/[^\s]+@\d+\.\d{2}$/;
+export const isMomentKey = (k) => typeof k === "string" && KEY_RE.test(k);
+
+/** The key's parts, or null. */
+export function parseMomentKey(k) {
+ if (!isMomentKey(k)) return null;
+ const at = k.lastIndexOf("@");
+ const slash = k.indexOf("/");
+ return { channel: k.slice(0, slash), video: k.slice(slash + 1, at), at: Number(k.slice(at + 1)) };
+}
+
+/**
+ * A clip's moment key, or null for an entry that is not a clip (or names no
+ * channel, video or time). The moment is the clip's `cutStart`, else `start`.
+ *
+ * @param {Record<string, any>} entry
+ * @param {{ provenance?: { channelSlug?: string } } | null} [manifest]
+ */
+export function clipMomentKey(entry, manifest = null) {
+ if (!isObj(entry) || entry.type !== "clip") return null;
+ const channel = entry.channel ?? manifest?.provenance?.channelSlug ?? null;
+ const at = finite(entry.cutStart) ? entry.cutStart : entry.start;
+ if (typeof channel !== "string" || !channel || typeof entry.video !== "string" || !entry.video || !finite(at)) return null;
+ const key = momentKey({ channel, video: entry.video, at });
+ return isMomentKey(key) ? key : null;
+}
+
+/**
+ * What is wrong with one ruling, as sentences.
+ * @param {string} key
+ * @param {unknown} r
+ */
+export function rulingProblems(key, r) {
+ const where = `ruling ${JSON.stringify(key)}`;
+ if (!isMomentKey(key)) return [`${where}: the key is not <channel>/<video>@<seconds to 2 decimals>`];
+ if (!isObj(r)) return [`${where} is not an object`];
+ const out = [];
+ if (!RULING_VERDICTS.includes(/** @type {any} */ (r).verdict)) out.push(`${where}: verdict must be one of ${RULING_VERDICTS.join(", ")}`);
+ if (typeof r.reason !== "string") out.push(`${where}: reason must be a string`);
+ else if (r.reason.length > RULING_REASON_LIMIT) out.push(`${where}: reason is over ${RULING_REASON_LIMIT} characters`);
+ if (r.match !== undefined && (typeof r.match !== "string" || !r.match.trim() || r.match.length > RULING_MATCH_LIMIT)) {
+ out.push(`${where}: match must be a phrase of 1–${RULING_MATCH_LIMIT} characters`);
+ }
+ if (typeof r.at !== "string" || Number.isNaN(Date.parse(r.at))) out.push(`${where}: at must be an ISO time`);
+ return out;
+}
+
+/**
+ * The file's contents, checked. Throws a sentence naming what is wrong.
+ * @param {unknown} raw
+ * @returns {{ version: 1, rulings: Record<string, { verdict: string, reason: string, match?: string, at: string }> }}
+ */
+export function parseMontageRulings(raw) {
+ if (!isObj(raw)) throw new Error(`${MONTAGE_RULINGS_FILE} is not an object`);
+ if (raw.version !== RULINGS_VERSION) throw new Error(`${MONTAGE_RULINGS_FILE}: version must be ${RULINGS_VERSION}`);
+ if (!isObj(raw.rulings)) throw new Error(`${MONTAGE_RULINGS_FILE}: rulings must be an object`);
+ const problems = Object.entries(raw.rulings).flatMap(([k, r]) => rulingProblems(k, r));
+ if (problems.length) throw new Error(`${MONTAGE_RULINGS_FILE}: ${problems.join("; ")}`);
+ return /** @type {any} */ (raw);
+}
+
+/**
+ * The rulings beside a manifest: null when there is no file; throws when it
+ * does not parse or is not the shape (never read as empty).
+ * @param {string} dir the manifest's directory
+ */
+export async function readMontageRulings(dir) {
+ let text;
+ try {
+ text = await readFile(montageRulingsFileOf(dir), "utf8");
+ } catch (err) {
+ if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT") return null;
+ throw err;
+ }
+ let raw;
+ try {
+ raw = JSON.parse(text);
+ } catch (e) {
+ throw new Error(`${MONTAGE_RULINGS_FILE} does not parse (${e instanceof Error ? e.message : String(e)}) — fix it or remove it`);
+ }
+ return parseMontageRulings(raw);
+}
+
+/**
+ * @typedef {{ id: string, key: string, verdict: string, reason: string }} LeftOut
+ * @typedef {{ id: string, key: string, match: string, was: string | null }} Matched
+ * @typedef {{ manifest: Record<string, any>, left: LeftOut[], matched: Matched[], renumbered: boolean }} Applied
+ */
+
+/**
+ * The manifest as the rulings have it. Pure. With no rulings, or none that
+ * change anything, `manifest` itself comes back (the same object).
+ *
+ * @param {Record<string, any>} manifest
+ * @param {{ rulings: Record<string, any> } | null | undefined} doc
+ * @param {{ keep?: string[] }} [opts] clip ids never left out (an `--only` rebuild of a ruled-out clip)
+ * @returns {Applied}
+ */
+export function applyMontageRulings(manifest, doc, { keep = [] } = {}) {
+ const none = { manifest, left: [], matched: [], renumbered: false };
+ const rulings = doc?.rulings;
+ if (!isObj(rulings) || !Object.keys(rulings).length || !Array.isArray(manifest?.timeline)) return none;
+ /** @type {LeftOut[]} */
+ const left = [];
+ /** @type {Matched[]} */
+ const matched = [];
+ const timeline = [];
+ for (const e of manifest.timeline) {
+ const key = clipMomentKey(e, manifest);
+ const r = key ? rulings[key] : null;
+ if (!r) {
+ timeline.push(e);
+ continue;
+ }
+ if (LEFT_OUT_VERDICTS.includes(r.verdict) && !keep.includes(e.id)) {
+ left.push({ id: e.id, key: /** @type {string} */ (key), verdict: r.verdict, reason: typeof r.reason === "string" ? r.reason : "" });
+ continue;
+ }
+ const was = typeof e.montage?.match === "string" ? e.montage.match : null;
+ if (typeof r.match === "string" && r.match.trim() && r.match !== was) {
+ matched.push({ id: e.id, key: /** @type {string} */ (key), match: r.match, was });
+ timeline.push({ ...e, montage: { ...(isObj(e.montage) ? e.montage : {}), match: r.match } });
+ } else timeline.push(e);
+ }
+ if (!left.length && !matched.length) return none;
+ let renumbered = false;
+ if (left.length) {
+ // The counter numbers the KEPT clips 1…N, in order. A clip that carries no
+ // number of its own is numbered by its place already (planMontage).
+ const clips = timeline.filter((e) => isObj(e) && e.type === "clip");
+ const total = clips.length;
+ clips.forEach((e, k) => {
+ if (!isObj(e.montage) || (e.montage.n === undefined && e.montage.of === undefined)) return;
+ const next = { ...e.montage };
+ if (next.n !== undefined) next.n = k + 1;
+ if (next.of !== undefined) next.of = total;
+ timeline[timeline.indexOf(e)] = { ...e, montage: next };
+ renumbered = true;
+ });
+ }
+ return { manifest: { ...manifest, timeline }, left, matched, renumbered };
+}
+
+/** One clip left out, in words: `s04 (not him: another speaker)`. */
+export const leftOutWords = (l) => `${l.id} (${VERDICT_WORDS[l.verdict] ?? l.verdict}${l.reason ? `: ${l.reason}` : ""})`;
+
+/**
+ * What the rulings did, as the build log's lines: nothing when they did nothing.
+ * @param {Applied} applied
+ */
+export function rulingsLines(applied) {
+ if (!applied.left.length && !applied.matched.length) return [];
+ const lines = [];
+ if (applied.left.length) {
+ lines.push(`montage rulings: ${applied.left.length} clip(s) left out — ${applied.left.map(leftOutWords).join(", ")}`);
+ }
+ for (const m of applied.matched) {
+ lines.push(`montage rulings: ${m.id} cut to "${m.match}"${m.was ? ` (was "${m.was}")` : ""}`);
+ }
+ if (applied.renumbered) {
+ const n = applied.manifest.timeline.filter((e) => e?.type === "clip").length;
+ lines.push(`montage rulings: the counter numbers the ${n} kept clip(s) 1–${n}`);
+ }
+ return lines;
+}
diff --git a/umtool/report-to-video/montage-rulings.test.mjs b/umtool/report-to-video/montage-rulings.test.mjs
@@ -0,0 +1,243 @@
+// Montage rulings (release 34 N1): the key rule, the file's shape, and how a
+// render applies the clip deck's rulings -- the ruled-out clips left out of
+// the cut and the wall, a ruled phrase in place of `montage.match`, the
+// counter numbered over the kept clips -- and that no file (or a file that
+// changes nothing) is today's render, byte for byte.
+//
+// Run with: pnpm test:scripts
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import test from "node:test";
+
+import {
+ applyMontageRulings, clipMomentKey, isMomentKey, leftOutWords, momentKey, MONTAGE_RULINGS_FILE, parseMomentKey,
+ parseMontageRulings, readMontageRulings, rulingsLines,
+} from "./montage-rulings.mjs";
+
+// The build's cue reader takes its corpus from CHANNELS_DIR when the module
+// loads, so the variable is set before the import: the render tests' clips are
+// corpus moments (a channel, a video, a cut start), their windows and cues in
+// a synthetic channels tree.
+const corpus = await mkdtemp(path.join(os.tmpdir(), "rtv-rulings-corpus-"));
+process.env.CHANNELS_DIR = corpus;
+const { buildVideo } = await import("./build-video.mjs");
+const { verifyBuild } = await import("./verify-build.mjs");
+const { MONO_BOLD_FONT_FILE, MONO_FONT_FILE } = await import("./brand.mjs");
+test.after(() => rm(corpus, { recursive: true, force: true }));
+
+const AT = "2026-10-18T12:00:00.000Z";
+const clip = (id, video, cutStart, extra = {}) => ({
+ type: "clip", id, channel: "chan", video, start: cutStart - 2.5, end: cutStart + 4, cutStart, cutEnd: cutStart + 2,
+ montage: { n: Number(id.slice(1)), of: 5, match: "slow news day" }, ...extra,
+});
+const five = () => ({
+ slug: "m", provenance: { channelSlug: "chan" }, render: {},
+ timeline: [clip("s1", "va", 10), clip("s2", "vb", 20.5), clip("s3", "vc", 30.25), clip("s4", "vd", 40), clip("s5", "ve", 50)],
+});
+const doc = (rulings) => ({ version: 1, rulings: Object.fromEntries(Object.entries(rulings).map(([k, r]) => [k, { reason: "", at: AT, ...r }])) });
+
+test("the key: <channel>/<video>@<cutStart to 2 decimals>; the manifest's channel when the clip names none; start without a cut", () => {
+ assert.equal(momentKey({ channel: "c", video: "v-1_x", at: 3127.5 }), "c/v-1_x@3127.50");
+ assert.equal(clipMomentKey(clip("s1", "va", 10)), "chan/va@10.00");
+ assert.equal(clipMomentKey({ type: "clip", id: "x", video: "vz", start: 4.256 }, { provenance: { channelSlug: "fallback" } }), "fallback/vz@4.26");
+ assert.equal(clipMomentKey({ type: "clip", id: "x", video: "vz", start: 4 }), null, "no channel anywhere");
+ assert.equal(clipMomentKey({ type: "card", id: "k" }), null);
+ assert.equal(clipMomentKey({ type: "clip", id: "x", src: "a.mp4", start: 1 }), null, "a local file is no moment");
+ assert.ok(isMomentKey("a-channel-rumble/v1a2b3c@3597.60"));
+ assert.ok(!isMomentKey("a/b@1.5"), "two decimals");
+ assert.ok(!isMomentKey("a b/c@1.50"));
+ assert.deepEqual(parseMomentKey("ch/v@12.30"), { channel: "ch", video: "v", at: 12.3 });
+});
+
+test("parseMontageRulings: the shape, each problem in words", () => {
+ assert.deepEqual(parseMontageRulings({ version: 1, rulings: {} }), { version: 1, rulings: {} });
+ assert.throws(() => parseMontageRulings([]), /is not an object/);
+ assert.throws(() => parseMontageRulings({ version: 2, rulings: {} }), /version must be 1/);
+ assert.throws(() => parseMontageRulings({ version: 1 }), /rulings must be an object/);
+ assert.throws(() => parseMontageRulings(doc({ "chan/va@10.00": { verdict: "maybe" } })), /verdict must be one of keep, cut, not-him, read-aloud/);
+ assert.throws(() => parseMontageRulings(doc({ "s01": { verdict: "cut" } })), /the key is not <channel>\/<video>@<seconds/);
+ assert.throws(() => parseMontageRulings(doc({ "chan/va@10.00": { verdict: "keep", match: " " } })), /match must be a phrase/);
+ assert.throws(() => parseMontageRulings({ version: 1, rulings: { "chan/va@10.00": { verdict: "cut", reason: "", at: "soon" } } }), /at must be an ISO time/);
+});
+
+test("readMontageRulings: no file is null; a file that does not parse refuses, never reads as empty", async () => {
+ const dir = await mkdtemp(path.join(os.tmpdir(), "rulings-"));
+ try {
+ assert.equal(await readMontageRulings(dir), null);
+ await writeFile(path.join(dir, MONTAGE_RULINGS_FILE), "{ nope");
+ await assert.rejects(readMontageRulings(dir), /does not parse .* fix it or remove it/);
+ await writeFile(path.join(dir, MONTAGE_RULINGS_FILE), JSON.stringify(doc({ "chan/va@10.00": { verdict: "cut" } })));
+ assert.equal((await readMontageRulings(dir)).rulings["chan/va@10.00"].verdict, "cut");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
+test("applyMontageRulings: no rulings, or none that change anything -- the very same manifest object", () => {
+ const m = five();
+ for (const d of [null, undefined, { version: 1, rulings: {} }, doc({ "chan/va@10.00": { verdict: "keep" } }), doc({ "chan/gone@1.00": { verdict: "cut" } }),
+ doc({ "chan/va@10.00": { verdict: "keep", match: "slow news day" } })]) {
+ const r = applyMontageRulings(m, d);
+ assert.equal(r.manifest, m);
+ assert.deepEqual([r.left, r.matched, r.renumbered], [[], [], false]);
+ assert.deepEqual(rulingsLines(r), []);
+ }
+});
+
+test("applyMontageRulings: cut, not-him and read-aloud leave; the counter numbers the kept 1…N of N; match widens the phrase", () => {
+ const m = five();
+ const before = JSON.stringify(m);
+ const r = applyMontageRulings(m, doc({
+ "chan/vb@20.50": { verdict: "not-him", reason: "another speaker" },
+ "chan/vc@30.25": { verdict: "keep", match: "it's not that it's a slow news day" },
+ "chan/vd@40.00": { verdict: "read-aloud", reason: "a post read out" },
+ "chan/ve@50.00": { verdict: "cut" },
+ }));
+ assert.equal(JSON.stringify(m), before, "the input is never changed");
+ assert.deepEqual(r.manifest.timeline.map((e) => e.id), ["s1", "s3"]);
+ assert.deepEqual(r.manifest.timeline.map((e) => [e.montage.n, e.montage.of]), [[1, 2], [2, 2]]);
+ assert.equal(r.manifest.timeline[1].montage.match, "it's not that it's a slow news day");
+ assert.deepEqual(r.left.map((l) => [l.id, l.verdict]), [["s2", "not-him"], ["s4", "read-aloud"], ["s5", "cut"]]);
+ assert.deepEqual(r.matched, [{ id: "s3", key: "chan/vc@30.25", match: "it's not that it's a slow news day", was: "slow news day" }]);
+ assert.equal(r.renumbered, true);
+ assert.equal(leftOutWords(r.left[0]), "s2 (not him: another speaker)");
+ assert.deepEqual(rulingsLines(r), [
+ "montage rulings: 3 clip(s) left out — s2 (not him: another speaker), s4 (read aloud: a post read out), s5 (cut)",
+ 'montage rulings: s3 cut to "it\'s not that it\'s a slow news day" (was "slow news day")',
+ "montage rulings: the counter numbers the 2 kept clip(s) 1–2",
+ ]);
+});
+
+test("applyMontageRulings: a card stays; `keep` holds an --only rebuild's clip; applying twice changes nothing more", () => {
+ const m = five();
+ m.timeline.splice(2, 0, { type: "card", id: "k1", seconds: 2 });
+ const d = doc({ "chan/va@10.00": { verdict: "cut" }, "chan/vc@30.25": { verdict: "keep", match: "a wider phrase" } });
+ const r = applyMontageRulings(m, d);
+ assert.deepEqual(r.manifest.timeline.map((e) => e.id), ["s2", "k1", "s3", "s4", "s5"]);
+ assert.deepEqual(r.manifest.timeline.filter((e) => e.montage).map((e) => e.montage.n), [1, 2, 3, 4]);
+ assert.deepEqual(applyMontageRulings(m, d, { keep: ["s1"] }).manifest.timeline.map((e) => e.id), ["s1", "s2", "k1", "s3", "s4", "s5"]);
+ // A take's window of an already-ruled manifest: its numbers are the whole cut's, and stay.
+ const window = { ...r.manifest, timeline: r.manifest.timeline.slice(3) };
+ const again = applyMontageRulings(window, d);
+ assert.equal(again.manifest, window);
+ assert.deepEqual(again.manifest.timeline.map((e) => e.montage.n), [3, 4]);
+});
+
+// ---- real renders -----------------------------------------------------------------
+
+const have = ["ffmpeg", "ffprobe"].every((b) => spawnSync(b, ["-version"]).status === 0);
+const FPS = 30;
+const PALETTE = { bg: "#15121c", fg: "#ece8f4", muted: "#9a93ad", accent: "#7c5cff", amber: "#f2b84b" };
+const RENDER = {
+ width: 320, height: 180, fps: FPS, audioRate: 48000, audioChannels: 2, preset: "ultrafast", transition: 0,
+ headerHeight: 0, qr: false, palette: PALETTE, fontRegular: MONO_FONT_FILE, fontBold: MONO_BOLD_FONT_FILE,
+ snapWindow: 0.4, silenceMinDur: 0.1,
+};
+
+/**
+ * Four corpus moments (channel "demo", videos vid1–vid4, each cut at 1.5 s),
+ * numbered 1–4 of 4: a four-second window in each video's clips/ and its
+ * cues. A fresh channel per fixture, so two fixtures never share a window.
+ */
+let fixtures = 0;
+async function fixture({ montage = { tighten: "phrase", counter: { style: "chip", of: true } }, rulings = null } = {}) {
+ const root = await mkdtemp(path.join(os.tmpdir(), "rtv-rulings-"));
+ fixtures += 1;
+ const slug = `demo${fixtures}`;
+ const timeline = [];
+ for (let i = 1; i <= 4; i += 1) {
+ const dir = path.join(corpus, slug, "data", `vid${i}`);
+ await mkdir(path.join(dir, "clips"), { recursive: true });
+ const r = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", `color=c=0x808080:s=320x180:r=${FPS}:d=4`,
+ "-f", "lavfi", "-i", `aevalsrc='0.5*sin(2*PI*${300 + 40 * i}*t)*between(mod(t,1.5),0,1.0)':s=48000:d=4`,
+ "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", path.join(dir, "clips", "0.00-4.00.mp4"),
+ ]);
+ assert.equal(r.status, 0, String(r.stderr));
+ await writeFile(path.join(dir, "transcript.cues.json"), JSON.stringify({
+ id: `vid${i}`, title: `Clip ${i}`, channel: "Demo", uploadDate: `20${18 + i}0${i}0${i}`, duration: 4, platform: "youtube",
+ cues: [
+ { start: 0.2, end: 1.5, text: "well it is a" },
+ { start: 1.5, end: 3.0, text: "slow news day again" },
+ { start: 3.0, end: 3.8, text: "here we go" },
+ ],
+ }));
+ timeline.push({
+ id: `c${i}`, type: "clip", channel: slug, video: `vid${i}`, start: 0.2, end: 3.8, cutStart: 1.5, cutEnd: 3.0,
+ montage: { n: i, of: 4, date: `20${18 + i}0${i}0${i}`, platform: "youtube", match: "slow news day" },
+ });
+ }
+ const manifestPath = path.join(root, "video.manifest.json");
+ await writeFile(manifestPath, JSON.stringify({
+ slug: "demo", title: "Demo", provenance: { channelSlug: slug }, render: { ...RENDER, fetchPad: 0, montage }, timeline,
+ }));
+ const key = (i) => `${slug}/vid${i}@1.50`;
+ if (rulings) await writeFile(path.join(root, MONTAGE_RULINGS_FILE), JSON.stringify(doc(rulings(key))));
+ return { root, manifestPath, key };
+}
+
+const OPTS = { noNetwork: true, cueSource: "local" };
+const md5 = (f) => spawnSync("md5sum", [f]).stdout.toString().split(" ")[0];
+
+test("render: no rulings file, or one that changes nothing, is byte for byte the same cut", { skip: !have && "needs ffmpeg" }, async () => {
+ const a = await fixture();
+ const b = await fixture({ rulings: (k) => ({ [k(2)]: { verdict: "keep" }, "demo/gone@9.00": { verdict: "cut" } }) });
+ try {
+ await buildVideo({ manifestPath: a.manifestPath, opts: OPTS });
+ await buildVideo({ manifestPath: b.manifestPath, opts: OPTS });
+ for (const f of ["demo.mp4", "sourced/segments/c2.mp4", "sourced/segments/c4.mp4"]) {
+ assert.equal(md5(path.join(a.root, "out", f)), md5(path.join(b.root, "out", f)), f);
+ }
+ } finally {
+ await rm(a.root, { recursive: true, force: true });
+ await rm(b.root, { recursive: true, force: true });
+ }
+});
+
+test("render: the ruled-out clips are left out, the counter is the kept clips', verify-build counts what was built; --no-rulings builds them all", { skip: !have && "needs ffmpeg" }, async () => {
+ const ruled = await fixture({ rulings: (k) => ({ [k(2)]: { verdict: "not-him", reason: "guest" }, [k(3)]: { verdict: "read-aloud" } }) });
+ const kept = await fixture({ rulings: null });
+ try {
+ const r = await buildVideo({ manifestPath: ruled.manifestPath, opts: OPTS });
+ const segs = (await readdir(path.join(ruled.root, "out", "sourced", "segments"))).filter((f) => /^c\d\.mp4$/.test(f)).sort();
+ assert.deepEqual(segs, ["c1.mp4", "c4.mp4"]);
+ const v = await verifyBuild(ruled.manifestPath);
+ assert.equal(v.ok, true, v.problems?.join("; "));
+ assert.equal(v.entries, 2);
+ // The kept fourth clip is #2 of 2: built as the second clip of a two-clip
+ // cut, it is the very file a manifest of those two clips numbered 1, 2 of 2 makes.
+ const twoOf = JSON.parse(spawnSync("cat", [kept.manifestPath]).stdout.toString());
+ twoOf.timeline = [twoOf.timeline[0], { ...twoOf.timeline[3], montage: { ...twoOf.timeline[3].montage, n: 2, of: 2 } }];
+ twoOf.timeline[0].montage.of = 2;
+ await writeFile(kept.manifestPath, JSON.stringify(twoOf));
+ await buildVideo({ manifestPath: kept.manifestPath, opts: OPTS });
+ assert.equal(md5(path.join(ruled.root, "out", "sourced", "segments", "c4.mp4")), md5(path.join(kept.root, "out", "sourced", "segments", "c4.mp4")));
+ assert.equal(md5(r.out), md5(path.join(kept.root, "out", "demo.mp4")));
+ // --no-rulings: every clip again, and verify-build told the same.
+ await buildVideo({ manifestPath: ruled.manifestPath, opts: { ...OPTS, noRulings: true } });
+ const all = await verifyBuild(ruled.manifestPath, { noRulings: true });
+ assert.equal(all.ok, true, all.problems?.join("; "));
+ assert.equal(all.entries, 4);
+ } finally {
+ await rm(ruled.root, { recursive: true, force: true });
+ await rm(kept.root, { recursive: true, force: true });
+ }
+});
+
+test("render: a ruled-out clip is not a tile of the wall either", { skip: !have && "needs ffmpeg" }, async () => {
+ const { root, manifestPath } = await fixture({
+ montage: { tighten: "phrase", wall: { tiles: 9, build: 2 } },
+ rulings: (k) => ({ [k(1)]: { verdict: "cut" } }),
+ });
+ try {
+ await buildVideo({ manifestPath, opts: OPTS });
+ const tiles = (await readdir(path.join(root, "out", "sourced", "segments", "montage-wall"))).filter((f) => f.endsWith(".mp4")).sort();
+ assert.ok(tiles.length > 0);
+ assert.ok(!tiles.includes("c1.mp4"), tiles.join(", "));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json
@@ -30,6 +30,7 @@
"./ledger-totals": "./ledger-totals.mjs",
"./montage": "./montage.mjs",
"./montage-styles": "./montage-styles.mjs",
+ "./montage-rulings": "./montage-rulings.mjs",
"./lint": "./lint.mjs",
"./local-media": "./local-media.mjs",
"./mute": "./mute.mjs",
diff --git a/umtool/report-to-video/verify-build.mjs b/umtool/report-to-video/verify-build.mjs
@@ -23,17 +23,21 @@ import { deckGeometry, deckOn, frameCount, postsGeometry, resolveDeck, teaserSec
import { statsClips } from "./stats.mjs";
import { frameKeyOf, framesOf } from "./prune-frames.mjs";
import { montageSplit, resolveMontage } from "./montage.mjs";
+import { applyMontageRulings, readMontageRulings } from "./montage-rulings.mjs";
const execFileP = promisify(execFile);
const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe";
const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg";
-export async function verifyBuild(manifestPath, { outDir, variant = "sourced", noXfade = false } = {}) {
+export async function verifyBuild(manifestPath, { outDir, variant = "sourced", noXfade = false, noRulings = false } = {}) {
// The SAME filter the build ran. Verifying the whole manifest against one
// variant's file would report a missing chapter for every entry the other cut
// carries -- i.e. it would be red exactly when the build was right.
+ // And the same rulings (montage-rulings.mjs): a clip the clip deck left out
+ // has no chapter. `noRulings` matches a `--no-rulings` build.
+ const parsed = JSON.parse(await readFile(manifestPath, "utf8"));
const manifest = selectVariant(
- JSON.parse(await readFile(manifestPath, "utf8")),
+ noRulings ? parsed : applyMontageRulings(parsed, await readMontageRulings(path.dirname(path.resolve(manifestPath)))).manifest,
variant,
);
const root = outDir ?? path.join(path.dirname(path.resolve(manifestPath)), "out");
@@ -329,7 +333,7 @@ async function main() {
const argv = process.argv.slice(2);
const manifestPath = argv.find((a) => !a.startsWith("--"));
if (!manifestPath) {
- console.error("usage: verify-build.mjs <manifest.json> [--out <dir>] [--variant sourced|full] [--no-xfade] [--json]");
+ console.error("usage: verify-build.mjs <manifest.json> [--out <dir>] [--variant sourced|full] [--no-xfade] [--no-rulings] [--json]");
process.exit(2);
}
const flag = (n) => { const i = argv.indexOf(n); return i >= 0 ? argv[i + 1] : undefined; };
@@ -338,6 +342,7 @@ async function main() {
variant: flag("--variant") ?? "sourced",
// The build's own flag: a cut joined without crossfades.
noXfade: argv.includes("--no-xfade"),
+ noRulings: argv.includes("--no-rulings"),
});
if (argv.includes("--json")) {