// TASK cut — which of the report's citations a video's cut keeps, and in what // order (release 28 M1). A STEP on a done iteration (./media.ts), one unit: // the timeline's ORDER (`drafted.timeline`). // // The model sees the report's claims (section, text, verdict) with the // citation ids the cut can show and their quotes, and answers an ordered list // of ids grouped under the section headings. Code checks it — ids only from // the candidates, none twice, at least CUT_MIN_CLIPS and at most `maxClips` // (settings.generation.cut.maxClips), every pinned id kept (a post rides on // it, a flip names it), headings that are the cut's — and then BUILDS the // timeline itself (`buildCut`): the existing entries of the chosen citations, // untouched (their windows, cite, quote, on-screen text: fetch and snap stay // code), chapter cards kept for the sections that still have entries and // dropped when nothing is left (S7's rule), the title card and everything // before the first chapter, the teaser and everything after the last clip, // kept where they are. It never invents an entry. The built cut must pass the // build's own validators as the cut it replaces did (`TaskDeps.deckChecks`). // // WHO OWNS THE ORDER (the M1 ruling). A timeline marked by a code path // (`model: "code"` — the converter's, `convertManifest.ts`) is nobody's: the // task drafts it without `force`. So is an unmarked one whose clips, in order, // are exactly what the converter makes from the project's report (a project // from before release 28). One marked by a model is a draft (`force` // redrafts it); any other is the operator's, never replaced: the draft goes // to cut-draft.json as an alternative. // // Q0: counts are code's; the prompt carries rules only; the better of two // attempts is kept; the local prompt is fitted under its cap. import { applyDraft, draftedOf, isCodeDraft, makeProvenance } from "../../drafted.mjs"; import { citedIds } from "../../convertShared"; import { reportToManifest, CONVERT_TASK } from "../../convertManifest"; import { providerOf } from "../../../llm"; import type { ManifestEntry, VideoManifest } from "../videoOps"; import { fitLocalAsk } from "./revise-report"; import type { DeckChecks } from "./deckChecks"; import { runMediaTask, type MediaContext, type MediaReport, type MediaSkip, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; import type { TaskDeps, TaskResult } from "./types"; export const CUT_MIN_CLIPS = 3; export const DEFAULT_MAX_CLIPS = 20; // The room a re-ask's words take on top of the fitted prompt. const RETRY_ROOM_CHARS = 1500; export type CutInput = MediaTaskInput & { // settings.generation.cut.maxClips (the job passes it). maxClips?: number; }; /** One citation the cut can show: its entry in the timeline, and what the report says of it. */ export type CutCandidate = { citation: string; entry: string; kind: "clip" | "still"; // The chapter it sits under now (its card's heading), or "". chapter: string; claim: { id?: string; text: string; verdict?: string } | null; quote: string; label: string; date: string; }; /** The model's answer, as code reads it. */ export type CutValue = { groups: { heading: string; clips: string[] }[] }; type Obj = Record; const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v); const norm = (s: unknown) => String(s ?? "").replace(/\s+/g, " ").trim().toLowerCase(); const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); const isChapter = (e: Obj) => e?.type === "card" && e?.style === "chapter"; const isCandidateType = (e: Obj) => e?.type === "clip" || e?.type === "image"; /** * The citation each clip or still of the timeline shows: its id when the * report has a citation of that id (the converter's rule), else the video * citation of its recording and second. First entry per citation. */ export function cutCandidates(manifest: VideoManifest, report: MediaReport): CutCandidate[] { const cites: Record = isObj(report.citations) ? report.citations : {}; const used = new Set(); const claimOf = new Map(); for (const s of Array.isArray(report.sections) ? report.sections : []) { for (const c of Array.isArray(s?.claims) ? s.claims : []) { const ids = [...(Array.isArray(c?.citations) ? c.citations : []), ...citedIds(typeof c?.findings === "string" ? c.findings : undefined)]; if (c?.sourceQuote?.citation) ids.unshift(c.sourceQuote.citation); for (const id of ids) { if (!claimOf.has(id)) claimOf.set(id, { ...(c.id ? { id: c.id } : {}), text: stripCites(String(c.text ?? "")), ...(c.verdict ? { verdict: c.verdict } : {}) }); } } } const slug = isObj(manifest.provenance) ? manifest.provenance.channelSlug : undefined; const out: CutCandidate[] = []; let chapter = ""; for (const e of manifest.timeline) { if (isChapter(e)) chapter = String(e.heading ?? ""); if (!isCandidateType(e)) continue; let cid: string | null = cites[e.id] && !used.has(e.id) ? e.id : null; if (!cid && e.type === "clip") { const ch = e.channel ?? slug; cid = Object.entries(cites).find( ([id, c]) => !used.has(id) && (c.kind === "video" || c.kind === "audio") && c.channel === ch && c.id === e.video && typeof c.start === "number" && Math.floor(c.start) === e.cite, )?.[0] ?? null; } if (!cid || used.has(cid)) continue; used.add(cid); const c = cites[cid]!; out.push({ citation: cid, entry: e.id, kind: e.type === "clip" ? "clip" : "still", chapter, claim: claimOf.get(cid) ?? null, quote: String(e.quote ?? c.quote ?? ""), label: String(c.label ?? ""), date: String(e.date ?? c.date ?? ""), }); } return out; } /** The entries something else names, which a cut must keep: posts ride on them, flips pair them. */ export function pinnedEntries(manifest: VideoManifest): Map { const out = new Map(); for (const p of Array.isArray(manifest.posts) ? manifest.posts : []) { if (isObj(p) && typeof p.attachTo === "string" && p.attachTo) out.set(p.attachTo, `post ${p.id ?? "?"} rides on it`); } const pairs = isObj(manifest.render) && isObj(manifest.render.chrome) && isObj(manifest.render.chrome.flips) ? manifest.render.chrome.flips.pairs : null; for (const pr of Array.isArray(pairs) ? pairs : []) { for (const side of ["then", "now"]) { const id = isObj(pr?.[side]) ? pr[side].entry : null; if (typeof id === "string" && id) out.set(id, `flip ${pr.id ?? "?"} pairs it`); } } return out; } /** * The cut the answer makes (pure; the timeline's entries only, never a new * one): what is before the first chapter or citation entry stays first, what * is after the last citation entry stays last (the teaser), and between them * each group plays under its chapter card (kept only when the group keeps an * entry), its chosen entries in the answer's order. An entry no citation * names (a hand-added clip, a still) stays with its chapter, after its card; * a chapter only such entries keep goes after the groups. Variant twins (one * id, several entries) move together. */ export function buildCut(manifest: VideoManifest, candidates: readonly CutCandidate[], value: CutValue): ManifestEntry[] { const T = manifest.timeline; const entryOf = new Map(candidates.map((c) => [c.citation, c.entry])); const candidateEntries = new Set(candidates.map((c) => c.entry)); const isCand = (e: ManifestEntry) => candidateEntries.has(e.id) && isCandidateType(e); const first = T.findIndex((e) => isChapter(e) || isCand(e)); let last = -1; T.forEach((e, i) => { if (isCand(e)) last = i; }); if (first < 0 || last < 0) return T.map((e) => ({ ...e })); const head = T.slice(0, first); const tail = T.slice(last + 1).filter((e) => !isChapter(e)); // The chapters between: a card (or none, before the first) and the entries // under it that no citation names. type Chapter = { card: ManifestEntry | null; others: ManifestEntry[] }; const chapters: Chapter[] = [{ card: null, others: [] }]; for (const e of T.slice(first, last + 1)) { if (isChapter(e)) { // A variant twin of a card already seen joins it. if (chapters.some((c) => c.card?.id === e.id)) continue; chapters.push({ card: e, others: [] }); } else if (!isCand(e)) chapters.at(-1)!.others.push(e); } const twins = (id: string) => T.filter((e) => e.id === id); const cardTwins = (c: ManifestEntry) => twins(c.id).filter(isChapter); const byHeading = new Map(); for (const c of chapters) if (c.card && !byHeading.has(norm(c.card.heading))) byHeading.set(norm(c.card.heading), c); const placed = new Set(); const middle: ManifestEntry[] = [...chapters[0]!.others]; placed.add(chapters[0]!); for (const g of value.groups) { const ids = g.clips.map((cid) => entryOf.get(cid)).filter((x): x is string => !!x); if (!ids.length) continue; const ch = g.heading.trim() ? byHeading.get(norm(g.heading)) : undefined; if (ch && !placed.has(ch)) { placed.add(ch); middle.push(...cardTwins(ch.card!), ...ch.others); } for (const id of ids) middle.push(...twins(id).filter(isCand)); } for (const c of chapters) { if (placed.has(c) || !c.others.length) continue; middle.push(...(c.card ? cardTwins(c.card) : []), ...c.others); } return JSON.parse(JSON.stringify([...head, ...middle, ...tail])) as ManifestEntry[]; } const clipOrder = (timeline: readonly Obj[]) => timeline.filter((e) => e?.type === "clip").map((e) => e.id); /** Is this timeline's clip order exactly the converter's from the report (a cut nobody reordered)? */ export async function isConverterOrder(manifest: VideoManifest, report: MediaReport): Promise { try { const made = await reportToManifest(report, {}); if (!made.ok) return false; const want = clipOrder(made.manifest.timeline as Obj[]); const have = clipOrder(manifest.timeline); return want.length === have.length && want.every((id, i) => id === have[i]); } catch { return false; } } type CutUnit = MediaUnit & { candidates: CutCandidate[]; pinned: Map; headings: string[]; max: number; // The order is code's (a converter mark, or the converter's order unmarked). codeMade: boolean; deck: DeckChecks | null; // The build's validator errors of the cut as read (unindexed): the draft may not add any. before: Set; }; const words = (s: string, n: number) => { const w = s.split(/\s+/).filter(Boolean); return w.length <= n ? w.join(" ") : `${w.slice(0, n).join(" ")} …`; }; // The evidence, at a level of detail: 0 the quotes in full, 1 shortened, // 2 none, 3 claims shortened too. function evidenceText(u: CutUnit, report: MediaReport, level: number): string { const lines = [`Report: ${String(report.title ?? "")}`, "", "Candidates, by the section each sits in now:"]; let chapter: string | null = null; let claim: string | null = null; for (const c of u.candidates) { if (c.chapter !== chapter) { chapter = c.chapter; claim = null; lines.push("", `## ${c.chapter || "(before the first section)"}`); } const ct = c.claim ? `${c.claim.verdict ? `[${c.claim.verdict}] ` : ""}${level >= 3 ? words(c.claim.text, 15) : c.claim.text}` : "(no claim: cited in the section's text)"; if (ct !== claim) { claim = ct; lines.push(`- Claim: ${ct}`); } const where = [c.kind === "still" ? "a still" : "a clip", c.label, c.date].filter(Boolean).join(", "); const q = level >= 2 || !c.quote ? "" : ` — "${level === 1 ? words(c.quote, 10) : words(c.quote, 40)}"`; lines.push(` - ${c.citation} (${where})${q}`); } const pinned = u.candidates.filter((c) => u.pinned.has(c.entry)); lines.push("", `Section headings: ${u.headings.map((h) => `"${h}"`).join(", ") || "(none)"}`); if (pinned.length) lines.push(`Must stay: ${pinned.map((c) => `${c.citation} (${u.pinned.get(c.entry)})`).join("; ")}`); lines.push(`Choose from ${CUT_MIN_CLIPS} to ${u.max} ids.`); return lines.join("\n"); } export function cutSystem(max: number): string { const rules = [ "Use only the citation ids listed under the candidates, each at most once.", `Choose at least ${CUT_MIN_CLIPS} and at most ${max} ids in all.`, "Keep every id listed under Must stay.", "Order the ids so the video builds its case: each one sets up or supports what follows, and the strongest evidence is not buried in the middle.", "Group them under the report's section headings, written exactly as given, in the order the groups play; each heading heads at most one group. An id may move to the group where it argues best.", "When two candidates show the same thing, keep the clearer one and leave the other out.", "Do not add anything that is not a candidate: no new clips, no new headings.", ]; return ( "You choose the clips of a short evidence video cut from a cited report, and their order. " + `Rules: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + 'Answer with "groups": a list of {"heading", "clips"} in play order, "clips" the citation ids in play order.' ); } const SCHEMA = { type: "object", properties: { groups: { type: "array", items: { type: "object", properties: { heading: { type: "string" }, clips: { type: "array", items: { type: "string" } } }, required: ["heading", "clips"], }, }, }, required: ["groups"], }; /** The model's answer to a CutValue (a throw is a hard failure). */ export function parseCut(answer: unknown): CutValue { const a = isObj(answer) ? answer : {}; const raw = Array.isArray(a.groups) ? a.groups : Array.isArray(a.clips) ? [{ heading: "", clips: a.clips }] : null; if (!raw) throw new Error('no "groups" in the answer'); const groups = raw.map((g: unknown) => { const o = isObj(g) ? g : {}; const clips = (Array.isArray(o.clips) ? o.clips : []).map((x: unknown) => String(x ?? "").trim()).filter(Boolean); return { heading: String(o.heading ?? "").replace(/\s+/g, " ").trim(), clips }; }); return { groups: groups.filter((g: { clips: string[] }) => g.clips.length) }; } const LIST_AT_MOST = 6; // A validator's sentence with its timeline positions taken out: a reorder // moves an old problem, it does not make a new one. const unindexed = (e: string) => e.replace(/\[\d+\]/g, "[]"); const listed = (xs: string[]) => (xs.length > LIST_AT_MOST ? [...xs.slice(0, LIST_AT_MOST), `and ${xs.length - LIST_AT_MOST} more`] : xs).join(", "); /** Every code check of a cut: `hard` refuses it. */ export function checkCut(value: CutValue, u: CutUnit, manifest: VideoManifest): { hard: string[]; soft: string[] } { const hard: string[] = []; const known = new Map(u.candidates.map((c) => [c.citation, c])); const ids = value.groups.flatMap((g) => g.clips); const unknown = [...new Set(ids.filter((id) => !known.has(id)))]; if (unknown.length) hard.push(`not a candidate of this cut: ${listed(unknown)} (choose only the ids listed)`); const twice = [...new Set(ids.filter((id, i) => ids.indexOf(id) !== i))]; if (twice.length) hard.push(`chosen more than once: ${listed(twice)}`); const n = new Set(ids.filter((id) => known.has(id))).size; if (n > u.max) hard.push(`${n} ids chosen (at most ${u.max})`); if (n < CUT_MIN_CLIPS) hard.push(`${n} ids chosen (at least ${CUT_MIN_CLIPS})`); const missing = u.candidates.filter((c) => u.pinned.has(c.entry) && !ids.includes(c.citation)); for (const c of missing) hard.push(`${c.citation} must stay (${u.pinned.get(c.entry)})`); const headings = new Set(u.headings.map(norm)); const seen = new Set(); for (const g of value.groups) { if (!g.heading) continue; const h = norm(g.heading); if (!headings.has(h)) hard.push(`"${g.heading}" is not a section heading of this cut (${u.headings.map((x) => `"${x}"`).join(", ")})`); else if (seen.has(h)) hard.push(`"${g.heading}" heads two groups`); seen.add(h); } if (!hard.length && u.deck) { const next = { ...manifest, timeline: buildCut(manifest, u.candidates, value) }; const added = u.deck.validatorErrors(next).filter((e) => !u.before.has(unindexed(e))); for (const e of added.slice(0, LIST_AT_MOST)) hard.push(`the cut would not build: ${e}`); } return { hard, soft: [] }; } /** The cut as a media task (./media.ts): one unit, the timeline's order. */ export const CUT_SPEC: MediaTaskSpec = { task: "cut", noun: "cut", verb: "drafted", progressMetric: "entries", async units(ctx) { const { manifest, report, input } = ctx; const candidates = cutCandidates(manifest, report); if (candidates.length < CUT_MIN_CLIPS) { return [{ id: "cut", skipped: `only ${candidates.length} of the report's citations are in the cut (a cut needs ${CUT_MIN_CLIPS})` } satisfies MediaSkip]; } let deck: DeckChecks | null = null; try { deck = (await ctx.handle.deps.deckChecks?.()) ?? null; } catch (e) { ctx.handle.log(` the build's validators are not loaded (${(e as Error).message}); the cut is checked without them`); } const mark = draftedOf(manifest, { field: "timeline" }); const codeMade = mark ? isCodeDraft(mark) : await isConverterOrder(manifest, report); // The chapters a group may play under: the cards before the last // candidate (one after it has nothing to head, and is dropped). const lastAt = Math.max(...candidates.map((c) => manifest.timeline.findIndex((e) => e.id === c.entry))); const headings: string[] = []; for (const e of manifest.timeline.slice(0, lastAt)) { if (isChapter(e) && e.heading && !headings.some((h) => norm(h) === norm(e.heading))) headings.push(String(e.heading)); } return [ { id: "cut", target: { field: "timeline" }, label: "the cut's clips and order", candidates, pinned: pinnedEntries(manifest), headings, max: Math.max(CUT_MIN_CLIPS, input.maxClips ?? DEFAULT_MAX_CLIPS), codeMade, deck, before: new Set(deck ? deck.validatorErrors(manifest).map(unindexed) : []), }, ]; }, owner(manifest, u) { const mark = draftedOf(manifest, { field: "timeline" }); if (mark) return isCodeDraft(mark) ? "empty" : "drafted"; return u.codeMade ? "empty" : "operator"; }, schema: () => SCHEMA, system: (u) => cutSystem(u.max), user(u, ctx: MediaContext) { const ask = "\n\nChoose the cut's ids and their order."; const build = (maxChars: number) => { for (let level = 0; level <= 3; level++) { const t = evidenceText(u, ctx.report, level) + ask; if (t.length <= maxChars || level === 3) return t; } return ""; }; if (providerOf(ctx.input.model) !== "local") return build(Number.POSITIVE_INFINITY); const system = cutSystem(u.max); return fitLocalAsk({ llm: ctx.handle.deps.llm, model: ctx.input.model, system, schema: SCHEMA, build: (max) => build(max - RETRY_ROOM_CHARS) }).user; }, parse: (answer) => parseCut(answer), check: (value, u, ctx) => checkCut(value, u, ctx.manifest), toField: (value, u, manifest) => buildCut(manifest, u.candidates, value), apply(manifest, u, value, provenance, force) { const mark = draftedOf(manifest, { field: "timeline" }); // A code-made order is nobody's: drafted over as a draft would be. One // with no mark is given the converter's first, so the writer sees a draft. if (u.codeMade && !mark) { manifest.drafted = { ...(isObj(manifest.drafted) ? manifest.drafted : {}), timeline: makeProvenance({ task: CONVERT_TASK, model: "code", attempt: 1 }) }; } const code = u.codeMade || isCodeDraft(mark); return applyDraft(manifest, { field: "timeline", value, provenance, force: force || code }); }, describe: (v) => v.groups.map((g) => `${g.heading || "—"}: ${g.clips.join(" ")}`).join(" | "), }; export async function cut(input: CutInput, deps: TaskDeps): Promise { return runMediaTask(CUT_SPEC, input, deps); }