// TASK threads — the cut's clips grouped into the few lines of argument they // make (release 28, M5): `render.chrome.threads.list` and each clip's // `thread` key, drawn as the rail down the frame's left // (umtool/report-to-video/threads.mjs). A STEP on a done iteration, on the // media task scaffold (./media.ts): one unit, the whole field. // // The model names the threads (an id and a label) and puts each clip in one, // or in none. CODE checks it all: // - 2 to 4 threads (THREADS_TASK_COUNT; the rail takes up to // THREADS_LIMITS.threads[1]), ids that are ids and not listed twice, // labels of one line of at most THREADS_LIMITS.label characters whose // names and numbers are the report's (grounding); // - every assignment names a clip of the cut and a listed thread, a clip // is in one thread at most, every thread has a clip; // - a thread's OUTCOME is code's: the claim verdict its last clip carries in // the manifest (`claim.verdict`), when it carries one — the model never // sets a verdict; // - the result passes the build's own validateThreads and // validateThreadEntries (common's panels.mjs). // A thread failing a check is dropped with its clips when at least two stand // (the repair); the better of two attempts is kept. Applied: the list through // applyDraft, then every clip's `thread` set (or removed: a clip in no thread // has none) — the mark covers both. // // ONE LEFT PANEL: flips and threads share it. A cut with flips is refused — // unless `force` and the flips are a draft: then the threads replace them and // the log says so. A cut with no on-screen deck (`render.chrome`) is refused. import { applyDraft, clearDrafted, ownerOf } from "../../drafted.mjs"; import { THREADS_LIMITS, flipsOn, validateThreadEntries, validateThreads } from "../../panels.mjs"; import { VERDICTS } from "../../verdicts.mjs"; import type { GroundingInput } from "../grounding"; import type { VideoManifest } from "../videoOps"; import { checkLine, clipFacts, clipLine, fitLines, fitShortLine, 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 ThreadsInput = MediaTaskInput; /** How many threads a draft makes. */ export const THREADS_TASK_COUNT = Object.freeze([2, 4] as const); export type ProposedThread = { id: string; label: string }; export type ThreadsValue = { threads: ProposedThread[]; assign: { clip: string; thread: string }[] }; export type Thread = { id: string; label: string; outcome?: { verdict: string } }; export type ThreadsPlan = { list: Thread[]; // clip id → thread id, for every clip in a thread. clips: Record; threadProblems: string[][]; problems: string[]; soft: string[]; }; type ThreadsUnit = MediaUnit & { manifest: VideoManifest; clips: ClipFact[]; g: GroundingInput; dropFlips: boolean; chosen?: ThreadsPlan; }; const EVIDENCE_BUDGET = 14_000; const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,47}$/; const oneLine = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim(); /** A thread id as code keeps it: the model's, else made from its label. */ export function threadId(raw: string, label: string, i: number): string { const id = oneLine(raw); if (ID_RE.test(id)) return id; const base = (id || label).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40).replace(/-+$/, ""); return /^[a-z0-9]/.test(base) ? base : `thread-${i + 1}`; } /** A clip's verdict as the manifest has it (`claim.verdict`), or null. */ const manifestVerdict = (m: VideoManifest, id: string): string | null => { const v = (m.timeline.find((e) => e.type === "clip" && e.id === id)?.claim as { verdict?: unknown } | undefined)?.verdict; return typeof v === "string" && (VERDICTS as readonly string[]).includes(v) ? v : null; }; /** Code's reading of a proposal over this cut (pure). */ export function planThreads(value: ThreadsValue, unit: Pick, manifest: VideoManifest): ThreadsPlan { const [lo, hi] = THREADS_TASK_COUNT; const problems: string[] = []; const soft: string[] = []; const n = value.threads.length; if (n < lo || n > hi) problems.push(`${n} thread(s): ${lo} to ${hi}`); const byClip = new Map(unit.clips.map((c) => [c.id, c])); // The model's id → code's, and each thread's problems. const ids = new Map(); const seen = new Set(); const threadProblems: string[][] = value.threads.map((t, i) => { const bad: string[] = []; const label = oneLine(t.label); const id = threadId(t.id, label, i); const w = `thread ${i + 1} (${id})`; if (seen.has(id)) bad.push(`${w}: the id ${id} is listed twice`); seen.add(id); if (!ids.has(oneLine(t.id))) ids.set(oneLine(t.id), id); if (!label) bad.push(`${w}: no label`); else if (label.length > THREADS_LIMITS.label) bad.push(`${w}: the label is ${label.length} characters (at most ${THREADS_LIMITS.label})`); else for (const h of checkLine(label, unit.g).hard) bad.push(`${w}: the label: ${h}`); return bad; }); const listed = value.threads.map((t, i) => threadId(t.id, oneLine(t.label), i)); const clips: Record = {}; for (const a of value.assign) { const clip = oneLine(a.clip); const raw = oneLine(a.thread); if (!raw) continue; // in no thread const t = ids.get(raw) ?? (listed.includes(raw) ? raw : null); if (!byClip.has(clip)) problems.push(`${clip || "(none)"} is not a clip of the cut`); else if (!t) problems.push(`${clip} is put in ${raw}, which is not a listed thread`); else if (clips[clip] !== undefined && clips[clip] !== t) problems.push(`${clip} is put in two threads (${clips[clip]}, ${t})`); else clips[clip] = t; } listed.forEach((id, i) => { if (!Object.values(clips).includes(id)) threadProblems[i]!.push(`thread ${i + 1} (${id}) has no clip`); }); // The outcome: the verdict its last clip (in the cut's order) carries. const list: Thread[] = value.threads.map((t, i) => { const id = listed[i]!; const mine = unit.clips.filter((c) => clips[c.id] === id).sort((a, b) => a.index - b.index); const verdict = mine.length ? manifestVerdict(manifest, mine.at(-1)!.id) : null; return { id, label: oneLine(t.label), ...(verdict ? { outcome: { verdict } } : {}) }; }); if (!problems.length && !threadProblems.some((x) => x.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 } }; if (after.render?.chrome) { if (unit.dropFlips) delete after.render.chrome.flips; after.render.chrome.threads = { list }; } setClipThreads(after, clips); problems.push(...validateThreads({ list }), ...validateThreadEntries(after)); } return { list, clips, threadProblems, problems, soft }; } /** Every clip's `thread`: the one it is in, or none. */ export function setClipThreads(m: VideoManifest, clips: Record) { for (const e of m.timeline) { if (e.type !== "clip") continue; if (clips[e.id]) e.thread = clips[e.id]; else delete e.thread; } } const allProblems = (p: ThreadsPlan) => [...p.problems, ...p.threadProblems.flat()]; export function threadsSystem(): string { const [lo, hi] = THREADS_TASK_COUNT; return ( "You group the clips of a short evidence video into threads: the few lines of argument the clips make, drawn as a " + `rail of cards beside the footage. Rules: (1) ${lo} to ${hi} threads; (2) each thread has an id (letters, digits ` + `and -) and a label of at most ${THREADS_LIMITS.label} characters in plain words, no quotation marks, no first ` + "person, nothing the evidence does not say; (3) put each clip in at most one thread, by its id from the list; a " + "clip that fits none is left out; (4) every thread has at least one clip; (5) you never write a verdict or an " + "outcome." ); } export const THREADS_SPEC: MediaTaskSpec = { task: "threads", noun: "thread rail", async units(ctx: MediaContext) { const m = ctx.manifest as VideoManifest & { render?: { chrome?: unknown } }; if (!m.render?.chrome || typeof m.render.chrome !== "object") { throw new TaskInputError("threads are drawn by the on-screen deck (render.chrome), and this cut has none — turn the deck on first"); } let dropFlips = false; if (flipsOn(m.render)) { const owner = ownerOf(m, { field: "render.chrome.flips" }); if (!ctx.input.force || owner === "operator") { throw new TaskInputError( "this cut has flips (render.chrome.flips), and flips and threads share the left panel" + (owner === "operator" ? ": the flips are the operator's — remove them first" : ": force replaces drafted flips"), ); } dropFlips = true; } const clips = await clipFacts(m, ctx.report, null, { dates: false }); if (clips.length < THREADS_TASK_COUNT[0]) { return [{ id: "threads", skipped: `${clips.length} clip(s): ${THREADS_TASK_COUNT[0]} threads need at least ${THREADS_TASK_COUNT[0]}` }]; } return [{ id: "threads", target: { field: "render.chrome.threads" }, label: "Threads", manifest: m, clips, g: ctx.grounding, dropFlips }]; }, schema: () => ({ type: "object", properties: { threads: { type: "array", items: { type: "object", properties: { id: { type: "string" }, label: { type: "string" } }, required: ["id", "label"] }, }, clips: { type: "array", items: { type: "object", properties: { clip: { type: "string" }, thread: { type: "string" } }, required: ["clip", "thread"] }, }, }, required: ["threads", "clips"], }), system: () => threadsSystem(), user(u, ctx) { const r = ctx.report as { title?: string; summary?: string | null }; const ev = fitLines(u.clips.map((c) => clipLine(c, { date: false })), EVIDENCE_BUDGET); return ( `Report: ${r.title ?? ""}` + (r.summary ? `\n${String(r.summary).slice(0, 600)}` : "") + `\n\nThe cut's clips, in order (id (chapter): "quote" — the claim it stands for):\n${ev.text}` + (ev.omitted ? `\n(${ev.omitted} more clip(s) not shown)` : "") + '\n\nName the threads, then give every clip its thread ("" for none).' ); }, parse(answer) { const a = answer as { threads?: unknown; clips?: unknown } | null; if (!Array.isArray(a?.threads)) throw new Error("no threads list in the answer"); const objs = (v: unknown) => (Array.isArray(v) ? v : []).filter((x): x is Record => !!x && typeof x === "object"); return { threads: objs(a.threads).map((t) => ({ id: oneLine(t.id), label: fitShortLine(oneLine(t.label), THREADS_LIMITS.label) })), assign: objs(a.clips).map((c) => ({ clip: oneLine(c.clip), thread: oneLine(c.thread) })), }; }, check(value, u) { const plan = planThreads(value, u, u.manifest); return { hard: allProblems(plan), soft: plan.soft }; }, // The best attempt's threads that pass, with their clips, when at least two stand. repair(attempts, u) { let best: MediaAttempt | null = null; for (const a of attempts) { if (!a.value) continue; const plan = planThreads(a.value, u, u.manifest); const keepIdx = plan.list.map((_, i) => i).filter((i) => !plan.threadProblems[i]?.length).slice(0, THREADS_TASK_COUNT[1]); const keep = new Set(keepIdx.map((i) => plan.list[i]!.id)); const v: ThreadsValue = { threads: keepIdx.map((i) => ({ id: plan.list[i]!.id, label: plan.list[i]!.label })), assign: Object.entries(plan.clips) .filter(([, t]) => keep.has(t)) .map(([clip, thread]) => ({ clip, thread })), }; if (v.threads.length < THREADS_TASK_COUNT[0]) continue; const again = planThreads(v, u, u.manifest); if (allProblems(again).length) continue; if (!best || v.threads.length > best.value!.threads.length) { best = { value: v, hard: [], soft: [...again.soft, `${a.value.threads.length - v.threads.length} refused thread(s) dropped`] }; } } return best; }, // The field is `{list}`; what an alternative keeps also carries `clips`, the // clip → thread assignments, so umtool's "Use this" sets each clip's thread // with the list (release 28 M9). `apply` writes the list alone. toField(value, u) { u.chosen = planThreads(value, u, u.manifest); return { list: u.chosen.list, clips: u.chosen.clips }; }, apply(manifest, u, value, provenance, force, ctx) { const { list } = value as { list: unknown }; const res = applyDraft(manifest, { field: "render.chrome.threads", value: { list }, provenance, force }); if (!res.applied) return res; setClipThreads(manifest, u.chosen?.clips ?? {}); const m = manifest as VideoManifest & { render?: { chrome?: Record } }; if (u.dropFlips && m.render?.chrome) { delete m.render.chrome.flips; clearDrafted(m, { field: "render.chrome.flips" }); ctx.handle.log(" the drafted flips were removed: flips and threads share the left panel"); } return res; }, describe(v, u) { const plan = planThreads(v, u, u.manifest); const count = (id: string) => Object.values(plan.clips).filter((t) => t === id).length; return ( plan.list.map((t) => `${t.label} (${count(t.id)} clip(s)${t.outcome ? `, ${t.outcome.verdict}` : ""})`).join("; ") + (u.dropFlips ? " — replaces the drafted flips" : "") ); }, }; export async function threads(input: ThreadsInput, deps: TaskDeps): Promise { return runMediaTask(THREADS_SPEC, input, deps); }