commit 03f756b38ac989bfa49ca9a82f81b0fedf262323
parent ea26a9e74c66a24e9038f434830bda67ea0a92a6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 18 Oct 2026 17:02:07 -0400
umtool: the clip deck — a montage's instances ruled by ear at /projects/<id>/clips
One card per montage clip: its cut playing from the project's cached window (w plays the
whole extent), the quote with its phrase marked, date and source, the clip's note, and
voice-match.json's score when it is there. → keep, ← cut, ↓ not him, ↑ read aloud, e keeps
with a wider phrase, s skips, space replays, z undoes; reason chips or a few words; swipe
or the bar under the thumb. Filters: unruled, doubtful first (voice unlikely, unsure, a
voice check in the note), ruled, all. The seed's edits.json is offered as an import once.
The end card counts the rulings, lists the left out, shows the next render's kept clips
(the build's own rules, from GET /api/report/montage-rulings) and re-renders the picked or
whole-cut take through the take maker's job. The Cut tab links it ("Clips — n to rule").
`umtool rulings` (show, import, set, clear) is the same writer. e2e clip-deck.spec.ts.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
17 files changed, 1678 insertions(+), 4 deletions(-)
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)
import process from "node:process";
import {
PROJECT_KINDS,
@@ -718,6 +720,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 refresh <article> [--iteration N] [--no-fetch] [--yes] [--json]",
" re-fetch an article's scope, see what changed, update: the plan (the editor's);",
" --yes starts it, one editor job (needs WORKER_TOKEN and the editor)",
@@ -754,6 +758,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))),
inbox: cmdInbox,
schedule: () => tsxScript("schedule"),
refresh: () => tsxScript("refresh"),
diff --git a/umtool/components/projects/ClipDeckPage.tsx b/umtool/components/projects/ClipDeckPage.tsx
@@ -0,0 +1,45 @@
+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";
+
+// `/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)} />
+ </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,7 +8,8 @@ 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";
@@ -53,6 +54,15 @@ 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;
// ---- what a clip's "mix" link opens ---------------------------------------
//
@@ -122,6 +132,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({ variant: unruled ? "go" : "outline", 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 ? (
diff --git a/umtool/components/projects/review/ClipDeck.tsx b/umtool/components/projects/review/ClipDeck.tsx
@@ -0,0 +1,943 @@
+"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,
+}: {
+ project: string;
+ view: ClipDeckView;
+ initialShow: ClipDeckShow;
+ back: string;
+ takesHref: string;
+}) {
+ 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: "go", 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>
+ )}
+ </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={buttonVariants({ variant: "go", size: "lg" })}
+ 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)) |
A project argument is an exact id, a directory, or a **unique** basename. Two
projects answering to one name is reported, never resolved by picking one.
diff --git a/umtool/e2e/clip-deck.spec.ts b/umtool/e2e/clip-deck.spec.ts
@@ -0,0 +1,159 @@
+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);
+});
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";
@@ -1766,6 +1767,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).
@@ -2101,6 +2104,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/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
@@ -27,11 +27,13 @@ import {
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";
@@ -56,6 +58,7 @@ function withRulingsLock(fn) {
* 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;
@@ -72,6 +75,7 @@ export async function readRulingsState(projectDir) {
}
}
+/** @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) {
@@ -274,9 +278,9 @@ export function mapEarlierRulings(manifest, edits, instances = null) {
* @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(projectDir, EDITS_FILE));
+ const edits = await readJsonIf(path.join(/* turbopackIgnore: true */ projectDir, EDITS_FILE));
if (!edits) return { exists: false, rulings: [], unmapped: [] };
- const instances = await readJsonIf(path.join(projectDir, INSTANCES_FILE));
+ 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();
@@ -300,3 +304,31 @@ export async function importEarlierRulings(projectDir, manifest, { now = new Dat
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
@@ -135,3 +135,34 @@ test("the import: offered while something is new, written once, then not offered
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/report-to-video/montage-rulings.mjs b/umtool/report-to-video/montage-rulings.mjs
@@ -47,7 +47,7 @@ export const RULING_REASON_LIMIT = 500;
export const RULING_MATCH_LIMIT = 300;
/** `<manifest's directory>/montage-rulings.json`. */
-export const montageRulingsFileOf = (dir) => path.join(dir, MONTAGE_RULINGS_FILE);
+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);