Archilyzer · Source

archilyzer

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

commit 3656ae4747a9bb1794418af389bce9a0d3c5396b
parent 757a391cd718924fd28117bdf26ee216a8c4b3df
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Fri, 23 Oct 2026 02:22:37 -0400

Merge lane/clip-marks: several Seizure/Grift marks per clip, each its own stamp and tally step; the clip editor's Marks box (Shift+M, Shift+S); umtool set mark.*

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

Diffstat:
Meditor/CHANGELOG.md | 1+
Aplans/clip-marks.md | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/app/api/report/onscreen/route.ts | 6++++--
Mumtool/bin/umtool.mjs | 5++++-
Mumtool/components/projects/review/ClipEditor.tsx | 49++++++++++++++++++-------------------------------
Mumtool/components/projects/review/ClipKnobs.tsx | 355++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mumtool/docs/cli.md | 2+-
Mumtool/docs/knobs.md | 50+++++++++++++++++++++++++++++++++++++++++++++-----
Mumtool/e2e/fixtures/make-fixture.mjs | 3+++
Aumtool/e2e/fixtures/marks-fixture.mjs | 34++++++++++++++++++++++++++++++++++
Mumtool/e2e/knobs.spec.ts | 14++++++++------
Aumtool/e2e/marks.spec.ts | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/clipEditor.mjs | 50++++++++++++++++++++++++++++++++++++++++++--------
Mumtool/lib/report/clipEditor.test.mjs | 33++++++++++++++++++++++++++++++++-
Mumtool/lib/report/clipEditorTypes.ts | 8+++++++-
Mumtool/lib/report/knobs.mjs | 109+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/knobsCli.mjs | 98++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mumtool/lib/report/manifest.mjs | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Aumtool/lib/report/marks.test.mjs | 202+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/onscreen.mjs | 16+++++++++-------
Mumtool/report-to-video/build-video.mjs | 7++++---
Aumtool/report-to-video/clip-marks.test.mjs | 260+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/deck.mjs | 17+++++++++++------
Mumtool/report-to-video/factcheck.mjs | 215+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
24 files changed, 1671 insertions(+), 205 deletions(-)

diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A clip in a fact-check video can stamp and count more than once.** The clip editor's **Count & stamp** box is now **Marks**, on every clip: a list of the clip's marks, each its own stamp and its own step of the tally at its own second — its verdict picked by this cut's words (Episodes, Grift…), when it lands (**Set at playhead**, Shift+S for the selected mark), how long it stays, whether it is drawn, how much it counts, what it says, **Remove**. **Add mark at playhead** (Shift+M) adds one under a new id; **Clear** removes them all. Two stamps on one clip that would sit on each other are refused, saying where the second may land. From a terminal: `umtool set <project> <clip> mark.add=Episodes@190.2`, `mark.remove=<id>`, `mark.verdict=…`, `marks=<json>`; `umtool show` lists them. A clip with one mark is written as before, so an existing video renders the same. - **A video attached from a local archive gets its date when the archive writes it as 2019-10-31.** `attach-media` with `createRecords` read a folder's "Published on …" line only as "July 13th 2018" or "March 1, 2019"; it now reads "2019-10-31" and "2019/10/31" too, and a date that is not on the calendar is no date. Records it made before without a date can be dated now: `"fillDates": true` on `pnpm ops attach-media` (`--fill-dates` on `archilyzer media attach`) gives a held record that attach-media made, and that has no upload date, the date from its folder's description.txt — recorded in its metadata history. A record that has a date, or that attach-media did not make, is never touched. The log and the summary list them as "dated"; with `"dryRun": true` it only lists them. - **A report video's sound stays with its picture from the first clip to the last.** A clip whose sound started late (its cut reached back before the fetched window's media) or had a gap in it (a seam in the source's stream) used to pull that clip's sound, and every later clip's, early — on a 20-minute cut by half a second from the 13th minute on. Each clip's sound is now laid on its own clock before the clips are joined, and every build writes `sync.json` beside its schedule saying where each clip's sound landed against its picture; the build log names any clip more than a frame off. A video's manifest can now also set when a fact-check stamp lands and the count steps (`claim.at`, a second of the source), how long it stays, a count of more than one, a stamp that counts without showing, the stamp's words, size, entrance and opacity; nudge a clip's sound against its picture, its volume and fades (`audio`); align a timeline flag's label and lay crowded labels in two rows; and `node umtool/report-to-video/variants.mjs <take out dir>` makes smaller copies of a finished cut — 1080p, 720p and one under 24 MiB by default (`render.variants`). Needs a rebuild of the video. - **A fact-check video can count without the stamp, colour its timeline by verdict, flag the moments time passes, and leave the QR off posts.** In umtool's fact-check form, **stamp effect** off draws no verdict stamp over the footage, while the tally in the panel still counts each claim at the second its stamp would have landed. The On-screen settings have **colour** under timeline: **verdict** lights each clip that carries a claim in its verdict's colour — the tally's colour — with a shape per verdict (circle, diamond, square, triangle, ring), and the tally's cells carry the same shapes. **qr codes** under posts off leaves the QR off every post card, popup or feed, and the words take its width; each clip's own QR stays. A video's manifest can flag moments on the timeline (`render.chrome.deck.markers`: "3 to 5 weeks pass" after a clip), each popping in as the timeline reaches it and staying lit. Needs a restart of umtool. diff --git a/plans/clip-marks.md b/plans/clip-marks.md @@ -0,0 +1,70 @@ +# Clip marks — more than one stamp and count per clip (lane `lane/clip-marks`, M) + +Asked by the operator on 2026-10-23 for the Huck video's final pass: walk the clips in umtool, adjust windows and +text there, and add another grift or seizure mark — the first seizure clip mentions two seizures. The reference +for people and agents is `umtool/docs/knobs.md`, "Marks". + +## Rulings + +- **Shape.** A timeline entry's `claims: [mark, …]`, 1–8 marks (`CLAIM_MARKS_MAX`), each a claim + `{id, verdict, at?, hold?, stamp?, count?, label?}`. A lone `claim` is a list of one. `claim` and `claims` on one + entry is refused. Writers store one mark as `claim` and two or more as `claims`, in the marks' place among the + entry's keys (`setMarks`): a manifest with one mark per clip is byte-identical, and a mark added then removed + leaves the file the bytes it was. +- **Ids.** A mark added without an id gets a new one (`freshMarkId`): the entry's id when no mark in the manifest + uses it, else `<entry>.2`, `.3`, …. The same id on several entries keeps its meaning: one event, counted once, + stamped on the last entry carrying it, its knobs read there. One id appears once per entry. +- **Verdict.** One id, one verdict across the timeline. A verdict change on a mark (`{mark, verdict}`) is applied to + every entry carrying the id. A verdict may be given by name or by this cut's `label` / `stampLabel` + (`verdictOfInput`). The editor lists the cut's own verdicts first (relabelled or in use, `markVerdictsOf`). +- **Schedule** (`stampSchedule`). Each mark is its own stamp and tally step. A segment stamping one mark places it + exactly as before marks (a 200-cut randomized comparison with the pre-marks function is a test). On a segment + stamping two or more: a mark with `at` lands as a lone claim's `at`; marks without `at` land in order back to + back, the last as a lone claim, each earlier one leaving over the transition's length to be gone as the next + comes in; then, in landing order, a drawn stamp leaves in time to be gone as the next drawn one starts. Stamps + are emitted per segment in landing order. +- **Validation** (`validateClaims`). Per mark: shape, `at` inside the window, verdict consistency. Per entry: two + drawn marks with `at`, both stamping on this entry, closer than the first's `hold` (else `stamp.seconds`) are + refused with the second's earliest second. Marks without `at` are not checked for overlap (the schedule lays them + back to back). +- **Colour.** A multi-mark clip's pip and rail take its first mark's verdict (the schedule segment's `claim` is the + first mark; `claims` rides beside it only for two or more). Tally, `tallyFinals` and the finale's totals count + every mark; a mark stamping on a finale clip counts as the finale opens, as a claim did. +- **Writers.** `manifest.mjs updateMarks(dir, entry, change)`: `{add}`, `{remove}`, `{mark, verdict}`, `{set}`; + refused when the change adds a `validateClaims` problem. `updateClaimKnobs(..., {mark})` patches one mark (default + the first), in place. `updateClip`'s window rule covers every mark. `updateOnscreen` and the On-screen preview + treat a row's claim as the entry's first mark and keep the others. Split and duplicate drop `claims` as they drop + `claim`. +- **Route.** `POST /api/report/clip-editor` op `marks` (`add` | `remove` | `mark`+`verdict` | `set`) and op `claim` + with `mark`; page or agent token (`lib/report/caller.ts`), manifest token as every write. The view gives each + clip `marks` (each with `stampsOn`) beside `claim`/`stampsOn` (the first mark's), and `knobs.verdicts`. +- **UI.** The Count & stamp box is the **Marks** box (`ClipKnobs.tsx MarksBox`), on every clip: a row per mark + (verdict, id, lands at + Set at playhead + Clear, Remove, hold, draw the stamp, count, label, where it stamps when + elsewhere); one row selected; **Add mark at playhead** with a verdict picker (it follows the selected mark's); + **Clear** removes every mark. Keys: Shift+S sets the selected mark's `at`, Shift+M adds a mark at the playhead; + the box owns both (ClipEditor's handler leaves Shift+S/M to it; S and M alone stay Split and Merge). The box's + keys work with focus on a select or a checkbox. +- **CLI.** `umtool set <p> <clip>` `mark.add=<verdict>[@<sec>]` (or a JSON object), `mark.remove=<id>`, + `mark.verdict=<verdict>` (`--mark <id>`, else the first), `marks=<json>` (`marks=` none); `claim.*` with + `--mark <id>`. `umtool show`: a multi-mark clip's line lists its marks; `--json` carries `marks` with `stampsOn`. + +## Files + +`umtool/report-to-video/`: `factcheck.mjs` (`CLAIM_MARKS_MAX`, `rawMarksOf`, `normalizeMarks`, `marksOf`, +`claimOf` = first mark, `validateClaims`, `stampSchedule`), `deck.mjs` (segments' `claims`, `sourceFrom` for any +timed mark), `build-video.mjs` (the cut-record clock for any timed mark), `clip-marks.test.mjs` (new). +`umtool/lib/report/`: `knobs.mjs` (`setMarks`, `marksCopyOf`, `markIdsOf`, `freshMarkId`, `verdictOfInput`, +`markVerdictsOf`, `stampingEntryId` over marks), `manifest.mjs` (`updateMarks`, `updateClaimKnobs` `mark`, window +rule, `updateOnscreen`, split/duplicate), `clipEditor.mjs` (op `marks`, view `marks`, `knobs.verdicts`), +`clipEditorTypes.ts`, `onscreen.mjs` (preview), `knobsCli.mjs` (`set`, `show`), `marks.test.mjs` (new), +`clipEditor.test.mjs`. `umtool/app/api/report/onscreen/route.ts` (a row's claim: the first mark). +`umtool/components/projects/review/ClipKnobs.tsx` (`MarksBox`), `ClipEditor.tsx` (the mount, the keys). +`umtool/bin/umtool.mjs` (help). e2e: `e2e/marks.spec.ts`, `e2e/fixtures/marks-fixture.mjs` (new), +`e2e/fixtures/make-fixture.mjs`, `e2e/knobs.spec.ts` (the box's new selectors). Docs: `umtool/docs/knobs.md` +("Marks"), `editor/CHANGELOG.md`. + +## Open + +- The Huck manifest is unchanged here; the operator adds the second seizure mark on `first` in umtool (or + `umtool set <p> first mark.add=Episodes@<sec>`), then a build. +- Lane P (live deck preview) may read `clip.marks` from the view for its schedule; merge order M then P. diff --git a/umtool/app/api/report/onscreen/route.ts b/umtool/app/api/report/onscreen/route.ts @@ -21,7 +21,7 @@ export const dynamic = "force-dynamic"; // reads as saved. type Claim = { id: string; verdict: string }; -type Entry = Record<string, unknown> & { id: string; type?: string; onscreen?: Record<string, string>; claim?: Claim }; +type Entry = Record<string, unknown> & { id: string; type?: string; onscreen?: Record<string, string>; claim?: Claim; claims?: Claim[] }; const noStore = { "cache-control": "no-store" }; @@ -56,7 +56,9 @@ export async function GET(request: Request) { id: e.id, type: e.type ?? "entry", onscreen: onscreen ?? null, - claim: e.claim ?? null, + // An entry with marks (`claims`) shows its first here; the clip editor's Marks box edits them all. + claim: e.claim ?? (Array.isArray(e.claims) ? (e.claims[0] ?? null) : null), + ...(Array.isArray(e.claims) ? { marks: e.claims.length } : {}), auto: deckText(bare, metas[i] ?? null, provenance, deck, multi), }; }); diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -24,6 +24,7 @@ // [--correction TEXT] [--verdict confirmed|incorrect|''] // [--cut-start S] [--cut-end E] [--lock-cut] the cut inside the extent // umtool set <project> <clip> key=value … a clip's knobs: claim.at|hold|stamp|count|label, +// marks=<json> mark.add=<verdict>[@<sec>] mark.remove=<id> mark.verdict=<v> [--mark <id>], // audio.offset|gain|fadeIn|fadeOut (`key=` clears) (docs/knobs.md) // umtool look <project> key=value … the cut's knobs: factcheck.stamp.*, factcheck.verdicts.<V>.*, // deck.markers=<json>, deck.markerLayout, variants=<json>, the look's keys @@ -710,7 +711,9 @@ function usage() { " an empty value (--title '') deletes the field", " umtool set <project> <clip> key=value … a clip's knobs (`key=` clears; umtool/docs/knobs.md):", " claim.at (a source second: the stamp lands, the count steps) claim.hold claim.stamp", - " claim.count claim.label · audio.offset (ms, + later) audio.gain (dB) audio.fadeIn audio.fadeOut", + " claim.count claim.label (the first mark's, or --mark <id>'s) · marks: mark.add=<verdict>[@<sec>]", + " mark.remove=<id> mark.verdict=<verdict> marks=<json> (≤ 8, each its own stamp and count)", + " · audio.offset (ms, + later) audio.gain (dB) audio.fadeIn audio.fadeOut", " umtool look <project> key=value … the cut's knobs: factcheck.stamp.scale|motion|opacity|seconds,", " factcheck.verdicts.<V>.stampLabel|label|color, deck.markers=<json>, deck.markerLayout,", " variants=<json>, and the look's keys (transition=0.3, …)", diff --git a/umtool/components/projects/review/ClipEditor.tsx b/umtool/components/projects/review/ClipEditor.tsx @@ -14,7 +14,7 @@ import { cn } from "@/lib/utils"; import { ROOM, roomShade } from "umtool-report-to-video/room"; import { startTakeJob } from "../NewTakePanel"; import AssistBox from "../report/AssistBox"; -import { AudioBox, CountStampBox } from "./ClipKnobs"; +import { AudioBox, MarksBox } from "./ClipKnobs"; // Release 36 lane D: the assistant's labels, Suggest, Ask and Apply (all optional). import type { ReplyProposal } from "@/lib/annotations/types"; import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy, useClipSuggest, type ClipSuggest } from "./ClipSuggest"; @@ -38,9 +38,10 @@ import { proposalWords, ReplyProposalRow, SuggestLabel, SuggestPanel, SuggestWhy // the short (release 36) a 9:16 box dragged on the player (the clip's // `vertical.crop`), Make a short (a job: shorts/<clip>.mp4); // a speaker's name for the captions in the Speakers list -// the knobs (video knobs) Count & stamp on a claimed clip -- the stamp's +// the knobs (video knobs) Marks on every clip -- each mark's verdict, // second (Set at playhead, Shift+S), hold, on/off, count, -// label -- and Audio: sync nudge, gain, fades (./ClipKnobs.tsx) +// label; Add mark at playhead (Shift+M) -- and Audio: sync +// nudge, gain, fades (./ClipKnobs.tsx) // // Every write is one POST to /api/report/clip-editor; the answer is the whole // view again, so the page never guesses what the server did. Edge edits are @@ -355,14 +356,7 @@ export default function ClipEditor({ setPlayhead(t); player.current?.seek(t); }; - // The video knobs: the claim's stamp at the playhead (Shift+S), and the 3 s around it, heard. - const stampAtPlayhead = () => { - if (playhead === null) { - setError("put the playhead where the stamp should land first"); - return; - } - void flush().then(() => write({ op: "claim", clip: clip.id, knobs: { at: r2(playhead) } }, `The stamp lands at ${edgeClock(playhead)}`)); - }; + // The video knobs: the 3 s around the playhead, heard. (The marks' keys are the Marks box's.) const listen = () => { if (playhead === null) return; player.current?.listen(playhead); @@ -374,13 +368,9 @@ export default function ClipEditor({ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return; const t = e.target as HTMLElement | null; if (t?.closest?.(TYPING) || t?.closest?.("dialog[open]")) return; - // Shift+S: the claim's stamp lands at the playhead (S alone splits). - if (e.shiftKey && e.key.toLowerCase() === "s") { - if (!clip.claim) return; - e.preventDefault(); - stampAtPlayhead(); - return; - } + // Shift+S and Shift+M are the Marks box's (a mark's moment at the + // playhead, a mark added there); S and M alone split and merge. + if (e.shiftKey && (e.key.toLowerCase() === "s" || e.key.toLowerCase() === "m")) return; const k = e.key.length === 1 ? e.key.toLowerCase() : e.key; const act: Record<string, () => void> = { " ": () => player.current?.toggle(), @@ -596,19 +586,16 @@ export default function ClipEditor({ )} {/* ---- the knobs (video knobs) -------------------------------------- */} - {clip.claim && ( - <CountStampBox - clipId={clip.id} - claim={clip.claim} - stampsOn={clip.stampsOn ?? null} - defaults={view.knobs} - playhead={playhead} - span={{ start: clip.start, end: clip.end, cutStart: cut.cutStart, cutEnd: cut.cutEnd }} - busy={busy} - write={write} - onGo={choose} - /> - )} + <MarksBox + clipId={clip.id} + marks={clip.marks ?? (clip.claim ? [{ ...clip.claim, stampsOn: clip.stampsOn ?? null }] : [])} + defaults={view.knobs} + playhead={playhead} + span={{ start: clip.start, end: clip.end, cutStart: cut.cutStart, cutEnd: cut.cutEnd }} + busy={busy} + write={(body, done) => flush().then(() => write(body, done))} + onGo={choose} + /> <AudioBox clipId={clip.id} audio={clip.audio ?? null} busy={busy} write={write} canListen={playhead !== null} onListen={listen} /> {/* ---- the decisions ----------------------------------------------- */} diff --git a/umtool/components/projects/review/ClipKnobs.tsx b/umtool/components/projects/review/ClipKnobs.tsx @@ -1,24 +1,27 @@ "use client"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { buttonVariants } from "@/components/ui/button"; import { edgeClock } from "@/lib/report/clipEditorModel.mjs"; -import type { ClaimKnobs, ClipAudio, KnobDefaults } from "@/lib/report/clipEditorTypes"; +import type { ClipAudio, KnobDefaults, MarkVerdict, MarkView } from "@/lib/report/clipEditorTypes"; // THE CLIP'S KNOBS (video knobs, plans/video-knobs-ui.md), in the clip editor: // -// Count & stamp on a clip that carries a claim: the source second its stamp -// lands and the tally steps (`claim.at`, Set at playhead, -// Shift+S), how long it stays (`hold`), whether it is drawn -// (`stamp`), how much it counts (`count`), what it says -// (`label`) +// Marks on every clip (plans/clip-marks.md): its marks, each its +// own stamp and tally step -- the verdict (this cut's words), +// the source second it lands and the tally steps (`at`, Set +// at playhead, Shift+S for the selected mark), how long it +// stays (`hold`), whether it is drawn (`stamp`), how much it +// counts (`count`), what it says (`label`), remove; Add mark +// at playhead (Shift+M); Clear (every mark) // Audio the clip's sound at the encode: a sync nudge in ms (+ = // later), gain in dB, fades in s; "listen" replays the 3 s // around the playhead // // Every field shows the default it gets when its key is absent; Clear removes // the key (the default again). Each change is one write through the clip -// editor's route (op claim / op audio), the same writer `umtool set` uses. +// editor's route (op marks / op claim / op audio), the same writers `umtool +// set` uses. const input = "num w-[6em] rounded border border-seam-2 bg-ground px-1.5 py-0.5 font-mono text-[12px] text-text outline-none focus:border-signal"; const box = "space-y-1.5 rounded-[3px] border border-seam bg-panel p-2 text-[12px] text-text-2"; @@ -93,10 +96,120 @@ function KnobField({ const numOrNull = (s: string) => (s === "" ? null : Number(s)); -export function CountStampBox({ +/** + * Where a key is typing, not a command: the clip editor's rule, less a select + * and a checkbox -- Shift+S / Shift+M still work just after a verdict is + * picked or the stamp toggled (the word buttons never take the focus). + */ +const TYPING = "input:not([type='checkbox']), textarea, [contenteditable=''], [contenteditable='true']"; +const r2 = (n: number) => Math.round(n * 100) / 100; + +/** A verdict's words for the picker: this cut's label, and the verdict's name when the label is not it. */ +const verdictText = (v: MarkVerdict) => (v.label.toUpperCase().replace(/[\s-]+/g, "_") === v.verdict ? v.label : `${v.label} (${v.verdict})`); + +function VerdictPicker({ + name, + value, + verdicts, + busy, + onPick, +}: { + name: string; + value: string; + verdicts: MarkVerdict[]; + busy: boolean; + onPick: (v: string) => unknown; +}) { + const stock = verdicts.filter((v) => v.stock); + const other = verdicts.filter((v) => !v.stock); + const known = verdicts.some((v) => v.verdict === value); + // The choice shows at once until the view comes back with it (or does not). + const [draft, setDraft] = useState<string | null>(null); + useEffect(() => setDraft(null), [value]); + return ( + <select + data-mark-verdict={name} + value={draft ?? value} + disabled={busy} + onChange={(e) => { + const v = e.target.value; + setDraft(v); + const r = onPick(v); + if (r instanceof Promise) void r.finally(() => setDraft(null)); + else setDraft(null); + }} + className="rounded border border-seam-2 bg-ground px-1 py-0.5 text-[12px] text-text outline-none focus:border-signal" + > + {!known && <option value={value}>{value}</option>} + {stock.length > 0 && other.length > 0 ? ( + <> + <optgroup label="this cut's"> + {stock.map((v) => ( + <option key={v.verdict} value={v.verdict}> + {verdictText(v)} + </option> + ))} + </optgroup> + <optgroup label="other verdicts"> + {other.map((v) => ( + <option key={v.verdict} value={v.verdict}> + {verdictText(v)} + </option> + ))} + </optgroup> + </> + ) : ( + verdicts.map((v) => ( + <option key={v.verdict} value={v.verdict}> + {verdictText(v)} + </option> + )) + )} + </select> + ); +} + +/** "draw the stamp": shows the choice at once (a draft) until the view comes back with it. */ +function StampToggle({ on, busy, onSet }: { on: boolean; busy: boolean; onSet: (on: boolean) => Promise<unknown> }) { + const [draft, setDraft] = useState<boolean | null>(null); + useEffect(() => setDraft(null), [on]); + return ( + <label className="inline-flex items-center gap-1.5 text-text"> + <input + type="checkbox" + data-knob="stamp" + checked={draft ?? on} + disabled={busy} + onChange={(e) => { + const next = e.target.checked; + setDraft(next); + void onSet(next).finally(() => setDraft(null)); + }} + /> + draw the stamp + </label> + ); +} + +/** The verdicts when the view names none (an older server): the five, by name. */ +const FALLBACK_VERDICTS: MarkVerdict[] = ["CORROBORATED", "PARTLY", "CONTRADICTED", "NOT_FOUND", "UNTESTABLE"].map((v) => ({ + verdict: v, + label: v, + stampLabel: v, + color: "currentColor", + stock: false, +})); + +/** + * THE MARKS of one clip (plans/clip-marks.md): a list, each mark its own stamp + * and tally step. One mark is selected (click its row): Shift+S puts its + * moment at the playhead. Shift+M adds a mark at the playhead with the + * verdict beside "Add mark at playhead". The box keeps its own keys (the + * editor's own key handler leaves Shift+S and Shift+M to it). + */ +export function MarksBox({ clipId, - claim, - stampsOn, + marks, defaults, playhead, span, @@ -105,8 +218,7 @@ export function CountStampBox({ onGo, }: { clipId: string; - claim: ClaimKnobs; - stampsOn: string | null; + marks: MarkView[]; defaults: KnobDefaults | undefined; playhead: number | null; span: { start: number; end: number; cutStart: number; cutEnd: number }; @@ -114,76 +226,187 @@ export function CountStampBox({ write: Write; onGo: (id: string) => void; }) { - const set = (knobs: Record<string, unknown>, done: string) => void write({ op: "claim", clip: clipId, knobs }, done); + const verdicts = defaults?.verdicts?.length ? defaults.verdicts : FALLBACK_VERDICTS; const hold = defaults?.hold ?? 3; - const word = defaults?.labels?.[claim.verdict] ?? claim.verdict; - // The box shows the choice at once (stampDraft) until the view comes back with it. - const [stampDraft, setStampDraft] = useState<boolean | null>(null); - useEffect(() => setStampDraft(null), [claim.stamp, clipId]); - const stampOn = stampDraft ?? claim.stamp !== false; - const outsideCut = typeof claim.at === "number" && (claim.at < span.cutStart || claim.at > span.cutEnd); + const [selected, setSelected] = useState<string | null>(marks[0]?.id ?? null); + const [hint, setHint] = useState<string | null>(null); + // A new clip: its first mark selected. A selected mark removed: the first. + useEffect(() => { + setSelected(marks[0]?.id ?? null); + setHint(null); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [clipId]); + useEffect(() => { + if (selected !== null && !marks.some((m) => m.id === selected)) setSelected(marks[0]?.id ?? null); + if (selected === null && marks.length) setSelected(marks[0].id); + }, [marks, selected]); + const current = marks.find((m) => m.id === selected) ?? null; + const [addVerdict, setAddVerdict] = useState<string>(verdicts.find((v) => v.stock)?.verdict ?? verdicts[0].verdict); + // The verdict a new mark takes follows the selected mark's. + useEffect(() => { + if (current) setAddVerdict(current.verdict); + }, [current?.verdict]); // eslint-disable-line react-hooks/exhaustive-deps + + const setKnobs = (id: string, knobs: Record<string, unknown>, done: string) => void write({ op: "claim", clip: clipId, mark: id, knobs }, done); + const addAtPlayhead = () => { + if (playhead === null) { + setHint("put the playhead where the mark should land first (play, or click the strip)"); + return; + } + if (marks.length >= 8) { + setHint("a clip carries at most 8 marks"); + return; + } + setHint(null); + const at = r2(playhead); + void write({ op: "marks", clip: clipId, add: { verdict: addVerdict, at } }, `Mark added at ${edgeClock(at)}`).then((r) => { + const added = (r as { result?: { added?: string } } | null)?.result?.added; + if (added) setSelected(added); + }); + }; + const atPlayhead = () => { + if (!current) { + setHint("no mark to move: add one at the playhead first (⇧M)"); + return; + } + if (playhead === null) { + setHint("put the playhead where the stamp should land first"); + return; + } + setHint(null); + setKnobs(current.id, { at: r2(playhead) }, `${current.id} lands at ${edgeClock(playhead)}`); + }; + + // Shift+S (the selected mark's moment at the playhead) and Shift+M (a mark + // added at the playhead). S and M alone stay Split and Merge. + const keys = useRef<(e: KeyboardEvent) => void>(() => {}); + keys.current = (e: KeyboardEvent) => { + if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey || !e.shiftKey) return; + const t = e.target as HTMLElement | null; + if (t?.closest?.(TYPING) || t?.closest?.("dialog[open]")) return; + const k = e.key.toLowerCase(); + if (k === "s") { + e.preventDefault(); + atPlayhead(); + } else if (k === "m") { + e.preventDefault(); + addAtPlayhead(); + } + }; + useEffect(() => { + const on = (e: KeyboardEvent) => keys.current(e); + document.addEventListener("keydown", on); + return () => document.removeEventListener("keydown", on); + }, []); + + const timedAny = marks.some((m) => typeof m.at === "number"); return ( - <section id="clip-stamp" data-count-stamp={clipId} data-claim-id={claim.id} className={box}> - <div className="flex flex-wrap items-baseline gap-2"> - <h2 className="micro m-0">Count &amp; stamp</h2> - <span className="font-mono text-[11.5px]"> - {claim.id} · {claim.verdict} - </span> - {stampsOn && stampsOn !== clipId && ( - <span data-stamps-on={stampsOn} className="text-muted"> - this claim stamps on{" "} - <button type="button" onClick={() => onGo(stampsOn)} className="underline"> - {stampsOn} - </button>{" "} - (the last clip carrying it) — its knobs are read there - </span> - )} - </div> - <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5"> - <span className="inline-flex items-center gap-1.5" data-knob-at={claim.at ?? ""}> - <span className="micro">lands at</span> - <span className="num font-mono">{typeof claim.at === "number" ? edgeClock(claim.at) : "default (before the clip leaves)"}</span> + <section id="clip-stamp" data-marks={clipId} data-mark-count={marks.length} className={box}> + <div className="flex flex-wrap items-center gap-2"> + <h2 className="micro m-0">Marks</h2> + <span className="text-muted">{marks.length ? "each its own stamp and count" : "none: this clip stamps nothing and counts nothing"}</span> + <span className="ml-auto inline-flex flex-wrap items-center gap-1.5"> + <VerdictPicker name="add" value={addVerdict} verdicts={verdicts} busy={busy} onPick={setAddVerdict} /> <button type="button" - data-claim-at-playhead="" - disabled={busy || playhead === null} + data-mark-add="" + disabled={busy || marks.length >= 8} onMouseDown={(e) => e.preventDefault()} - onClick={() => playhead !== null && set({ at: Math.round(playhead * 100) / 100 }, `The stamp lands at ${edgeClock(playhead)}`)} + onClick={addAtPlayhead} className={buttonVariants({ size: "sm" })} - title="the stamp lands and the count steps at the playhead (a source second inside the clip)" + title="a new mark, landing at the playhead (a source second inside the clip)" > - Set at playhead <kbd>⇧S</kbd> + Add mark at playhead <kbd>⇧M</kbd> </button> - {typeof claim.at === "number" && ( - <button type="button" data-knob-clear="at" disabled={busy} onClick={() => set({ at: null }, "The stamp lands at its default")} className={buttonVariants({ variant: "quiet", size: "sm" })}> + {marks.length > 0 && ( + <button type="button" data-marks-clear="" disabled={busy} onClick={() => write({ op: "marks", clip: clipId, set: null }, "No marks on this clip")} className={buttonVariants({ variant: "quiet", size: "sm" })} title="remove every mark on this clip"> Clear </button> )} </span> - <KnobField name="hold" label="hold" unit="s" step={0.5} value={claim.hold} placeholder={String(hold)} busy={busy} onSave={(v) => set({ hold: numOrNull(v) }, v ? `The stamp stays ${v} s` : "The stamp stays the cut's default")} /> - <label className="inline-flex items-center gap-1.5 text-text"> - <input type="checkbox" data-knob="stamp" checked={stampOn} disabled={busy} onChange={(e) => { - const on = e.target.checked; - setStampDraft(on); - void write({ op: "claim", clip: clipId, knobs: { stamp: on ? null : false } }, on ? "Stamp drawn" : "Counts, no stamp").finally(() => setStampDraft(null)); - }} - /> - draw the stamp - </label> - <KnobField name="count" label="count" step={1} value={claim.count} placeholder={String(defaults?.count ?? 1)} busy={busy} onSave={(v) => set({ count: numOrNull(v) }, v ? `Counts ${v}` : "Counts 1")} /> - <KnobField name="label" label="label" kind="text" maxLength={20} value={claim.label} placeholder={word} busy={busy} onSave={(v) => set({ label: v || null }, v ? `The stamp says “${v}”` : "The stamp says the verdict's word")} /> </div> - {typeof claim.at === "number" && ( - <p data-knob-at-hint="" className="m-0 text-muted"> - The On-screen preview places this second from the last build&rsquo;s cut of the clip: it is approximate until the next build. + {marks.map((m, i) => { + const on = m.id === selected; + const word = m.label ?? defaults?.labels?.[m.verdict] ?? m.verdict; + const outsideCut = typeof m.at === "number" && (m.at < span.cutStart || m.at > span.cutEnd); + return ( + <div + key={m.id} + data-mark={m.id} + data-mark-at={m.at ?? ""} + data-claim-id={m.id} + aria-selected={on} + onClick={() => setSelected(m.id)} + className={`space-y-1 rounded-[3px] border px-1.5 py-1 ${on ? "border-signal" : "border-seam"}`} + > + <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5"> + <span className="num font-mono text-[11.5px] text-muted">{i + 1}</span> + <VerdictPicker name={m.id} value={m.verdict} verdicts={verdicts} busy={busy} onPick={(v) => write({ op: "marks", clip: clipId, mark: m.id, verdict: v }, `${m.id} is ${verdicts.find((x) => x.verdict === v)?.label ?? v}`)} /> + <span className="font-mono text-[11.5px]" title="the mark's id: the same id on another clip is the same event, counted once"> + {m.id} + </span> + <span className="inline-flex items-center gap-1.5" data-knob-at={m.at ?? ""}> + <span className="micro">lands at</span> + <span className="num font-mono">{typeof m.at === "number" ? edgeClock(m.at) : i < marks.length - 1 ? "default (before the next)" : "default (before the clip leaves)"}</span> + <button + type="button" + data-claim-at-playhead={m.id} + disabled={busy || playhead === null} + onMouseDown={(e) => e.preventDefault()} + onClick={(e) => { + e.stopPropagation(); + setSelected(m.id); + if (playhead !== null) setKnobs(m.id, { at: r2(playhead) }, `${m.id} lands at ${edgeClock(playhead)}`); + }} + className={buttonVariants({ size: "sm" })} + title="this mark's stamp lands and the count steps at the playhead (a source second inside the clip)" + > + Set at playhead{on && <kbd>⇧S</kbd>} + </button> + {typeof m.at === "number" && ( + <button type="button" data-knob-clear="at" disabled={busy} onClick={() => setKnobs(m.id, { at: null }, `${m.id} lands at its default`)} className={buttonVariants({ variant: "quiet", size: "sm" })}> + Clear + </button> + )} + </span> + <button type="button" data-mark-remove={m.id} disabled={busy} onClick={(e) => { e.stopPropagation(); void write({ op: "marks", clip: clipId, remove: m.id }, `${m.id} removed`); }} className={`${buttonVariants({ variant: "quiet", size: "sm" })} ml-auto`} title="remove this mark"> + Remove + </button> + </div> + <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5"> + <KnobField name="hold" label="hold" unit="s" step={0.5} value={m.hold} placeholder={String(hold)} busy={busy} onSave={(v) => setKnobs(m.id, { hold: numOrNull(v) }, v ? `${m.id}'s stamp stays ${v} s` : `${m.id}'s stamp stays the cut's default`)} /> + <StampToggle on={m.stamp !== false} busy={busy} onSet={(on) => write({ op: "claim", clip: clipId, mark: m.id, knobs: { stamp: on ? null : false } }, on ? `${m.id}: stamp drawn` : `${m.id}: counts, no stamp`)} /> + <KnobField name="count" label="count" step={1} value={m.count} placeholder={String(defaults?.count ?? 1)} busy={busy} onSave={(v) => setKnobs(m.id, { count: numOrNull(v) }, v ? `${m.id} counts ${v}` : `${m.id} counts 1`)} /> + <KnobField name="label" label="label" kind="text" maxLength={20} value={m.label} placeholder={word} busy={busy} onSave={(v) => setKnobs(m.id, { label: v || null }, v ? `${m.id}'s stamp says “${v}”` : `${m.id}'s stamp says the verdict's word`)} /> + </div> + {m.stampsOn && m.stampsOn !== clipId && ( + <p data-stamps-on={m.stampsOn} className="m-0 text-muted"> + {m.id} stamps on{" "} + <button type="button" onClick={() => onGo(m.stampsOn as string)} className="underline"> + {m.stampsOn} + </button>{" "} + (the last clip carrying it) — its knobs are read there + </p> + )} + {outsideCut && ( + <p data-knob-warning="" className="m-0 text-reject-text"> + {edgeClock(m.at as number)} is outside the cut ({edgeClock(span.cutStart)}–{edgeClock(span.cutEnd)}): the stamp would land on footage the cut does not play. + </p> + )} + </div> + ); + })} + {hint && ( + <p data-marks-hint="" className="m-0 text-reject-text"> + {hint} </p> )} - {defaults && !defaults.stampShown && <p className="m-0 text-muted">The cut draws no stamps (the fact-check's stamp effect is off): the count still steps here.</p>} - {outsideCut && ( - <p data-knob-warning="" className="m-0 text-reject-text"> - {edgeClock(claim.at as number)} is outside the cut ({edgeClock(span.cutStart)}–{edgeClock(span.cutEnd)}): the stamp would land on footage the cut does not play. + {timedAny && ( + <p data-knob-at-hint="" className="m-0 text-muted"> + The On-screen preview places a mark&rsquo;s second from the last build&rsquo;s cut of the clip: it is approximate until the next build. </p> )} + {marks.length > 0 && defaults && !defaults.stampShown && <p className="m-0 text-muted">The cut draws no stamps (the fact-check&rsquo;s stamp effect is off): the counts still step here.</p>} </section> ); } diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -23,7 +23,7 @@ Inbox cannot disagree about what is wrong with one. | `inbox [--all] [--json]` | the decisions grouped and ranked by piece (`a:<site>/<report>`, `p:<project>`): Your call, Review, Blocking, Notes, Open, Ready to finish, Quiet — one card per piece and kind, and how many sit hidden on parked or done pieces (`--all` lists them). Every decision, songs' and articles' included; runs `bin/inbox.ts` through tsx | | `folders [--json]` · `kinds [--json]` | the tree, the registry | | `window <project> <clip> [--start S] [--end E] [--lock] [--lock-end] [--no-lock-end] [--note …]` | edit a window | -| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`; `key=` clears one ([knobs.md](knobs.md)) | +| `set <project> <clip> key=value …` | a clip's **knobs**: `claim.at` `claim.hold` `claim.stamp` `claim.count` `claim.label` (the first mark's, or `--mark <id>`'s), its **marks** `mark.add=<verdict>[@<sec>]` `mark.remove=<id>` `mark.verdict=<verdict>` `marks=<json>`, `audio.offset` `audio.gain` `audio.fadeIn` `audio.fadeOut`; `key=` clears one ([knobs.md](knobs.md#marks)) | | `look <project> key=value …` | the cut's **knobs**: `factcheck.stamp.*`, `factcheck.verdicts.<V>.stampLabel\|label\|color`, `deck.markers=<json>`, `deck.markerLayout`, `variants=<json>`, and the look's keys ([knobs.md](knobs.md)) | | `variants <project> [--take <t>] [--list] [--json]` | **Make variants**: the encode ladder of the build (or of a take's); `--list` what was made and the build's sync report, each clip's lag (past a frame flagged) ([knobs.md](knobs.md)) | | `build <project> [--preset preview\|fast\|final] [--only ID]` | **prints** the chain | diff --git a/umtool/docs/knobs.md b/umtool/docs/knobs.md @@ -15,11 +15,12 @@ that generates it ([notes.md](notes.md)). | Knob | In umtool | From a terminal | Route | |---|---|---|---| -| `claim.at` — the SOURCE second the stamp lands and the tally steps; inside the clip's window | clip editor, **Count & stamp**: **Set at playhead** (Shift+S) | `umtool set <p> <clip> claim.at=12.4` | `POST /api/report/clip-editor {op: "claim", clip, knobs: {at}}` | -| `claim.hold` — seconds the stamp stays (0.5–10; default the cut's `factcheck.stamp.seconds`) | Count & stamp, **hold** | `claim.hold=4` | same | -| `claim.stamp` — `false`: the claim counts, no stamp is drawn | Count & stamp, **draw the stamp** | `claim.stamp=false` | same | -| `claim.count` — how much the tally steps (1–99; default 1) | Count & stamp, **count** | `claim.count=2` | same | -| `claim.label` — this stamp's text (≤ 20; default the verdict's stamp word) | Count & stamp, **label** | `claim.label="2 SEIZURES"` | same | +| `claim.at` — the SOURCE second the stamp lands and the tally steps; inside the clip's window | clip editor, **Marks**: a mark's **Set at playhead** (Shift+S: the selected mark's) | `umtool set <p> <clip> claim.at=12.4` | `POST /api/report/clip-editor {op: "claim", clip, mark?, knobs: {at}}` | +| `claim.hold` — seconds the stamp stays (0.5–10; default the cut's `factcheck.stamp.seconds`) | Marks, **hold** | `claim.hold=4` | same | +| `claim.stamp` — `false`: the claim counts, no stamp is drawn | Marks, **draw the stamp** | `claim.stamp=false` | same | +| `claim.count` — how much the tally steps (1–99; default 1) | Marks, **count** | `claim.count=2` | same | +| `claim.label` — this stamp's text (≤ 20; default the verdict's stamp word) | Marks, **label** | `claim.label="2 SEIZURES"` | same | +| marks — more than one stamp and count on a clip (≤ 8): see [Marks](#marks) | Marks: **Add mark at playhead** (Shift+M), a mark's verdict, **Remove**, **Clear** | `mark.add=Episodes@190.2` `mark.remove=<id>` `mark.verdict=Grift` `marks=<json>` | `POST /api/report/clip-editor {op: "marks", clip, add \| remove \| mark+verdict \| set}` | | `audio.offset` — ms, + = the sound later (−2000…2000) | clip editor, **Audio**: **sync**, the ±10/±40 nudges, **listen** (the 3 s around the playhead) | `umtool set <p> <clip> audio.offset=-40` | `POST /api/report/clip-editor {op: "audio", clip, audio: {offset}}` | | `audio.gain` — dB (−20…20) | Audio, **gain** | `audio.gain=-3` | same | | `audio.fadeIn`, `audio.fadeOut` — seconds (0–5) | Audio, **fade in / fade out** | `audio.fadeIn=0.3` | same | @@ -31,6 +32,45 @@ clip says which one that is, and `umtool set` prints a NOTE. A window save that clip's window is refused: widen the window, or clear `claim.at`. The On-screen table's claim column edits the claim's id and verdict and keeps its knobs while the id stays the same. +## Marks + +A clip may carry more than one MARK — each its own stamp and its own tally step, at its own second — e.g. a clip +that mentions the seizure in question and one before it. The Marks box is on every clip in the clip editor. + +```json +"claims": [ + { "id": "first", "verdict": "CORROBORATED", "at": 188.41 }, + { "id": "first.2", "verdict": "CORROBORATED", "at": 180.5, "label": "EARLIER" } +] +``` + +- **Shape.** `claims: [mark, …]`, 2–8 marks; a mark is a claim (`{id, verdict, at?, hold?, stamp?, count?, + label?}`). One mark is written `claim`, as ever — a manifest with one mark per clip is the bytes it always was — + and `claim` beside `claims` is refused. +- **Ids.** A mark added to a clip gets a NEW id: the clip's id when no mark uses it, else `<clip>.2`, `.3`, …. The + same id on several clips is one event, counted once and stamped on the last clip carrying it (as `claim` always + was); a verdict changed on a mark changes on every clip carrying its id. +- **Verdicts.** Picked by this cut's words: the box lists the fact-check's relabelled verdicts first ("Episodes", + "Grift" on the Huck cut), and `umtool set` takes a verdict's name or its label (`mark.add=Episodes@190.2`). +- **Timing.** A mark with `at` lands there. Marks without `at` land in order, back to back, the last as a lone + claim would (before the clip leaves). In landing order a stamp leaves in time to be gone as the next one comes in. +- **Refused** (the renderer's words, the file left as it was): an `at` outside the clip's window; two drawn stamps + on one clip closer than the first's hold (`the marks a (at 110) and b (at 111.5) overlap -- a's stamp stays 3 s; + land b at 113 or later, or shorten a's hold`); a ninth mark; one id given two verdicts. +- **Colour.** A clip's pip and rail take its FIRST mark's verdict. The tally, the finale's totals and `tallyFinals` + count every mark. +- **The On-screen table** shows and edits a clip's first mark; its other marks stay. +- **In umtool:** select a mark (click its row); **Set at playhead** / Shift+S puts that mark's second at the + playhead; **Add mark at playhead** / Shift+M adds one with the verdict beside the button (it follows the selected + mark's); **Remove** one; **Clear** them all. +- **From a terminal:** `umtool set <p> <clip> mark.add=<verdict>[@<sec>]` (or a JSON object with knobs), + `mark.remove=<id>`, `mark.verdict=<verdict> [--mark <id>]`, `marks='[…]'` (all; `marks=` none); the `claim.*` keys + set the first mark's knobs, or `--mark <id>`'s. `umtool show` prints a clip's marks (`--json`: `marks`, each with + `stampsOn`). +- **The route:** `POST /api/report/clip-editor` `{op: "marks", clip, add: {verdict, at?, …}}`, `{…, remove: id}`, + `{…, mark: id, verdict}`, `{…, set: [..] | null}`; `{op: "claim", clip, mark, knobs}` for a mark's knobs. Token- + and agent-token-guarded like every write. The writer: `lib/report/manifest.mjs` `updateMarks`. + ## The cut | Knob | In umtool | From a terminal | Route | diff --git a/umtool/e2e/fixtures/make-fixture.mjs b/umtool/e2e/fixtures/make-fixture.mjs @@ -39,6 +39,7 @@ import { makeRunTraceFixture } from "./run-trace-fixture.mjs"; import { makeClipsSuggestFixture } from "./clips-suggest-fixture.mjs"; import { makeVideoAssistFixture } from "./video-assist-fixture.mjs"; import { makeKnobsFixture } from "./knobs-fixture.mjs"; +import { makeMarksFixture } from "./marks-fixture.mjs"; const CODE = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", "..", "song"); const dest = path.resolve(process.argv[2] ?? path.join(process.cwd(), ".e2e-song")); @@ -1825,6 +1826,8 @@ makeClipsSuggestFixture({ reports, manifest, cachedWindow: path.join(REPORT, "ou makeVideoAssistFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); // Video knobs (plans/video-knobs-ui.md): Count & stamp, Audio, Make variants, Sync and the Markers editor (knobs.spec.ts). makeKnobsFixture({ reports, manifest, deckManifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); +// Marks (plans/clip-marks.md): the clip editor's Marks box -- add at the playhead, verdict, Shift+S/M, remove (marks.spec.ts). +makeMarksFixture({ reports, manifest, cachedWindow: path.join(REPORT, "out", "clips-raw", "vid1_0.00-9.00.mp4"), cues: CUES.vid1 }); // TWO MORE cached windows for vid1, and they are the regression rather than // decoration. diff --git a/umtool/e2e/fixtures/marks-fixture.mjs b/umtool/e2e/fixtures/marks-fixture.mjs @@ -0,0 +1,34 @@ +// What marks.spec.ts edits (plans/clip-marks.md): the clip editor's three clips +// (clip-editor-fixture.mjs, its own copy) with the fact-check relabelled as +// the Huck cut's (CORROBORATED "Episodes", CONTRADICTED "Grift"), the stamp's +// seconds at 1, and ONE mark on r001 (`claim`, at 1.2) -- the Marks box: add a +// mark at the playhead (button and Shift+M), its verdict, hold, Shift+S on the +// selected mark, remove, Clear. +// +// Synthetic, like every fixture. +import { readFileSync, writeFileSync } from "node:fs"; +import path from "node:path"; +import { makeClipEditorFixture } from "./clip-editor-fixture.mjs"; + +/** + * @param {{ reports: string, manifest: Function, cachedWindow: string, cues: Array<[number, number, string]> }} o + */ +export function makeMarksFixture({ reports, manifest, cachedWindow, cues }) { + const { dir } = makeClipEditorFixture({ reports, manifest, cachedWindow, cues, name: "marks-fixture", title: "The Marks Fixture" }); + const file = path.join(dir, "video.manifest.json"); + const m = JSON.parse(readFileSync(file, "utf8")); + m.render.chrome = { + engine: "hyperframes", + layout: "deck", + factcheck: { + verdicts: { + CORROBORATED: { label: "Episodes", stampLabel: "Seizure" }, + CONTRADICTED: { label: "Grift", stampLabel: "Grift" }, + }, + stamp: { seconds: 1 }, + }, + }; + for (const e of m.timeline) if (e.id === "r001") e.claim = { id: "r001", verdict: "CORROBORATED", at: 1.2 }; + writeFileSync(file, JSON.stringify(m, null, 2) + "\n"); + return { dir }; +} diff --git a/umtool/e2e/knobs.spec.ts b/umtool/e2e/knobs.spec.ts @@ -6,9 +6,10 @@ import * as urls from "./urls"; // --------------------------------------------------------------------------- // The video knobs (plans/video-knobs-ui.md): -// - the clip editor's Count & stamp box: Set at playhead (and Shift+S) writes -// claim.at, count / label / stamp on-off write and Clear removes; a clip -// that carries the claim but does not stamp it says where it stamps +// - the clip editor's Marks box (was Count & stamp) on a clip with one mark: +// Set at playhead (and Shift+S) writes claim.at, count / label / stamp +// on-off write and Clear removes; a clip that carries the claim but does +// not stamp it says where it stamps (marks.spec.ts: two marks and more) // - the Audio box: a sync nudge, the gain, Clear all // - an agent's token on a manifest-write route: right one writes, a wrong one is 401 // - the On-screen Markers editor: add, label, colour, align, re-order, the @@ -37,7 +38,7 @@ test("Count & stamp and Audio in the clip editor; an agent's token on the route" await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r003"); await expect(page.locator("[data-editor-player]")).not.toHaveAttribute("data-editor-player", "looking", { timeout: 15_000 }); - const box = page.locator('[data-count-stamp="r003"]'); + const box = page.locator('[data-marks="r003"]'); await expect(box).toBeVisible(); // The defaults show where a key is absent: the cut's stamp seconds, a count of 1. await expect(box.locator('[data-knob="hold"]')).toHaveAttribute("placeholder", "3"); @@ -82,9 +83,10 @@ test("Count & stamp and Audio in the clip editor; an agent's token on the route" // r002 carries the claim but r003 stamps it: the box says so; r001 has none. await page.locator('[data-editor-row="r002"]').click(); - await expect(page.locator('[data-count-stamp="r002"] [data-stamps-on="r003"]')).toBeVisible(); + await expect(page.locator('[data-marks="r002"] [data-stamps-on="r003"]')).toBeVisible(); await page.locator('[data-editor-row="r001"]').click(); - await expect(page.locator("[data-count-stamp]")).toHaveCount(0); + await expect(page.locator('[data-marks="r001"]')).toHaveAttribute("data-mark-count", "0"); + await expect(page.locator("[data-mark]")).toHaveCount(0); // An agent's token writes through the same route; a wrong one is refused. const view = await (await request.get(`/api/report/clip-editor?project=${encodeURIComponent(PROJECT)}`)).json(); diff --git a/umtool/e2e/marks.spec.ts b/umtool/e2e/marks.spec.ts @@ -0,0 +1,97 @@ +import { test, expect } from "@playwright/test"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import * as urls from "./urls"; + +// --------------------------------------------------------------------------- +// Marks (plans/clip-marks.md): the clip editor's Marks box, on every clip. +// - Add mark at playhead (the button, and Shift+M): a second mark on a clip +// with one makes `claims`, under a NEW id (<clip>.2) +// - the verdicts offered are this cut's words ("Episodes", "Grift") +// - a mark that would sit on another's stamp is refused, the file unchanged +// - a mark's verdict, its hold, Shift+S on the selected mark +// - Remove back to one mark (`claim` again), Clear (none) +// - a clip with no marks shows the box, empty +// Fixture: e2e/fixtures/marks-fixture.mjs (r001 carries one mark, at 1.2; the +// stamp stays 1 s). +// --------------------------------------------------------------------------- + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const DIR = path.join(HERE, "..", ".e2e-song", "reports", "marks-fixture"); +const PROJECT = "reports/marks-fixture"; + +type Mark = { id: string; verdict: string; at?: number; hold?: number }; +type Entry = { id: string; type: string; claim?: Mark; claims?: Mark[] }; +const entry = (id: string): Entry | null => + (JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")).timeline as Entry[]).find((e) => e.id === id) ?? null; + +test("the Marks box: add at the playhead, this cut's verdicts, Shift+M / Shift+S, overlap refused, remove, clear", async ({ page }) => { + test.setTimeout(150_000); + await page.setViewportSize({ width: 1366, height: 900 }); + await page.goto(urls.clipEditorHref(PROJECT, { clip: "r001", mode: "edit" })); + await expect(page.locator("[data-clip-editor]")).toHaveAttribute("data-clip-editor", "r001"); + await expect(page.locator("[data-editor-player]")).not.toHaveAttribute("data-editor-player", "looking", { timeout: 15_000 }); + + const box = page.locator('[data-marks="r001"]'); + await expect(box).toHaveAttribute("data-mark-count", "1"); + await expect(box.locator('[data-mark="r001"]')).toHaveAttribute("aria-selected", "true"); + // This cut's words for the verdicts, its own first. + const options = await box.locator('[data-mark-verdict="add"] option').allTextContents(); + expect(options.slice(0, 2)).toEqual(["Episodes (CORROBORATED)", "Grift (CONTRADICTED)"]); + + // The button: a second mark at the playhead (the word at 2.4 s), a NEW id. + await page.locator('[data-word-t="2.4"]').click(); + await box.locator("[data-mark-add]").click(); + await expect.poll(() => entry("r001")?.claims?.map((m) => [m.id, m.verdict, m.at])).toEqual([ + ["r001", "CORROBORATED", 1.2], + ["r001.2", "CORROBORATED", 2.4], + ]); + expect(entry("r001")?.claim).toBeUndefined(); + await expect(box).toHaveAttribute("data-mark-count", "2"); + await expect(box.locator('[data-mark="r001.2"]')).toHaveAttribute("aria-selected", "true"); + + // Its verdict, from this cut's words. + await box.locator('[data-mark-verdict="r001.2"]').selectOption("CONTRADICTED"); + await expect.poll(() => entry("r001")?.claims?.[1]?.verdict).toBe("CONTRADICTED"); + + // Shift+M at 1.8: on the first's stamp (it stays 1 s) -- refused, nothing written. + await page.locator('[data-word-t="1.8"]').click(); + await page.keyboard.press("Shift+M"); + await expect(page.locator("[data-editor-error]")).toContainText("overlap"); + expect(entry("r001")?.claims?.length).toBe(2); + + // A shorter hold on the first, then Shift+S moves the SELECTED mark (the first) to 1.8. + await box.locator('[data-mark="r001"]').click(); + await expect(box.locator('[data-mark="r001"]')).toHaveAttribute("aria-selected", "true"); + const hold = box.locator('[data-mark="r001"] [data-knob="hold"]'); + await expect(async () => { + await hold.fill("0.5"); + await hold.press("Enter"); + await expect.poll(() => entry("r001")?.claims?.[0]?.hold, { timeout: 2000 }).toBe(0.5); + }).toPass({ timeout: 15_000 }); + await page.locator('[data-word-t="1.8"]').click(); + await page.keyboard.press("Shift+S"); + await expect.poll(() => entry("r001")?.claims?.[0]?.at).toBe(1.8); + // S and M alone are still Split and Merge: Shift did neither. + expect((JSON.parse(readFileSync(path.join(DIR, "video.manifest.json"), "utf8")).timeline as Entry[]).filter((e) => e.type === "clip").map((e) => e.id)).toEqual(["r001", "r002", "r003"]); + + // Remove the second: one mark, written as `claim` again. + await box.locator('[data-mark-remove="r001.2"]').click(); + await expect.poll(() => entry("r001")?.claim).toEqual({ id: "r001", verdict: "CORROBORATED", at: 1.8, hold: 0.5 }); + expect(entry("r001")?.claims).toBeUndefined(); + + // Shift+M on a clip with no marks: its first, under the clip's id. + await page.locator('[data-editor-row="r002"]').click(); + const box2 = page.locator('[data-marks="r002"]'); + await expect(box2).toHaveAttribute("data-mark-count", "0"); + await page.locator('[data-word-t="4.71"]').click(); + await box2.locator('[data-mark-verdict="add"]').selectOption("CONTRADICTED"); + await page.keyboard.press("Shift+M"); + await expect.poll(() => entry("r002")?.claim).toEqual({ id: "r002", verdict: "CONTRADICTED", at: 4.71 }); + + // Clear: no marks. + await box2.locator("[data-marks-clear]").click(); + await expect.poll(() => entry("r002")?.claim ?? entry("r002")?.claims ?? null).toBeNull(); + await expect(box2).toHaveAttribute("data-mark-count", "0"); +}); diff --git a/umtool/lib/report/clipEditor.mjs b/umtool/lib/report/clipEditor.mjs @@ -36,9 +36,10 @@ import { restoreClip, splitClip, updateClaimKnobs, + updateMarks, updateClip, } from "./manifest.mjs"; -import { CLAIM_KNOB_DEFAULTS, stampingEntryId } from "./knobs.mjs"; +import { CLAIM_KNOB_DEFAULTS, markVerdictsOf, rawMarksOf, stampingEntryId } from "./knobs.mjs"; import { resolveFactcheck } from "umtool-report-to-video/factcheck"; import { momentKeysOf, readRulingsState, setMontageRuling } from "./montageRulings.mjs"; import { readReactions, reproposeAvailable, REPROPOSE_UNAVAILABLE, setSpeakerLabel, setSpeakerRole, SPEAKER_ROLES } from "./clipEditorBridge.mjs"; @@ -125,8 +126,9 @@ export async function clipEditorView(project) { roomEdges: roomEdgesOf(e, manifest.render), // The video knobs: the claim as written (its id, verdict and knobs), // the entry that stamps it (the last carrying its id), and the sound. - claim: isObj(e.claim) && typeof e.claim.id === "string" ? e.claim : null, - stampsOn: isObj(e.claim) && typeof e.claim.id === "string" ? stampingEntryId(manifest, e.claim.id) : null, + // `claim` / `stampsOn` are the FIRST mark's; `marks` every one, each + // with the entry that stamps it (plans/clip-marks.md). + ...marksView(manifest, e), audio: isObj(e.audio) ? e.audio : null, }; }); @@ -151,7 +153,22 @@ export async function clipEditorView(project) { repropose: { available: reproposeAvailable, why: reproposeAvailable ? null : REPROPOSE_UNAVAILABLE }, shorts: Object.fromEntries(shorts.filter((x) => !x.gone).map((x) => [x.clip, { mtimeMs: x.mtimeMs, size: x.size, stale: x.stale }])), room: roomViewOf(manifest.render), - knobs: knobDefaultsOf(manifest.render), + knobs: { ...knobDefaultsOf(manifest.render), verdicts: markVerdictsOf(manifest) }, + }; +} + +/** + * A clip's marks for the view: `claim` and `stampsOn` (its first mark's, as + * before marks), and `marks` -- each as written, with `stampsOn`, the entry + * that stamps it. + */ +function marksView(manifest, e) { + const marks = rawMarksOf(e).filter((m) => isObj(m) && typeof m.id === "string"); + const first = marks[0] ?? null; + return { + claim: first, + stampsOn: first ? stampingEntryId(manifest, first.id) : null, + marks: marks.map((m) => ({ ...m, stampsOn: stampingEntryId(manifest, m.id) })), }; } @@ -297,8 +314,13 @@ const num = (v, what) => { * vertical { clip, crop | null, aspect? } the clip's 9:16 box for its short * room { clip, room: false | {tail?, head?} | null } room at this clip's edges * (null: the cut's render.room again) - * claim { clip, knobs: { at?, hold?, stamp?, count?, label? } } the claim's stamp and - * count (null on a knob: its default again) + * claim { clip, mark?, knobs: { at?, hold?, stamp?, count?, label? } } a mark's stamp and + * count (null on a knob: its default again); + * `mark` its id (default: the clip's first) + * marks { clip, add: { verdict, at?, id?, … } } a new mark (a new id unless given) + * { clip, remove: <mark id> } one mark gone + * { clip, mark: <mark id>, verdict } a mark's verdict (every clip carrying the id) + * { clip, set: [mark, …] | null } all of them (manifest.mjs updateMarks) * audio { clip, audio: { offset?, gain?, fadeIn?, fadeOut? } | null } the clip's sound * (null on a key, or the whole: the default) * with `token` (the manifest's, from the view) on every manifest edit. @@ -440,7 +462,17 @@ export async function runClipEditorOp(project, body, { now = null } = {}) { // whether it is drawn, how much it counts, what it says. Not structural: no clip moves. const e = needClip(); if (!isObj(body.knobs)) throw new OpError("claim needs knobs: { at?, hold?, stamp?, count?, label? }"); - result = await updateClaimKnobs(dir, e.id, body.knobs, { token }); + result = await updateClaimKnobs(dir, e.id, body.knobs, { token, mark: typeof body.mark === "string" ? body.mark : null }); + structural = false; + break; + } + case "marks": { + // The clip's marks (plans/clip-marks.md): add, remove, a verdict, or all + // of them. Not structural: no clip moves. + const e = needClip(); + const change = "add" in body ? { add: body.add } : "remove" in body ? { remove: body.remove } : "set" in body ? { set: body.set } : "mark" in body ? { mark: body.mark, verdict: body.verdict } : null; + if (!change) throw new OpError("marks needs add, remove, set, or mark with verdict"); + result = await updateMarks(dir, e.id, change, { token }); structural = false; break; } @@ -453,7 +485,7 @@ export async function runClipEditorOp(project, body, { now = null } = {}) { break; } default: - throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical, room, claim or audio"); + throw new OpError("op must be trim, restore, split, merge, add, bring-in, ruling, role, label, vertical, room, claim, marks or audio"); } let carried = null; if (structural) { @@ -472,6 +504,8 @@ function summarise(r) { if (isObj(r.speaker)) out.speaker = r.speaker; if (isObj(r.claim)) out.claim = r.claim; if (typeof r.stamps === "boolean") out.stamps = r.stamps; + if (Array.isArray(r.marks)) out.marks = r.marks; + if (typeof r.added === "string") out.added = r.added; if (r.ruling !== undefined) out.ruling = r.ruling; return out; } diff --git a/umtool/lib/report/clipEditor.test.mjs b/umtool/lib/report/clipEditor.test.mjs @@ -350,7 +350,11 @@ test("runClipEditorOp: the video knobs -- claim (Count & stamp) and audio; the v m.render.chrome = { engine: "hyperframes", layout: "deck", factcheck: { stamp: { seconds: 4 }, verdicts: { CONTRADICTED: { label: "Seizures", stampLabel: "SEIZURE" } } } }; await writeFile(path.join(p.dir, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n"); const v0 = await clipEditorView(p); - assert.deepEqual(v0.knobs, { hold: 4, stampShown: true, count: 1, labels: { ...v0.knobs.labels, CONTRADICTED: "SEIZURE" } }); + const { verdicts, ...knobs0 } = v0.knobs; + assert.deepEqual(knobs0, { hold: 4, stampShown: true, count: 1, labels: { ...v0.knobs.labels, CONTRADICTED: "SEIZURE" } }); + // The marks' verdicts: the cut's own (relabelled, or in use) first, with its words. + assert.deepEqual(verdicts[0], { verdict: "CONTRADICTED", label: "Seizures", stampLabel: "SEIZURE", color: "#e5534b", stock: true }); + assert.equal(verdicts.length, 5); assert.equal(v0.knobs.labels.PARTLY, "Partly true"); const r = await runClipEditorOp(p, { op: "claim", clip: "r003", token: v0.token, knobs: { at: 55.5, count: 2 } }); assert.deepEqual(r.result.claim, { id: "k7", verdict: "CONTRADICTED", at: 55.5, count: 2 }); @@ -367,3 +371,30 @@ test("runClipEditorOp: the video knobs -- claim (Count & stamp) and audio; the v await rm(p.dir, { recursive: true, force: true }); } }); + +test("runClipEditorOp marks: add at a second (a new id), a mark's knobs and verdict, remove, clear; the view lists every mark", async () => { + const p = await project({ withReactions: false }); + try { + const v0 = await clipEditorView(p); + assert.deepEqual(v0.clips.find((x) => x.id === "r003").marks, [], "a clip with no marks: an empty list (the box shows on every clip)"); + const a = await runClipEditorOp(p, { op: "marks", clip: "r003", token: v0.token, add: { verdict: "PARTLY", at: 52 } }); + assert.equal(a.result.added, "r003"); + const b = await runClipEditorOp(p, { op: "marks", clip: "r003", token: a.view.token, add: { verdict: "PARTLY", at: 56 } }); + assert.equal(b.result.added, "r003.2"); + const c = b.view.clips.find((x) => x.id === "r003"); + assert.deepEqual(c.marks.map((m) => [m.id, m.at, m.stampsOn]), [["r003", 52, "r003"], ["r003.2", 56, "r003"]]); + assert.equal(c.claim.id, "r003", "claim: the first mark"); + const k = await runClipEditorOp(p, { op: "claim", clip: "r003", token: b.view.token, mark: "r003.2", knobs: { count: 2 } }); + assert.equal(k.view.clips.find((x) => x.id === "r003").marks[1].count, 2); + const v = await runClipEditorOp(p, { op: "marks", clip: "r003", token: k.view.token, mark: "r003.2", verdict: "CONTRADICTED" }); + assert.equal(v.view.clips.find((x) => x.id === "r003").marks[1].verdict, "CONTRADICTED"); + await assert.rejects(runClipEditorOp(p, { op: "marks", clip: "r003", token: v.view.token, add: { verdict: "PARTLY", at: 53 } }), /overlap/); + const r = await runClipEditorOp(p, { op: "marks", clip: "r003", token: v.view.token, remove: "r003" }); + assert.deepEqual(r.view.clips.find((x) => x.id === "r003").marks.map((m) => m.id), ["r003.2"]); + const z = await runClipEditorOp(p, { op: "marks", clip: "r003", token: r.view.token, set: null }); + assert.deepEqual(z.view.clips.find((x) => x.id === "r003").marks, []); + await assert.rejects(runClipEditorOp(p, { op: "marks", clip: "r003" }), /marks needs add, remove, set, or mark/); + } finally { + await rm(p.dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/report/clipEditorTypes.ts b/umtool/lib/report/clipEditorTypes.ts @@ -33,15 +33,21 @@ export type EditorClip = { /** The video knobs: the claim as written (id, verdict, and its stamp's knobs), the entry that stamps it, the sound. */ claim?: ClaimKnobs | null; stampsOn?: string | null; + /** Every mark (plans/clip-marks.md), in order, each with the entry that stamps it; `claim` is the first. */ + marks?: MarkView[]; audio?: ClipAudio | null; }; /** A claim with its knobs (plans/video-knobs-plan.md): `at` is a source second. */ export type ClaimKnobs = { id: string; verdict: string; at?: number; hold?: number; stamp?: boolean; count?: number; label?: string }; +/** A mark as the clip editor shows it: its knobs, and the clip that stamps it (the last carrying its id). */ +export type MarkView = ClaimKnobs & { stampsOn: string | null }; +/** A verdict a mark may take, with this cut's words and colour; `stock`: the cut's own (relabelled, or in use). */ +export type MarkVerdict = { verdict: string; label: string; stampLabel: string; color: string; stock: boolean }; /** A clip's sound at the encode: offset in ms (+ = later), gain in dB, fades in s. */ export type ClipAudio = { offset?: number; gain?: number; fadeIn?: number; fadeOut?: number }; /** What a claim knob is when absent: the cut's stamp seconds, whether stamps are drawn, the count, each verdict's stamp word. */ -export type KnobDefaults = { hold: number; stampShown: boolean; count: number; labels: Record<string, string> }; +export type KnobDefaults = { hold: number; stampShown: boolean; count: number; labels: Record<string, string>; verdicts?: MarkVerdict[] }; export type Speaker = { index: number; role?: "host" | "subject" | "other"; label?: string; seconds?: number; turns?: number; how?: "auto" | "operator"; sameAs?: number }; export type Proposal = { id: string; start: number; end: number; score?: number; why?: string; moments?: string[]; used?: boolean; clipId?: string | null }; diff --git a/umtool/lib/report/knobs.mjs b/umtool/lib/report/knobs.mjs @@ -17,7 +17,9 @@ // and which entry's knobs the build reads. // // PURE: no fs. Plain ESM so `umtool set` runs it under bare node. -import { CLAIM_KEYS, CLAIM_LIMITS, FACTCHECK_DEFAULTS, FACTCHECK_LIMITS, STAMP_MOTIONS } from "umtool-report-to-video/factcheck"; +import { + CLAIM_KEYS, CLAIM_LIMITS, CLAIM_MARKS_MAX, FACTCHECK_DEFAULTS, FACTCHECK_LIMITS, STAMP_MOTIONS, VERDICTS, rawMarksOf, resolveFactcheck, +} from "umtool-report-to-video/factcheck"; import { MARKER_ALIGNS, MARKER_LAYOUTS } from "umtool-report-to-video/deck"; import { DEFAULT_VARIANTS, validateVariants, variantsOf } from "umtool-report-to-video/variants"; @@ -132,7 +134,7 @@ export function claimKnobsOf(claim) { export function stampingEntryId(manifest, claimId, variant = null) { let last = null; for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { - if (!isObj(e) || !isObj(e.claim) || e.claim.id !== claimId) continue; + if (!isObj(e) || !rawMarksOf(e).some((m) => isObj(m) && m.id === claimId)) continue; if (variant && e.variant && e.variant !== variant) continue; last = e.id; } @@ -140,6 +142,109 @@ export function stampingEntryId(manifest, claimId, variant = null) { } // --------------------------------------------------------------------------- +// An entry's MARKS (plans/clip-marks.md): `claims: [mark, …]`, or a lone +// `claim` for one. Every writer stores one mark as `claim` -- so a manifest +// with one mark per clip is the bytes it always was -- and two or more as +// `claims`. +// --------------------------------------------------------------------------- + +export { CLAIM_MARKS_MAX, rawMarksOf }; + +/** An entry's marks as written, copied (a writer edits the copy, then setMarks). */ +export const marksCopyOf = (entry) => rawMarksOf(entry).filter(isObj).map((m) => ({ ...m })); + +/** + * Store `marks` on `entry`: none removes `claim` and `claims`; one is `claim`; + * two or more are `claims`. Mutates `entry`. + */ +export function setMarks(entry, marks) { + const list = Array.isArray(marks) ? marks.filter(isObj) : []; + const key = list.length === 0 ? null : list.length === 1 ? "claim" : "claims"; + const value = list.length === 1 ? list[0] : list; + // In the place the marks had among the entry's keys (else last): a mark + // added and removed again leaves the entry the bytes it was. + const keys = Object.keys(entry); + const at = keys.findIndex((k) => k === "claim" || k === "claims"); + if (at === -1) { + if (key) entry[key] = value; + return entry; + } + const after = keys.slice(at + 1).filter((k) => k !== "claim" && k !== "claims").map((k) => [k, entry[k]]); + for (const k of keys.slice(at)) delete entry[k]; + if (key) entry[key] = value; + for (const [k, v] of after) entry[k] = v; + return entry; +} + +/** Every mark id the manifest uses. */ +export function markIdsOf(manifest) { + const ids = new Set(); + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + for (const m of rawMarksOf(e)) if (isObj(m) && typeof m.id === "string") ids.add(m.id); + } + return ids; +} + +/** + * A NEW mark id for a mark added to `entryId`: the entry's id when no mark + * uses it, else `<entryId>.2`, `.3`, … -- never an id another mark has (a + * shared id is one event, counted once). + */ +export function freshMarkId(manifest, entryId) { + const used = markIdsOf(manifest); + const base = String(entryId ?? "").replace(/[^A-Za-z0-9_.:-]/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 56) || "mark"; + if (!used.has(base)) return base; + for (let n = 2; ; n += 1) { + const id = `${base}.${n}`; + if (!used.has(id)) return id; + } +} + +/** + * A verdict as typed: its name (`CORROBORATED`, any case) or its label in this + * cut (`Episodes`, any case -- the fact-check's `verdicts.<V>.label` or + * `stampLabel`). Throws a sentence naming the choices. + * + * @param {unknown} v + * @param {Record<string, any>} [render] + */ +export function verdictOfInput(v, render) { + const s = typeof v === "string" ? v.trim() : ""; + const upper = s.toUpperCase().replace(/[\s-]+/g, "_"); + if (VERDICTS.includes(upper)) return upper; + const fc = resolveFactcheck(render); + const given = isObj(render?.chrome?.factcheck?.verdicts) ? render.chrome.factcheck.verdicts : {}; + for (const V of VERDICTS) { + const words = [fc.verdicts[V]?.label, isObj(given[V]) ? given[V].stampLabel : null].filter((x) => typeof x === "string"); + if (words.some((w) => w.trim().toLowerCase() === s.toLowerCase())) return V; + } + const names = VERDICTS.map((V) => (fc.verdicts[V]?.label && fc.verdicts[V].label !== V ? `${V} (${fc.verdicts[V].label})` : V)); + throw new Error(`${q(v)} is not a verdict: ${names.join(", ")}`); +} + +/** + * The verdicts a mark is picked from, for the clip editor: each with its tally + * label, stamp word and colour, the cut's own first (`stock`: the ones the + * fact-check relabels, or any mark already uses), then the rest. + * + * @returns {Array<{ verdict: string, label: string, stampLabel: string, color: string, stock: boolean }>} + */ +export function markVerdictsOf(manifest) { + const render = manifest?.render; + const fc = resolveFactcheck(render); + const given = isObj(render?.chrome?.factcheck?.verdicts) ? render.chrome.factcheck.verdicts : {}; + const used = new Set(); + for (const e of Array.isArray(manifest?.timeline) ? manifest.timeline : []) { + for (const m of rawMarksOf(e)) if (isObj(m) && typeof m.verdict === "string") used.add(m.verdict); + } + const all = VERDICTS.map((V) => { + const own = isObj(given[V]) && typeof given[V].stampLabel === "string" && given[V].stampLabel.trim() ? given[V].stampLabel.trim() : null; + return { verdict: V, label: fc.verdicts[V].label, stampLabel: own ?? fc.verdicts[V].label, color: fc.verdicts[V].color, stock: V in given || used.has(V) }; + }); + return [...all.filter((x) => x.stock), ...all.filter((x) => !x.stock)]; +} + +// --------------------------------------------------------------------------- // The fact-check's stamp knobs, for the editor's placeholders. // --------------------------------------------------------------------------- diff --git a/umtool/lib/report/knobsCli.mjs b/umtool/lib/report/knobsCli.mjs @@ -5,6 +5,9 @@ // before it, so a write here beside an open page is refused rather than lost. // // umtool set <project> <clip> key=value … claim.at claim.hold claim.stamp claim.count claim.label +// (a clip's first mark, or --mark <id>'s) +// marks=<json> mark.add=<verdict>[@<sec>] mark.remove=<id> +// mark.verdict=<verdict> (plans/clip-marks.md) // audio.offset audio.gain audio.fadeIn audio.fadeOut // umtool look <project> key=value … factcheck.stamp.<k>, factcheck.verdicts.<V>.<k>, // deck.markers=<json>, deck.markerLayout=…, variants=<json>, @@ -26,22 +29,29 @@ import { updateClip, updateDeckKeys, updateFactcheck, + updateMarks, updateRender, updateVariants, } from "./manifest.mjs"; -import { CLAIM_KNOBS, STAMP_KNOB_DEFAULTS, VARIANTS_DEFAULT, stampingEntryId, variantsOf } from "./knobs.mjs"; +import { CLAIM_KNOBS, STAMP_KNOB_DEFAULTS, VARIANTS_DEFAULT, rawMarksOf, stampingEntryId, variantsOf } from "./knobs.mjs"; import { variantsSteps } from "./driver.mjs"; import { outDirOf, variantsState } from "./variantsView.mjs"; export const AUDIO_KNOBS = Object.freeze(["offset", "gain", "fadeIn", "fadeOut"]); -const SET_KEYS = [...CLAIM_KNOBS.map((k) => `claim.${k}`), ...AUDIO_KNOBS.map((k) => `audio.${k}`), "layout"]; +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}`), "layout"]; export const SET_USAGE = [ - "usage: umtool set <project> <clip> key=value … [--json]", + "usage: umtool set <project> <clip> key=value … [--mark <id>] [--json]", ` keys: ${SET_KEYS.join(" ")}`, " claim.at is a SOURCE second inside the clip's window: the stamp lands and the count steps there", " (read from the last clip carrying the claim); claim.hold s (0.5–10); claim.stamp true|false;", - " claim.count 1–99; claim.label ≤ 20 chars. audio.offset ms (-2000…2000, + = sound later),", + " claim.count 1–99; claim.label ≤ 20 chars. The claim.* keys set the clip's first mark, or --mark <id>'s.", + " Marks (a clip may carry up to 8, each its own stamp and count): mark.add=<verdict>[@<sec>] adds one", + " (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).", + " audio.offset ms (-2000…2000, + = sound later),", " audio.gain dB (-20…20), audio.fadeIn / audio.fadeOut s (0–5). layout=finale|clip (the deck's finale", " layout for this clip; clip is the default). `key=` clears it (the default).", ].join("\n"); @@ -88,7 +98,7 @@ const splitArgs = (args) => { const flags = new Map(); for (let i = 0; i < args.length; i += 1) { const a = args[i]; - if (a === "--take") { + if (a === "--take" || a === "--mark") { flags.set(a, args[i + 1] ?? ""); i += 1; } else if (a.startsWith("--")) flags.set(a, true); @@ -119,8 +129,13 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso return 2; } const project = await projectOf(projectArg, root); + const markFlag = flags.get("--mark"); + const mark = typeof markFlag === "string" && markFlag ? markFlag : null; + if (flags.has("--mark") && !mark) throw new CliError("--mark needs a mark id"); const claim = {}; const audio = {}; + /** @type {Record<string, unknown>[]} the marks changes, in the order given */ + const markChanges = []; /** @type {Record<string, unknown>} */ const entryPatch = {}; for (const [key, value] of parseAssignments(rest)) { @@ -129,15 +144,27 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso entryPatch.layout = value; continue; } + if (MARK_KEYS.includes(key)) { + markChanges.push(markChangeOf(key, value, mark)); + continue; + } const [group, k] = key.split("."); (group === "claim" ? claim : audio)[k] = value; } if (Object.keys(audio).length) entryPatch.audio = audio; const results = {}; let notes = null; + for (const change of markChanges) { + const token = await manifestToken(project.dir); + const { result, editNotes } = await withEditNotes(project, () => updateMarks(project.dir, clipId, change, { token })); + results.marks = result.marks; + results.stampsOnByMark = result.stampsOn; + if (result.added) (results.added ??= []).push(result.added); + notes = editNotes ?? notes; + } if (Object.keys(claim).length) { const token = await manifestToken(project.dir); - const { result, editNotes } = await withEditNotes(project, () => updateClaimKnobs(project.dir, clipId, claim, { token })); + const { result, editNotes } = await withEditNotes(project, () => updateClaimKnobs(project.dir, clipId, claim, { token, mark })); results.claim = result.claim; results.stamps = result.stamps; results.stampsOn = result.stampsOn; @@ -154,6 +181,10 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso out(JSON.stringify({ ok: true, clip: clipId, ...results, editNotes: notes }, null, 2)); return 0; } + if (results.marks) { + out(`${clipId}: ${results.marks.length ? `marks ${results.marks.map((m) => markLine(m, results.stampsOnByMark?.[m.id], clipId)).join(" | ")}` : "no marks"}`); + if (results.added) out(` added ${results.added.join(", ")}`); + } if (results.claim) { out(`${clipId}: claim ${JSON.stringify(results.claim)}`); if (!results.stamps) out(` NOTE: ${results.claim.id} stamps on ${results.stampsOn} (the last clip carrying it) — these knobs are read there, not here`); @@ -171,6 +202,44 @@ export async function setCommand(args, { root = REPORTS_ROOT, out = (s) => conso const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v); +/** + * One `mark.*` / `marks` assignment as an updateMarks change: `mark.add=Episodes@190.2` + * (or a JSON object), `mark.remove=<id>`, `mark.verdict=<verdict>` (for --mark's + * id, else the clip's first mark), `marks=<json list>` (`marks=` none). + */ +export function markChangeOf(key, value, mark = null) { + switch (key) { + case "marks": + if (value !== null && !Array.isArray(value)) throw new CliError("marks= takes a JSON list of marks, or nothing for none"); + return { set: value }; + case "mark.add": { + if (isObj(value)) return { add: value }; + if (typeof value !== "string" || !value.trim()) throw new CliError("mark.add= takes <verdict>[@<source second>], or a JSON object"); + const [verdict, at, ...more] = value.split("@"); + if (more.length) throw new CliError(`mark.add=${value}: one @ (the source second)`); + if (at === undefined || at === "") return { add: { verdict: verdict.trim() } }; + const s = Number(at); + if (!Number.isFinite(s)) throw new CliError(`mark.add=${value}: ${at} is not a source second`); + return { add: { verdict: verdict.trim(), at: s } }; + } + case "mark.remove": + if (value === null) throw new CliError("mark.remove= takes the mark's id"); + return { remove: String(value) }; + case "mark.verdict": + if (value === null) throw new CliError("mark.verdict= takes a verdict (its name or this cut's label)"); + return { mark, verdict: String(value) }; + default: + throw new CliError(`${key} is not a marks key`); + } +} + +/** One mark for a line: `id VERDICT at=… (stamps on x)`. */ +function markLine(m, stampsOn, clipId) { + const knobs = CLAIM_KNOBS.filter((k) => m[k] !== undefined).map((k) => `${k}=${JSON.stringify(m[k])}`); + const where = stampsOn && stampsOn !== clipId ? ` (stamps on ${stampsOn})` : ""; + return [m.id, m.verdict, ...knobs].join(" ") + where; +} + /** Set (or with null, remove) `a.b.c` in a copy of `obj`, pruning objects left empty. */ function setPath(obj, keys, value) { const root = structuredClone(isObj(obj) ? obj : {}); @@ -327,14 +396,18 @@ export function knobsOf(manifest) { const clips = []; for (const e of timeline) { if (!isObj(e)) continue; - const claim = isObj(e.claim) ? Object.fromEntries(CLAIM_KNOBS.filter((k) => e.claim[k] !== undefined).map((k) => [k, e.claim[k]])) : null; + // The first mark is `claim…` (as before marks); two or more are `marks` too. + const all = rawMarksOf(e).filter(isObj); + const first = all[0] ?? null; + const claim = first ? Object.fromEntries(CLAIM_KNOBS.filter((k) => first[k] !== undefined).map((k) => [k, first[k]])) : null; const audio = isObj(e.audio) ? e.audio : null; - if ((claim && Object.keys(claim).length) || audio || isObj(e.claim) || typeof e.layout === "string") { + if ((claim && Object.keys(claim).length) || audio || first || typeof e.layout === "string") { clips.push({ id: e.id, ...(e.variant ? { variant: e.variant } : {}), - ...(isObj(e.claim) ? { claimId: e.claim.id, verdict: e.claim.verdict, stamps: stampingEntryId(manifest, e.claim.id) === e.id } : {}), + ...(first ? { claimId: first.id, verdict: first.verdict, stamps: stampingEntryId(manifest, first.id) === e.id } : {}), ...(claim && Object.keys(claim).length ? { claim } : {}), + ...(all.length > 1 ? { marks: all.map((m) => ({ ...m, stampsOn: stampingEntryId(manifest, m.id) })) } : {}), ...(audio ? { audio } : {}), ...(typeof e.layout === "string" ? { layout: e.layout } : {}), }); @@ -361,8 +434,11 @@ export function knobsLines(manifest) { const lines = []; for (const c of k.clips) { const bits = []; - if (c.claimId) bits.push(`claim ${c.claimId} ${c.verdict}${c.stamps ? " (stamps here)" : ""}`); - if (c.claim) bits.push(Object.entries(c.claim).map(([a, b]) => `${a}=${JSON.stringify(b)}`).join(" ")); + if (c.marks) bits.push(`marks ${c.marks.map((m) => markLine(m, m.stampsOn, c.id) + (m.stampsOn === c.id ? " (stamps here)" : "")).join(" | ")}`); + else { + if (c.claimId) bits.push(`claim ${c.claimId} ${c.verdict}${c.stamps ? " (stamps here)" : ""}`); + if (c.claim) bits.push(Object.entries(c.claim).map(([a, b]) => `${a}=${JSON.stringify(b)}`).join(" ")); + } if (c.layout) bits.push(`layout ${c.layout}`); if (c.audio) bits.push(`audio ${Object.entries(c.audio).map(([a, b]) => `${a}=${b}`).join(" ")}`); lines.push(` ${String(c.id).padEnd(8)} ${bits.join(" · ")}`); diff --git a/umtool/lib/report/manifest.mjs b/umtool/lib/report/manifest.mjs @@ -40,7 +40,10 @@ import { applySectionEnter } from "./sections.mjs"; import { normalizeClaim, validateClaims } from "umtool-report-to-video/factcheck"; import { validateFinaleEntries } from "umtool-report-to-video/finale"; import { validateClipAudio } from "umtool-report-to-video/clip-audio"; -import { CLAIM_KNOBS, claimKnobsOf, claimKnobValue, normalizeClaimKnobPatch, stampingEntryId, variantsProblems } from "./knobs.mjs"; +import { + CLAIM_KNOBS, CLAIM_MARKS_MAX, claimKnobsOf, claimKnobValue, freshMarkId, marksCopyOf, normalizeClaimKnobPatch, rawMarksOf, setMarks, stampingEntryId, + variantsProblems, verdictOfInput, +} from "./knobs.mjs"; import { validateNarration } from "umtool-report-to-video/narration"; import { parseMuteFrom } from "./playback.mjs"; import { DELIVERABLES_MODES } from "./storage.mjs"; @@ -347,13 +350,16 @@ export async function updateClip(dir, clipId, patch, { token = null, edit = "tri // The source second its stamp lands, on the entry's clock: a window save // that leaves it outside is refused, as the mute mark's is, rather than // keeping a mark that no longer says anything about the clip. - if ((patch.start !== undefined || patch.end !== undefined) && isObj(entry.claim) && typeof entry.claim.at === "number") { - if (entry.claim.at < entry.start || entry.claim.at > entry.end) { + if (patch.start !== undefined || patch.end !== undefined) { + const many = Array.isArray(entry.claims); + rawMarksOf(entry).forEach((m, k) => { + if (!isObj(m) || typeof m.at !== "number" || (m.at >= entry.start && m.at <= entry.end)) return; + const name = many ? `the mark ${m.id}'s second (claims[${k}].at ${m.at})` : `the stamp's second (claim.at ${m.at})`; throw new Error( - `the stamp's second (claim.at ${entry.claim.at}) must lie inside the window ` + - `${entry.start}–${entry.end} — widen the window, or clear claim.at`, + `${name} must lie inside the window ` + + `${entry.start}–${entry.end} — widen the window, or clear ${many ? "that mark's at" : "claim.at"}`, ); - } + }); } // ---- the clip's sound (video knobs) ------------------------------------- @@ -592,6 +598,7 @@ export async function splitClip(dir, clipId, at, { token = null, quotes = {}, no if (typeof b.cite === "number") b.cite = t; if (b.muteFrom != null && b.muteFrom < t) delete b.muteFrom; delete b.claim; + delete b.claims; const qb = textOr(quotes.second, b.quote ?? null); if (qb) b.quote = qb; else delete b.quote; @@ -933,8 +940,13 @@ export async function updateOnscreen(dir, onscreen, { token = null } = {}) { // A row that does not name the knobs keeps the entry's while the claim // stays the same claim: the On-screen table edits the id and verdict, // the clip editor the knobs, and neither may drop the other's work. - const keep = c && !withKnobs.has(e.id) && isObj(e.claim) && e.claim.id === c.id ? claimKnobsOf(e.claim) : {}; - if (c) e.claim = { ...c, ...keep }; + // On an entry with marks (`claims`) the row is its FIRST mark; the + // others stay as they are. + const marks = marksCopyOf(e); + const first = marks[0]; + const keep = c && !withKnobs.has(e.id) && isObj(first) && first.id === c.id ? claimKnobsOf(first) : {}; + if (marks.length > 1) setMarks(e, c ? [{ ...c, ...keep }, ...marks.slice(1)] : marks.slice(1)); + else if (c) e.claim = { ...c, ...keep }; else delete e.claim; } } @@ -1415,6 +1427,7 @@ export async function duplicateEntry(dir, id, { token = null, at = null } = {}) const copy = JSON.parse(JSON.stringify(m.timeline[i])); copy.id = freshEntryId(m.timeline, `${id}-copy`); delete copy.claim; + delete copy.claims; m.timeline.splice(i + 1, 0, copy); return { id: copy.id, at: i + 1, entry: copy }; }); @@ -1737,13 +1750,16 @@ export async function updateFactcheck(dir, factcheck, { token = null } = {}) { * The build reads the knobs of the entry that STAMPS the claim -- the last * carrying its id -- so `stamps` in the answer says whether this one does. * + * On an entry with MARKS (`claims`), `mark` names the one patched (its id); + * without it, the first. + * * @param {string} dir * @param {string} entryId * @param {Record<string, unknown>} patch - * @param {{ token?: string | null }} [opts] + * @param {{ token?: string | null, mark?: string | null }} [opts] * @returns {Promise<{ claim: Record<string, unknown>, stamps: boolean, stampsOn: string | null, token: string | null }>} */ -export async function updateClaimKnobs(dir, entryId, patch, { token = null } = {}) { +export async function updateClaimKnobs(dir, entryId, patch, { token = null, mark = null } = {}) { const next = normalizeClaimKnobPatch(patch); return withManifestLock(async () => { const current = await manifestToken(dir); @@ -1751,20 +1767,145 @@ export async function updateClaimKnobs(dir, entryId, patch, { token = null } = { const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); const entries = (manifest.timeline ?? []).filter((e) => isObj(e) && e.id === entryId); if (!entries.length) throw new Error(`no timeline entry with id ${entryId}`); - if (!isObj(entries[0].claim)) throw new Error(`${entryId} carries no claim — give it one (the On-screen table's claim column) before its stamp's knobs`); + const pick = (e) => rawMarksOf(e).find((m) => isObj(m) && (mark === null || m.id === mark)); + if (!rawMarksOf(entries[0]).some(isObj)) throw new Error(`${entryId} carries no claim — add a mark (the clip editor's Marks, or mark.add=) before its stamp's knobs`); + if (!pick(entries[0])) throw new Error(`${entryId} carries no mark ${mark} (its marks: ${rawMarksOf(entries[0]).map((m) => m?.id).join(", ")})`); + // Edited in place: a lone claim keeps its keys' order, so its bytes are what they were. for (const e of entries) { - if (!isObj(e.claim)) continue; + const m = pick(e); + if (!m) continue; for (const [k, v] of Object.entries(next)) { - if (v === null) delete e.claim[k]; - else e.claim[k] = v; + if (v === null) delete m[k]; + else m[k] = v; } } - // The renderer's own check -- each knob, and `at` inside the entry's window -- on this entry's rows. + // The renderer's own check -- each knob, `at` inside the entry's window, no two stamps over each other -- on this entry's rows. const bad = validateClaims(manifest).filter((e) => e.includes(`(${entryId})`)); if (bad.length) throw new Error(`${bad.join("; ")} — nothing was written`); const nextToken = await writeManifestAtomic(dir, manifest); - const stampsOn = stampingEntryId(manifest, entries[0].claim.id); - return { claim: entries[0].claim, stamps: stampsOn === entryId, stampsOn, token: nextToken }; + const claim = pick(entries[0]); + const stampsOn = stampingEntryId(manifest, claim.id); + return { claim, stamps: stampsOn === entryId, stampsOn, token: nextToken }; + }); +} + +/** + * Change ONE entry's MARKS (plans/clip-marks.md) -- every entry carrying the + * id (a variant's twin) alike. `change` is one of: + * + * { add: { verdict, at?, id?, hold?, stamp?, count?, label? } } + * a new mark after the others; its id a NEW one unless given + * (freshMarkId: the entry's id, else `<id>.2`, …); `verdict` its name + * or its label in this cut ("Episodes") + * { remove: "<mark id>" } + * { mark: "<mark id>" | null, verdict } the mark's verdict (null: the + * first mark's) -- on every entry carrying the id (one claim, one verdict) + * { set: [mark, …] | null } all of them (null or []: none) + * + * One mark is stored as `claim`, two or more as `claims` (≤ 8). Refused, with + * the renderer's sentence, when the result would not build: a mark outside + * the window, two stamps over each other, one id given two verdicts. + * + * @param {string} dir + * @param {string} entryId + * @param {Record<string, unknown>} change + * @param {{ token?: string | null }} [opts] + * @returns {Promise<{ marks: Record<string, unknown>[], added: string | null, stampsOn: Record<string, string | null>, token: string | null }>} + */ +export async function updateMarks(dir, entryId, change, { token = null } = {}) { + if (!isObj(change)) throw new Error("a marks change is { add } | { remove } | { mark, verdict } | { set }"); + const kinds = ["add", "remove", "mark", "set"].filter((k) => k in change); + if (kinds.length !== 1) throw new Error("a marks change names exactly one of add, remove, mark (with verdict), set"); + return withManifestLock(async () => { + const current = await manifestToken(dir); + if (token !== null && current !== token) throw new StaleToken(token, current); + const manifest = JSON.parse(await readFile(manifestFile(dir), "utf8")); + const entries = (manifest.timeline ?? []).filter((e) => isObj(e) && e.id === entryId); + if (!entries.length) throw new Error(`no timeline entry with id ${entryId}`); + if (entries[0].type === "teaser") throw new Error(`${entryId} is a teaser: a teaser is not evidence for a claim`); + const before = new Set(validateClaims(manifest)); + let added = null; + let marks = marksCopyOf(entries[0]); + switch (kinds[0]) { + case "add": { + const a = change.add; + if (!isObj(a)) throw new Error("add is { verdict, at?, id?, hold?, stamp?, count?, label? }"); + if (marks.length >= CLAIM_MARKS_MAX) throw new Error(`${entryId} carries ${marks.length} marks already (at most ${CLAIM_MARKS_MAX})`); + const verdict = verdictOfInput(a.verdict, manifest.render); + const id = a.id === undefined || a.id === null || a.id === "" ? freshMarkId(manifest, entryId) : String(a.id).trim(); + if (marks.some((m) => m.id === id)) throw new Error(`${entryId} carries the mark ${id} already`); + /** @type {Record<string, unknown>} */ + const mark = { id, verdict }; + for (const k of Object.keys(a)) { + if (k !== "id" && k !== "verdict" && !CLAIM_KNOBS.includes(k)) throw new Error(`add.${k} is not a mark field (id, verdict, ${CLAIM_KNOBS.join(", ")})`); + } + const given = Object.fromEntries(CLAIM_KNOBS.filter((k) => a[k] !== undefined && a[k] !== null && a[k] !== "").map((k) => [k, a[k]])); + const knobs = Object.keys(given).length ? normalizeClaimKnobPatch(given) : {}; + for (const [k, v] of Object.entries(knobs)) if (v !== null) mark[k] = v; + marks.push(normalizeClaim(mark)); + added = id; + break; + } + case "remove": { + const id = String(change.remove ?? ""); + if (!marks.some((m) => m.id === id)) throw new Error(`${entryId} carries no mark ${id}`); + marks = marks.filter((m) => m.id !== id); + break; + } + case "mark": { + // null: the entry's first mark. + const id = change.mark === null || change.mark === undefined ? String(marks[0]?.id ?? "") : String(change.mark); + if (!marks.some((m) => m.id === id)) throw new Error(`${entryId} carries no mark ${id}`); + const verdict = verdictOfInput(change.verdict, manifest.render); + // One claim, one verdict: every entry carrying the id. + for (const e of manifest.timeline) { + if (!isObj(e) || e.id === entryId) continue; + for (const m of rawMarksOf(e)) if (isObj(m) && m.id === id) m.verdict = verdict; + } + marks = marks.map((m) => (m.id === id ? { ...m, verdict } : m)); + break; + } + case "set": { + const v = change.set; + if (v === null || (Array.isArray(v) && !v.length)) marks = []; + else if (Array.isArray(v)) marks = normalizeMarksInput(v, manifest.render); + else throw new Error("set is a list of marks [{ id, verdict, … }], or null for none"); + break; + } + } + for (const e of entries) setMarks(e, marks.map((m) => ({ ...m }))); + // The renderer's own check: refused when this change adds a problem. + const bad = validateClaims(manifest).filter((x) => !before.has(x)); + if (bad.length) throw new Error(`${bad.join("; ")} — nothing was written`); + const nextToken = await writeManifestAtomic(dir, manifest); + const stored = marksCopyOf(entries[0]); + return { + marks: stored, + added, + stampsOn: Object.fromEntries(stored.map((m) => [m.id, stampingEntryId(manifest, m.id)])), + token: nextToken, + }; + }); +} + +/** A list of marks as typed (a verdict by its name or label, knobs as typed), normalised. */ +function normalizeMarksInput(list, render) { + if (list.length > CLAIM_MARKS_MAX) throw new Error(`claims holds ${list.length} marks (at most ${CLAIM_MARKS_MAX})`); + return list.map((m, k) => { + if (!isObj(m)) throw new Error(`claims[${k}] must be { id, verdict, … }`); + /** @type {Record<string, unknown>} */ + const mark = { id: typeof m.id === "string" ? m.id.trim() : m.id, verdict: verdictOfInput(m.verdict, render) }; + for (const k2 of Object.keys(m)) { + if (k2 === "id" || k2 === "verdict") continue; + if (!CLAIM_KNOBS.includes(k2)) throw new Error(`claims[${k}].${k2} is not a mark field (id, verdict, ${CLAIM_KNOBS.join(", ")})`); + const v = claimKnobValue(k2, m[k2]); + if (v !== null) mark[k2] = v; + } + try { + return normalizeClaim(mark); + } catch (e) { + throw new Error(String(e instanceof Error ? e.message : e).replace(/^claim\b/, `claims[${k}]`)); + } }); } diff --git a/umtool/lib/report/marks.test.mjs b/umtool/lib/report/marks.test.mjs @@ -0,0 +1,202 @@ +// MARKS, the writers (plans/clip-marks.md): updateMarks (add, remove, a +// verdict, all), updateClaimKnobs on one mark, the On-screen table on the +// first, the window rule over every mark, and `umtool set` / `umtool show`. +// One mark is written `claim`, two or more `claims`; a mark added and removed +// again leaves the file the bytes it was. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +const ROOT = await mkdtemp(path.join(tmpdir(), "umtool-marks-")); +process.env.REPORTS_DIR = ROOT; + +const { MANIFEST_NAME, StaleToken, manifestToken, updateClaimKnobs, updateClip, updateMarks, updateOnscreen } = await import("./manifest.mjs"); +const { freshMarkId, markVerdictsOf, setMarks, verdictOfInput } = await import("./knobs.mjs"); +const { knobsLines, knobsOf, setCommand } = await import("./knobsCli.mjs"); + +const HUCK_FC = { + verdicts: { + CONTRADICTED: { label: "Grift", color: "#e3b23c", stampLabel: "Grift" }, + CORROBORATED: { label: "Episodes", color: "#6fa8dc", stampLabel: "Seizure" }, + }, + stamp: { seconds: 3 }, +}; +const base = () => ({ + schemaVersion: 1, + slug: "huck", + title: "Huck", + provenance: { siteOrigin: "https://example.test", channelSlug: "chan" }, + render: { width: 1920, height: 1080, fps: 30, transition: 0.5, chrome: { engine: "hyperframes", layout: "deck", factcheck: HUCK_FC } }, + timeline: [ + { type: "clip", id: "first", video: "v1", start: 171.33, end: 211.78, claim: { id: "first", verdict: "CORROBORATED", at: 188.41 }, quote: "q" }, + { type: "clip", id: "er", video: "v2", start: 275.2, end: 304.21, claim: { id: "er", verdict: "CORROBORATED" } }, + { type: "clip", id: "dozen", video: "v3", start: 336.96, end: 385.89, claim: { id: "er", verdict: "CORROBORATED", at: 349.25 } }, + { type: "clip", id: "fed", video: "v4", start: 6117, end: 6155.63 }, + ], +}); + +let n = 0; +async function project(manifest = base()) { + const name = `p${(n += 1)}`; + const dir = path.join(ROOT, name); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, MANIFEST_NAME), JSON.stringify(manifest, null, 2) + "\n"); + return { dir, name }; +} +const readRaw = (dir) => readFile(path.join(dir, MANIFEST_NAME), "utf8"); +const read = async (dir) => JSON.parse(await readRaw(dir)); +const entry = (m, id) => m.timeline.find((e) => e.id === id); + +test.after(() => rm(ROOT, { recursive: true, force: true })); + +test("knobs: setMarks writes one as claim, two as claims, none as neither -- in the marks' place among the keys", () => { + const e = { id: "c", claim: { id: "a", verdict: "PARTLY" }, quote: "q" }; + setMarks(e, [{ id: "a", verdict: "PARTLY" }, { id: "b", verdict: "PARTLY" }]); + assert.deepEqual(Object.keys(e), ["id", "claims", "quote"]); + setMarks(e, [{ id: "a", verdict: "PARTLY" }]); + assert.deepEqual(Object.keys(e), ["id", "claim", "quote"]); + setMarks(e, []); + assert.deepEqual(Object.keys(e), ["id", "quote"]); + setMarks(e, [{ id: "z", verdict: "PARTLY" }]); + assert.deepEqual(Object.keys(e), ["id", "quote", "claim"]); +}); + +test("knobs: a new mark's id is the clip's when free, else <clip>.2, .3 …; a verdict by name or this cut's label", () => { + const m = base(); + assert.equal(freshMarkId(m, "fed"), "fed"); + assert.equal(freshMarkId(m, "first"), "first.2"); + m.timeline[0].claims = [{ id: "first", verdict: "CORROBORATED" }, { id: "first.2", verdict: "CORROBORATED" }]; + delete m.timeline[0].claim; + assert.equal(freshMarkId(m, "first"), "first.3"); + assert.equal(verdictOfInput("Episodes", m.render), "CORROBORATED"); + assert.equal(verdictOfInput("grift", m.render), "CONTRADICTED"); + assert.equal(verdictOfInput("Seizure", m.render), "CORROBORATED", "the stamp word too"); + assert.equal(verdictOfInput("partly", m.render), "PARTLY"); + assert.throws(() => verdictOfInput("nonsense", m.render), /"nonsense" is not a verdict: CORROBORATED \(Episodes\)/); + const v = markVerdictsOf(m); + assert.deepEqual(v.slice(0, 2).map((x) => [x.verdict, x.label, x.stampLabel, x.stock]), [["CORROBORATED", "Episodes", "Seizure", true], ["CONTRADICTED", "Grift", "Grift", true]]); + assert.equal(v.length, 5); +}); + +test("updateMarks add: a second mark on the clip gets a NEW id and makes claims; add then remove is the bytes it was", async () => { + const { dir } = await project(); + const before = await readRaw(dir); + const r = await updateMarks(dir, "first", { add: { verdict: "Episodes", at: 180.5 } }, { token: await manifestToken(dir) }); + assert.equal(r.added, "first.2"); + const e = entry(await read(dir), "first"); + assert.equal("claim" in e, false); + assert.deepEqual(e.claims, [{ id: "first", verdict: "CORROBORATED", at: 188.41 }, { id: "first.2", verdict: "CORROBORATED", at: 180.5 }]); + assert.deepEqual(r.stampsOn, { first: "first", "first.2": "first" }); + await updateMarks(dir, "first", { remove: "first.2" }); + assert.equal(await readRaw(dir), before, "back to one mark: `claim`, byte for byte"); + // A first mark on a clip with none takes the clip's id. + const f = await updateMarks(dir, "fed", { add: { verdict: "CONTRADICTED", at: 6149.65, count: 2, stamp: true } }); + assert.equal(f.added, "fed"); + assert.deepEqual(entry(await read(dir), "fed").claim, { id: "fed", verdict: "CONTRADICTED", at: 6149.65, count: 2 }); +}); + +test("updateMarks: refuses overlapping stamps, an at outside the window, a ninth mark, a stale token -- the file as it was", async () => { + const { dir } = await project(); + const before = await readRaw(dir); + await assert.rejects( + updateMarks(dir, "first", { add: { verdict: "CORROBORATED", at: 189.5 } }), + /the marks first \(at 188\.41\) and first\.2 \(at 189\.5\) overlap -- first's stamp stays 3 s; land first\.2 at 191\.41 or later/, + ); + await assert.rejects(updateMarks(dir, "first", { add: { verdict: "CORROBORATED", at: 250 } }), /claims\[1\]\.at 250 is outside the clip's window 171\.33–211\.78/); + await assert.rejects(updateMarks(dir, "first", { add: { verdict: "nope" } }), /is not a verdict/); + await assert.rejects(updateMarks(dir, "first", { add: { verdict: "PARTLY", colour: 1 } }), /add\.colour is not a mark field/); + await assert.rejects(updateMarks(dir, "first", { remove: "zz" }), /carries no mark zz/); + await assert.rejects(updateMarks(dir, "first", { add: { verdict: "PARTLY" } }, { token: "stale" }), StaleToken); + await assert.rejects(updateMarks(dir, "first", { add: {}, remove: "x" }), /exactly one of/); + assert.equal(await readRaw(dir), before); + const eight = Array.from({ length: 8 }, (_, i) => ({ id: `m${i}`, verdict: "PARTLY" })); + await updateMarks(dir, "fed", { set: eight }); + await assert.rejects(updateMarks(dir, "fed", { add: { verdict: "PARTLY" } }), /carries 8 marks already \(at most 8\)/); +}); + +test("updateMarks set / mark-verdict: all at once (null: none); a verdict changes on every clip carrying the id", async () => { + const { dir } = await project(); + await updateMarks(dir, "first", { set: [{ id: "first", verdict: "Episodes", at: 188.41 }, { id: "first.0", verdict: "Episodes", at: "175", label: "EARLIER" }] }); + assert.deepEqual(entry(await read(dir), "first").claims[1], { id: "first.0", verdict: "CORROBORATED", at: 175, label: "EARLIER" }); + await assert.rejects(updateMarks(dir, "first", { set: [{ id: "a", verdict: "PARTLY", when: 1 }] }), /claims\[0\]\.when is not a mark field/); + // "er" is one event on two clips: its verdict moves on both. + await updateMarks(dir, "er", { mark: "er", verdict: "Grift" }); + const m = await read(dir); + assert.equal(entry(m, "er").claim.verdict, "CONTRADICTED"); + assert.equal(entry(m, "dozen").claim.verdict, "CONTRADICTED"); + await updateMarks(dir, "first", { set: null }); + const e = entry(await read(dir), "first"); + assert.equal("claim" in e || "claims" in e, false); +}); + +test("updateClaimKnobs: `mark` names the mark (default the first); a lone claim edited in place", async () => { + const { dir } = await project(); + await updateMarks(dir, "first", { add: { verdict: "CORROBORATED", at: 195 } }); + const r = await updateClaimKnobs(dir, "first", { count: 2, hold: 2 }, { mark: "first.2" }); + assert.deepEqual(r.claim, { id: "first.2", verdict: "CORROBORATED", at: 195, count: 2, hold: 2 }); + assert.equal(r.stamps, true); + const r1 = await updateClaimKnobs(dir, "first", { label: "ONE" }); + assert.equal(r1.claim.id, "first"); + await assert.rejects(updateClaimKnobs(dir, "first", { count: 2 }, { mark: "zz" }), /carries no mark zz/); + // Moving the second mark onto the first's stamp is refused. + await assert.rejects(updateClaimKnobs(dir, "first", { at: 189 }, { mark: "first.2" }), /overlap/); +}); + +test("updateClip: a window that leaves any mark outside is refused, naming the mark", async () => { + const { dir } = await project(); + await updateMarks(dir, "first", { add: { verdict: "CORROBORATED", at: 205 } }); + await assert.rejects(updateClip(dir, "first", { end: 200 }), /the mark first\.2's second \(claims\[1\]\.at 205\) must lie inside the window 171\.33–200/); + await updateClip(dir, "first", { end: 206 }); +}); + +test("updateOnscreen: the table's claim is the FIRST mark; the others stay", async () => { + const { dir } = await project(); + await updateMarks(dir, "first", { add: { verdict: "CORROBORATED", at: 195 } }); + await updateOnscreen(dir, { first: { title: "First", claim: { id: "first", verdict: "CORROBORATED" } } }); + let e = entry(await read(dir), "first"); + assert.deepEqual(e.claims.map((m) => [m.id, m.at]), [["first", 188.41], ["first.2", 195]], "the first's knobs kept, the second untouched"); + await updateOnscreen(dir, { first: { title: "First", claim: null } }); + e = entry(await read(dir), "first"); + assert.deepEqual(e.claim, { id: "first.2", verdict: "CORROBORATED", at: 195 }, "the first removed: one mark left, written as claim"); +}); + +test("previewSchedule: a clip's marks stamp in the On-screen preview; a drafted row replaces only the first", async () => { + const { previewSchedule } = await import("./onscreen.mjs"); + const m = base(); + setMarks(m.timeline[0], [{ id: "first", verdict: "CORROBORATED", at: 188.41 }, { id: "first.2", verdict: "CONTRADICTED", at: 200 }]); + const ids = (s) => s.factcheck.stamps.map((x) => x.claim); + const plain = previewSchedule({ variantManifest: m, built: null, draft: new Map(), metas: [] }); + assert.deepEqual(ids(plain), ["first", "first.2", "er"]); + const drafted = previewSchedule({ variantManifest: m, built: null, draft: new Map(), metas: [], claimsDraft: new Map([["first", { id: "lead", verdict: "PARTLY" }]]) }); + assert.ok(ids(drafted).includes("lead") && ids(drafted).includes("first.2") && !ids(drafted).includes("first")); +}); + +test("umtool set: mark.add=<verdict>@<sec>, mark.remove, mark.verdict, marks=<json>, claim.* --mark; show prints the marks", async () => { + const { dir, name } = await project(); + const lines = []; + const run = (...args) => setCommand(args, { root: ROOT, out: (s) => lines.push(s), err: (s) => lines.push(`ERR ${s}`) }); + assert.equal(await run(name, "first", "mark.add=Episodes@176.2"), 0); + assert.match(lines.at(-2), /^first: marks first CORROBORATED at=188\.41 \| first\.2 CORROBORATED at=176\.2$/); + assert.match(lines.at(-1), /added first\.2/); + assert.equal(await run(name, "first", "claim.count=2", "--mark", "first.2"), 0); + assert.equal(entry(await read(dir), "first").claims[1].count, 2); + assert.equal(await run(name, "first", "mark.verdict=Grift", "--mark", "first.2"), 0); + assert.equal(entry(await read(dir), "first").claims[1].verdict, "CONTRADICTED"); + const show = knobsLines(await read(dir)).find((l) => l.trim().startsWith("first ")); + assert.match(show, /marks first CORROBORATED at=188\.41 \(stamps here\) \| first\.2 CONTRADICTED at=176\.2 count=2 \(stamps here\)/); + assert.equal(knobsOf(await read(dir)).clips.find((c) => c.id === "first").marks.length, 2); + assert.equal(await run(name, "first", "mark.add=Episodes@177"), 1); + assert.match(lines.at(-1), /^ERR .*overlap/); + assert.equal(await run(name, "first", "mark.add=Episodes@1@2"), 2); + assert.equal(await run(name, "first", "mark.remove=first.2"), 0); + assert.deepEqual(entry(await read(dir), "first").claim, { id: "first", verdict: "CORROBORATED", at: 188.41 }); + assert.equal(await run(name, "fed", 'marks=[{"id":"fed","verdict":"Grift","at":6149.65},{"id":"fed.2","verdict":"Episodes","at":6130}]'), 0); + assert.equal(entry(await read(dir), "fed").claims.length, 2); + assert.equal(await run(name, "fed", "marks="), 0); + assert.equal("claims" in entry(await read(dir), "fed"), false); + assert.match(lines.at(-1), /fed: no marks/); +}); diff --git a/umtool/lib/report/onscreen.mjs b/umtool/lib/report/onscreen.mjs @@ -34,7 +34,8 @@ import { resolveDeck, roundPosts, } from "umtool-report-to-video/deck"; -import { claimOf, roundStamps, stampSchedule } from "umtool-report-to-video/factcheck"; +import { marksOf, rawMarksOf, roundStamps, stampSchedule } from "umtool-report-to-video/factcheck"; +import { setMarks } from "./knobs.mjs"; import { channelsDirFor, cuePathFor, @@ -197,8 +198,9 @@ export function previewSchedule({ variantManifest, built, draft, metas, postsDra } if (claimsDraft.has(e.id)) { const c = claimsDraft.get(e.id); - const { claim: _c, ...rest } = out; - out = c ? { ...rest, claim: c } : rest; + // A row is the entry's FIRST mark; its others stay (plans/clip-marks.md). + const others = rawMarksOf(out).slice(1); + out = setMarks({ ...out }, c ? [c, ...others] : others); } return out; }; @@ -236,14 +238,14 @@ export function previewSchedule({ variantManifest, built, draft, metas, postsDra const moves = placed.length && !feed ? footageMoves({ posts: placed, segments, render }) : []; // The claims as they are NOW, stamped over the build's segments. const claimed = segments.map((s, i) => { - const { claim: _c, ...bare } = s; - const c = claimOf(patchedEntries[i]); - return c ? { ...bare, claim: c } : bare; + const { claim: _c, claims: _cs, ...bare } = s; + const marks = marksOf(patchedEntries[i]); + return marks.length ? { ...bare, claim: marks[0], ...(marks.length > 1 ? { claims: marks } : {}) } : bare; }); // A claim stamped at a source second (`claim.at`): the play window's start // stands in for the cut record's (the build's is exact; snapping moves it). const stamps = stampSchedule({ - segments: claimed.map((s, i) => (s.claim?.at !== undefined + segments: claimed.map((s, i) => (marksOf(patchedEntries[i]).some((c) => c.at !== undefined) ? { ...s, sourceFrom: s.sourceFrom ?? playWindow(patchedEntries[i], render).from } : s)), D: built.transition, total, render, diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -145,7 +145,7 @@ import { } from "./deck.mjs"; // The effects region (`render.chrome.fx`, release 35): pure, in fx.mjs. import { fxOn, fxQuoteSpan, resolveFx, fxWhipJoins, fxWipeJoins, fxWordsOf, fxZoomJoins, validateFxEntries } from "./fx.mjs"; -import { claimOf, stampsDrawn, validateClaims } from "./factcheck.mjs"; +import { marksOf, stampsDrawn, validateClaims } from "./factcheck.mjs"; import { AUDIO_ON_CLOCK, clipAudioFilters, clipAudioOf, offsetWindow, validateClipAudioEntries } from "./clip-audio.mjs"; import { validateFinaleEntries } from "./finale.mjs"; import { SYNC_FILE, writeSyncReport } from "./sync-report.mjs"; @@ -4969,10 +4969,11 @@ export async function measureChromeSchedule({ manifest, entries, segments, D }) // claimed clip's segment really starts at, from its cut record (snapped, // room included). Read only then. let clipClock = null; - if (entries.some((e) => claimOf(e)?.at !== undefined)) { + const timedMarks = (e) => marksOf(e).some((c) => c.at !== undefined); + if (entries.some(timedMarks)) { clipClock = new Map(); for (let i = 0; i < entries.length; i += 1) { - if (claimOf(entries[i])?.at === undefined || !segments[i]) continue; + if (!timedMarks(entries[i]) || !segments[i]) continue; const rec = await readCutRecord(segments[i]).catch(() => null); if (Number.isFinite(rec?.start)) clipClock.set(entries[i].id, rec.start); } diff --git a/umtool/report-to-video/clip-marks.test.mjs b/umtool/report-to-video/clip-marks.test.mjs @@ -0,0 +1,260 @@ +// MARKS (plans/clip-marks.md): an entry's `claims: [mark, …]` -- each mark +// its own stamp and tally step at its own `at`. A lone `claim` is a list of +// one, and a cut whose entries carry one claim each schedules, stamps and +// counts exactly as it did before marks. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + CLAIM_MARKS_MAX, claimOf, marksOf, normalizeMarks, rawMarksOf, resolveFactcheck, roundStamps, STAMP_MOTION, + stampSchedule, tallyFinals, tallySteps, validateClaims, +} from "./factcheck.mjs"; +import { deckSchedule } from "./deck.mjs"; +import { deckCues } from "./chrome-deck.mjs"; +import { stampCues } from "./chrome-stamp.mjs"; + +const PALETTE = { bg: "#12101a", fg: "#f4f1ea", muted: "#9a93ad", accent: "#a97bff", amber: "#ffc860" }; +const CHROME = { engine: "hyperframes", layout: "deck", deck: {} }; +const RENDER = { width: 1920, height: 1080, fps: 30, transition: 0.5, palette: PALETTE, chrome: CHROME }; +const PROV = { siteOrigin: "https://example.test", channelSlug: "demo-channel" }; +const near = (a, b, msg) => assert.ok(Math.abs(a - b) < 1e-3, `${msg}: ${a} != ${b}`); + +// ---- the shape ---------------------------------------------------------------- + +test("normalizeMarks: each mark normalised; 1–8, one id once; errors named claims[k]", () => { + assert.deepEqual( + normalizeMarks([{ id: "a", verdict: "PARTLY", at: 12, count: 1 }, { id: "a.2", verdict: "CONTRADICTED", stamp: true }]), + [{ id: "a", verdict: "PARTLY", at: 12 }, { id: "a.2", verdict: "CONTRADICTED" }], + ); + assert.throws(() => normalizeMarks([]), /at least one mark/); + assert.throws(() => normalizeMarks({ id: "a" }), /claims must be a list/); + const nine = Array.from({ length: CLAIM_MARKS_MAX + 1 }, (_, i) => ({ id: `m${i}`, verdict: "PARTLY" })); + assert.throws(() => normalizeMarks(nine), /9 marks \(at most 8\)/); + assert.throws(() => normalizeMarks([{ id: "a", verdict: "PARTLY" }, { id: "a", verdict: "PARTLY" }]), /the mark a is on this entry twice/); + assert.throws(() => normalizeMarks([{ id: "a", verdict: "PARTLY" }, { id: "b", verdict: "PARTLY", hold: 0.1 }]), /^Error: claims\[1\]\.hold must be from 0\.5 to 10/); +}); + +test("marksOf / claimOf / rawMarksOf: a lone claim is a list of one; claimOf is the first mark", () => { + const one = { type: "clip", id: "c", claim: { id: "k", verdict: "PARTLY" } }; + const two = { type: "clip", id: "c", claims: [{ id: "k", verdict: "PARTLY" }, { id: "k.2", verdict: "CONTRADICTED", at: 3 }] }; + assert.deepEqual(marksOf(one), [{ id: "k", verdict: "PARTLY" }]); + assert.deepEqual(marksOf(two).map((m) => m.id), ["k", "k.2"]); + assert.deepEqual(claimOf(two), { id: "k", verdict: "PARTLY" }); + assert.deepEqual(marksOf({ ...two, type: "teaser" }), []); + assert.deepEqual(marksOf({ ...two, claim: { id: "x", verdict: "PARTLY" } }), [], "both set: none (validateClaims refuses it)"); + assert.equal(claimOf({ type: "clip", id: "c" }), null); + assert.equal(rawMarksOf(two).length, 2); + assert.equal(rawMarksOf({ claim: null }).length, 0); +}); + +// ---- validation ----------------------------------------------------------------- + +const clip = (id, start, end, extra) => ({ type: "clip", id, start, end, ...extra }); + +test("validateClaims: claim and claims together refused; a mark's at in the window; one id, one verdict across entries", () => { + const both = { timeline: [clip("c1", 0, 30, { claim: { id: "k", verdict: "PARTLY" }, claims: [{ id: "k", verdict: "PARTLY" }] })] }; + assert.match(validateClaims(both)[0], /timeline\[0\] \(c1\): claim and claims are both set/); + const out = { timeline: [clip("c1", 100, 130, { claims: [{ id: "a", verdict: "PARTLY", at: 101 }, { id: "b", verdict: "PARTLY", at: 131 }] })] }; + assert.match(validateClaims(out)[0], /timeline\[0\] \(c1\)\.claims\[1\]\.at 131 is outside the clip's window 100–130/); + const split = { + timeline: [ + clip("c1", 0, 30, { claims: [{ id: "a", verdict: "PARTLY" }, { id: "b", verdict: "CORROBORATED", at: 20 }] }), + clip("c2", 40, 60, { claim: { id: "b", verdict: "CONTRADICTED" } }), + ], + }; + assert.match(validateClaims(split)[0], /timeline\[1\] \(c2\)\.claim b is CONTRADICTED here and CORROBORATED at timeline\[0\] \(c1\)/); + assert.match(validateClaims({ timeline: [clip("c1", 0, 30, { claims: [] })] })[0], /claims must name at least one mark/); + assert.match(validateClaims({ timeline: [{ type: "teaser", id: "t", claims: [{ id: "a", verdict: "PARTLY" }] }] })[0], /\.claims: a teaser is not evidence/); +}); + +test("validateClaims: two stamps on one entry may not overlap -- the first's hold (else stamp.seconds) before the next lands", () => { + const two = (a, b, extra = {}, render = RENDER) => ({ + render, + timeline: [clip("c1", 100, 140, { claims: [{ id: "a", verdict: "PARTLY", at: a, ...extra }, { id: "b", verdict: "PARTLY", at: b }] })], + }); + assert.deepEqual(validateClaims(two(110, 113)), [], "3 s apart: the default 3 s hold has passed"); + const [msg] = validateClaims(two(110, 111.5)); + assert.match(msg, /timeline\[0\] \(c1\)\.claims: the marks a \(at 110\) and b \(at 111\.5\) overlap -- a's stamp stays 3 s; land b at 113 or later, or shorten a's hold/); + assert.deepEqual(validateClaims(two(110, 111.5, { hold: 1.5 })), [], "a shorter hold"); + assert.deepEqual(validateClaims(two(110, 111.5, { stamp: false })), [], "a mark that draws nothing overlaps nothing"); + // The order written does not matter: they are taken in landing order. + assert.equal(validateClaims(two(111.5, 110)).length, 1); + // stamp.seconds is the cut's. + const long = { ...RENDER, chrome: { ...CHROME, factcheck: { stamp: { seconds: 5 } } } }; + assert.equal(validateClaims(two(110, 113, {}, long)).length, 1); + // A mark that stamps on a later entry (its id carried on) is not drawn here. + const carried = { + render: RENDER, + timeline: [ + clip("c1", 100, 140, { claims: [{ id: "a", verdict: "PARTLY", at: 110 }, { id: "b", verdict: "PARTLY", at: 111 }] }), + clip("c2", 200, 240, { claim: { id: "a", verdict: "PARTLY" } }), + ], + }; + assert.deepEqual(validateClaims(carried), []); +}); + +// ---- the schedule ----------------------------------------------------------------- + +// Three 10 s segments, D 0.5: starts 0, 9.5, 19; c2's source starts at 200. +const SEGS = (marks) => [ + { id: "c1", start: 0, duration: 10, claim: null }, + { id: "c2", start: 9.5, duration: 10, claim: marks[0], ...(marks.length > 1 ? { claims: marks } : {}), sourceFrom: 200 }, + { id: "c3", start: 19, duration: 10, claim: null }, +]; +const TOTAL = 29; + +test("stampSchedule: two marks with `at` on one clip -- each lands at its own second, each steps the tally", () => { + const stamps = stampSchedule({ + segments: SEGS([{ id: "a", verdict: "CORROBORATED", at: 201 }, { id: "a.2", verdict: "CORROBORATED", at: 205, count: 2 }]), + D: 0.5, total: TOTAL, render: RENDER, + }); + assert.deepEqual(stamps.map((s) => s.claim), ["a", "a.2"]); + near(stamps[0].landed, 10.5, "a: 1 s into c2"); + near(stamps[1].landed, 14.5, "a.2: 5 s into c2"); + near(stamps[0].out[0], stamps[0].at + 3, "a stays stamp.seconds"); + assert.ok(stamps[0].out[1] <= stamps[1].at + 1e-9, "a is gone before a.2 comes in"); + const steps = tallySteps(stamps); + assert.deepEqual(steps.map((s) => [s.verdict, s.count, s.step]), [["CORROBORATED", 1, 1], ["CORROBORATED", 3, 2]]); + assert.deepEqual(tallyFinals(stamps).CORROBORATED, 3); +}); + +test("stampSchedule: a stamp whose hold reaches the next leaves early, gone as the next comes in", () => { + const [a, b] = stampSchedule({ + segments: SEGS([{ id: "a", verdict: "PARTLY", at: 201, hold: 6 }, { id: "b", verdict: "PARTLY", at: 204 }]), + D: 0.5, total: TOTAL, render: RENDER, + }); + near(a.out[1], b.at, "a's leaving ends where b starts"); + near(a.out[1] - a.out[0], 0.5, "over the transition's length"); +}); + +test("stampSchedule: two marks without `at` land in order, back to back -- the last as a lone claim would", () => { + const [a, b] = stampSchedule({ + segments: SEGS([{ id: "a", verdict: "PARTLY" }, { id: "b", verdict: "CONTRADICTED" }]), D: 0.5, total: TOTAL, render: RENDER, + }); + const [lone] = stampSchedule({ segments: SEGS([{ id: "b", verdict: "CONTRADICTED" }]), D: 0.5, total: TOTAL, render: RENDER }); + assert.deepEqual(b, lone, "the last: exactly a lone claim's stamp"); + near(a.out[1], b.at, "a gone as b comes in"); + near(a.out[0], b.at - 0.5, "a leaves over the transition's length"); + near(a.at, a.out[0] - 3, "a stays stamp.seconds"); + near(a.landed, a.at + STAMP_MOTION.slam, "a lands a slam after it starts"); + assert.ok(a.landed < b.landed); +}); + +test("stampSchedule: a mark id carried on to a later clip stamps once, there", () => { + const segments = [ + { id: "c1", start: 0, duration: 10, claim: { id: "a", verdict: "PARTLY" }, claims: [{ id: "a", verdict: "PARTLY" }, { id: "b", verdict: "PARTLY" }] }, + { id: "c2", start: 9.5, duration: 10, claim: { id: "a", verdict: "PARTLY" } }, + ]; + const stamps = stampSchedule({ segments, D: 0.5, total: 19.5, render: RENDER }); + assert.deepEqual(stamps.map((s) => [s.claim, s.segment]), [["b", "c1"], ["a", "c2"]]); +}); + +test("stamp cues: two stamps on one clip are two stamp elements, in landing order", () => { + const stamps = roundStamps(stampSchedule({ + segments: SEGS([{ id: "a", verdict: "PARTLY", at: 201 }, { id: "b", verdict: "PARTLY", at: 205 }]), D: 0.5, total: TOTAL, render: RENDER, + })); + const { init, cues } = stampCues({ factcheck: { stamps } }, RENDER); + assert.ok("st0" in init && "st1" in init); + assert.deepEqual([...new Set(cues.filter((c) => c.k.startsWith("st")).map((c) => c.why.split(" ")[1]))], ["a", "b"]); +}); + +// ---- byte identity: one claim per clip is what it always was ------------------------- + +/** stampSchedule as it was before marks (main at lane/clip-marks' base), verbatim. */ +function legacyStampSchedule({ segments, D, total, render }) { + const seconds = resolveFactcheck(render).stamp.seconds; + const last = new Map(); + segments.forEach((s, i) => { if (s.claim) last.set(s.claim.id, i); }); + return [...last.entries()] + .sort((a, b) => a[1] - b[1]) + .map(([claim, i]) => { + const seg = segments[i]; + const c = seg.claim; + const next = segments[i + 1]; + const out = !next + ? [total - 0.3, total] + : D > 0 ? [next.start, next.start + D] : [next.start - 0.3, next.start]; + const from = seg.start + (i > 0 ? D : 0); + const stay = c.hold ?? seconds; + const knobs = { + ...(c.count !== undefined && c.count !== 1 ? { count: c.count } : {}), + ...(c.stamp === false ? { stamp: false } : {}), + ...(c.label !== undefined ? { label: c.label } : {}), + }; + if (c.at !== undefined && Number.isFinite(seg.sourceFrom)) { + const want = seg.start + (c.at - seg.sourceFrom); + const landed = Math.min(Math.max(seg.start, want), out[0]); + const at = Math.max(seg.start, landed - STAMP_MOTION.slam); + const leave = Math.min(at + stay, out[0]); + const own = leave < out[0] ? [leave, leave + (out[1] - out[0])] : out; + return { claim, verdict: c.verdict, segment: seg.id, at, landed, out: own, ...knobs }; + } + const at = Math.min(Math.max(from, out[0] - stay), out[0]); + const landed = Math.min(at + STAMP_MOTION.slam, out[0]); + return { claim, verdict: c.verdict, segment: seg.id, at, landed, out, ...knobs }; + }); +} + +test("stampSchedule: one claim per clip -- the stamps it always placed, byte for byte (200 random cuts)", () => { + let seed = 7; + const rand = () => ((seed = (seed * 16807) % 2147483647) / 2147483647); + const verdicts = ["CORROBORATED", "PARTLY", "CONTRADICTED"]; + for (let n = 0; n < 200; n += 1) { + const D = rand() < 0.2 ? 0 : 0.5; + const count = 2 + Math.floor(rand() * 8); + let t = 0; + const segments = []; + for (let i = 0; i < count; i += 1) { + const duration = 1 + rand() * 20; + const sourceFrom = Math.round(rand() * 5000); + const claimed = rand() < 0.6; + const id = `k${Math.floor(rand() * 5)}`; + const claim = claimed + ? { + id, + verdict: verdicts[Number(id.slice(1)) % 3], + ...(rand() < 0.5 ? { at: sourceFrom + rand() * duration } : {}), + ...(rand() < 0.3 ? { hold: 0.5 + rand() * 5 } : {}), + ...(rand() < 0.2 ? { count: 2 } : {}), + ...(rand() < 0.2 ? { stamp: false } : {}), + ...(rand() < 0.2 ? { label: "X" } : {}), + } + : null; + segments.push({ id: `c${i}`, start: t, duration, claim, sourceFrom }); + t += duration - (i < count - 1 ? D : 0); + } + const args = { segments, D, total: t, render: RENDER }; + assert.equal(JSON.stringify(roundStamps(stampSchedule(args))), JSON.stringify(roundStamps(legacyStampSchedule(args))), `cut ${n}`); + } +}); + +test("deckSchedule: `claim` and `claims: [claim]` are the same schedule; a lone claim writes no `claims`", () => { + const c = { id: "k", verdict: "PARTLY", at: 203.4 }; + const entries = (e2) => [{ type: "clip", id: "c1", video: "v1", start: 10, end: 20 }, { type: "clip", id: "c2", video: "v2", start: 200, end: 210, ...e2 }]; + const one = deckSchedule({ entries: entries({ claim: c }), durs: [10, 10], D: 0.5, render: RENDER, provenance: PROV }); + const list = deckSchedule({ entries: entries({ claims: [c] }), durs: [10, 10], D: 0.5, render: RENDER, provenance: PROV }); + assert.equal(JSON.stringify(list), JSON.stringify(one)); + assert.equal("claims" in one.segments[1], false); +}); + +test("deckSchedule: two marks on a clip -- `claim` the first (the pip's verdict), `claims` both, two stamps, the finals count both", () => { + const render = { ...RENDER, chrome: { ...CHROME, deck: { pip: { color: "verdict" } } } }; + const marks = [{ id: "s1", verdict: "CORROBORATED", at: 201 }, { id: "g1", verdict: "CONTRADICTED", at: 206 }]; + const entries = [ + { type: "clip", id: "c1", video: "v1", start: 10, end: 20 }, + { type: "clip", id: "c2", video: "v2", start: 200, end: 210, claims: marks }, + { type: "clip", id: "c3", video: "v3", start: 300, end: 310, claim: { id: "s2", verdict: "CORROBORATED" } }, + ]; + const s = deckSchedule({ entries, durs: [10, 10, 10], D: 0.5, render, provenance: PROV, clipClock: new Map([["c2", 200]]) }); + assert.deepEqual(s.segments[1].claim, marks[0]); + assert.deepEqual(s.segments[1].claims, marks); + assert.equal(s.segments[1].sourceFrom, 200); + assert.deepEqual(s.factcheck.stamps.map((x) => [x.claim, x.segment]), [["s1", "c2"], ["g1", "c2"], ["s2", "c3"]]); + near(s.factcheck.stamps[0].landed, 10.5, "s1"); + near(s.factcheck.stamps[1].landed, 15.5, "g1"); + assert.deepEqual(tallyFinals(s.factcheck.stamps), { CORROBORATED: 2, PARTLY: 0, CONTRADICTED: 1, NOT_FOUND: 0, UNTESTABLE: 0 }); + const { pips } = deckCues(s, render); + assert.equal(pips.find((p) => p.id === "c2").verdict, "CORROBORATED", "a multi-mark clip's pip: its first mark's verdict"); +}); diff --git a/umtool/report-to-video/deck.mjs b/umtool/report-to-video/deck.mjs @@ -19,7 +19,7 @@ import { COMPOSITION_PARAMS } from "yt-dlp-transcript-common/lib/report/fxParams import { attributionParts, deckSubtitle } from "./attribution.mjs"; import { - claimOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, validateFactcheck, + claimOf, marksOf, originalUrlAt, resolveFactcheck, roundStamps, stampSchedule, validateFactcheck, } from "./factcheck.mjs"; import { threadOf, threadSchedule, threadsOn, validateThreads } from "./threads.mjs"; import { flipSchedule, flipsOn, validateFlips } from "./flips.mjs"; @@ -945,7 +945,7 @@ export function deckQrUrl(entry, provenance = {}, { links = DECK_DEFAULTS.qr.lin * transition: number, total: number, multiChannel: boolean, * segments: Array<{ id: string, type: string, start: number, duration: number, * end: number, title: string, subtitle: string, qrUrl: string|null, - * hideDeck: boolean, claim?: { id: string, verdict: string } }>, + * hideDeck: boolean, claim?: { id: string, verdict: string }, claims?: Array<{ id: string, verdict: string }> }>, * factcheck?: { stamps: Array<{ claim: string, verdict: string, segment: string, * at: number, landed: number, out: [number, number] }> } }} */ @@ -984,12 +984,15 @@ export function deckSchedule({ // A claim stamped at a source second (`claim.at`) needs the source second // its segment starts at: the cut record's (`clipClock`), else the play // window's estimate. Only then: a cut without `at` places what it did. + // An entry's marks (`claims`, two or more) ride beside its first. const stamped = stampSchedule({ segments: segs.map((s, i) => { - const claim = claimOf(entries[i]); - if (claim?.at === undefined) return { ...s, claim }; + const marks = marksOf(entries[i]); + const claim = marks[0] ?? null; + const many = marks.length > 1 ? { claims: marks } : {}; + if (!marks.some((c) => c.at !== undefined)) return { ...s, claim, ...many }; const e = entries[i]; - return { ...s, claim, sourceFrom: clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from }; + return { ...s, claim, ...many, sourceFrom: clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from }; }), D, total, render, }); @@ -1057,9 +1060,11 @@ export function deckSchedule({ ...(dipOf(e, fps) ? { dip: dipOf(e, fps) } : {}), // Only on an entry that carries a claim (factcheck.mjs), likewise. ...(claimOf(e) ? { claim: claimOf(e) } : {}), + // Its marks, only when it carries two or more (`claim` is the first). + ...(marksOf(e).length > 1 ? { claims: marksOf(e) } : {}), // And on one stamped at a source second, the second its segment starts // at -- what placed the stamp, kept for a preview to place it again. - ...(claimOf(e)?.at !== undefined ? { sourceFrom: round(clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from) } : {}), + ...(marksOf(e).some((c) => c.at !== undefined) ? { sourceFrom: round(clipClock?.get(e.id) ?? fxClock?.get(e.id) ?? playWindow(e, render).from) } : {}), // Only on a finale clip, likewise. ...(finIds.has(e.id) ? { finale: true } : {}), }; diff --git a/umtool/report-to-video/factcheck.mjs b/umtool/report-to-video/factcheck.mjs @@ -8,6 +8,10 @@ // lands and the count steps), "hold" (seconds on screen), // "stamp": false (counts, draws nothing), "count" (steps // the tally by n), "label" (the stamp's words) +// -- or MARKS: "claims": [ { "id": "k3", "verdict": … }, … ] +// (2–8; each its own stamp and tally step at its own +// `at`, with its own knobs). A lone `claim` is a list of +// one, and the writers keep writing `claim` for one mark. // render.chrome: "factcheck": { "verdicts": { "PARTLY": { "label": "Half true", "stampLabel": "Half" } }, // "stamp": { "show": true, "seconds": 3, "position": "top-left", // "scale": 1, "motion": "slam", "opacity": 1 }, @@ -80,6 +84,9 @@ export const CLAIM_LIMITS = Object.freeze({ hold: Object.freeze([0.5, 10]), coun /** The keys a `claim` may carry. */ export const CLAIM_KEYS = Object.freeze(["id", "verdict", "at", "hold", "stamp", "count", "label"]); +/** The most marks (`claims`) one entry may carry. */ +export const CLAIM_MARKS_MAX = 8; + /** * The stamp's motion, in seconds: it slams in over `slam` (landing is when the * tally steps), flashes up over `flashUp` and down over `flashDown`; the @@ -235,17 +242,69 @@ export function claimKnobs(claim) { return knobs; } -/** An entry's claim when it carries a sound one, else null. Never throws. */ -export function claimOf(entry) { - if (!entry || entry.type === "teaser") return null; +/** + * An entry's marks as written: its `claims` list, else its lone `claim` as a + * list of one, else none. Not normalised (marksOf is). + * + * @returns {unknown[]} + */ +export function rawMarksOf(entry) { + if (!isObj(entry)) return []; + if (Array.isArray(entry.claims)) return entry.claims; + return entry.claim === undefined || entry.claim === null ? [] : [entry.claim]; +} + +/** + * A `claims` value, normalised: each mark through normalizeClaim (its errors + * named `claims[k].…`), 1 to CLAIM_MARKS_MAX of them, each id once. Throws a + * sentence on a shape no writer should store. + * + * @returns {Array<NonNullable<ReturnType<typeof normalizeClaim>>>} + */ +export function normalizeMarks(v) { + if (!Array.isArray(v)) throw new Error("claims must be a list of marks [{ id, verdict, … }]"); + if (!v.length) throw new Error("claims must name at least one mark (remove the key for none)"); + if (v.length > CLAIM_MARKS_MAX) throw new Error(`claims holds ${v.length} marks (at most ${CLAIM_MARKS_MAX})`); + const seen = new Set(); + return v.map((m, k) => { + let c; + try { + c = normalizeClaim(m); + } catch (err) { + throw new Error(String(err.message).replace(/^claim\b/, `claims[${k}]`)); + } + if (!c) throw new Error(`claims[${k}] must be { id, verdict }`); + if (seen.has(c.id)) throw new Error(`claims[${k}]: the mark ${c.id} is on this entry twice -- one mark, one id`); + seen.add(c.id); + return c; + }); +} + +/** + * An entry's MARKS, normalised: each `{ id, verdict, …knobs }`, in the order + * written. None on a teaser, or on a shape that does not normalise. Never + * throws. + */ +export function marksOf(entry) { + if (!isObj(entry) || entry.type === "teaser") return []; try { - return normalizeClaim(entry.claim); + if (Array.isArray(entry.claims)) return entry.claim === undefined || entry.claim === null ? normalizeMarks(entry.claims) : []; + const c = normalizeClaim(entry.claim); + return c ? [c] : []; } catch { - return null; + return []; } } /** + * An entry's claim when it carries a sound one, else null: its FIRST mark -- + * the one its pip and rail take their verdict's colour from. Never throws. + */ +export function claimOf(entry) { + return marksOf(entry)[0] ?? null; +} + +/** * Every `claim` in the timeline, checked: its shape, that it is not on a * teaser (a full-frame finale is no evidence), and that every entry naming a * claim id names the same verdict. The build refuses with these before it @@ -256,25 +315,60 @@ export function claimOf(entry) { export function validateClaims(manifest) { const errors = []; const verdictOf = new Map(); - (manifest?.timeline ?? []).forEach((e, i) => { - if (e?.claim === undefined || e?.claim === null) return; + const timeline = Array.isArray(manifest?.timeline) ? manifest.timeline : []; + // The last entry carrying each id: a mark stamps there, and only there. + const lastOf = new Map(); + timeline.forEach((e, i) => { + for (const m of rawMarksOf(e)) if (isObj(m) && typeof m.id === "string") lastOf.set(m.id.trim(), i); + }); + timeline.forEach((e, i) => { + const many = Array.isArray(e?.claims); + const one = e?.claim !== undefined && e?.claim !== null; + if (!many && !one) return; const where = `timeline[${i}] (${e.id ?? "?"})`; - if (e.type === "teaser") { errors.push(`${where}.claim: a teaser is not evidence for a claim`); return; } - let c; + const key = many ? "claims" : "claim"; + if (many && one) { errors.push(`${where}: claim and claims are both set -- one mark is \`claim\`, two or more \`claims\``); return; } + if (e.type === "teaser") { errors.push(`${where}.${key}: a teaser is not evidence for a claim`); return; } + let marks; try { - c = normalizeClaim(e.claim); + marks = many ? normalizeMarks(e.claims) : [normalizeClaim(e.claim)]; } catch (err) { errors.push(`${where}.${err.message}`); return; } - // `at` is the entry's own clock: a second of the source inside its window. - if (c.at !== undefined && Number.isFinite(e.start) && Number.isFinite(e.end) && (c.at < e.start || c.at > e.end)) { - errors.push(`${where}.claim.at ${c.at} is outside the clip's window ${e.start}–${e.end} (source seconds)`); + marks.forEach((c, k) => { + const name = many ? `claims[${k}]` : "claim"; + // `at` is the entry's own clock: a second of the source inside its window. + if (c.at !== undefined && Number.isFinite(e.start) && Number.isFinite(e.end) && (c.at < e.start || c.at > e.end)) { + errors.push(`${where}.${name}.at ${c.at} is outside the clip's window ${e.start}–${e.end} (source seconds)`); + } + const seen = verdictOf.get(c.id); + if (seen && seen.verdict !== c.verdict) { + errors.push(`${where}.${name} ${c.id} is ${c.verdict} here and ${seen.verdict} at ${seen.where} -- one claim, one verdict`); + } else if (!seen) verdictOf.set(c.id, { verdict: c.verdict, where }); + }); + // Marks stamped on one entry at their own seconds: one's stamp must have + // stayed its hold before the next lands. (Marks without `at` are laid back + // to back by the schedule; a mark that stamps on a later entry, or draws + // nothing, is not drawn here.) + if (marks.length > 1) { + const hold = resolveFactcheck(manifest?.render).stamp.seconds; + const timed = marks + .filter((c) => c.at !== undefined && c.stamp !== false && lastOf.get(c.id) === i) + .sort((a, b) => a.at - b.at); + for (let k = 1; k < timed.length; k += 1) { + const a = timed[k - 1]; + const b = timed[k]; + const stay = a.hold ?? hold; + if (b.at - a.at < stay - 1e-9) { + const free = Math.round((a.at + stay) * 100) / 100; + errors.push( + `${where}.claims: the marks ${a.id} (at ${a.at}) and ${b.id} (at ${b.at}) overlap -- ${a.id}'s stamp stays ${stay} s; ` + + `land ${b.id} at ${free} or later, or shorten ${a.id}'s hold`, + ); + } + } } - const seen = verdictOf.get(c.id); - if (seen && seen.verdict !== c.verdict) { - errors.push(`${where}.claim ${c.id} is ${c.verdict} here and ${seen.verdict} at ${seen.where} -- one claim, one verdict`); - } else if (!seen) verdictOf.set(c.id, { verdict: c.verdict, where }); }); return errors; } @@ -307,45 +401,92 @@ export function validateClaims(manifest) { * tally's step), `stamp: false` (counted, not drawn), `label` (the stamp's * words). A claim without knobs stamps exactly as it always did. * + * MARKS (a segment's `claims`, two or more): each mark is its own stamp and + * tally step, stamped on the last segment carrying its id. On a segment that + * stamps two or more, each mark with `at` lands as above; those without land + * in order, back to back, the last as a lone claim would (the one before + * leaving as the next comes in); and, in landing order, a stamp leaves in + * time to be gone as the next one starts. A segment stamping one mark places + * it exactly as a lone claim. + * * `segments` are the schedule's, in order, each `{ id, start, duration, - * claim?, sourceFrom? }` (`claim` as `claimOf` gives it). + * claim?, claims?, sourceFrom? }` (`claim` as `claimOf` gives it, `claims` + * as `marksOf`; `claims` wins when both are set). * * @returns {Array<{ claim: string, verdict: string, segment: string, at: number, * landed: number, out: [number, number], count?: number, stamp?: false, label?: string }>} */ export function stampSchedule({ segments, D, total, render }) { const seconds = resolveFactcheck(render).stamp.seconds; + const marksAt = (s) => (Array.isArray(s.claims) && s.claims.length ? s.claims : s.claim ? [s.claim] : []); + // Each mark id's last segment: where it stamps. const last = new Map(); - segments.forEach((s, i) => { if (s.claim) last.set(s.claim.id, i); }); - return [...last.entries()] - .sort((a, b) => a[1] - b[1]) - .map(([claim, i]) => { + segments.forEach((s, i) => { for (const c of marksAt(s)) last.set(c.id, i); }); + const bySegment = new Map(); + for (const [id, i] of last) { + if (!bySegment.has(i)) bySegment.set(i, []); + bySegment.get(i).push(marksAt(segments[i]).find((c) => c.id === id)); + } + const knobsOf = (c) => ({ + ...(c.count !== undefined && c.count !== 1 ? { count: c.count } : {}), + ...(c.stamp === false ? { stamp: false } : {}), + ...(c.label !== undefined ? { label: c.label } : {}), + }); + return [...bySegment.entries()] + .sort((a, b) => a[0] - b[0]) + .flatMap(([i, marks]) => { const seg = segments[i]; - const c = seg.claim; const next = segments[i + 1]; const out = !next ? [total - 0.3, total] : D > 0 ? [next.start, next.start + D] : [next.start - 0.3, next.start]; const from = seg.start + (i > 0 ? D : 0); - const stay = c.hold ?? seconds; - const knobs = { - ...(c.count !== undefined && c.count !== 1 ? { count: c.count } : {}), - ...(c.stamp === false ? { stamp: false } : {}), - ...(c.label !== undefined ? { label: c.label } : {}), - }; - if (c.at !== undefined && Number.isFinite(seg.sourceFrom)) { - // The cut's second the source's `at` plays at, inside the segment - // and before its stamp has to leave. + const leaving = out[1] - out[0]; + // A mark at its source second: the cut's second the source's `at` + // plays at, inside the segment and before its stamp has to leave. + const timed = (c) => { + const stay = c.hold ?? seconds; const want = seg.start + (c.at - seg.sourceFrom); const landed = Math.min(Math.max(seg.start, want), out[0]); const at = Math.max(seg.start, landed - STAMP_MOTION.slam); const leave = Math.min(at + stay, out[0]); - const own = leave < out[0] ? [leave, leave + (out[1] - out[0])] : out; - return { claim, verdict: c.verdict, segment: seg.id, at, landed, out: own, ...knobs }; + const own = leave < out[0] ? [leave, leave + leaving] : out; + return { claim: c.id, verdict: c.verdict, segment: seg.id, at, landed, out: own, ...knobsOf(c) }; + }; + const isTimed = (c) => c.at !== undefined && Number.isFinite(seg.sourceFrom); + if (marks.length === 1) { + const c = marks[0]; + if (isTimed(c)) return [timed(c)]; + const stay = c.hold ?? seconds; + const at = Math.min(Math.max(from, out[0] - stay), out[0]); + const landed = Math.min(at + STAMP_MOTION.slam, out[0]); + return [{ claim: c.id, verdict: c.verdict, segment: seg.id, at, landed, out, ...knobsOf(c) }]; + } + // Two or more on this segment. The untimed, back to back from the + // segment's out: the last as a lone claim, each before it gone as the + // one after comes in. + const placed = new Map(); + let until = null; // when the stamp after this one comes in + for (const c of marks.filter((m) => !isTimed(m)).reverse()) { + const stay = c.hold ?? seconds; + const own = until === null ? out : [Math.max(from, until - leaving), Math.max(from, until - leaving) + leaving]; + const at = Math.min(Math.max(from, own[0] - stay), own[0]); + const landed = Math.min(at + STAMP_MOTION.slam, own[0]); + placed.set(c.id, { claim: c.id, verdict: c.verdict, segment: seg.id, at, landed, out: own, ...knobsOf(c) }); + until = at; + } + for (const c of marks) if (isTimed(c)) placed.set(c.id, timed(c)); + // In landing order, each drawn stamp gone by the time the next drawn one starts. + const stamps = marks.map((c) => placed.get(c.id)).sort((a, b) => a.at - b.at || a.landed - b.landed); + const drawn = stamps.filter((s) => s.stamp !== false); + for (let k = 0; k + 1 < drawn.length; k += 1) { + const s = drawn[k]; + const nextAt = drawn[k + 1].at; + if (s.out[1] <= nextAt) continue; + const go = Math.max(s.landed, nextAt - leaving); + s.out = [go, Math.max(go, Math.min(go + leaving, nextAt))]; } - const at = Math.min(Math.max(from, out[0] - stay), out[0]); - const landed = Math.min(at + STAMP_MOTION.slam, out[0]); - return { claim, verdict: c.verdict, segment: seg.id, at, landed, out, ...knobs }; + return stamps; }); }