Archilyzer · Source

archilyzer

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

commit 88ceb5de9ba55caf3d01427f605cd2e5f99f66ae
parent e8b4412de936787d67c04f4612cf68b970de9554
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 29 Oct 2026 15:58:57 -0400

Play the cut: story modules via a module `play` contract; incorrect clips skipped and blocking; Wrong speaker; Edit/Back keeps the place

MODULE CONTRACT `play` (modules/contract.mjs): `{ clock: "cut", ready:
"<region>:ready" }` -- an overlay module's HyperFrames page is its live
preview. The full chrome preview (POST /api/report/chrome/preview) returns
`layers`: every module declaring `play` that the cut draws (its own `on`,
the build's predicate), composed through its own page (onscreen.mjs
composePlayLayers), by z, with geometry, clock, ready and one src (whole
cut) or windows (cut seconds). Play the cut and the clip editor's live
preview lay them generically (OnscreenSection.tsx ModuleLayers): over the
deck, under the finale, a window module only inside its windows.
Declaring `play`: chapter, pair, status, stats, fx, threads, flips. Still
on their own paths, with what porting each needs in knobs.md's generated
Modules section: shell (deck), feed, popup-posts, stamp, finale.

CLIPS RULED INCORRECT: Play the cut skips them by default (skipEntries;
the strip marks them struck through, correction on hover; "Show clips
marked incorrect", remembered); `umtool check` reports `clip-incorrect`,
blocking ("e01 is marked incorrect: … — remove it, fix it and re-confirm,
or clear the verdict"); a take refuses with the same sentence.

WRONG SPEAKER: `reason: "wrong-speaker"` beside an incorrect verdict
(validated in patchClipEntry; stands for the note; `umtool set <p> <clip>
verdict=wrong-speaker`). One write (removeWrongSpeaker; `umtool timeline
<p> wrong-speaker <id>`; route op `wrong-speaker`) marks the clip and
removes it with an undo point, on record in removed.json (`umtool
corrections` lists those still out). A Wrong speaker button on the clip
bench and in Play the cut asks in the page first and offers Undo. Every
project removal now re-anchors what named the clip (marker to the clip
before, chapter to the next in its section; pair/status/deck-claim
references dropped) and prints each change; a take's removal does not
(its patch holds only the timeline).

EDIT / BACK: Play keeps its place in its URL (clip, at, t, incorrect;
replaceState at most once a second); Edit this clip writes it before its
one push, so the browser's Back lands paused on the same second of the
same clip; when an edit moved the clip, it resumes by clip + offset and
says "Back at <clip> · <time> (the cut changed)".

Tests: composePlayLayers, the play contract, skipEntries, clip-incorrect
decisions, take refusal, wrong-speaker (reason, re-anchor, record, undo);
e2e play-modules.spec.ts (chapter card visible in its window and down
outside; incorrect clip skipped and played with the toggle; Edit → Back
at the same second; Wrong speaker → confirm → gone from the reel → Undo).

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

Diffstat:
Mumtool/app/api/report/chrome/preview/route.ts | 18++++++++++++++++++
Mumtool/app/api/report/timeline/route.ts | 6+++++-
Mumtool/bin/umtool.mjs | 15++++++++++++++-
Mumtool/components/projects/ClipBench.tsx | 21+++++++++++++++++++++
Mumtool/components/projects/OnscreenSection.tsx | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/components/projects/review/LiveDeckPreview.tsx | 4+++-
Mumtool/components/projects/review/PlayCut.tsx | 153++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/components/projects/review/ReelStrip.tsx | 23+++++++++++++++++++++--
Aumtool/components/projects/review/WrongSpeaker.tsx | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/docs/cli.md | 2+-
Mumtool/docs/inbox.md | 1+
Mumtool/docs/knobs.md | 41++++++++++++++++++++++++++++++++++++++++-
Mumtool/docs/report-video.md | 24++++++++++++++++++++++++
Mumtool/e2e/fixtures/make-fixture.mjs | 25+++++++++++++++++++++++++
Mumtool/e2e/fixtures/play-cut-fixture.mjs | 5+++--
Aumtool/e2e/play-modules.spec.ts | 163+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/inbox/groups.mjs | 1+
Mumtool/lib/inbox/what.mjs | 1+
Mumtool/lib/projects/report.mjs | 31+++++++++++++++++++++++++++++--
Aumtool/lib/report/clip-incorrect.test.mjs | 60++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/knobsCli.mjs | 18+++++++++++++++++-
Mumtool/lib/report/layerPreview.test.mjs | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/manifest.mjs | 243+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/onscreen.mjs | 46++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playCut.mjs | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playCut.test.mjs | 34++++++++++++++++++++++++++++++++++
Mumtool/lib/report/playView.mjs | 4+++-
Mumtool/lib/report/takeEdit.mjs | 2+-
Mumtool/lib/report/takeMaker.mjs | 6++++++
Mumtool/lib/report/takeMaker.test.mjs | 18++++++++++++++++++
Mumtool/lib/report/timelineCli.mjs | 19+++++++++++++++++--
Aumtool/lib/report/wrong-speaker.test.mjs | 135+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/modules/chapter.mjs | 2++
Mumtool/report-to-video/modules/contract.mjs | 29++++++++++++++++++++++++++++-
Mumtool/report-to-video/modules/docs.mjs | 20++++++++++++++++++++
Mumtool/report-to-video/modules/flips.mjs | 2++
Mumtool/report-to-video/modules/fx.mjs | 2++
Mumtool/report-to-video/modules/index.mjs | 11+++++++++--
Mumtool/report-to-video/modules/pair.mjs | 2++
Mumtool/report-to-video/modules/registry.test.mjs | 12++++++++++++
Mumtool/report-to-video/modules/stats.mjs | 2++
Mumtool/report-to-video/modules/status.mjs | 2++
Mumtool/report-to-video/modules/threads.mjs | 2++
43 files changed, 1522 insertions(+), 33 deletions(-)

diff --git a/umtool/app/api/report/chrome/preview/route.ts b/umtool/app/api/report/chrome/preview/route.ts @@ -3,6 +3,7 @@ import { composeFeedPreview, composeLayerPreviews, composeFinalePreview, + composePlayLayers, composePostsPreviews, composeStampPreview, normalizeClaimsDraft, @@ -74,6 +75,16 @@ export const dynamic = "force-dynamic"; // composed under takes/<id>/out/<variant>/chrome/, served under // `<project>/<variant>/@take/<id>/` -- never over the project's own preview. // +// THE PLAY LAYERS (`layers` in the full answer): every module that declares +// `play` (the module contract, contract.mjs) and that this cut draws -- the +// chapters, the then-and-now pair, the status ledger, the stats, the +// effects, the side panel, the flips -- each its own page composed for +// preview (composePlayLayers), in z order, with its geometry, its clock and +// the message its page posts when it can be seeked, and either one `src` +// for the whole cut or `windows` (cut seconds) it is up inside. The deck, +// the feed, the popup posts, the stamps and the finale keep their own keys +// above. Not on the clip bench's strip (`posts: false`). +// // `layers: [<module id>, …]` composes only those modules, each alone through // its own page (modules/<id>.mjs) -- the module panel's single-layer preview: // `{ layers: [{ id, region, geometry, src | windows | off | error }] }`. @@ -244,6 +255,12 @@ export async function POST(request: Request) { }; } + const layers = body.posts === false + ? [] + : await composePlayLayers(target, r.variant, schedule, render, { + srcOf: (name: string) => `${layerPreviewSrc(r.project.id, r.variant, name, take)}?v=${stamp}`, + }); + return Response.json( { // `v` so the iframe reloads a recomposed preview; the files themselves @@ -268,6 +285,7 @@ export async function POST(request: Request) { ...(feed ? { feed } : {}), ...(stampDoc ? { stamp: stampDoc } : {}), ...(finale ? { finale } : {}), + layers, // The lead-in breath before a clip's cut (render.leadIn): the play // window's start, which the live preview maps the source through. leadIn: typeof render.leadIn === "number" ? render.leadIn : 0.4, diff --git a/umtool/app/api/report/timeline/route.ts b/umtool/app/api/report/timeline/route.ts @@ -8,6 +8,7 @@ import { manifestToken, moveEntry, removeEntry, + removeWrongSpeaker, removePost, undoStructural, updateFactcheck, @@ -104,6 +105,9 @@ export async function POST(request: Request) { return moveEntry(dir, id, Number(body.toIndex), { token, at }); case "remove": return removeEntry(dir, id, { token, at }); + case "wrong-speaker": + // Marked incorrect (wrong speaker) and removed in one write, on the record (removed.json). + return removeWrongSpeaker(dir, id, { token, at, correction: typeof body.correction === "string" ? body.correction : null }); case "duplicate": return duplicateEntry(dir, id, { token, at }); case "insert": @@ -119,7 +123,7 @@ export async function POST(request: Request) { case "undo": return undoStructural(dir, { token }); default: - throw new Error("op must be move, remove, duplicate, insert, teaser, post, post-remove, factcheck or undo"); + throw new Error("op must be move, remove, wrong-speaker, duplicate, insert, teaser, post, post-remove, factcheck or undo"); } }; diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -1142,7 +1142,13 @@ async function cmdCorrections() { // different when sixty clips have never been looked at. const review = reviewOf(manifest); - if (json) return out({ project: p.id, corrections: rows, review }); + // Taken out of the cut on the record (Wrong speaker: manifest.mjs + // removed.json) and not back in it -- an undo puts a clip back. + const inCut = new Set((manifest.timeline ?? []).map((e) => e?.id)); + const { readRemoved } = await import("../lib/report/manifest.mjs"); + const removed = (await readRemoved(p.dir)).filter((r) => r && !inCut.has(r.id)); + + if (json) return out({ project: p.id, corrections: rows, review, removed }); const summary = `${review.total} clips: ${review.incorrect} incorrect, ` + @@ -1164,6 +1170,13 @@ async function cmdCorrections() { console.log(`${summary}\n`); if (!wrong.length) console.log("No corrections: nobody has said the report got anything wrong here."); for (const c of wrong) bullet(c); + if (removed.length) { + console.log(`\n## Taken out of the cut\n`); + for (const r of removed) { + const where = `${r.channel ?? manifest.provenance?.channelSlug ?? "?"}/${r.video ?? "?"} ${r.start ?? "?"}–${r.end ?? "?"}`; + console.log(`- **${r.id}** · ${where} · ${r.reason}${r.correction ? ` — ${r.correction}` : ""} · ${r.when}`); + } + } if (notes.length) { console.log(`\n## Notes on confirmed clips\n`); console.log(`These clips are RIGHT. The note says why the window moved, or what a`); diff --git a/umtool/components/projects/ClipBench.tsx b/umtool/components/projects/ClipBench.tsx @@ -1,5 +1,6 @@ "use client"; +import WrongSpeaker from "./review/WrongSpeaker"; import AnchoredNotes, { notesOn } from "@/components/notes/AnchoredNotes"; import GeneratedBanner from "@/components/notes/GeneratedBanner"; import { useSharedNotes, wroteNotes } from "@/components/notes/NotesProvider"; @@ -3775,6 +3776,26 @@ export default function ClipBench({ data }: { data: ClipBenchData }) { <span className="text-[var(--color-text)]">{data.uploadDate || "—"}</span> </div> + {/* Wrong speaker: this clip out of the cut, on record, with an undo (the project's cut, not a take's walk). */} + {!takeId && ( + <WrongSpeaker + project={data.project} + clip={{ id: clip.id, video: clip.video, channel: clip.channel, start: clip.start, end: clip.end }} + className={secBody("attribution", "max-md:order-[81]")} + after={ + hrefOf("next") ? ( + <a href={hrefOf("next")!} data-wrong-speaker-next="" className="ink-link"> + Next clip › + </a> + ) : data.fromPlay ? ( + <a href={data.fromPlay.href} className="ink-link"> + ‹ Back to the cut + </a> + ) : null + } + /> + )} + {/* ---- the six fields that decide the header ---- Each field's reason is a tooltip now rather than a paragraph: the explanations are read once and the boxes are used every clip. */} diff --git a/umtool/components/projects/OnscreenSection.tsx b/umtool/components/projects/OnscreenSection.tsx @@ -111,6 +111,28 @@ export type DeckPreviewDoc = { finale?: { geometry: Rect; from: number; to: number; src?: string; error?: string }; /** Each verdict's word as the tally prints it. */ verdictLabels?: Record<string, string>; + /** The play layers: every module that declares `play` (the module contract) and that the cut draws, by z. */ + layers?: PlayLayer[]; +}; +/** + * One module's live layer (the module contract's `play`, onscreen.mjs + * composePlayLayers): its page at `geometry`, seeked on its `clock`, posting + * `ready` once it can be; up for the whole cut (`src`) or inside each of its + * `windows` (cut seconds). + */ +export type PlayLayer = { + id: string; + region: string; + kind: string; + z: number; + clock: "cut"; + ready: string; + geometry: Rect | null; + from?: number; + to?: number; + src?: string; + error?: string; + windows?: { segment: string | null; from: number; to: number; src?: string; error?: string }[]; }; /** An unsaved change to a post, as PUT /api/report/posts takes it. */ export type PostPatch = { attachTo?: string | null; hide?: boolean; thread?: boolean }; @@ -2310,3 +2332,68 @@ export default function OnscreenSection({ </section> ); } + +// --------------------------------------------------------------------------- +// ModuleLayers: the PLAY LAYERS -- every module that declares `play` in the +// module contract (contract.mjs), each its own page laid at its region over +// the footage, in z order, seeked on the cut clock (FeedOverlay's contract, +// with the module's own `ready` message). A window module's page is mounted +// a moment before its window (so it is ready when it comes up) and shown +// only inside it, as the build lays it at its own second; a whole-cut +// module's page is up for the whole cut and draws its own comings and goings. +// Laid over the deck's page (the build lays the deck first) and under the +// finale (which the caller lays last). +// --------------------------------------------------------------------------- + +/** How long before its window a window layer's page is mounted, and how long after it stays. */ +const LAYER_LEAD_S = 4; +const LAYER_TAIL_S = 1; + +export function ModuleLayers({ + layers, + frame: g, + t, + testid = "module-layer", +}: { + layers: PlayLayer[] | undefined; + frame: DeckGeometry; + t: number; + testid?: string; +}) { + if (!layers?.length) return null; + const rows: { key: string; layer: PlayLayer; segment: string | null; src?: string; error?: string; up: boolean }[] = []; + for (const l of [...layers].sort((a, b) => a.z - b.z)) { + if (!l.geometry) continue; + if (Array.isArray(l.windows)) { + for (const w of l.windows) { + if (t < w.from - LAYER_LEAD_S || t > w.to + LAYER_TAIL_S) continue; + rows.push({ key: `${l.id}:${w.segment ?? ""}:${w.src ?? "none"}`, layer: l, segment: w.segment, src: w.src, error: w.error, up: t >= w.from && t <= w.to }); + } + } else { + rows.push({ key: `${l.id}:${l.src ?? "none"}`, layer: l, segment: null, src: l.src, error: l.error, up: true }); + } + } + return ( + <div className="pointer-events-none absolute inset-0" style={{ zIndex: 1 }} data-module-layers=""> + {rows.map((r) => ( + <div + key={r.key} + className="pointer-events-none absolute inset-0" + data-play-layer={r.layer.id} + data-play-layer-segment={r.segment ?? undefined} + data-play-layer-up={r.up ? "1" : "0"} + style={{ opacity: r.up ? 1 : 0 }} + > + <FeedOverlay + feed={{ geometry: r.layer.geometry!, src: r.src, error: r.error }} + frame={g} + t={t} + ready={r.layer.ready} + testid={`${testid}-${r.layer.id}`} + name={r.layer.id} + /> + </div> + ))} + </div> + ); +} diff --git a/umtool/components/projects/review/LiveDeckPreview.tsx b/umtool/components/projects/review/LiveDeckPreview.tsx @@ -10,7 +10,7 @@ import { clipStamps, clockText, cutTimeAt, finaleUp, liveClock, stampAt, tallyAt import { tallyVerdicts } from "umtool-report-to-video/factcheck"; import { BLUR_CAPTION_DEFAULT, BLUR_STRENGTH } from "umtool-report-to-video/clip-blur"; import { drawFootage } from "./footageCanvas"; -import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type DeckTexts, type Rect } from "../OnscreenSection"; +import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type DeckTexts, type Rect } from "../OnscreenSection"; // --------------------------------------------------------------------------- // THE LIVE PREVIEW (plans/live-preview.md): the clip editor's playing source @@ -329,6 +329,8 @@ export default function LiveDeckPreview({ {doc.stamp && ( <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={t} ready="stamp:ready" testid="live-stamp" name="fact-check stamps" /> )} + {/* Every module that declares `play` (chapters, then and now, the status ledger …), by z. */} + <ModuleLayers layers={doc.layers} frame={g} t={t} testid="live-layer" /> {doc.finale && finaleNow && ( // Laid last, over the deck's own page, as the build lays it. <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }} data-live-finale=""> diff --git a/umtool/components/projects/review/PlayCut.tsx b/umtool/components/projects/review/PlayCut.tsx @@ -12,15 +12,16 @@ import { cn } from "@/lib/utils"; import { footageAt } from "@/lib/report/footage-move.mjs"; import { finaleUp, stampAt, tallyAt } from "@/lib/report/liveClock.mjs"; import { - chromeTime, counterSteps, cutAtSource, cutNotesRequest, playPlan, playTimeOfChrome, runningTime, seamsOf, sourceAt, startOf, + chromeTime, counterSteps, cutAtSource, cutNotesRequest, playPlan, playTimeOfChrome, runningTime, seamsOf, skipEntries, sourceAt, startOf, } from "@/lib/report/playCut.mjs"; import { tallyVerdicts } from "umtool-report-to-video/factcheck"; import { AssistReplyApply, ProposalList, routeLine, jobLine, useAssist } from "../report/AssistBox"; -import { DeckFrame, FeedOverlay, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection"; +import { DeckFrame, FeedOverlay, ModuleLayers, PostsOverlay, postsWindowAt, type DeckPreviewDoc, type Rect } from "../OnscreenSection"; import { usePlayEngine } from "./playEngine/usePlayEngine"; import { useRenderCuts, type RenderCuts } from "./playEngine/useRenderCuts"; import type { EngineInfo } from "./playEngine/engine"; import ReelStrip, { type StripCounter } from "./ReelStrip"; +import WrongSpeaker from "./WrongSpeaker"; // --------------------------------------------------------------------------- // THE PLAY VIEW (umtool/docs/knobs.md, "Play the cut"): a screening room. The @@ -100,6 +101,8 @@ export type PlayEntry = { cutEnd?: number | null; blur?: { on?: boolean; caption?: string; strength?: number; from?: number; to?: number } | null; media?: { name: string; from: number; to: number } | null; + /** Ruled incorrect by the walk: its correction (skipped unless "Show clips marked incorrect"). */ + incorrect?: string | null; }; export type PlayViewData = { @@ -134,6 +137,8 @@ const SKIP_S = 5; /** The player is as wide as leaves the strip and Now on screen under it (never under 480 px). */ const PLAYER_MAX_W = "max(480px, min(1100px, calc((100dvh - 430px) * 16 / 9)))"; const PAUSE_KEY = "umtool.play.pauseWhileWriting"; +/** "on": play the clips ruled incorrect too (for re-review); absent or "off": skip them. */ +const SHOW_INCORRECT_KEY = "umtool.play.showIncorrect"; /** The dailies' kinds of note: what it asks for, and its key (with Alt, in the composer). */ const ASKS: { id: CutAsk; label: string; key: string }[] = [ @@ -254,7 +259,25 @@ export default function PlayCut({ // The render's edges (useRenderCuts: the build's snap), asked again when an entry's edges change. const edgesKey = useMemo(() => JSON.stringify(view.entries.map((e) => [e.id, e.start, e.end, e.cutStart, e.cutEnd])), [view.entries]); const edges = useRenderCuts(project, take, edgesKey); - const plan = useMemo(() => playPlan(segments, view.entries, { leadIn, cuts: edges.cuts }), [segments, view.entries, leadIn, edges.cuts]); + // Clips ruled incorrect (the walk's verdict) are SKIPPED unless asked for: + // the cut the operator means to ship does not hold them (umtool check + // blocks on them, a take refuses them). Remembered per browser. + const [showIncorrect, setShowIncorrect] = useState(false); + useEffect(() => { + try { + // The URL first (Back from the bench lands on the URL Play left), then this browser's choice. + const u = new URLSearchParams(window.location.search).get("incorrect"); + if (u === "1" || (u === null && window.localStorage.getItem(SHOW_INCORRECT_KEY) === "on")) setShowIncorrect(true); + } catch { + // No storage: skipped, the default. + } + }, []); + const incorrect = useMemo(() => view.entries.filter((e) => e.incorrect), [view.entries]); + const skipIds = useMemo(() => new Set(showIncorrect ? [] : incorrect.map((e) => e.id)), [showIncorrect, incorrect]); + const plan = useMemo( + () => skipEntries(playPlan(segments, view.entries, { leadIn, cuts: edges.cuts }), skipIds), + [segments, view.entries, leadIn, edges.cuts, skipIds], + ); const entryOf = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]); const planRef = useRef(plan); planRef.current = plan; @@ -280,7 +303,27 @@ export default function PlayCut({ // placed again (cutAtSource) whenever the plan is re-timed under it: the // composed schedule replacing the estimate's, the render's edges arriving. // Let go once both have settled. A card keeps its offset. - const anchor = useRef<{ clip: string; at: number; src?: number } | null>(initialAt); + const anchor = useRef<{ clip: string; at: number; src?: number; t?: number } | null>(initialAt); + // THE PLACE IN THE URL: Play keeps where it is -- the clip, the offset into + // it, the cut second and the incorrect-clips toggle -- in its own URL + // (replaceState, at most once a second, never a history entry of its own), + // so the browser's Back from the clip bench (one push, Edit this clip) + // lands here, paused at the same place. A page restored without the + // server's `?clip=&at=` reads them from the location instead. + const [backToast, setBackToast] = useState<string | null>(null); + useEffect(() => { + const q = new URLSearchParams(window.location.search); + const clip = q.get("clip"); + const at = Number(q.get("at")); + const ct = q.get("t") !== null ? Number(q.get("t")) : NaN; + const t = Number.isFinite(ct) ? { t: ct } : {}; + // The server's `?clip=&at=` is already the anchor: the cut second rides along for the toast. + if (anchor.current) { + if (anchor.current.clip === clip) Object.assign(anchor.current, t); + return; + } + if (clip) anchor.current = { clip, at: Number.isFinite(at) && at > 0 ? at : 0, ...t }; + }, []); useEffect(() => { const a = anchor.current; if (!a) return; @@ -293,10 +336,22 @@ export default function PlayCut({ const inside = (v: number) => Math.min(Math.max(it.from, v), Math.max(it.from, it.to - 0.05)); // (The offset was taken on the render's clock: turned into a source second once the render's edges are in.) if (it.clip && a.src === undefined && edges.state !== "measuring") a.src = sourceAt(it, inside(it.from + a.at)) ?? undefined; - seekTo(it.clip && a.src !== undefined ? inside(cutAtSource(it, a.src)) : inside(it.from + a.at)); - if (composeState !== "composing" && edges.state !== "measuring") anchor.current = null; + const landed = it.clip && a.src !== undefined ? inside(cutAtSource(it, a.src)) : inside(it.from + a.at); + seekTo(landed); + if (composeState !== "composing" && edges.state !== "measuring") { + anchor.current = null; + // The cut second it was left at is not where that clip's offset is now: an edit moved it. + if (a.t !== undefined && Math.abs(landed - a.t) > 0.1) setBackToast(`Back at ${a.clip} · ${timecode(landed)} (the cut changed)`); + } }, [plan, composeState, edges.state, seekTo]); + // A structural write landed (Wrong speaker, its undo): the view and the chrome are read again. + const afterStructure = useCallback(() => { + setPlaying(false); + router.refresh(); + if (view.deckOn) void compose(); + }, [router, view.deckOn, compose, setPlaying]); + // ---- the controls ---------------------------------------------------------------- const next = useCallback(() => seekTo(startOf(planRef.current, now().cur + 1)), [seekTo, now]); const prev = useCallback(() => seekTo(startOf(planRef.current, now().cur - 1)), [seekTo, now]); @@ -387,12 +442,41 @@ export default function PlayCut({ if (!it?.clip) return null; return clipBenchHref(project, it.id, { play: { at: Math.round(Math.max(0, e.t - it.from) * 100) / 100, take } }); }, [project, take, now]); + /** Play's place as its own URL: the clip on screen, the offset into it, the cut second, the toggle. */ + const placeHref = useCallback(() => { + const e = now(); + const it = planRef.current.items[e.cur]; + const u = new URL(window.location.href); + if (it) { + u.searchParams.set("clip", it.id); + u.searchParams.set("at", (Math.round(Math.max(0, e.t - it.from) * 100) / 100).toFixed(2)); + u.searchParams.set("t", (Math.round(e.t * 100) / 100).toFixed(2)); + } + if (showIncorrect) u.searchParams.set("incorrect", "1"); + else u.searchParams.delete("incorrect"); + return `${u.pathname}${u.search}${u.hash}`; + }, [now, showIncorrect]); const editHere = useCallback(() => { const h = editHref(); if (!h) return; setPlaying(false); + // Where Back lands: this place, written now (the one push is the bench's). + window.history.replaceState(null, "", placeHref()); router.push(h); - }, [editHref, router, setPlaying]); + }, [editHref, router, setPlaying, placeHref]); + const lastPlace = useRef(0); + useEffect(() => { + // Not while a place is still being restored: the URL holds it until it lands. + if (anchor.current) return; + const due = () => { + lastPlace.current = performance.now(); + const h = placeHref(); + if (h !== `${window.location.pathname}${window.location.search}${window.location.hash}`) window.history.replaceState(null, "", h); + }; + const wait = ui.playing ? 1000 - (performance.now() - lastPlace.current) : 150; + const id = setTimeout(due, Math.max(0, wait)); + return () => clearTimeout(id); + }, [ui.t, ui.cur, ui.playing, showIncorrect, placeHref]); // ---- the keys ---------------------------------------------------------------------- const [help, setHelp] = useState(false); @@ -463,7 +547,7 @@ export default function PlayCut({ const placed = stamps.map((x) => ({ ...x, landed: playTimeOfChrome(plan, x.landed) })); return ids.map((id) => ({ id, label: doc?.verdictLabels?.[id] ?? labels.get(id) ?? id, steps: counterSteps(placed, id) })); }, [schedule, view.counter, doc?.verdictLabels, plan]); - const seams = useMemo(() => seamsOf(view.entries, view.markers), [view.entries, view.markers]); + const seams = useMemo(() => seamsOf(view.entries.filter((e) => !skipIds.has(e.id)), view.markers), [view.entries, view.markers, skipIds]); const pins = useMemo(() => mine.map((n) => ({ id: n.id, t: noteT(n.anchor as CutAnchor), text: n.text, open: n.status === "open" })), [mine, noteT, plan]); const stripEntries = useMemo(() => new Map(view.entries.map((e) => [e.id, e])), [view.entries]); @@ -627,6 +711,8 @@ export default function PlayCut({ {doc.feed && <FeedOverlay key={doc.feed.src ?? "none"} feed={doc.feed} frame={g} t={tc} testid="play-feed" />} {postsWin && doc.posts && <PostsOverlay key={`${postsWin.segment}:${postsWin.src ?? "none"}`} win={postsWin} geometry={doc.posts.geometry} frame={g} t={tc} />} {doc.stamp && <FeedOverlay key={`stamp:${doc.stamp.src ?? "none"}`} feed={doc.stamp} frame={g} t={tc} ready="stamp:ready" testid="play-stamp" name="fact-check stamps" />} + {/* Every module that declares `play` (chapters, then and now, the status ledger …), by z. */} + <ModuleLayers layers={doc.layers} frame={g} t={tc} testid="play-layer" /> {doc.finale && finaleNow && ( <div className="pointer-events-none absolute inset-0" style={{ zIndex: 2 }} data-play-finale=""> <FeedOverlay key={`finale:${doc.finale.src ?? "none"}`} feed={doc.finale} frame={g} t={tc} ready="finale:ready" testid="play-finale" name="finale" /> @@ -712,6 +798,23 @@ export default function PlayCut({ {composeState === "no-deck" && <span>no on-screen deck: the footage alone</span>} </span> </div> + {backToast && ( + <p role="status" data-play-back-toast="" className="m-0 flex items-center gap-2 text-[11.5px] text-text-2"> + {backToast} + <button type="button" className="ink-link" onClick={() => setBackToast(null)}> + dismiss + </button> + </p> + )} + {/* Wrong speaker: the clip on screen out of the cut, on record, with an undo (the project's cut: not on a take). */} + {!take && ( + <WrongSpeaker + project={project} + clip={item?.clip && entry ? { id: item.id, video: entry.video ?? null, channel: entry.channel ?? null, start: entry.start ?? null, end: entry.end ?? null } : null} + onRemoved={afterStructure} + onUndone={afterStructure} + /> + )} {composeState === "error" && ( <p role="alert" className="m-0 text-[11.5px] text-reject-text" data-play-compose-error=""> The chrome did not compose: {composeError}. The footage plays without it; Recompose after fixing the cut. @@ -733,7 +836,41 @@ export default function PlayCut({ timecode={timecode} onSeek={seekTo} onSeekItem={(i) => seekTo(startOf(planRef.current, i))} + skipped={plan.skipped.map((x) => ({ ...x, correction: entryOf.get(x.id)?.incorrect ?? "" }))} /> + {incorrect.length > 0 && ( + <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-[11.5px] text-muted" data-play-incorrect={incorrect.map((e) => e.id).join(" ")}> + <span> + {showIncorrect ? "Playing" : "Skipping"} {incorrect.length} clip{incorrect.length === 1 ? "" : "s"} marked incorrect:{" "} + {incorrect.map((e, k) => ( + <span key={e.id}> + {k > 0 ? ", " : ""} + <s className="font-mono" title={`${e.id}: ${e.incorrect}`} data-play-incorrect-id={e.id}> + {e.id} + </s> + </span> + ))} + {!showIncorrect && <span title="the deck's pages are composed from the whole cut, so the tally still counts their marks"> · the deck still counts their marks</span>} + </span> + <label className="inline-flex items-center gap-1.5 text-text-2"> + <input + type="checkbox" + data-play-show-incorrect="" + checked={showIncorrect} + onChange={(ev) => { + const on = ev.target.checked; + setShowIncorrect(on); + try { + window.localStorage.setItem(SHOW_INCORRECT_KEY, on ? "on" : "off"); + } catch { + // A preference, not state. + } + }} + /> + Show clips marked incorrect + </label> + </div> + )} {/* ---- now ---- */} <NowReader project={project} item={item} entry={entry ?? null} t={t} next={plan.items[ui.cur + 1] ?? null} nextEntry={plan.items[ui.cur + 1] ? (entryOf.get(plan.items[ui.cur + 1].id) ?? null) : null} broken={broken} /> diff --git a/umtool/components/projects/review/ReelStrip.tsx b/umtool/components/projects/review/ReelStrip.tsx @@ -18,7 +18,7 @@ type PlayItem = ReturnType<typeof playPlan>["items"][number]; // counts the minutes. // --------------------------------------------------------------------------- -export type StripEntry = { id: string; type: string; heading: string; dateKey?: number | null; dateLabel?: string | null; media?: unknown }; +export type StripEntry = { id: string; type: string; heading: string; dateKey?: number | null; dateLabel?: string | null; media?: unknown; incorrect?: string | null }; export type StripCounter = { id: string; label: string; steps: Array<{ t: number; n: number }> }; export type StripPin = { id: string; t: number; text: string; open: boolean }; export type StripSeam = { before: string; index: number; date: string | null; label: string | null }; @@ -39,6 +39,7 @@ export default function ReelStrip({ timecode, onSeek, onSeekItem, + skipped = [], }: { items: PlayItem[]; total: number; @@ -52,6 +53,8 @@ export default function ReelStrip({ timecode: (t: number) => string; onSeek: (t: number) => void; onSeekItem: (i: number) => void; + /** Entries left out of the plan (clips ruled incorrect): a struck-through marker at the seam, the correction on hover. */ + skipped?: { id: string; at: number; correction: string }[]; }) { const cells = useRef<HTMLDivElement | null>(null); const [hover, setHover] = useState<number | null>(null); @@ -156,6 +159,7 @@ export default function ReelStrip({ const e = entries.get(it.id); const f = ramp.get(it.id); const missing = noMedia(it); + const wrong = e?.incorrect ?? null; const base = it.clip ? `color-mix(in srgb, var(--seam-2) ${Math.round(30 + 60 * (f ?? 0.5))}%, var(--ground))` : "var(--panel)"; @@ -167,8 +171,9 @@ export default function ReelStrip({ data-play-row={it.id} aria-current={i === cur ? "true" : undefined} aria-label={`${it.id}${e?.dateLabel ? `, ${e.dateLabel}` : ""}, ${shownSeconds(it).toFixed(1)} seconds${missing ? ", no media" : ""}`} - title={missing ? `${it.id}: no media — fetch it` : undefined} + title={wrong ? `${it.id}: marked incorrect — ${wrong}` : missing ? `${it.id}: no media — fetch it` : undefined} data-play-row-missing={missing ? "" : undefined} + data-play-row-incorrect={wrong ? "" : undefined} onClick={(ev) => { // A pointer's click scrubbed on pointerdown; a key's (Enter) jumps to the entry's start. if (ev.detail === 0) onSeekItem(i); @@ -176,6 +181,7 @@ export default function ReelStrip({ className={cn( "absolute top-0 h-full overflow-hidden border-r border-ground px-1 pt-0.5 text-left font-mono text-[10px] leading-3", it.clip ? "text-text-2" : "text-muted", + wrong && "text-muted line-through opacity-60", i === cur && "shadow-[inset_0_-2px_0_var(--signal)]", )} style={{ @@ -192,6 +198,19 @@ export default function ReelStrip({ ); })} + {/* the entries skipped (ruled incorrect): a greyed, struck-through tag where they would play */} + {skipped.map((x) => ( + <span + key={`skip:${x.id}`} + data-play-skipped={x.id} + title={`${x.id} skipped — marked incorrect${x.correction ? `: ${x.correction}` : ""}`} + className="absolute bottom-0 z-[1] -translate-x-1/2 rounded-[2px] bg-ground/90 px-0.5 font-mono text-[9px] leading-3 text-muted line-through opacity-80" + style={{ left: pctOf(x.at, total) }} + > + {x.id} + </span> + ))} + {/* the sections' seams */} {seams.map((s) => { const it = items[s.index]; diff --git a/umtool/components/projects/review/WrongSpeaker.tsx b/umtool/components/projects/review/WrongSpeaker.tsx @@ -0,0 +1,161 @@ +"use client"; + +import { useState } from "react"; +import { buttonVariants } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; +import { announceManifestChanged, refusalOf, timelineOp } from "../timelineApi"; + +// --------------------------------------------------------------------------- +// WRONG SPEAKER: the walk's one-click "this is somebody else talking". One +// structural write (POST /api/report/timeline `wrong-speaker`, +// manifest.mjs removeWrongSpeaker) marks the clip incorrect with the reason +// "wrong-speaker" and takes it out of the cut -- an undo point first, what +// named it re-anchored, the removal on record in removed.json. Asked in the +// page first (what will be removed, an optional note), never window.confirm; +// afterwards an Undo (the structural undo: the clip back where it was). +// +// The clip bench and Play the cut both carry it. +// --------------------------------------------------------------------------- + +export type WrongSpeakerClip = { id: string; video?: string | null; channel?: string | null; start?: number | null; end?: number | null }; + +type Phase = { k: "idle" } | { k: "asking" } | { k: "busy" } | { k: "removed"; notes: string[] } | { k: "undone" }; + +const secs = (n: number | null | undefined) => (typeof n === "number" && Number.isFinite(n) ? `${n.toFixed(2)} s` : "?"); + +export default function WrongSpeaker({ + project, + clip, + onRemoved, + onUndone, + after, + className, +}: { + project: string; + /** The clip on screen; null (a card, nothing) shows only a removal still to undo. */ + clip: WrongSpeakerClip | null; + /** After the removal landed (the page re-reads what it plays). */ + onRemoved?: (id: string) => void; + /** After the undo landed. */ + onUndone?: (id: string) => void; + /** What follows the "removed" line (the bench's Next clip link). */ + after?: React.ReactNode; + className?: string; +}) { + const [phase, setPhase] = useState<Phase>({ k: "idle" }); + const [note, setNote] = useState(""); + const [error, setError] = useState<string | null>(null); + const [removedId, setRemovedId] = useState<string | null>(null); + + const remove = async () => { + setPhase({ k: "busy" }); + setError(null); + if (!clip) return; + const res = await timelineOp(project, null, "wrong-speaker", { id: clip.id, ...(note.trim() ? { correction: note.trim() } : {}) }); + if (!res.ok) { + setError(refusalOf(res)); + setPhase({ k: "asking" }); + return; + } + setRemovedId(clip.id); + setNote(""); + setPhase({ k: "removed", notes: Array.isArray(res.json.reanchored) ? (res.json.reanchored as string[]) : [] }); + announceManifestChanged(project); + onRemoved?.(clip.id); + }; + const undo = async () => { + const id = removedId ?? clip?.id ?? ""; + setPhase({ k: "busy" }); + setError(null); + const res = await timelineOp(project, null, "undo"); + if (!res.ok) { + setError(refusalOf(res)); + setPhase({ k: "removed", notes: [] }); + return; + } + setRemovedId(null); + setPhase({ k: "undone" }); + announceManifestChanged(project); + onUndone?.(id); + }; + + const shown = removedId ?? clip?.id ?? ""; + if (!clip && (phase.k === "idle" || phase.k === "asking")) return null; + return ( + <div className={cn("text-[12px] text-text-2", className)} data-wrong-speaker={shown} data-wrong-speaker-phase={phase.k}> + {(phase.k === "idle" || phase.k === "undone") && ( + <div className="flex flex-wrap items-center gap-2"> + {clip && ( + <button + type="button" + data-wrong-speaker-start="" + onClick={() => setPhase({ k: "asking" })} + className={cn(buttonVariants({ variant: "outline", size: "sm" }))} + title="somebody else is talking: mark it incorrect (wrong speaker) and take it out of the cut, with an undo" + > + Wrong speaker + </button> + )} + {phase.k === "undone" && <span data-wrong-speaker-undone="">Undone: the clip is back in the cut.</span>} + </div> + )} + {clip && (phase.k === "asking" || (phase.k === "busy" && !removedId)) && ( + <div role="group" aria-label="Wrong speaker" data-wrong-speaker-ask="" className="space-y-1.5 rounded-[3px] border border-seam-2 bg-panel p-2"> + <p className="m-0 text-text" data-wrong-speaker-what=""> + Remove <span className="font-mono">{clip.id}</span> + {clip.video ? ( + <> + {" "} + ({clip.channel ? `${clip.channel}/` : ""} + {clip.video} {secs(clip.start)}–{secs(clip.end)}) + </> + ) : null}{" "} + from the cut as <strong>wrong speaker</strong>? It is marked incorrect and put on record; Undo puts it back. + </p> + <input + type="text" + data-wrong-speaker-note="" + value={note} + onChange={(e) => setNote(e.target.value)} + placeholder="who it is, if you know (optional)" + maxLength={300} + className="w-full rounded border border-seam-2 bg-ground px-1.5 py-1 text-[12px] text-text outline-none focus:border-signal" + /> + <div className="flex gap-2"> + <button type="button" data-wrong-speaker-remove="" disabled={phase.k === "busy"} onClick={() => void remove()} className={cn(buttonVariants({ variant: "go", size: "sm" }))}> + Remove {clip.id} + </button> + <button type="button" data-wrong-speaker-cancel="" disabled={phase.k === "busy"} onClick={() => setPhase({ k: "idle" })} className={cn(buttonVariants({ variant: "quiet", size: "sm" }))}> + Cancel + </button> + </div> + </div> + )} + {(phase.k === "removed" || (phase.k === "busy" && removedId)) && ( + <div role="status" data-wrong-speaker-removed={shown} className="space-y-1 rounded-[3px] border border-seam-2 bg-panel p-2"> + <div className="flex flex-wrap items-center gap-2"> + <span className="text-text"> + Removed <span className="font-mono">{shown}</span> from the cut (wrong speaker). + </span> + <button type="button" data-wrong-speaker-undo="" disabled={phase.k === "busy"} onClick={() => void undo()} className={cn(buttonVariants({ variant: "outline", size: "sm" }))}> + Undo + </button> + {after} + </div> + {phase.k === "removed" && phase.notes.length > 0 && ( + <ul className="m-0 list-disc pl-5 text-[11.5px] text-muted" data-wrong-speaker-reanchored=""> + {phase.notes.map((n) => ( + <li key={n}>{n}</li> + ))} + </ul> + )} + </div> + )} + {error && ( + <p role="alert" className="m-0 mt-1 text-[11.5px] text-reject-text"> + {error} + </p> + )} + </div> + ); +} diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -59,7 +59,7 @@ Inbox cannot disagree about what is wrong with one. | `phrases "<phrase>" ["<phrase>" …] --channels a,b [--prefer c] [--exclude RE] [--words \| --regex] [--samples N] [--no-cache] [--json \| --full]` | the phrase finder's search ([tools.md](tools.md#the-phrase-finder-toolsphrases)): every phrase in one pass, each with its count once folded, by year, the preferred channel's share or Rumble's, speaker changes, sample contexts. Plain words become a tolerant pattern unless the phrase holds a regular expression's characters. `--json` the numbers, `--full` every instance; `--spec FILE --out FILE --progress` is the page's job form. **Exit 1** on a bad phrase | | `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)) | | `clips analyze <project> [--from <channel>/<id>] [--rescan] [--no-laughs] [--no-voices] [params] [--words FILE] [--progress ndjson] [--json]` · `clips propose <project> [--from <channel>/<id>] [--host N] [params] [--words FILE] [--dry] [--json]` · `clips show <project> [--json]` · `clips segments <project> [--json]` | the **clip finder** on a long recording ([report-video.md](report-video.md#highlights-the-clip-finder)): `analyze` runs the laugh scan (CED-mini) and a voice centroid per speaker on the recording's sound (cached in `<project>/scans/`), then proposes; `propose` proposes again from what is there (after a role flip, a param change, new words); `show` prints the speakers, laughs and the cut. Params `--target S` (600) `--laugh-min X` (0.25) `--merge-gap S` (6) `--setup-max S` (20) `--clip-max S` (75) and the scope `--scope FROM:TO` (either side may be empty; `all` clears it) or `--from S --to S` with numbers (a `--from` that is a `<channel>/<id>` names the recording), kept in `reactions.json`; `--host N` is your word on the host, kept. `--keep-cut` proposes without touching the cut (nothing moved, removed or added; the proposals are listed). **`--scope auto`** reads the narrated video auto-scope finds in the speaker turns (`--segment sN` names one, else the longest); `segments` lists them. A chat replay beside the recording (`live_chat.cues.json`) adds chat-burst moments and the log names the chat's lag. A channel on no site gets each clip linked to its platform page (`citeUrl`). A clip you edited, ruled, locked or added is never moved. **Exit 2** with no `diarization.json` (the message names the `archilyzer diarize backfill` to run) | -| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `remove <id>` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | +| `timeline <project> [ls] [--json]` · `timeline <project> insert --after <id\|-> <channel>/<video>@<start>-<end> [--id ID] [--section N] [--lock] [--lock-end] [--title T] [--stream-title T] [--date YYYY-MM-DD] [--quote Q] [--cite S] [--cite-url U]` · `timeline <project> move <id> --to <index>` · `remove <id>` · `wrong-speaker <id> [--correction T]` · `duplicate <id>` (`--at <index>` names one of an id's twins) · `post <json\|@file>` · `post-remove <id>` · `teaser <id> <patch-json\|@file>` · `undo` | the **structure** of the cut (the Cut tab's timeline, the On-screen section's teasers and posts) through the writers `POST /api/report/timeline` runs: `ls` prints index, id, type, video, start–end, date and title (`--json` adds the token and the posts); an insert's attribution is a second write through `window`'s writer, its date checked before anything is written; it is written in the manifest's own convention — under the deck `--title` is the deck's title (`onscreen.title`, `--stream-title` the stream's), a cut whose deck titles are dates gets `--date` as one in their format, and the clip takes the section of the clip it goes after (`--section N` names another) and, from the same recording, its deck title and its citation link. A removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; a pair, a status reference or a deck claim dropped) and prints each `re-anchored:` line; `wrong-speaker` marks the clip incorrect (reason `wrong-speaker`) and removes it, on record in `removed.json` ([report-video.md](report-video.md#verdict--what-the-walk-said)). Every write snapshots the manifest first (`revisions/…-auto-before-<op>`), is refused only for what it breaks in the build's own words (**exit 1**), and on a generated manifest leaves an `edit` note ([report-video.md](report-video.md#structural-edits)) | | `timeline <project> --take <take> [ls \| move <id> --to <index> \| remove <id> \| undo]` | a **take's** timeline (walk a take): the same structure checks, written into the take's patch, each write with an undo point of the take's own (`takes/<take>/revisions/`); `undo` takes the take's newest edit back, whichever writer made it | | `scenes <project> <clip> [--black-min 0.05] [--threshold 8] [--pix-th 0.10] [--pad 30 \| --from S --to S] [--json]` | the picture's **scene cuts** (ffmpeg `scdet`, score ≥ threshold) and **black spans** (`blackdetect`) in the clip's fetched window, in SOURCE seconds — for `blur.from`/`blur.to` and trims ([knobs.md](knobs.md#a-clips-picture-blurred)). The window is the one the build would cut from (the project's `out/clips-raw`, the editor's `channels/<slug>/data/<id>/clips/`, a saved source); the extent ± `--pad` inside it is scanned. Nothing is fetched: **exit 1** with no window on disk (`fetch` first) | | `posts set <project> <post> thread=on\|off [hide=on\|off] [attach=<clipId>\|auto] [--json]` | the Posts table's writer (`updatePosts`, `PUT /api/report/posts`) from a terminal: `<post>` is the manifest's id (`x-<postId>`) or the bare `<postId>`; `thread=on` draws a reply with the post it answers above it (`shot-thread.png` beside its `shot`, taken by `capture-posts` `"thread": true`; its own shot while there is none), `off` removes the key. Refused in the build's words (a post with no `shot`, an `attach` that is not a clip) — **exit 1** | diff --git a/umtool/docs/inbox.md b/umtool/docs/inbox.md @@ -74,6 +74,7 @@ on (`decisionTab`, `songTabOfSection`). | `storage-unreachable` | blocking | an `out/` or deliverables link whose drive is not there | Reconnect the media drive | | `storage-mismatch` | open | a storage move that was cut, with the command that finishes it | Settle the storage | | `clip-cut-outside` | blocking | a `cutStart`/`cutEnd` without its pair, under half a second, or outside its window | Fix the cut | +| `clip-incorrect` | blocking | a clip whose verdict is `incorrect` (or a legacy `correction` with no verdict) still in the timeline: "e01 is marked incorrect: … — remove it, fix it and re-confirm, or clear the verdict". A take of a cut holding one refuses with the same sentence; Play the cut skips it | Remove or fix the clip | **song** — `unjudged-variant` (Judge variant), `missing-cut` (Ship the cut), `no-recipe` / `stale-recipe` (Record the recipe), `spec-problem` (Fix the spec), `no-plan` (Name the plan), `unattributed` (Attribute variant), diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -228,11 +228,30 @@ browser. **Render this clip** is the pixel-true check of all of that but the joi (`/projects/<p>/play?take=<id>`) — plays the WHOLE cut in this browser in its final look, for iterating without a render: every entry in timeline order, each clip from its cached source window (the bench's media route, an excerpt of a long recording), the live preview's chrome over it on ONE cut clock — the rail's pip, the tally, the -stamps, the markers and the finale advance as in the render — at the render's own edges (below). A take plays the project's manifest **as it is now** with the take's style patch and its +stamps, the markers and the finale advance as in the render, and every module that declares **`play`** in the +module contract — the chapter cards over the first seconds of the clip each opens, the then-and-now pair strip, the +status ledger, the stats, the effects, the side panel, the flips — laid at its region in the build's z order, up +only where the build lays it ([Modules](#modules), "Play the cut and the live preview") — at the render's own edges (below). A take plays the project's manifest **as it is now** with the take's style patch and its own patch (a take's own `timeline` included), from `takes/<id>/take.json` or — not rendered yet — a recipe that names it; its pages are composed under `takes/<id>/out/`, never over the project's. `render.blur: "off"` on the take plays its blurred clips as recorded. +**A clip ruled incorrect is skipped.** A clip whose walk verdict is `incorrect` (or that carries a legacy +`correction` and no verdict) is left out of what Play plays — its neighbours meet at the seam — and the reel strip +shows it struck through where it would be, its correction on hover. **Show clips marked incorrect** (under the strip, +remembered by this browser) plays them again, greyed and struck through, for re-review. The deck's pages are still +composed from the whole cut, so its tally counts their marks. `umtool check` calls such a clip **blocking** +(`clip-incorrect`) and a take refuses it by name ([report-video.md](report-video.md)). + +**Wrong speaker** (under the transport; on the clip bench too) takes the clip on screen out of the project's cut in +one write — asked in the page first, with an **Undo** after, on record in `removed.json` +([report-video.md](report-video.md#verdict--what-the-walk-said)). Not on a take. + +**Play keeps its place in its URL** (`?clip=&at=&t=` and `incorrect=1`, replaced at most once a second, never a +history entry of its own), so **Edit this clip** (E) and then the browser's **Back** — or the bench's **‹ Back to the +cut** — lands paused on the same second of the same clip. When an edit moved that clip in the cut, Play resumes by +the clip and the offset into it, and says **Back at c02 · 00:03.0 (the cut changed)**. + **To judge a take clip by clip, walk it** (`/projects/<p>/takes/<id>/walk`, **Walk this take** on its card): the clip bench on the take's own clips, whose verdicts, trims and removals go into the take's patch, never the project's manifest; `umtool walk <p> --take <id>`, `umtool window <p> <clip> --take <id> …` and `umtool timeline @@ -375,6 +394,26 @@ filter. A knob absent is its default, and a module whose knobs are all absent dr | [Chapters](#chapters) `chapter` | A section bumper over the first seconds of the clip it opens: title, subtitle, date. (pages at their own seconds) | `render.chrome.chapter` | | [Finale](#finale) `finale` | The cut's last clips under the rail redrawn large, the final totals and stats cards. (pages at their own seconds) | `render.chrome.deck.finale` | +### Play the cut and the live preview + +A module's HyperFrames page IS its live preview: the build captures it frame by frame; Play the cut and the clip +editor's live preview load the same page (composed with `preview: true`, no render) in an iframe at the module's +region and seek it by message. A module joins them by declaring `play: { clock: "cut", ready: "<region>:ready" }` +in its definition (`modules/contract.mjs`): its page takes `deck:seek` in the cut's seconds and posts `ready` once +it can be seeked. `POST /api/report/chrome/preview` returns every such module the cut draws (its own `on`, the +build's predicate) as `layers: [{id, z, region, clock, ready, geometry, src | windows}]`; the client lays them +by z over the deck's page, a whole-cut page for the whole cut, a window module's page only inside each window. + +Declaring `play`: `stats`, `pair`, `status`, `fx`, `threads`, `flips`, `chapter`. + +Still drawn by their own paths (the response's `src`, `feed`, `posts`, `stamp` and `finale` keys), and what moving +each onto `play` needs: the deck (`shell`) -- its typed words patched in live (`deck:text`) and the `deck:ready` +handshake DeckFrame waits on; the feed -- its footage box and per-segment framing boxes (`feed.footage`, +`feed.boxes`) that move the picture; the popup posts -- one page per window composed with the posts draft, and +`posts:ready`; the stamps -- their geometry follows the feed layout (`stampGeometry`) and the HUD reads +`stampAt`; the finale -- its window is the schedule's `finale` (not a region's) and it is laid over the deck. +Each is a `play` declaration plus moving its consumers (the live-preview and Play specs' testids) to the layer. + ### Deck (the shell) The panel at the foot of the frame and each clip's title (`render.chrome.deck`); its parts -- the subtitle, the QR, the rail, the counter, the claim checks -- are their own modules below. diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -142,6 +142,12 @@ a second. The writer refuses anything else and `umtool check` reports it as nobody reviewed, and half a pair renders the whole extent while the manifest reads as though it were trimmed. +**A clip ruled incorrect blocks.** A walk's `verdict: "incorrect"` (with its `correction`) on a clip still in the +timeline is `clip-incorrect`, **blocking**, in `umtool check` — "e01 is marked incorrect: Other speaker, not Ember — +remove it, fix it and re-confirm, or clear the verdict" — and a take of the cut refuses with that sentence before it +renders anything (`umtool take`, the takes page, a batch). Play the cut skips the clip unless **Show clips marked +incorrect** is ticked. + - **The build** cuts to `[cutStart − render.leadIn, cutEnd]` (lead-in 0.4 s by default, clamped into the extent) when both are present, and to the extent when they are not — so a manifest written before any of this behaves exactly @@ -174,6 +180,24 @@ empty value deletes the key. A clip is a *claim*: the report said somebody said this, here. Walking the cut is somebody checking that claim against the audio. +**`reason` — wrong speaker.** Beside `verdict: "incorrect"`, `reason: "wrong-speaker"` says what is wrong without a +note (a `correction` stays optional; it is the only structured reason — say anything else in the correction). +`umtool set <p> <clip> verdict=wrong-speaker` (shorthand for incorrect + the reason) marks it; a verdict changed to +anything else drops the reason. **Wrong speaker** on the clip bench and in Play the cut does more in one write +(`umtool timeline <p> wrong-speaker <clip> [--correction T]`, `POST /api/report/timeline` `op: "wrong-speaker"`): it +marks the clip so and **removes it from the timeline** — asked in the page first (what goes, an optional note), an +undo point first (**Undo** right after, or `umtool timeline <p> undo`), and the removal **on record** in +`removed.json` beside the manifest (id, channel, video, window, reason, correction, when; append-only — `umtool +corrections` lists those still out of the cut under "Taken out of the cut"). + +**A removal re-anchors what named the clip** (every `remove`, not only Wrong speaker), and says so line by line +(`re-anchored: …` in the CLI, `reanchored` in the route's answer): a deck marker `after` it moves to the clip before +it (the same boundary), a chapter `at` it to the next clip in its section (dropped when there is none), a +then-and-now pair naming it on a side is dropped, a status item loses the reference (and goes when it names no clip +any more), a deck claim check said in it is dropped. Its own marks go with it, so the counter recounts. A post +attached to it still refuses the removal, and so does any reference on a **take's** timeline (`--take`: its patch +holds only the timeline, so nothing else could move with it). + | on disk | state | `correction` | |---|---|---| | `verdict: "confirmed"` | **confirmed** | optional — a *note* | diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -1868,6 +1868,31 @@ makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out // The same cut for Play → Edit this clip → Back (phone-walk.spec.ts), which WRITES // an edge: its own copy, so play-cut.spec's clock is never moved. makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), name: "play-edit-fixture", title: "The Play Edit Fixture", video: "vid1" }); +// The same cut with the story modules on (play-modules.spec.ts): a chapter opening c02, +// a then-and-now pair (c01 → c02) and a status ledger -- drawn in Play the cut through +// the module contract's `play`. Its own copy, so play-cut.spec's pages stay as they are. +// And c03 ruled INCORRECT by the walk: Play skips it unless "Show clips marked incorrect". +{ +const { dir: playModulesDir } = makePlayCutFixture({ + reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), + name: "play-modules-fixture", title: "The Play Modules Fixture", + chrome: { + chapter: { list: [{ at: "c02", title: "Part two", subtitle: "the second clip", date: "2024-12-02" }], seconds: 2 }, + pair: { pairs: [{ topic: "The opening", then: { clip: "c01", date: "2020-10-24" }, now: { clip: "c02", date: "2024-12-02" }, caption: "The same opening, renamed." }] }, + status: { items: [{ item: "The seizures", announced: { clip: "c01", date: "2020-10-24" }, outcome: "no follow-up found" }] }, + // The tally's word fitted to its cell (the Play cut's own "Seizures" overflows it, so its chrome never composes). + factcheck: { verdicts: { CORROBORATED: { label: "Seizures", tallyLabel: "Seized", color: "#6fa8dc" } }, stamp: { seconds: 1 } }, + }, +}); +const pmFile = path.join(playModulesDir, "video.manifest.json"); +const pm = JSON.parse(readFileSync(pmFile, "utf8")); +pm.timeline = pm.timeline.map((e) => (e.id === "c03" ? { ...e, verdict: "incorrect", correction: "Other speaker, not the host." } : e)); +writeFileSync(pmFile, JSON.stringify(pm, null, 2) + "\n"); +} + +// Wrong speaker in Play the cut (play-modules.spec.ts), which WRITES (removes c02, then undoes): +// its own copy, so no other spec's cut moves under it. +makePlayCutFixture({ reports, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), name: "play-wrong-fixture", title: "The Play Wrong Speaker Fixture" }); // TWO MORE cached windows for vid1, and they are the regression rather than // decoration. diff --git a/umtool/e2e/fixtures/play-cut-fixture.mjs b/umtool/e2e/fixtures/play-cut-fixture.mjs @@ -21,8 +21,9 @@ import path from "node:path"; * @param {{ reports: string, deckManifest: Function, cachedWindow: string, name?: string, title?: string, video?: string }} o * `name`: a second copy under another name (play-edit-fixture, which a spec writes to). * `video`: the recording id its clips cut (playvid; play-edit-fixture's walk needs vid1's cues). + * `chrome`: more render.chrome keys (play-modules-fixture: a chapter, a pair and a status ledger). */ -export function makePlayCutFixture({ reports, deckManifest, cachedWindow, name = "play-cut-fixture", title = "The Play Cut Fixture", video = "playvid" }) { +export function makePlayCutFixture({ reports, deckManifest, cachedWindow, name = "play-cut-fixture", title = "The Play Cut Fixture", video = "playvid", chrome = null }) { const dir = path.join(reports, name); mkdirSync(dir, { recursive: true }); const timeline = [ @@ -41,7 +42,7 @@ export function makePlayCutFixture({ reports, deckManifest, cachedWindow, name = const m = deckManifest(name, title, timeline); m.render.fetchPad = 0; // One counter, as the Huck cut has: the reel strip's staircase steps 1 at c02, 2 more at c04. - m.render.chrome = { ...m.render.chrome, factcheck: { verdicts: { CORROBORATED: { label: "Seizures", color: "#6fa8dc" } }, stamp: { seconds: 1 } } }; + m.render.chrome = { ...m.render.chrome, factcheck: { verdicts: { CORROBORATED: { label: "Seizures", color: "#6fa8dc" } }, stamp: { seconds: 1 } }, ...(chrome ?? {}) }; writeFileSync(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); mkdirSync(path.join(dir, "out", "clips-raw"), { recursive: true }); copyFileSync(cachedWindow, path.join(dir, "out", "clips-raw", `${video}_0.00-9.00.mp4`)); diff --git a/umtool/e2e/play-modules.spec.ts b/umtool/e2e/play-modules.spec.ts @@ -0,0 +1,163 @@ +import { test, expect, type Page } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +// --------------------------------------------------------------------------- +// Play the cut draws the story modules (umtool/docs/knobs.md, Modules, "Play +// the cut and the live preview"): every module that declares `play` in the +// module contract (report-to-video/modules/contract.mjs) comes back from the +// full preview as a layer -- its own page, composed for preview -- and is laid +// at its region over the footage, seeked on the cut clock. A window module +// (the chapter) is up only inside its window, as the build lays it; a +// whole-cut module (the pair strip, the status ledger) for the whole cut. +// +// Fixture: e2e/fixtures/play-cut-fixture.mjs as play-modules-fixture -- the +// Play cut with a chapter opening c02 (2 s), a then-and-now pair c01 → c02 +// and a status ledger. On the render's clock c02 is shown 2.033-4.967, c04 +// from 8.067. +// --------------------------------------------------------------------------- + +const PROJECT = "reports/play-modules-fixture"; + +const root = (page: Page) => page.locator("[data-play-cut]"); +const layer = (page: Page, id: string) => page.locator(`[data-play-layer="${id}"]`); +/** The chapter card's opacity inside its own page (the build's pixels, seeked by the parent). */ +const chapterOpacity = (page: Page) => + page + .frameLocator('[data-testid="play-layer-chapter-iframe"]') + .locator('.chapter[data-k="ch"]') + .evaluate((el) => Number(getComputedStyle(el).opacity)); + +test.beforeEach(() => { + test.setTimeout(120_000); +}); + +test("the chapter card, the pair strip and the status ledger play in Play the cut: the chapter only inside its window", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + // A second into c02 -- the chapter opens c02 and is up for its first 2 s. + await page.goto(urls.playHref(PROJECT, { clip: "c02", at: 1 })); + await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + await expect(root(page)).toHaveAttribute("data-play-item", "c02"); + await expect(page.locator('[data-testid="play-deck"]')).toBeVisible({ timeout: 30_000 }); + + // The whole-cut modules: laid, their pages ready. + for (const id of ["pair", "status"]) { + await expect(layer(page, id)).toHaveAttribute("data-play-layer-up", "1"); + await expect(page.getByTestId(`play-layer-${id}`)).toHaveAttribute("data-feed-ready", "1", { timeout: 30_000 }); + } + + // The chapter: inside its window, up -- and its card drawn by its own page. + const chapter = layer(page, "chapter"); + await expect(chapter).toHaveAttribute("data-play-layer-segment", "c02"); + await expect(chapter).toHaveAttribute("data-play-layer-up", "1"); + await expect(page.getByTestId("play-layer-chapter")).toHaveAttribute("data-feed-ready", "1", { timeout: 30_000 }); + await expect.poll(() => chapterOpacity(page), { timeout: 10_000 }).toBeGreaterThan(0.9); + await expect(page.frameLocator('[data-testid="play-layer-chapter-iframe"]').locator(".title")).toHaveText("Part two"); + // Laid in the build's z order: the pair (52) under the status ledger (55) under the chapter (85). + expect(await page.locator("[data-play-layer]").evaluateAll((els) => els.map((e) => e.getAttribute("data-play-layer")))).toEqual(["pair", "status", "chapter"]); + await page.screenshot({ path: test.info().outputPath("play-chapter-up.png") }); + + // Outside it (c04, past c02): no chapter on screen. + await page.locator('[data-play-row="c04"]').press("Enter"); + await expect(root(page)).toHaveAttribute("data-play-item", "c04"); + await expect(page.locator('[data-play-layer="chapter"][data-play-layer-up="1"]')).toHaveCount(0); + // ...and before it (c01's first second): still none, the whole-cut layers still laid. + await page.locator('[data-play-row="c01"]').press("Enter"); + await expect(root(page)).toHaveAttribute("data-play-item", "c01"); + await expect(page.locator('[data-play-layer="chapter"][data-play-layer-up="1"]')).toHaveCount(0); + await expect(layer(page, "pair")).toHaveAttribute("data-play-layer-up", "1"); + await page.screenshot({ path: test.info().outputPath("play-chapter-down.png") }); +}); + +test("a clip ruled incorrect is skipped by default (struck through on the strip, its correction on hover); the toggle plays it, remembered", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT)); + await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + const rows = page.locator("[data-play-row]"); + // c03 (ruled incorrect) is not in what plays: its neighbours meet. + await expect(rows).toHaveCount(4); + expect(await rows.evaluateAll((els) => els.map((e) => e.getAttribute("data-play-row")))).toEqual(["c01", "c02", "k01", "c04"]); + const marker = page.locator('[data-play-skipped="c03"]'); + await expect(marker).toHaveAttribute("title", "c03 skipped — marked incorrect: Other speaker, not the host."); + await expect(marker).toHaveCSS("text-decoration-line", "line-through"); + await expect(page.locator("[data-play-incorrect]")).toContainText("Skipping 1 clip marked incorrect: c03"); + // Next from k01 goes straight to c04. + await page.locator('[data-play-row="k01"]').press("Enter"); + await expect(root(page)).toHaveAttribute("data-play-item", "k01"); + await page.keyboard.press("n"); + await expect(root(page)).toHaveAttribute("data-play-item", "c04"); + await page.screenshot({ path: test.info().outputPath("play-incorrect-skipped.png") }); + + // Shown for re-review: back in the cut, greyed and struck through, the correction on hover. + await page.locator("[data-play-show-incorrect]").check(); + await expect(rows).toHaveCount(5); + const c03 = page.locator('[data-play-row="c03"]'); + await expect(c03).toHaveAttribute("data-play-row-incorrect", ""); + await expect(c03).toHaveAttribute("title", "c03: marked incorrect — Other speaker, not the host."); + await expect(page.locator("[data-play-skipped]")).toHaveCount(0); + await expect(page.locator("[data-play-incorrect]")).toContainText("Playing 1 clip marked incorrect"); + // Remembered by this browser. + await page.reload(); + await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + await expect(page.locator("[data-play-show-incorrect]")).toBeChecked(); + await expect(rows).toHaveCount(5); + await page.locator("[data-play-show-incorrect]").uncheck(); + await expect(rows).toHaveCount(4); +}); + +test("Edit this clip, then the browser's Back: Play the cut again, paused at the same second of the same clip", async ({ page }) => { + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(PROJECT, { clip: "c02", at: 1 })); + await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + await expect(root(page)).toHaveAttribute("data-play-item", "c02"); + const t0 = Number(await root(page).getAttribute("data-play-t")); + expect(t0).toBeGreaterThan(2.1); + // Play keeps its place in its URL (no history entry of its own). + await expect.poll(() => new URL(page.url()).searchParams.get("clip")).toBe("c02"); + await page.keyboard.press("e"); + await expect(page).toHaveURL(/\/clip\/c02/); + await expect(page.locator('[data-bench="c02"]')).toHaveCount(1, { timeout: 30_000 }); + await expect(page.locator("[data-back-to-play]")).toBeVisible(); + await page.goBack(); + await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + await expect(root(page)).toHaveAttribute("data-play-item", "c02"); + await expect(root(page)).toHaveAttribute("data-play-state", "paused"); + await expect.poll(async () => Math.abs(Number(await root(page).getAttribute("data-play-t")) - t0)).toBeLessThan(0.1); + // The cut did not change: no "the cut changed" note. + await expect(page.locator("[data-play-back-toast]")).toHaveCount(0); +}); + +test("Wrong speaker in Play the cut: asked in the page, the clip leaves the reel on record, Undo puts it back", async ({ page }) => { + const WRONG = "reports/play-wrong-fixture"; + const dir = path.join(HERE, "..", ".e2e-song", "reports", "play-wrong-fixture"); + await page.setViewportSize({ width: 1366, height: 1000 }); + await page.goto(urls.playHref(WRONG)); + await expect(root(page)).toHaveAttribute("data-play-edges", "render", { timeout: 30_000 }); + const rows = page.locator("[data-play-row]"); + await expect(rows).toHaveCount(5); + await page.locator('[data-play-row="c02"]').press("Enter"); + await expect(root(page)).toHaveAttribute("data-play-item", "c02"); + await page.locator("[data-wrong-speaker-start]").click(); + // It says what will go before anything is written. + await expect(page.locator("[data-wrong-speaker-what]")).toContainText("Remove c02 (playvid 3.50 s–5.50 s) from the cut as wrong speaker?"); + expect(readFileSync(path.join(dir, "video.manifest.json"), "utf8")).toContain('"id": "c02"'); + await page.locator("[data-wrong-speaker-note]").fill("Other speaker, not the host"); + await page.locator("[data-wrong-speaker-remove]").click(); + await expect(page.locator('[data-wrong-speaker-removed="c02"]')).toBeVisible(); + await expect(rows).toHaveCount(4, { timeout: 15_000 }); + await expect(page.locator('[data-play-row="c02"]')).toHaveCount(0); + const m = JSON.parse(readFileSync(path.join(dir, "video.manifest.json"), "utf8")) as { timeline: { id: string }[] }; + expect(m.timeline.map((e) => e.id)).not.toContain("c02"); + const rec = JSON.parse(readFileSync(path.join(dir, "removed.json"), "utf8")) as { removed: Record<string, unknown>[] }; + expect(rec.removed.at(-1)).toMatchObject({ id: "c02", reason: "wrong-speaker", correction: "Other speaker, not the host", video: "playvid", start: 3.5, end: 5.5 }); + await page.screenshot({ path: test.info().outputPath("play-wrong-speaker-removed.png") }); + // Undo: back in the reel, where it was. + await page.locator("[data-wrong-speaker-undo]").click(); + await expect(page.locator("[data-wrong-speaker-undone]")).toBeVisible(); + await expect(rows).toHaveCount(5, { timeout: 15_000 }); + expect(await rows.evaluateAll((els) => els.map((e) => e.getAttribute("data-play-row")))).toEqual(["c01", "c02", "k01", "c03", "c04"]); +}); diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -124,6 +124,7 @@ const ACTION_LABEL = { "clip-mid-sentence": "Trim to the sentence", "clip-cue-gap": "Fix the window", "clip-cut-outside": "Fix the cut", + "clip-incorrect": "Remove or fix the clip", "window-overlap": "Fix the windows", "no-punctuation": "Check the windows", "manifest-invalid": "Fix the manifest", diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -29,6 +29,7 @@ export const WHAT = { "clip-mid-sentence": "clips end mid-sentence", "clip-cue-gap": "clips over a cue gap", "clip-cut-outside": "cuts outside the window", + "clip-incorrect": "clips marked incorrect", "window-overlap": "windows overlap", "no-punctuation": "windows without punctuation", "manifest-invalid": "manifest invalid", diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -200,14 +200,16 @@ export const citeUrlFor = (m, e) => e.citeUrl ?? derivedCiteUrl(m, e); */ export function correctionsOf(m) { return clipsOf(m) - .filter((e) => String(e.correction ?? "").trim()) + .filter((e) => String(e.correction ?? "").trim() || (e.reason && clipVerdict(e) === "incorrect")) .map((e) => ({ id: e.id, channel: channelFor(m, e), video: e.video, at: e.cite ?? e.start ?? 0, href: citeUrlFor(m, e), - text: String(e.correction).trim(), + text: String(e.correction ?? "").trim() || (e.reason === "wrong-speaker" ? "Wrong speaker." : String(e.reason)), + // The structured reason beside an incorrect verdict (manifest.mjs VERDICT_REASONS), or null. + reason: typeof e.reason === "string" ? e.reason : null, // What the walk said about the clip this text is attached to. A note on a // CONFIRMED clip is not a defect in the report, and a reader who cannot // tell the two apart will go and "fix" a clip nobody complained about. @@ -236,6 +238,20 @@ export const clipVerdict = (e) => { return String(e?.correction ?? "").trim() ? "incorrect" : "unreviewed"; }; +/** + * A clip ruled INCORRECT that is still in the timeline, said once: what + * `umtool check` reports (blocking), a take refuses with, and Play the cut + * shows on hover for a clip it skips. + */ +export const incorrectWhy = (e) => { + const note = String(e?.correction ?? "").replace(/\s+/g, " ").trim().replace(/[.\s]+$/, "") || (e?.reason === "wrong-speaker" ? "wrong speaker" : ""); + return `${e?.id} is marked incorrect${note ? `: ${note}` : ""} — remove it, fix it and re-confirm, or clear the verdict`; +}; + +/** The timeline's clips ruled incorrect (clipVerdict, legacy corrections included), in timeline order. */ +export const incorrectClips = (timeline) => + (Array.isArray(timeline) ? timeline : []).filter((e) => e && (e.kind ?? e.type) === "clip" && clipVerdict(e) === "incorrect"); + /** Does this clip carry a written note, whatever the verdict says? */ export const clipHasNote = (e) => !!String(e?.correction ?? "").trim(); @@ -967,6 +983,11 @@ export const REPORT_DECISION_KINDS = [ // written -- silently ignore it and render the whole extent instead. Both // are the render disagreeing with the manifest about what the clip IS. "clip-cut-outside", + // A clip ruled `incorrect` (the walk's verdict, with its correction) that is + // still in the timeline. BLOCKING: the build would render it, the counter + // would count its marks, and the video would cite a clip somebody already + // said is wrong. Remove it, fix it and re-confirm, or clear the verdict. + "clip-incorrect", // A ledger entry nobody has ruled on. BLOCKING, which is earned here: both // the stated and the implied total lie if you act on an unadjudicated ledger, // and they lie quietly, in a chart, with his name on it. @@ -1218,6 +1239,12 @@ export async function reportDecisions(ctx, summary) { } } + // A CLIP RULED INCORRECT STILL IN THE CUT. The walk recorded it; nothing + // downstream acts on a verdict, so this is where it stops a render. + for (const e of incorrectClips(clips)) { + add("clip-incorrect", e.id, incorrectWhy(e), "blocking", { href: clipHref(e.id) }); + } + // THE CUT MUST BE INSIDE THE EXTENT. `start`/`end` is the reviewed extent and // `cutStart`/`cutEnd` is what actually plays; a cut outside it renders // seconds nobody looked at, and half a pair renders the whole extent while diff --git a/umtool/lib/report/clip-incorrect.test.mjs b/umtool/lib/report/clip-incorrect.test.mjs @@ -0,0 +1,60 @@ +// `clip-incorrect`: a clip the walk ruled INCORRECT that is still in the +// timeline is BLOCKING in `umtool check`, named with its correction -- the +// build would render it and the counter count its marks otherwise. A +// confirmed clip with a note, and an unreviewed one, are not. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { decisionsFor } from "../projects/core.mjs"; +import { incorrectClips, incorrectWhy } from "../projects/report.mjs"; +import { walkProjects } from "../projects/walk.mjs"; + +async function decisionsOf(timeline) { + const root = await mkdtemp(path.join(tmpdir(), "clip-incorrect-")); + try { + const channelsDir = path.join(root, "channels"); + const reportsRoot = path.join(root, "reports"); + const vdir = path.join(channelsDir, "chan", "data", "vid"); + await mkdir(vdir, { recursive: true }); + const cues = Array.from({ length: 200 }, (_, i) => ({ start: i, end: i + 1, text: `Line ${i}.` })); + await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ cues })); + const dir = path.join(reportsRoot, "cut"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ + schemaVersion: 1, slug: "cut", title: "Cut", + provenance: { channelSlug: "chan", channelsDir: path.relative(dir, channelsDir), siteOrigin: "https://example.test" }, + render: { width: 1920, height: 1080, fps: 30 }, + timeline: timeline.map((e) => ({ type: "clip", video: "vid", cite: Math.floor(e.start), lock: true, ...e })), + }, null, 2)); + const [ref] = (await walkProjects(reportsRoot)).filter((p) => p.id === "cut"); + return (await decisionsFor(ref, reportsRoot)).filter((d) => d.kind === "clip-incorrect"); + } finally { + await rm(root, { recursive: true, force: true }); + } +} + +test("a clip marked incorrect still in the timeline is blocking, with its correction and what to do", async () => { + const ds = await decisionsOf([ + { id: "c01", start: 10, end: 20, verdict: "confirmed", correction: "window moved to the sentence" }, + { id: "e01", start: 30, end: 40, verdict: "incorrect", correction: "Other speaker, not Ember." }, + { id: "c02", start: 50, end: 60 }, + // The bench's legacy `x`: a correction with no verdict reads as incorrect. + { id: "e02", start: 70, end: 80, correction: "wrong date" }, + ]); + assert.deepEqual(ds.map((d) => [d.target, d.severity, d.why]), [ + ["e01", "blocking", "e01 is marked incorrect: Other speaker, not Ember — remove it, fix it and re-confirm, or clear the verdict"], + ["e02", "blocking", "e02 is marked incorrect: wrong date — remove it, fix it and re-confirm, or clear the verdict"], + ]); + assert.match(ds[0].href, /\/clip\/e01$/); +}); + +test("none marked incorrect: nothing; the helpers skip cards and confirmed clips", async () => { + assert.deepEqual(await decisionsOf([{ id: "c01", start: 10, end: 20, verdict: "confirmed" }]), []); + assert.deepEqual(incorrectClips([{ type: "card", id: "k", correction: "x" }, { type: "clip", id: "a", verdict: "confirmed", correction: "note" }]), []); + assert.equal(incorrectWhy({ id: "a" }), "a is marked incorrect — remove it, fix it and re-confirm, or clear the verdict"); +}); diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -43,7 +43,9 @@ import { buildFileOf, outDirOf, variantsState } from "./variantsView.mjs"; export const AUDIO_KNOBS = Object.freeze(["offset", "gain", "fadeIn", "fadeOut"]); export const BLUR_KNOBS = Object.freeze(["on", "caption", "strength", "from", "to"]); const MARK_KEYS = ["marks", "mark.add", "mark.remove", "mark.verdict"]; -const SET_KEYS = [...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout"]; +/** The walk's verdict, set like a knob: verdict=confirmed|incorrect|wrong-speaker, reason=wrong-speaker, correction=… (`key=` clears). */ +const REVIEW_KEYS = ["verdict", "reason", "correction"]; +const SET_KEYS = [...CLAIM_KNOBS.map((k) => `claim.${k}`), ...MARK_KEYS, ...AUDIO_KNOBS.map((k) => `audio.${k}`), ...BLUR_KNOBS.map((k) => `blur.${k}`), "layout", ...REVIEW_KEYS]; export const SET_USAGE = [ "usage: umtool set <project> <clip> key=value … [--mark <id>] [--json]", @@ -57,6 +59,8 @@ export const SET_USAGE = [ " (the verdict by name or by this cut's label, e.g. Episodes@190.2; a JSON object for its knobs too);", " mark.remove=<id>; mark.verdict=<verdict> (the first mark's, or --mark <id>'s; every clip carrying", " the id); marks='[{\"id\":\"c1\",\"verdict\":\"CORROBORATED\",\"at\":190.2},…]' sets them all (`marks=` none).", + " verdict=confirmed|incorrect|wrong-speaker (the walk's; wrong-speaker is incorrect + reason=wrong-speaker,", + " which needs no correction); correction=<what the report got wrong>; `verdict=` clears it.", " audio.offset ms (-2000…2000, + = sound later),", " audio.gain dB (-20…20), audio.fadeIn / audio.fadeOut s (0–5).", " blur.on=true blurs the clip's picture at the encode (the sound untouched; `blur.on=` clears the whole blur);", @@ -161,6 +165,10 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso entryPatch.layout = value; continue; } + if (REVIEW_KEYS.includes(key)) { + entryPatch[key] = value === null || value === undefined ? "" : String(value); + continue; + } if (MARK_KEYS.includes(key)) { markChanges.push(markChangeOf(key, value, mark)); continue; @@ -196,6 +204,9 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso if ("audio" in entryPatch) results.audio = result.entry.audio ?? null; if ("blur" in entryPatch) results.blur = result.entry.blur ?? null; if ("layout" in entryPatch) results.layout = result.entry.layout ?? "clip"; + if (REVIEW_KEYS.some((k) => k in entryPatch)) { + results.review = { verdict: result.entry.verdict ?? null, reason: result.entry.reason ?? null, correction: result.entry.correction ?? null }; + } notes = editNotes ?? notes; } if (json) { @@ -213,6 +224,11 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso if ("audio" in results) out(`${clipId}: audio ${results.audio ? JSON.stringify(results.audio) : "as recorded"}`); if ("blur" in results) out(`${clipId}: blur ${results.blur ? JSON.stringify(results.blur) : "none (the picture as recorded)"}`); if ("layout" in results) out(`${clipId}: layout ${results.layout}`); + if (results.review) { + const r = results.review; + out(`${clipId}: ${r.verdict ?? "not reviewed"}${r.reason ? ` (${r.reason})` : ""}${r.correction ? ` — ${r.correction}` : ""}`); + if (r.reason === "wrong-speaker") out(` still in the cut: umtool timeline <project> wrong-speaker ${clipId} takes it out, on the record`); + } const n = noted(notes); if (n) out(n); return 0; diff --git a/umtool/lib/report/layerPreview.test.mjs b/umtool/lib/report/layerPreview.test.mjs @@ -51,3 +51,57 @@ test("the files route serves a layer's project by its name, a window's only for assert.equal(previewDirFor("/p", "sourced", ["index.html"], []).dir, "/p/out/sourced/chrome/deck-preview"); assert.equal(layerPreviewSrc("reports/x", "sourced", "pair-preview"), "/api/report/chrome/files/" + layerPreviewSrc("reports/x", "sourced", "pair-preview").split("/api/report/chrome/files/")[1]); }); + +// THE PLAY LAYERS (the module contract's `play`): what the full preview -- +// Play the cut, the clip editor's live preview -- returns beside the deck. +test("the full preview's play layers: every `play` module the cut draws, by z, with geometry, src and its windows", async () => { + const { composePlayLayers } = await import("./onscreen.mjs"); + const { playModules } = await import("umtool-report-to-video/modules"); + // The contract: the story modules (and the other overlays with a page of their own) declare it; the + // deck, the feed, the popup posts, the stamps and the finale are still drawn by their own paths. + const ids = playModules().map((m) => m.id); + for (const id of ["chapter", "pair", "status"]) assert.ok(ids.includes(id), id); + for (const id of ["shell", "feed", "popup-posts", "stamp", "finale"]) assert.ok(!ids.includes(id), id); + + const story = { + ...render, + chrome: { + ...render.chrome, + chapter: { list: [{ at: "b", title: "Two" }], seconds: 3 }, + status: { items: [{ item: "The lawsuit", announced: { clip: "a", date: "2019-06-01" }, outcome: "no follow-up found" }] }, + }, + }; + const calls = []; + const compose = async (args) => { + calls.push(args); + const name = args.region === "chapter" ? `chapter-preview-${args.segment}` : `${args.region}-preview`; + return { projDir: path.join("/p/out/sourced/chrome", name) }; + }; + const out = await composePlayLayers({ dir: "/p", manifestFile: "/p/video.manifest.json" }, "sourced", schedule, story, { + compose, srcOf: (name) => `/files/${name}/index.html`, + }); + assert.deepEqual(out.map((l) => l.id), ["pair", "status", "chapter"]); + assert.deepEqual(out.map((l) => l.z), [...out.map((l) => l.z)].sort((x, y) => x - y)); + const by = Object.fromEntries(out.map((l) => [l.id, l])); + for (const l of out) { + assert.equal(l.clock, "cut"); + assert.equal(l.ready, `${l.region}:ready`); + assert.ok(l.geometry.width > 0 && l.geometry.height > 0, l.id); + } + // A whole-cut page: one src, up for the whole cut. + assert.equal(by.pair.src, "/files/pair-preview/index.html"); + assert.deepEqual([by.pair.from, by.pair.to], [0, 20]); + assert.equal(by.status.src, "/files/status-preview/index.html"); + // A window page: the first `seconds` of the clip it opens, in cut seconds, its own src. + assert.equal(by.chapter.windows.length, 1); + const w = by.chapter.windows[0]; + assert.equal(w.segment, "b"); + assert.equal(w.from, 10); + assert.ok(Math.abs(w.to - 13) < 0.05, `to ${w.to}`); + assert.equal(w.src, "/files/chapter-preview-b/index.html"); + assert.deepEqual(calls.map((c) => [c.region, c.preview, c.segment ?? null]), [["pair", true, null], ["status", true, null], ["chapter", true, "b"]]); + + // A cut that draws none of them: nothing composed, nothing returned. + const none = await composePlayLayers({ dir: "/p" }, "sourced", schedule, { ...render, chrome: { engine: "hyperframes", layout: "deck" } }, { compose, srcOf: (n) => n }); + assert.deepEqual(none, []); +}); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -88,6 +88,14 @@ function withManifestLock(fn) { return run; } + +/** + * The structured reasons an incorrect verdict may carry (`reason`): each says + * what is wrong without a note. "wrong-speaker": somebody else is talking -- + * the clip comes out of the cut (removeWrongSpeaker), on the record. + */ +export const VERDICT_REASONS = Object.freeze(["wrong-speaker"]); + export const MANIFEST_NAME = "video.manifest.json"; const manifestFile = (dir) => path.join(dir, MANIFEST_NAME); @@ -504,17 +512,40 @@ export function patchClipEntry(manifest, clipId, patch, { edit = "trim", now = n // The requirement above is keyed on the explicit value, so those entries can // still be cleared -- a rule that refused to let somebody undo a note they // wrote before the rule existed would be a trap. + // + // A STRUCTURED REASON beside an incorrect verdict (`reason`, one of + // VERDICT_REASONS): "wrong-speaker" -- the clip is somebody else talking, + // which says what is wrong without a note, so it stands for one. A reason + // goes only with `incorrect`; a verdict changed to anything else drops it. + // `verdict: "wrong-speaker"` is shorthand for incorrect + that reason (the + // CLI's `umtool set <p> <clip> verdict=wrong-speaker`). + let reasonIn = patch.reason; if (patch.verdict !== undefined) { - const v = String(patch.verdict ?? "").trim(); + let v = String(patch.verdict ?? "").trim(); + if (VERDICT_REASONS.includes(v)) { + if (reasonIn === undefined) reasonIn = v; + v = "incorrect"; + } if (!v) delete entry.verdict; else if (v !== "confirmed" && v !== "incorrect") { throw new Error( - `verdict must be "confirmed" or "incorrect", or empty to clear it (got \`${v}\`)`, + `verdict must be "confirmed", "incorrect" or ${VERDICT_REASONS.map((r) => `"${r}"`).join(", ")}, or empty to clear it (got \`${v}\`)`, ); } else entry.verdict = v; + if (entry.verdict !== "incorrect" && reasonIn === undefined) delete entry.reason; + } + if (reasonIn !== undefined) { + const r = String(reasonIn ?? "").trim(); + if (!r) delete entry.reason; + else if (!VERDICT_REASONS.includes(r)) { + throw new Error(`reason must be ${VERDICT_REASONS.map((x) => `"${x}"`).join(", ")}, or empty to clear it (got \`${r}\`); say anything else in the correction`); + } else entry.reason = r; + } + if (entry.reason && entry.verdict !== "incorrect") { + throw new Error(`a reason (${entry.reason}) goes with an incorrect verdict`); } - if (entry.verdict === "incorrect" && !String(entry.correction ?? "").trim()) { + if (entry.verdict === "incorrect" && !String(entry.correction ?? "").trim() && !entry.reason) { throw new Error("an incorrect verdict needs its note: say what the report got wrong"); } @@ -1579,11 +1610,147 @@ export function moveIn(m, id, toIndex, at = null) { return { id, from, to }; } -/** Remove entry `id` from `m.timeline` (removeEntry's rule, in memory). */ -export function removeIn(m, id, at = null) { +/** + * Remove entry `id` from `m.timeline` (removeEntry's rule, in memory). What + * named the removed clip is RE-ANCHORED rather than refusing the removal + * (reanchorAfterRemove); every move and drop is in `reanchored`, in words. + * Not on a take (`reanchor: false`): its patch holds only its timeline. + */ +export function removeIn(m, id, at = null, { reanchor = true } = {}) { const i = entryIndex(m.timeline, id, at); const [removed] = m.timeline.splice(i, 1); - return { id, at: i, removed }; + // A twin with the same id still in the cut keeps whatever names that id. + // `reanchor: false` -- a take's walk, whose patch keeps only its timeline: + // a reference to the clip still refuses there, as it always did. + const reanchored = !reanchor || m.timeline.some((e) => e?.id === id) ? [] : reanchorAfterRemove(m, removed, i); + return { id, at: i, removed, reanchored }; +} + +/** + * After clip `removed` left `m.timeline` (it stood at index `i`), what named + * it follows the cut instead of blocking the removal: + * + * - a deck marker `after` it moves to the clip before it -- the same + * boundary (dropped when there is none); + * - a chapter `at` it moves to the next clip in its section (dropped when + * there is none); + * - a then-and-now pair naming it on a side is dropped (an `also` clip + * alone leaves its side); a status item's clip is dropped from it, and + * the item with it when it names no clip any more; + * - a deck claim check said in it is dropped (a step alone, its step). + * + * Its own marks go with it (the counter recounts). Mutates `m`; returns one + * sentence per change. A config left empty is removed (the module is off). + * + * @param {Record<string, any>} m + * @param {Record<string, any>} removed + * @param {number} i + * @returns {string[]} + */ +export function reanchorAfterRemove(m, removed, i) { + const id = removed?.id; + const notes = []; + const chrome = m?.render?.chrome; + if (!id || !chrome || typeof chrome !== "object") return notes; + const tl = m.timeline ?? []; + const isClip = (e) => e && (e.kind ?? e.type) === "clip"; + const prevClip = [...tl.slice(0, i)].reverse().find(isClip) ?? null; + const nextInSection = tl.slice(i).find((e) => isClip(e) && (e.section ?? null) === (removed.section ?? null)) ?? null; + const obj = (v) => v && typeof v === "object" && !Array.isArray(v); + + const markers = chrome.deck?.markers; + if (Array.isArray(markers)) { + chrome.deck.markers = markers.filter((mk, k) => { + if (!obj(mk) || String(mk.after ?? "").trim() !== id) return true; + if (prevClip) { + mk.after = prevClip.id; + notes.push(`deck marker ${k}${mk.label ? ` ("${mk.label}")` : ""} moved from after ${id} to after ${prevClip.id} (the same boundary)`); + return true; + } + notes.push(`deck marker ${k}${mk.label ? ` ("${mk.label}")` : ""} dropped: no clip before ${id}`); + return false; + }); + if (!chrome.deck.markers.length) delete chrome.deck.markers; + } + + const dc = chrome.deck?.claims; + if (Array.isArray(dc)) { + chrome.deck.claims = dc.filter((c, k) => { + if (!obj(c)) return true; + if (c.at === id) { + notes.push(`deck claim ${k}${c.id ? ` (${c.id})` : ""} dropped: it was said in ${id}`); + return false; + } + if (Array.isArray(c.steps)) { + const n = c.steps.length; + c.steps = c.steps.filter((st) => !(obj(st) && st.at === id)); + if (c.steps.length !== n) notes.push(`deck claim ${k}${c.id ? ` (${c.id})` : ""}: its step in ${id} dropped`); + } + return true; + }); + if (!chrome.deck.claims.length) delete chrome.deck.claims; + } + + if (obj(chrome.chapter) && Array.isArray(chrome.chapter.list)) { + const taken = new Set(chrome.chapter.list.map((c) => c?.at)); + chrome.chapter.list = chrome.chapter.list.filter((c, k) => { + if (!obj(c) || c.at !== id) return true; + if (nextInSection && !taken.has(nextInSection.id)) { + c.at = nextInSection.id; + taken.add(nextInSection.id); + notes.push(`chapter ${k}${c.title ? ` ("${c.title}")` : ""} moved from ${id} to ${nextInSection.id}, the next clip in its section`); + return true; + } + notes.push(`chapter ${k}${c.title ? ` ("${c.title}")` : ""} dropped: no other clip in ${id}'s section opens it`); + return false; + }); + if (!chrome.chapter.list.length) delete chrome.chapter; + } + + if (obj(chrome.pair) && Array.isArray(chrome.pair.pairs)) { + chrome.pair.pairs = chrome.pair.pairs.filter((p, k) => { + if (!obj(p)) return true; + if (p.then?.clip === id || p.now?.clip === id) { + notes.push(`then-and-now pair ${k}${p.topic ? ` ("${p.topic}")` : ""} dropped: its ${p.then?.clip === id ? "then" : "now"} clip was ${id}`); + return false; + } + if (Array.isArray(p.also) && p.also.some((a) => a?.clip === id)) { + p.also = p.also.filter((a) => a?.clip !== id); + if (!p.also.length) delete p.also; + notes.push(`then-and-now pair ${k}${p.topic ? ` ("${p.topic}")` : ""}: ${id} dropped from its side`); + } + return true; + }); + if (!chrome.pair.pairs.length) delete chrome.pair; + } + + if (obj(chrome.status) && Array.isArray(chrome.status.items)) { + chrome.status.items = chrome.status.items.filter((it, k) => { + if (!obj(it)) return true; + let hit = false; + for (const side of ["announced", "outcome"]) { + if (obj(it[side]) && it[side].clip === id) { + delete it[side].clip; + hit = true; + } + } + if (Array.isArray(it.evidence) && it.evidence.includes(id)) { + it.evidence = it.evidence.filter((c) => c !== id); + if (!it.evidence.length) delete it.evidence; + hit = true; + } + if (!hit) return true; + const named = (obj(it.announced) && it.announced.clip) || (obj(it.outcome) && it.outcome.clip) || it.evidence?.length; + if (!named) { + notes.push(`status item ${k}${it.item ? ` ("${it.item}")` : ""} dropped: ${id} was the only clip it named`); + return false; + } + notes.push(`status item ${k}${it.item ? ` ("${it.item}")` : ""}: ${id} dropped from it`); + return true; + }); + if (!chrome.status.items.length) delete chrome.status; + } + return notes; } /** @@ -1628,6 +1795,70 @@ export async function removeEntry(dir, id, { token = null, at = null } = {}) { return structural(dir, "remove", token, (m) => removeIn(m, id, at)); } +// ---- removals on the record ------------------------------------------------ +// +// `removed.json` beside the manifest: every clip taken out of the cut BECAUSE +// of what it is (Wrong speaker), newest last -- its id, where it came from +// (channel, video, window), the reason, the correction, when. Append-only: an +// undo puts the clip back in the timeline and leaves the line, and a reader +// (`umtool corrections`) lists only those still out of the cut. +export const REMOVED_FILE = "removed.json"; + +/** The removals on record, oldest first ([] when none). */ +export async function readRemoved(dir) { + try { + const doc = JSON.parse(await readFile(path.join(dir, REMOVED_FILE), "utf8")); + return Array.isArray(doc?.removed) ? doc.removed : []; + } catch { + return []; + } +} + +async function recordRemoved(dir, row) { + const rows = [...(await readRemoved(dir)), row]; + const file = path.join(dir, REMOVED_FILE); + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(tmp, JSON.stringify({ removed: rows }, null, 2) + "\n"); + await rename(tmp, file); +} + +/** + * WRONG SPEAKER: one write that marks clip `id` incorrect with the reason + * "wrong-speaker" (and the correction, when one is given) and takes it out + * of the timeline -- removeEntry's path, an undo point first, what named it + * re-anchored (reanchorAfterRemove) -- then puts the removal on record + * (removed.json). `umtool timeline <p> wrong-speaker <id>`, the walk's and + * Play the cut's Wrong speaker. + * + * @param {string} dir + * @param {string} id + * @param {{ token?: string | null, at?: number | null, correction?: string | null, now?: () => Date }} [opts] + */ +export async function removeWrongSpeaker(dir, id, { token = null, at = null, correction = null, now = () => new Date() } = {}) { + const res = await structural(dir, "wrong-speaker", token, (m) => { + const entry = m.timeline[entryIndex(m.timeline, id, at)]; + if (entry.type !== "clip") throw new Error(`${id} is a ${entry.type ?? "non-clip"} entry, not a clip`); + patchClipEntry(m, id, { verdict: "incorrect", reason: "wrong-speaker", ...(correction ? { correction } : {}) }); + return removeIn(m, id, at); + }); + const e = res.removed ?? {}; + const record = { + id, + reason: "wrong-speaker", + correction: String(e.correction ?? "").trim() || null, + channel: typeof e.channel === "string" ? e.channel : null, + video: typeof e.video === "string" ? e.video : null, + start: e.start ?? null, + end: e.end ?? null, + ...(Number.isFinite(Number(e.cutStart)) ? { cutStart: e.cutStart, cutEnd: e.cutEnd } : {}), + at: res.at, + reanchored: res.reanchored ?? [], + when: now().toISOString(), + }; + await recordRemoved(dir, record); + return { ...res, record }; +} + /** Copy one entry to just after itself, under a fresh id. A copied claim is dropped (one claim, one entry). * * @param {string} dir * @param {string} id diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs @@ -827,3 +827,49 @@ export async function composeLayerPreviews(project, variant, schedule, ids, rend } const pick = (g) => (g ? { x: g.x, y: g.y, width: g.width, height: g.height } : null); + +/** + * THE PLAY LAYERS (the module contract's `play`, contract.mjs): every module + * that declares `play` and that this cut draws (its own `on`, the build's + * predicate), each composed through its own page as composeLayerPreviews + * composes it, in z order -- what Play the cut and the clip editor's live + * preview lay over the footage beside the deck. Each row: + * + * { id, region, kind, z, clock, ready, geometry, + * src | error -- a whole-cut page, up for the whole cut + * windows: [{ segment, from, to, src | error }] -- a window module, up inside each (cut seconds) } + * + * `srcOf(name)` says where a composed project is served. A module this cut + * does not draw is left out (the module panel says why; this draws). + * + * @param {{ dir: string, manifestFile?: string }} project + * @param {string} variant + * @param {Record<string, any>} schedule + * @param {Record<string, any>} render + * @param {{ srcOf: (name: string) => string, compose?: typeof composeChrome }} o + * @returns {Promise<Array<Record<string, any>>>} + */ +export async function composePlayLayers(project, variant, schedule, render, { srcOf, compose = composeChrome }) { + const { playModules } = await import("umtool-report-to-video/modules"); + const mods = playModules().filter((m) => m.on(schedule, render)); + if (!mods.length) return []; + const total = Number(schedule.total) || 0; + const rows = await composeLayerPreviews(project, variant, schedule, mods.map((m) => m.id), render, { compose }); + return rows.map((l, i) => { + const m = mods[i]; + const base = { id: l.id, region: l.region, kind: l.kind ?? m.kind, z: m.z, clock: m.play.clock, ready: m.play.ready, geometry: l.geometry ?? null }; + if (Array.isArray(l.windows)) { + return { + ...base, + windows: l.windows.map((w) => ({ + segment: w.segment ?? null, + from: w.from, + to: typeof w.to === "number" ? w.to : w.from, + ...(w.name ? { src: srcOf(w.name) } : { error: w.error ?? "not composed" }), + })), + }; + } + if (l.off) return { ...base, error: l.off }; + return { ...base, from: 0, to: total, ...(l.name ? { src: srcOf(l.name) } : { error: l.error ?? "not composed" }) }; + }); +} diff --git a/umtool/lib/report/playCut.mjs b/umtool/lib/report/playCut.mjs @@ -154,6 +154,54 @@ export function playTimeOfChrome(plan, tc) { return clampTo(it.from + (tc - e.from)); } +/** + * The plan with some entries LEFT OUT (Play the cut skips the clips ruled + * incorrect unless asked to show them): each skipped item's shown span + * (`from`–`to`) is taken out of the clock and every later item moves up by + * it, so its neighbours meet at the same seam the render would cut them at. + * Every item keeps (or is given) its place on the estimate's clock (`est`), + * which the chrome was composed on, so `chromeTime` still seeks the pages to + * the second each item shows. `skipped` lists what was left out: its id and + * the Play second it would have been at (the strip's marker). + * + * @template {{ items: Array<PlayItem & { est?: Record<string, number> }>, total: number, edges: string }} P + * @param {P} plan + * @param {Set<string> | string[] | null} ids + * @returns {P & { skipped: Array<{ id: string, at: number }> }} + */ +export function skipEntries(plan, ids) { + const skip = ids instanceof Set ? ids : new Set(ids ?? []); + if (!skip.size || !plan?.items?.length) return { ...plan, skipped: [] }; + let shift = 0; + /** @type {Array<PlayItem & { est?: Record<string, number> }>} */ + const items = []; + /** @type {Array<{ id: string, at: number }>} */ + const skipped = []; + for (const it of plan.items) { + if (skip.has(it.id)) { + skipped.push({ id: it.id, at: round(it.from - shift) }); + shift += Math.max(0, it.to - it.from); + continue; + } + const est = it.est ?? { + start: it.start, end: it.end, from: it.from, to: it.to, + ...(it.clip ? { sourceFrom: it.clip.sourceFrom, sourceTo: it.clip.sourceTo, playEnd: it.clip.playEnd } : {}), + }; + const s = (v) => round(v - shift); + items.push({ + ...it, + index: items.length, + start: s(it.start), + end: s(it.end), + from: items.length ? s(it.from) : 0, + to: s(it.to), + clip: it.clip ? { ...it.clip, playEnd: s(it.clip.playEnd) } : null, + est, + }); + } + return { ...plan, items, total: items.length ? items[items.length - 1].end : 0, skipped }; +} + /** The plan on the estimate's clock alone (playPlan without the render's edges). */ function estimatePlan(segments, entries, { leadIn = 0.4 } = {}) { const byId = new Map((entries ?? []).map((e) => [e?.id, e])); diff --git a/umtool/lib/report/playCut.test.mjs b/umtool/lib/report/playCut.test.mjs @@ -223,3 +223,37 @@ test("the chrome's second: by source second inside a clip, held at the item's ow }); const round3 = (v) => Math.round(v * 1000) / 1000; + +test("skipEntries: a skipped clip's shown span leaves the clock, later items move up, the chrome still seeks the estimate", async () => { + const { skipEntries, playPlan, chromeTime } = await import("./playCut.mjs"); + const segs = [ + { id: "a", start: 0, duration: 3 }, + { id: "b", start: 2.5, duration: 3 }, + { id: "c", start: 5, duration: 3 }, + ]; + const ents = [ + { id: "a", type: "clip", start: 10, end: 12.6 }, + { id: "b", type: "clip", start: 20, end: 22.6 }, + { id: "c", type: "clip", start: 30, end: 32.6 }, + ]; + const plan = playPlan(segs, ents, { leadIn: 0.4 }); + const none = skipEntries(plan, []); + assert.deepEqual(none.items, plan.items); + assert.deepEqual(none.skipped, []); + const out = skipEntries(plan, new Set(["b"])); + assert.deepEqual(out.items.map((i) => i.id), ["a", "c"]); + assert.deepEqual(out.skipped, [{ id: "b", at: plan.items[1].from }]); + const bShown = plan.items[1].to - plan.items[1].from; + const c = out.items[1]; + assert.equal(c.index, 1); + assert.ok(Math.abs(c.from - (plan.items[2].from - bShown)) < 1e-6); + assert.ok(Math.abs(out.total - (plan.total - bShown)) < 1e-6); + // a's seam meets c's: c comes up where a's shown span ends. + assert.ok(Math.abs(c.from - out.items[0].to) < 1e-6); + // The chrome is seeked to c's own second on the estimate's clock. + assert.ok(Math.abs(chromeTime(out, c.from + 0.5) - (plan.items[2].from + 0.5)) < 0.01, String(chromeTime(out, c.from + 0.5))); + // The first item skipped: the next starts the clock at 0. + const first = skipEntries(plan, ["a"]); + assert.equal(first.items[0].id, "b"); + assert.equal(first.items[0].from, 0); +}); diff --git a/umtool/lib/report/playView.mjs b/umtool/lib/report/playView.mjs @@ -11,7 +11,7 @@ import { DEFAULT_VARIANT, selectVariant } from "umtool-report-to-video/build-video"; import { deckOn, estimatedDuration, estimateSchedule, scheduleFrom, transitionOf } from "umtool-report-to-video/deck"; import { resolveFactcheck } from "umtool-report-to-video/factcheck"; -import { clipDateKey, readManifest } from "../projects/report.mjs"; +import { clipDateKey, clipVerdict, readManifest } from "../projects/report.mjs"; import { dateKeyLabel } from "./playCut.mjs"; import { pickWindow, projectCache, windowsFor } from "./serve.mjs"; import { playableTakes, resolveTakeManifest } from "./takeManifest.mjs"; @@ -77,6 +77,8 @@ export async function playView(project, { take = null } = {}) { cutStart: fin(e.cutStart) ? e.cutStart : null, cutEnd: fin(e.cutEnd) ? e.cutEnd : null, blur: e.blur && typeof e.blur === "object" ? e.blur : null, + // Ruled incorrect (the walk's verdict): its correction -- Play skips it unless asked to show it. + incorrect: clipVerdict(e) === "incorrect" ? text(e.correction) || (e.reason === "wrong-speaker" ? "wrong speaker" : "marked incorrect") : null, // The window the bench would play: its name for the raw route, and the source second its file starts at. media: win ? { name: win.name, from: win.from, to: win.to } : null, }; diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -218,7 +218,7 @@ export async function moveTakeEntry(projectDir, id, entryId, toIndex, { token = * @param {{ token?: string | null, at?: number | null, now?: Date }} [opts] */ export async function removeTakeEntry(projectDir, id, entryId, { token = null, at = null, now = new Date() } = {}) { - return editTakeTimeline(projectDir, id, "remove", token, (m) => applyStructural(m, (x) => removeIn(x, entryId, at)), { now }); + return editTakeTimeline(projectDir, id, "remove", token, (m) => applyStructural(m, (x) => removeIn(x, entryId, at, { reanchor: false })), { now }); } /** diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -52,6 +52,7 @@ import { applyMontageRulings, readMontageRulings, rulingsLines } from "umtool-re import { markKeepFrames } from "umtool-report-to-video/prune-frames"; import { PIPELINE_DIR, RENDER_BUDGET, UMTOOL_DIR } from "./driver.mjs"; import { replaceManifest } from "./manifest.mjs"; +import { incorrectClips, incorrectWhy } from "../projects/report.mjs"; import { withEditNotes } from "./edit-guard.mjs"; import { isTakeId, listTakes, parseWindow, setTakePicked, takesDirOf, TAKE_FILE, TAKE_KINDS } from "./takes.mjs"; @@ -586,6 +587,11 @@ async function makeTakeLocked(projectDir, rawSpec, opts) { renderDoc = windowManifest(ruled.manifest, ids); } if (spec.quick) renderDoc = /** @type {Record<string, any>} */ (mergePatch(renderDoc, QUICK_RENDER)); + // A clip ruled incorrect (the walk's verdict) still in what would render: + // refused, by name, before anything is written -- `umtool check` calls it + // blocking (clip-incorrect), and a take is a render like any other. + const wrong = incorrectClips(renderDoc.timeline); + if (wrong.length) throw new Error(`${spec.id}: ${wrong.map(incorrectWhy).join("; ")}`); await mkdir(takeDir, { recursive: true }); await opts.onTakeDir?.(takeDir, spec.id); diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs @@ -572,3 +572,21 @@ test("withPatchEntries: a clip only the take's patch adds stays in the window be // An id the take dropped is passed on for the caller's present-check. assert.deepEqual(withPatchEntries([{ id: "a" }, { id: "c" }], base, ["b", "c"]), ["c", "b"]); }); + +test("makeTake refuses a cut that still holds a clip ruled incorrect, by name and correction; one the take leaves out renders", async () => { + const wrong = { ...MANIFEST, timeline: [clip("s01", 0, 10), clip("e01", 20, 25, { verdict: "incorrect", correction: "Other speaker, not Ember." }), clip("s03", 40, 50)] }; + const { root, dir } = await project(wrong); + const r = stubRender(); + try { + await assert.rejects( + makeTake(dir, { id: "full", label: "Full", window: "full" }, opts(r)), + (e) => e.message === "full: e01 is marked incorrect: Other speaker, not Ember — remove it, fix it and re-confirm, or clear the verdict", + ); + assert.equal(r.calls.length, 0); + // Taken out by the take's own timeline: nothing incorrect renders. + const ok = await makeTake(dir, { id: "without", label: "Without", window: "full", patch: { timeline: [clip("s01", 0, 10), clip("s03", 40, 50)] } }, opts(r)); + assert.equal(ok.skipped, false); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/timelineCli.mjs b/umtool/lib/report/timelineCli.mjs @@ -51,6 +51,8 @@ import { manifestToken, moveEntry, removeEntry, + removeWrongSpeaker, + REMOVED_FILE, removePost, undoStructural, updateClip, @@ -68,6 +70,8 @@ export const TIMELINE_USAGE = [ " are dates gets --date as one too. The section is <id>'s unless --section says", " umtool timeline <project> move <id> --to <index> <index> is its place AFTER the move (0 first)", " umtool timeline <project> remove <id> | duplicate <id> (--at <index> names one of an id's twins)", + " umtool timeline <project> wrong-speaker <id> [--correction TEXT] mark it incorrect (wrong speaker) and remove it, on the record (removed.json)", + " a removal re-anchors what named the clip (a marker to the clip before, a chapter to the next in its section; pair/status/deck-claim references dropped) and says so", " umtool timeline <project> post <json|@file> add a post, or replace the one with its id", " umtool timeline <project> post-remove <id>", " umtool timeline <project> teaser <id> <patch-json|@file> lines, beat, dip, tail, tailWait (null removes one)", @@ -80,8 +84,8 @@ export const TIMELINE_USAGE = [ "validators, and on a generated manifest leaves an `edit` note for its generator. The Cut tab's timeline.", ].join("\n"); -const VERBS = ["ls", "insert", "move", "remove", "duplicate", "post", "post-remove", "teaser", "undo"]; -const VALUED = new Set(["--after", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take"]); +const VERBS = ["ls", "insert", "move", "remove", "wrong-speaker", "duplicate", "post", "post-remove", "teaser", "undo"]; +const VALUED = new Set(["--after", "--to", "--at", "--id", "--section", "--title", "--stream-title", "--date", "--quote", "--cite", "--cite-url", "--take", "--correction"]); /** What `--take <id>` does on a take's timeline (takeEdit.mjs): the walk's structure and its undo. */ const TAKE_VERBS = ["ls", "move", "remove", "undo"]; @@ -402,6 +406,13 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => ({ result, editNotes } = await write((token) => removeEntry(project.dir, id, { token, at }))); break; } + case "wrong-speaker": { + const id = need(rest[0], "a clip id"); + const c = flags.get("--correction"); + const correction = typeof c === "string" && c.trim() ? c.trim() : null; + ({ result, editNotes } = await write((token) => removeWrongSpeaker(project.dir, id, { token, at, correction }))); + break; + } case "duplicate": { const id = need(rest[0], "an entry id"); ({ result, editNotes } = await write((token) => duplicateEntry(project.dir, id, { token, at }))); @@ -434,6 +445,8 @@ export async function timelineCommand(args, { root = REPORTS_ROOT, out = (s) => return 0; } out(summaryOf(verb, result, attribution)); + for (const line of result.reanchored ?? []) out(` re-anchored: ${line}`); + if (result.record) out(` on record: ${REMOVED_FILE} (${result.record.reason}${result.record.correction ? `: ${result.record.correction}` : ""})`); if (result.snapshot?.rel && !result.snapshot.skipped) out(` undo point: ${result.snapshot.rel}`); else if (result.snapshot?.error) out(` NO undo point: ${result.snapshot.error}`); const n = noted(editNotes); @@ -524,6 +537,8 @@ function summaryOf(verb, r, attribution) { return `moved ${r.id}: ${r.from} -> ${r.to}`; case "remove": return `removed ${r.id} (was at ${r.at})`; + case "wrong-speaker": + return `removed ${r.id} (was at ${r.at}): marked incorrect, wrong speaker`; case "duplicate": return `duplicated as ${r.id} at ${r.at}`; case "post": diff --git a/umtool/lib/report/wrong-speaker.test.mjs b/umtool/lib/report/wrong-speaker.test.mjs @@ -0,0 +1,135 @@ +// Wrong speaker: the walk's structured reason (`reason: "wrong-speaker"` +// beside `verdict: "incorrect"`), the one write that marks a clip so and +// takes it out of the cut (removeWrongSpeaker) with what named it +// re-anchored, and the record of it (removed.json). +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + MANIFEST_NAME, + REMOVED_FILE, + patchClipEntry, + readRemoved, + reanchorAfterRemove, + removeEntry, + removeWrongSpeaker, + undoStructural, +} from "./manifest.mjs"; +import { correctionsOf, incorrectWhy } from "../projects/report.mjs"; + +const clip = (id, section, extra = {}) => ({ type: "clip", id, video: `v-${id}`, start: 10, end: 20, section, ...extra }); +const base = () => ({ + slug: "t", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { + width: 1920, height: 1080, fps: 30, transition: 0.5, + chrome: { + engine: "hyperframes", layout: "deck", + deck: { markers: [{ after: "e01", label: "Weeks pass" }] }, + chapter: { list: [{ at: "e01", title: "Part two" }] }, + pair: { pairs: [{ topic: "Then", then: { clip: "c01", date: "2020" }, now: { clip: "e01", date: "2024" } }] }, + status: { items: [{ item: "The suit", announced: { clip: "e01" }, evidence: ["c01", "e01"] }] }, + }, + }, + timeline: [clip("c01", 0), clip("e01", 1, { channel: "other", cutStart: 11, cutEnd: 19 }), clip("c02", 1), clip("c03", 2)], +}); + +async function project(m = base()) { + const dir = await mkdtemp(path.join(tmpdir(), "umtool-wrong-speaker-")); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n"); + return dir; +} +const read = async (dir) => JSON.parse(await readFile(path.join(dir, MANIFEST_NAME), "utf8")); + +test("the reason: wrong-speaker stands for a note; only with incorrect; anything else refused; a new verdict drops it", () => { + const m = base(); + // The shorthand: verdict=wrong-speaker is incorrect + the reason, no note needed. + assert.equal(patchClipEntry(m, "c01", { verdict: "wrong-speaker" }).entry.reason, "wrong-speaker"); + assert.equal(m.timeline[0].verdict, "incorrect"); + assert.equal(incorrectWhy(m.timeline[0]), "c01 is marked incorrect: wrong speaker — remove it, fix it and re-confirm, or clear the verdict"); + assert.equal(correctionsOf(m)[0].text, "Wrong speaker."); + // Confirmed again: the reason goes. + patchClipEntry(m, "c01", { verdict: "confirmed" }); + assert.equal(m.timeline[0].reason, undefined); + assert.throws(() => patchClipEntry(m, "c01", { reason: "wrong-speaker" }), /goes with an incorrect verdict/); + assert.throws(() => patchClipEntry(m, "c02", { verdict: "incorrect", reason: "bad-date" }), /reason must be "wrong-speaker"/); + // Without a reason an incorrect verdict still needs its note. + assert.throws(() => patchClipEntry(m, "c03", { verdict: "incorrect" }), /needs its note/); + patchClipEntry(m, "c03", { verdict: "incorrect", reason: "wrong-speaker", correction: "It is the guest." }); + assert.equal(m.timeline[3].correction, "It is the guest."); + // Clearing the reason off a note-less incorrect clip is refused (it would be a complaint with no words). + const n = base(); + patchClipEntry(n, "c01", { verdict: "wrong-speaker" }); + assert.throws(() => patchClipEntry(n, "c01", { reason: "" }), /needs its note/); +}); + +test("reanchorAfterRemove: a marker to the clip before, a chapter to the next in its section, pair/status references dropped", () => { + const m = base(); + const i = m.timeline.findIndex((e) => e.id === "e01"); + const [removed] = m.timeline.splice(i, 1); + const notes = reanchorAfterRemove(m, removed, i); + assert.deepEqual(m.render.chrome.deck.markers, [{ after: "c01", label: "Weeks pass" }]); + assert.deepEqual(m.render.chrome.chapter.list, [{ at: "c02", title: "Part two" }]); + assert.equal(m.render.chrome.pair, undefined); + assert.deepEqual(m.render.chrome.status.items, [{ item: "The suit", announced: {}, evidence: ["c01"] }]); + assert.deepEqual(notes, [ + 'deck marker 0 ("Weeks pass") moved from after e01 to after c01 (the same boundary)', + 'chapter 0 ("Part two") moved from e01 to c02, the next clip in its section', + 'then-and-now pair 0 ("Then") dropped: its now clip was e01', + 'status item 0 ("The suit"): e01 dropped from it', + ]); + // No clip after it in its section: the chapter is dropped, and the module with it. + const k = base(); + k.render.chrome.chapter.list = [{ at: "c03", title: "Last" }]; + const j = k.timeline.findIndex((e) => e.id === "c03"); + const [gone] = k.timeline.splice(j, 1); + assert.deepEqual(reanchorAfterRemove(k, gone, j), ['chapter 0 ("Last") dropped: no other clip in c03\'s section opens it']); + assert.equal(k.render.chrome.chapter, undefined); +}); + +test("removeEntry re-anchors instead of refusing a clip a marker names, and says so", async () => { + const dir = await project(); + try { + const r = await removeEntry(dir, "e01"); + assert.equal(r.reanchored.length, 4); + const m = await read(dir); + assert.deepEqual(m.timeline.map((e) => e.id), ["c01", "c02", "c03"]); + assert.equal(m.render.chrome.deck.markers[0].after, "c01"); + // A plain removal is not on the wrong-speaker record. + assert.deepEqual(await readRemoved(dir), []); + } finally { + await rm(dir, { recursive: true }); + } +}); + +test("removeWrongSpeaker: marked, removed, re-anchored and on record; undo puts the clip back marked", async () => { + const dir = await project(); + try { + const r = await removeWrongSpeaker(dir, "e01", { correction: "Other speaker, not Ember.", now: () => new Date("2026-10-29T12:00:00Z") }); + assert.equal(r.removed.verdict, "incorrect"); + assert.equal(r.removed.reason, "wrong-speaker"); + assert.ok(r.snapshot?.rel, "an undo point"); + assert.deepEqual((await read(dir)).timeline.map((e) => e.id), ["c01", "c02", "c03"]); + const rec = JSON.parse(await readFile(path.join(dir, REMOVED_FILE), "utf8")).removed; + assert.equal(rec.length, 1); + assert.deepEqual( + { ...rec[0], reanchored: rec[0].reanchored.length }, + { id: "e01", reason: "wrong-speaker", correction: "Other speaker, not Ember.", channel: "other", video: "v-e01", start: 10, end: 20, cutStart: 11, cutEnd: 19, at: 1, reanchored: 4, when: "2026-10-29T12:00:00.000Z" }, + ); + // Undo: the clip is back where it was, still marked; the record stays (append-only). + await undoStructural(dir); + const back = await read(dir); + assert.deepEqual(back.timeline.map((e) => e.id), ["c01", "e01", "c02", "c03"]); + assert.equal(back.timeline[1].verdict, undefined, "the undo point is the file before the mark"); + assert.equal((await readRemoved(dir)).length, 1); + // A card is not a clip. + await assert.rejects(removeWrongSpeaker(dir, "nope"), /no timeline entry|not in the timeline|nope/); + } finally { + await rm(dir, { recursive: true }); + } +}); diff --git a/umtool/report-to-video/modules/chapter.mjs b/umtool/report-to-video/modules/chapter.mjs @@ -77,6 +77,8 @@ export default defineModule({ }, "window")); }, preview: (_slice, { render }) => ({ region: "chapter", geometry: chapterGeometry(render) }), + // Its page is its live preview: Play the cut seeks it in the cut's seconds (contract.mjs, PLAY). + play: { clock: "cut", ready: "chapter:ready" }, // A window of the cut: frame n is cut time `from` + n / fps. frameKeys: { data: "chapter-data", omit: ["init", "cues", "from", "dur"], offset: "from" }, }); diff --git a/umtool/report-to-video/modules/contract.mjs b/umtool/report-to-video/modules/contract.mjs @@ -10,7 +10,18 @@ // reaching into their slice), how it is drawn (`page` for a HyperFrames page, // `render` for an ffmpeg/IM one), where its frames land (`region`), what its // render cache keys on (`frameKeys`: the static part and the frame events), -// and how umtool shows it (`ui`, `preview`, `docs`). +// and how umtool shows it (`ui`, `preview`, `play`, `docs`). +// +// PLAY (`play`): an overlay module's HyperFrames page IS its live preview. +// The build captures the page frame by frame; Play the cut and the clip +// editor's live preview load the SAME page (composed with `preview: true`, +// no render) in an iframe at the module's region and seek it by message on +// the clock it declares -- `{ clock: "cut", ready: "<region>:ready" }`: the +// page takes `deck:seek` in the cut's seconds and posts `ready` once it can +// be seeked. A whole-cut module is up for the whole cut; a window module +// (`overlay-window`) only inside each of its regions' windows, as the build +// lays it. A module that declares `play` needs nothing else to appear there +// (onscreen.mjs composePlayLayers, OnscreenSection.tsx ModuleLayers). // // A PART (`host` set) is drawn inside its host module's page -- the subtitle, // the QR, the rail and the counter are all inside the deck's one page, so @@ -44,6 +55,12 @@ export const MODULE_KINDS = Object.freeze([ */ export const MODULE_SLOTS = Object.freeze(["footer", "column", "popup", "stamp", "panel", "footage", "side", "full", "inline"]); +/** + * The clocks a module's live page is seeked on (`play.clock`): the cut's + * seconds -- the one clock every page answers `deck:seek` on today. + */ +export const PLAY_CLOCKS = Object.freeze(["cut"]); + /** How a region is laid over the cut: a whole-cut sequence from frame 1, or a window at its own second. */ export const REGION_PLACEMENTS = Object.freeze(["whole", "window"]); @@ -78,6 +95,7 @@ const SPEC = Object.freeze({ frameKeys: "its frame-key model: { data, omit, offset?, eases?, events?, items? }", ui: "a field descriptor list for umtool's generic panel", preview: "a function (slice, ctx) => a single-layer preview request", + play: "its live-preview contract: { clock: \"cut\", ready: \"<region>:ready\" } -- its page seeked in an iframe by Play the cut and the live preview", docs: "its knobs.md section: { heading, intro?, rows: [[knob, range, terminal]], after? }", workers: "\"wide\" or \"narrow\": how many renderer workers its page takes", noun: "how a message names its sequence (\"the stamps'\")", @@ -143,6 +161,15 @@ export function defineModule(def) { if (!isObj(f) || typeof f.data !== "string" || !Array.isArray(f.omit)) throw new Error(`${where}: frameKeys must be ${SPEC.frameKeys}`); } if (def.ui !== undefined && !Array.isArray(def.ui)) throw new Error(`${where}: ui must be ${SPEC.ui}`); + if (def.play !== undefined) { + const p = def.play; + if (!isObj(p) || !PLAY_CLOCKS.includes(p.clock) || typeof p.ready !== "string" || !/^[a-z][a-z0-9-]*:ready$/.test(p.ready)) { + throw new Error(`${where}: play must be ${SPEC.play}`); + } + if (!(def.kind === "overlay-whole" || def.kind === "overlay-window") || !isFn(def.page) || !isFn(def.regions)) { + throw new Error(`${where}: only an overlay with a page and regions plays live`); + } + } if (def.docs !== undefined && !(isObj(def.docs) && typeof def.docs.heading === "string")) throw new Error(`${where}: docs must be ${SPEC.docs}`); if (def.workers !== undefined && !["wide", "narrow"].includes(def.workers)) throw new Error(`${where}: workers must be ${SPEC.workers}`); return Object.freeze({ ...def }); diff --git a/umtool/report-to-video/modules/docs.mjs b/umtool/report-to-video/modules/docs.mjs @@ -52,6 +52,26 @@ export function modulesMarkdown() { "|---|---|---|", ...ordered().map((m) => `| [${cell(m.docs.heading)}](#${anchor(m.docs.heading)}) \`${m.id}\` | ${cell(m.summary ?? "")} ${KIND_WORDS[m.kind] ? `(${KIND_WORDS[m.kind]})` : ""} | ${m.configKey ? `\`${m.configKey}\`` : "--"} |`), "", + "### Play the cut and the live preview", + "", + "A module's HyperFrames page IS its live preview: the build captures it frame by frame; Play the cut and the clip", + "editor's live preview load the same page (composed with `preview: true`, no render) in an iframe at the module's", + "region and seek it by message. A module joins them by declaring `play: { clock: \"cut\", ready: \"<region>:ready\" }`", + "in its definition (`modules/contract.mjs`): its page takes `deck:seek` in the cut's seconds and posts `ready` once", + "it can be seeked. `POST /api/report/chrome/preview` returns every such module the cut draws (its own `on`, the", + "build's predicate) as `layers: [{id, z, region, clock, ready, geometry, src | windows}]`; the client lays them", + "by z over the deck's page, a whole-cut page for the whole cut, a window module's page only inside each window.", + "", + `Declaring \`play\`: ${MODULES.filter((m) => m.play).map((m) => `\`${m.id}\``).join(", ")}.`, + "", + "Still drawn by their own paths (the response's `src`, `feed`, `posts`, `stamp` and `finale` keys), and what moving", + "each onto `play` needs: the deck (`shell`) -- its typed words patched in live (`deck:text`) and the `deck:ready`", + "handshake DeckFrame waits on; the feed -- its footage box and per-segment framing boxes (`feed.footage`,", + "`feed.boxes`) that move the picture; the popup posts -- one page per window composed with the posts draft, and", + "`posts:ready`; the stamps -- their geometry follows the feed layout (`stampGeometry`) and the HUD reads", + "`stampAt`; the finale -- its window is the schedule's `finale` (not a region's) and it is laid over the deck.", + "Each is a `play` declaration plus moving its consumers (the live-preview and Play specs' testids) to the layer.", + "", ]; for (const m of ordered()) { out.push(`### ${m.docs.heading}`, ""); diff --git a/umtool/report-to-video/modules/flips.mjs b/umtool/report-to-video/modules/flips.mjs @@ -38,6 +38,8 @@ export default defineModule({ regions(_schedule, { render, outDir, frames = null }) { return [sideRegion(render, frames ?? path.join(outDir, "chrome", "flips-frames"), "flips")]; }, + // Its page is its live preview: Play the cut seeks it in the cut's seconds (contract.mjs, PLAY). + play: { clock: "cut", ready: "flips:ready" }, // A cue interpreter like the deck's: keyed per frame (frame-keys.mjs). frameKeys: { data: "flips-data", omit: ["init", "cues", "window", "total", "ids"] }, }); diff --git a/umtool/report-to-video/modules/fx.mjs b/umtool/report-to-video/modules/fx.mjs @@ -48,6 +48,8 @@ export default defineModule({ ...fxGeometry(render, { feed: schedule.layout === "feed" }), })]; }, + // Its page is its live preview: Play the cut seeks it in the cut's seconds (contract.mjs, PLAY). + play: { clock: "cut", ready: "fx:ready" }, // A cue interpreter like the deck's: keyed per frame (frame-keys.mjs). frameKeys: { data: "fx-data", omit: ["init", "cues", "window", "total"] }, }); diff --git a/umtool/report-to-video/modules/index.mjs b/umtool/report-to-video/modules/index.mjs @@ -5,7 +5,7 @@ // is laid over one with a lower. // // Pure: the module files are, and so is this. -import { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, REGION_PLACEMENTS } from "./contract.mjs"; +import { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, PLAY_CLOCKS, REGION_PLACEMENTS } from "./contract.mjs"; import { settingsOf, settingValue } from "./settings.mjs"; import chart from "./chart.mjs"; @@ -30,7 +30,7 @@ import pair from "./pair.mjs"; import chapter from "./chapter.mjs"; import status from "./status.mjs"; -export { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, REGION_PLACEMENTS }; +export { assertRegion, defineModule, MODULE_KINDS, MODULE_SLOTS, PLAY_CLOCKS, REGION_PLACEMENTS }; /** Every module, by z (stack order), then id. */ export const MODULES = Object.freeze( @@ -79,6 +79,13 @@ export function regionModule(region) { export const deckOverlays = () => MODULES.filter((m) => (m.kind === "overlay-whole" || m.kind === "overlay-window") && m.cached !== false); /** + * The modules Play the cut and the live preview draw through the generic + * path, in z order: every module that declares `play` (contract.mjs, PLAY). + * Its own page, composed for preview and seeked on its clock. + */ +export const playModules = () => MODULES.filter((m) => m.play); + +/** * How a region is laid over the cut: "whole" (a sequence as long as the cut, * from frame 1 -- or a chunk's `startNumber`), "window" (a short sequence at * its own second), or null for the legacy chart band (its chain stays as it diff --git a/umtool/report-to-video/modules/pair.mjs b/umtool/report-to-video/modules/pair.mjs @@ -67,6 +67,8 @@ export default defineModule({ })]; }, preview: (_slice, { render }) => ({ region: "pair", geometry: pairGeometry(render) }), + // Its page is its live preview: Play the cut seeks it in the cut's seconds (contract.mjs, PLAY). + play: { clock: "cut", ready: "pair:ready" }, // A cue interpreter: each pair an item, so a changed caption recaptures only its frames. frameKeys: { data: "pair-data", omit: ["init", "cues", "window", "total", "ids"] }, }); diff --git a/umtool/report-to-video/modules/registry.test.mjs b/umtool/report-to-video/modules/registry.test.mjs @@ -142,3 +142,15 @@ test("scheduleSlices: each module's slice of the one schedule; moduleProblems: e assert.match(p.intro[0], /x-kit" is not a brand kit/); assert.deepEqual(moduleProblems({ render: {}, timeline: [] }), {}); }); + +test("play: a live-preview contract only an overlay with a page and regions declares", async () => { + const { playModules } = await import("./index.mjs"); + const base = { id: "x", version: 1, z: 1, kind: "overlay-whole", slot: "footer", title: "X", region: "x", page: async () => "", regions: () => [] }; + assert.equal(defineModule({ ...base, play: { clock: "cut", ready: "x:ready" } }).play.clock, "cut"); + assert.throws(() => defineModule({ ...base, play: { clock: "source", ready: "x:ready" } }), /play must be/); + assert.throws(() => defineModule({ ...base, play: { clock: "cut", ready: "x" } }), /play must be/); + assert.throws(() => defineModule({ ...base, page: undefined, play: { clock: "cut", ready: "x:ready" } }), /only an overlay with a page/); + assert.throws(() => defineModule({ ...base, kind: "segment", play: { clock: "cut", ready: "x:ready" } }), /only an overlay with a page/); + assert.deepEqual(playModules().map((m) => m.id), ["stats", "pair", "status", "fx", "threads", "flips", "chapter"]); + for (const m of playModules()) assert.equal(m.play.ready, `${m.region}:ready`, m.id); +}); diff --git a/umtool/report-to-video/modules/stats.mjs b/umtool/report-to-video/modules/stats.mjs @@ -44,6 +44,8 @@ export default defineModule({ ...statsGeometry(render, { feed: schedule.layout === "feed" }), })]; }, + // Its page is its live preview: Play the cut seeks it in the cut's seconds (contract.mjs, PLAY). + play: { clock: "cut", ready: "stats:ready" }, // A cue interpreter like the deck's: keyed per frame (frame-keys.mjs). frameKeys: { data: "stats-data", omit: ["init", "cues", "window", "total", "ids"] }, }); diff --git a/umtool/report-to-video/modules/status.mjs b/umtool/report-to-video/modules/status.mjs @@ -64,6 +64,8 @@ export default defineModule({ })]; }, preview: (_slice, { render }) => ({ region: "status", geometry: statusGeometry(render) }), + // Its page is its live preview: Play the cut seeks it in the cut's seconds (contract.mjs, PLAY). + play: { clock: "cut", ready: "status:ready" }, // A cue interpreter: each state of the ledger an item, keyed only where it is shown. frameKeys: { data: "status-data", omit: ["init", "cues", "window", "total", "ids"] }, }); diff --git a/umtool/report-to-video/modules/threads.mjs b/umtool/report-to-video/modules/threads.mjs @@ -46,6 +46,8 @@ export default defineModule({ regions(_schedule, { render, outDir, frames = null }) { return [sideRegion(render, frames ?? path.join(outDir, "chrome", "threads-frames"), "threads")]; }, + // Its page is its live preview: Play the cut seeks it in the cut's seconds (contract.mjs, PLAY). + play: { clock: "cut", ready: "threads:ready" }, // A cue interpreter like the deck's: keyed per frame (frame-keys.mjs). frameKeys: { data: "threads-data", omit: ["init", "cues", "window", "total", "ids"] }, });