// TASK flips — THEN/NOW pairs over the cut's clips (release 28, M4): the // `render.chrome.flips` panel (umtool/report-to-video/flips.mjs). A STEP on a // done iteration, on the media task scaffold (./media.ts): one unit, the // whole field. // // The model proposes pairs — a topic and two clip ids, and optionally a part // of each clip's quote. CODE does the rest and checks it all: // - the ids name clips of the cut, no clip is in two pairs, 1 to // FLIPS_LIMITS.pairs[1] pairs (and no more than the dated clips allow); // - the dates are the recordings' (./clipEvidence.ts), never the model's: // the earlier clip is THEN, the later NOW, and two clips of one day are // no pair; each side's `when` is written from its date ("Jan 2026"); // - a side's `words` are its clip's quote, verbatim — the model's part of // it only when the quote says exactly that — cut to the limit by code; // - the topic is one line of at most FLIPS_LIMITS.topic characters, its // names and numbers the report's (grounding); // - THEN plays before NOW: a pair the other way round is refused, unless // the cut's order is a draft itself (`drafted.timeline`) and the flips // will be applied — then code swaps the two clips' places in the // timeline, written through applyDraft with this task's provenance; // - the result passes the build's own validateFlips and validateFlipEntries // (common's panels.mjs). // A pair failing a check is dropped when the others stand (the repair); the // better of two attempts is kept. // // ONE LEFT PANEL: flips and threads share it. A cut with threads is refused — // unless `force` and the threads are a draft: then the flips replace them // (the list, each clip's `thread` and their mark go) and the log says so. // A cut with no on-screen deck (`render.chrome`) has no panel: refused. import { applyDraft, clearDrafted, entriesWithId, ownerOf } from "../../drafted.mjs"; import { FLIPS_LIMITS, threadsOn, validateFlipEntries, validateFlips } from "../../panels.mjs"; import type { GroundingInput } from "../grounding"; import type { ManifestEntry, VideoManifest } from "../videoOps"; import { checkLine, clipFacts, clipLine, fitLines, fitShortLine, whenOf, type ClipFact } from "./clipEvidence"; import { runMediaTask, type MediaAttempt, type MediaContext, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; import { TaskInputError } from "./run"; import type { TaskDeps, TaskResult } from "./types"; export type FlipsInput = MediaTaskInput; /** A pair as the model proposes it. */ export type ProposedPair = { topic: string; then: string; now: string; thenWords?: string; nowWords?: string }; export type FlipsValue = { pairs: ProposedPair[] }; type Side = { entry: string; when: string; words: string }; export type FlipPair = { id: string; topic: string; then: Side; now: Side }; /** What code makes of a proposal: the field, the swaps it needs, and what is wrong (per pair, and overall). */ export type FlipsPlan = { flips: { pairs: FlipPair[] }; swaps: [string, string][]; pairProblems: string[][]; problems: string[]; soft: string[]; }; type FlipsUnit = MediaUnit & { // The cut as read (what every plan is made over). manifest: VideoManifest; clips: ClipFact[]; g: GroundingInput; // The cut's order is a draft and the flips will be applied: a pair may swap its clips. reorderable: boolean; // The threads are a draft and `force` is set: the flips replace them. dropThreads: boolean; maxPairs: number; // The kept value's plan (set by toField, read by apply). chosen?: FlipsPlan; }; // The evidence's share of a prompt (characters), well under the local 8k tokens. const EVIDENCE_BUDGET = 14_000; const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim(); /** A pair id from its topic: letters, digits and `-`; unique among `taken`. */ export function pairId(topic: string, i: number, taken: Set): string { let base = topic.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, ""); if (!/^[a-z0-9]/.test(base)) base = `pair-${i + 1}`; let id = base; for (let k = 2; taken.has(id); k++) id = `${base}-${k}`; taken.add(id); return id; } /** * A side's words: the clip's quote, verbatim — or the part of it the model * named, when the quote says exactly that — cut to `max` characters at a word * (with `…`). `soft` when the model's part was not the quote's. */ export function sideWords(quote: string, part: string | undefined, max: number = FLIPS_LIMITS.words): { words: string; soft?: string } { const q = oneLine(quote); let w = q; let soft: string | undefined; const p = oneLine(part).replace(/^["“'…\s]+|["”'…\s]+$/g, ""); if (p) { const at = q.toLowerCase().indexOf(p.toLowerCase()); if (at >= 0) w = q.slice(at, at + p.length); else soft = "its words are not the clip's quote: the quote is used"; } if (w.length > max) { const cut = w.slice(0, max - 1); const sp = cut.lastIndexOf(" "); w = `${(sp > max / 2 ? cut.slice(0, sp) : cut).replace(/[\s,;:.]+$/, "")}…`; } return { words: w, ...(soft ? { soft } : {}) }; } /** The timeline with each pair of ids' places swapped. */ export function swapEntries(timeline: ManifestEntry[], swaps: readonly [string, string][]): ManifestEntry[] { const out = [...timeline]; for (const [a, b] of swaps) { const i = out.findIndex((e) => e.id === a); const j = out.findIndex((e) => e.id === b); if (i < 0 || j < 0) continue; [out[i], out[j]] = [out[j]!, out[i]!]; } return out; } const twins = (m: VideoManifest, id: string) => entriesWithId(m, id).length > 1; /** Code's reading of a proposal over this cut (pure). */ export function planFlips(value: FlipsValue, unit: Pick, manifest: VideoManifest): FlipsPlan { const byId = new Map(unit.clips.map((c) => [c.id, c])); const problems: string[] = []; const soft: string[] = []; const [lo] = FLIPS_LIMITS.pairs; const n = value.pairs.length; if (n < lo) problems.push("no pair: propose at least one"); if (n > unit.maxPairs) problems.push(`${n} pairs: at most ${unit.maxPairs}`); const used = new Set(); const taken = new Set(); const pairs: FlipPair[] = []; const pairProblems: string[][] = []; const swaps: [string, string][] = []; value.pairs.forEach((p, i) => { const bad: string[] = []; const w = `pair ${i + 1}`; const topic = oneLine(p.topic); if (!topic) bad.push(`${w}: no topic`); else if (topic.length > FLIPS_LIMITS.topic) bad.push(`${w}: the topic is ${topic.length} characters (at most ${FLIPS_LIMITS.topic})`); else for (const h of checkLine(topic, unit.g).hard) bad.push(`${w}: the topic: ${h}`); let a = byId.get(p.then); let b = byId.get(p.now); if (!a) bad.push(`${w}: ${p.then || "(none)"} is not a clip of the cut`); if (!b) bad.push(`${w}: ${p.now || "(none)"} is not a clip of the cut`); let side = { then: p.thenWords, now: p.nowWords }; if (a && b) { if (a.id === b.id) bad.push(`${w}: THEN and NOW are the same clip`); for (const c of [a, b]) { if (used.has(c.id)) bad.push(`${w}: ${c.id} is already in a pair`); if (!c.date) bad.push(`${w}: ${c.id}'s recording has no date`); if (!c.quote) bad.push(`${w}: ${c.id} has no quote`); } if (a.date && b.date) { if (a.date === b.date) bad.push(`${w}: ${a.id} and ${b.id} are of the same day (${a.date})`); else if (a.date > b.date) { // THEN is the earlier recording: the dates are code's. [a, b] = [b, a]; side = { then: p.nowWords, now: p.thenWords }; } } if (a.id !== b.id && a.index > b.index) { if (!unit.reorderable) bad.push(`${w}: THEN ${a.id} (${a.date}) plays after NOW ${b.id} (${b.date}) and the cut's order is not a draft — pick another pair, or reorder the cut by hand`); else if (twins(manifest, a.id) || twins(manifest, b.id)) bad.push(`${w}: ${a.id} or ${b.id} has variant twins — reorder the cut by hand`); } } if (a && b && !bad.length) { const tw = sideWords(a.quote, side.then); const nw = sideWords(b.quote, side.now); if (tw.soft) soft.push(`${w}: ${a.id} ${tw.soft}`); if (nw.soft) soft.push(`${w}: ${b.id} ${nw.soft}`); if (a.index > b.index) swaps.push([a.id, b.id]); pairs.push({ id: pairId(topic, i, taken), topic, then: { entry: a.id, when: whenOf(a.date!), words: tw.words }, now: { entry: b.id, when: whenOf(b.date!), words: nw.words }, }); } // Only a pair that stands takes its clips: a refused one leaves them free. if (a && b && !bad.length) for (const c of [a, b]) used.add(c.id); pairProblems.push(bad); }); const flips = { pairs }; if (pairs.length && !pairProblems.some((x) => x.length) && !problems.length) { // The build's own checks, on the cut as it will be. const after = JSON.parse(JSON.stringify(manifest)) as VideoManifest & { render?: { chrome?: Record } }; after.timeline = swapEntries(after.timeline, swaps); if (after.render?.chrome) { if (unit.dropThreads) delete after.render.chrome.threads; after.render.chrome.flips = flips; } problems.push(...validateFlips(flips), ...validateFlipEntries(after)); } return { flips, swaps, pairProblems, problems, soft }; } const allProblems = (p: FlipsPlan) => [...p.problems, ...p.pairProblems.flat()]; export function flipsSystem(maxPairs: number): string { return ( "You pick THEN/NOW pairs for a short evidence video: two clips of the same speaker on one topic, where what was said " + "at the earlier date is reversed or contradicted by what was said at the later one. Rules: (1) use only clip ids from " + "the list; (2) a clip is in one pair at most; (3) propose only pairs that really reverse, at most " + `${maxPairs}, best first; (4) the topic names what the pair is about in plain words, at most ${FLIPS_LIMITS.topic} ` + "characters, no quotation marks, no first person, nothing the evidence does not say; (5) the dates are given and " + "decide which clip is THEN — you never write a date; (6) thenWords and nowWords are optional: a part of that clip's " + `quote copied word for word, when the whole quote is longer than ${FLIPS_LIMITS.words} characters; leave them out ` + "otherwise." ); } export const FLIPS_SPEC: MediaTaskSpec = { task: "flips", noun: "flips panel", async units(ctx: MediaContext) { const m = ctx.manifest as VideoManifest & { render?: { chrome?: unknown } }; const chrome = m.render?.chrome; if (!chrome || typeof chrome !== "object") { throw new TaskInputError("flips are drawn by the on-screen deck (render.chrome), and this cut has none — turn the deck on first"); } let dropThreads = false; if (threadsOn(m.render)) { const owner = ownerOf(m, { field: "render.chrome.threads" }); if (!ctx.input.force || owner === "operator") { throw new TaskInputError( "this cut has threads (render.chrome.threads), and flips and threads share the left panel" + (owner === "operator" ? ": the threads are the operator's — remove them first" : ": force replaces drafted threads"), ); } dropThreads = true; } const clips = await clipFacts(m, ctx.report, ctx.handle.deps.corpus ?? null); const dated = clips.filter((c) => c.date && c.quote); const days = new Set(dated.map((c) => c.date)); if (dated.length < 2 || days.size < 2) { return [{ id: "flips", skipped: `a pair needs two clips of different dates: ${dated.length} dated clip(s), ${days.size} date(s)` }]; } const flipsOwner = ownerOf(m, { field: "render.chrome.flips" }); return [ { id: "flips", target: { field: "render.chrome.flips" }, label: "THEN/NOW pairs", manifest: m, clips, g: ctx.grounding, reorderable: ownerOf(m, { field: "timeline" }) === "drafted" && flipsOwner !== "operator", dropThreads, maxPairs: Math.min(FLIPS_LIMITS.pairs[1], Math.floor(dated.length / 2)), }, ]; }, schema: () => ({ type: "object", properties: { pairs: { type: "array", items: { type: "object", properties: { topic: { type: "string" }, then: { type: "string" }, now: { type: "string" }, thenWords: { type: "string" }, nowWords: { type: "string" }, }, required: ["topic", "then", "now"], }, }, }, required: ["pairs"], }), system: (u) => flipsSystem(u.maxPairs), user(u, ctx) { const r = ctx.report as { title?: string; summary?: string | null }; const ev = fitLines(u.clips.map((c) => clipLine(c)), EVIDENCE_BUDGET); return ( `Report: ${r.title ?? ""}` + (r.summary ? `\n${String(r.summary).slice(0, 600)}` : "") + `\n\nThe cut's clips (id [recording date] (chapter): "quote" — the claim it stands for):\n${ev.text}` + (ev.omitted ? `\n(${ev.omitted} more clip(s) not shown)` : "") + "\n\nPropose the pairs." ); }, parse(answer) { const list = (answer as { pairs?: unknown } | null)?.pairs; if (!Array.isArray(list)) throw new Error("no pairs list in the answer"); return { pairs: list .filter((p): p is Record => !!p && typeof p === "object") .map((p) => ({ topic: fitShortLine(oneLine(p.topic), FLIPS_LIMITS.topic), then: oneLine(p.then), now: oneLine(p.now), ...(typeof p.thenWords === "string" && p.thenWords.trim() ? { thenWords: p.thenWords } : {}), ...(typeof p.nowWords === "string" && p.nowWords.trim() ? { nowWords: p.nowWords } : {}), })), }; }, check(value, u) { const plan = planFlips(value, u, u.manifest); return { hard: allProblems(plan), soft: plan.soft }; }, // The best attempt's pairs that pass, when there is one (never a new pair). repair(attempts, u) { let best: MediaAttempt | null = null; for (const a of attempts) { if (!a.value) continue; const plan = planFlips(a.value, u, u.manifest); const good = a.value.pairs.filter((_, i) => !plan.pairProblems[i]?.length).slice(0, u.maxPairs); if (!good.length) continue; const v = { pairs: good }; const again = planFlips(v, u, u.manifest); const hard = allProblems(again); if (hard.length) continue; if (!best || good.length > best.value!.pairs.length) { best = { value: v, hard: [], soft: [...again.soft, `${a.value.pairs.length - good.length} refused pair(s) dropped`] }; } } return best; }, toField(value, u) { u.chosen = planFlips(value, u, u.manifest); return u.chosen.flips; }, apply(manifest, u, value, provenance, force, ctx) { const res = applyDraft(manifest, { field: "render.chrome.flips", value, provenance, force }); if (!res.applied) return res; const m = manifest as VideoManifest & { render?: { chrome?: Record } }; if (u.dropThreads && m.render?.chrome) { delete m.render.chrome.threads; for (const e of m.timeline) delete e.thread; clearDrafted(m, { field: "render.chrome.threads" }); ctx.handle.log(" the drafted threads were removed: flips and threads share the left panel"); } const swaps = u.chosen?.swaps ?? []; if (swaps.length) { const t = applyDraft(m, { field: "timeline", value: swapEntries(m.timeline, swaps), provenance, force: true }); ctx.handle.log( t.applied ? ` the cut's order changed so THEN plays first: ${swaps.map(([a, b]) => `${a} ⇄ ${b}`).join(", ")}` : ` the cut's order could not be changed (${t.reason}): THEN plays after NOW`, ); } return res; }, describe: (v, u) => { const pairs = planFlips(v, u, u.manifest).flips.pairs; return ( `${pairs.length} pair(s): ` + pairs.map((p) => `${p.topic} (${p.then.entry} ${p.then.when} → ${p.now.entry} ${p.now.when})`).join("; ") + (u.dropThreads ? " — replaces the drafted threads" : "") ); }, }; export async function flips(input: FlipsInput, deps: TaskDeps): Promise { return runMediaTask(FLIPS_SPEC, input, deps); }