// TASK revise-video — a new iteration of an article's video cut from the // operator's feedback (release 27, S5; the stopgap's `revise.py video`). // // The model reads the parent iteration's cut (its project's // video.manifest.json) and changes it ONLY through `apply_ops` // (./videoOps.ts: a narration passes grounding, a trim stays within the // fetched window ±3 s, a clip added comes from the report's citations). The // new cut is this iteration's project, seeded from the parent's: the report // and stills copied, the voices hard-linked. A video revision has no report of // its own (its article's report stays its nearest ancestor's). // // ON A LOCAL MODEL (release 28 Q3) there is no tool loop: one schema-bound ask // for the ops batch over the cut trimmed to the prompt cap (videoOps // trimmedCutView: the chapters the feedback names first, quotes shortened in // the view only), as revise-report does. The API path is unchanged. import { providerOf, runAgent, structuredAnswer, type AgentTool } from "../../../llm"; import { readIteration, type Iteration } from "../../iterations"; import { applyVideoOps, cutView, trimmedCutView, type AppliedVideoOp, type RefusedVideoOp, type ReportForVideo, type VideoManifest } from "../videoOps"; import { rewriteMomentBases, slugResolver } from "./links"; import { projectDirOf, readManifest, readProjectReport, seedProject, writeManifest } from "./project"; import { fieldSignature, makeProvenance, stableStringify } from "../../drafted.mjs"; import { COMMON_REVISE_RULES, LOCAL_REVISE_RULES, OPS_SCHEMA, localOpsBatch, reviseCorpusTools } from "./revise-report"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; import type { TaskDeps, TaskResult } from "./types"; export const VIDEO_OPS_TEXT = [ "Operations (objects for apply_ops; entries are named by id):", '- {"op":"drop","id":""} remove an entry', '- {"op":"move","id":"","after":""} reorder', '- {"op":"heading","id":"","text":"..."} a card\'s on-screen heading', '- {"op":"narration","id":"","text":"..."} a card\'s spoken narration (for the ear: short, casual, contractions; third person — never I, me, my, we, us or our; no quotes read out; no numbers or names the report lacks; no tags); "text":"" removes it', '- {"op":"trim","id":"","start":S,"end":E} a clip\'s in/out seconds, within 3 s of its current ones', '- {"op":"add_clip","citation":"","after":""} a clip for a cited moment not in the cut', '- {"op":"title","text":"..."} / {"op":"subtitle","text":"..."}', // Release 38: the look (the video assistant's look ops, checked by the look's own rules). '- {"op":"look","key":"transition","value":0.15} the join between clips in seconds (0 = hard cuts); key transitionStyle (fade, fadeblack, fadewhite, dissolve, blurslide), qr (true/false), loudness (a LUFS target, higher = louder; null = as recorded), captions (true/false), headerHeight / footerHeight (pixels, 0 = off)', '- {"op":"slide","key":"blur","value":0.3} the blur slide: key travel, blur (the smear) or grain', '- {"op":"room","key":"maxS","value":2} room at the clips\' edges: key tail / head (true/false), maxS (seconds the sound may run past a cut), minGap', ].join("\n"); // OPS_SCHEMA and the look ops' key and value (release 38). export const VIDEO_OPS_SCHEMA = { ...OPS_SCHEMA, properties: { ops: { ...OPS_SCHEMA.properties.ops, items: { ...OPS_SCHEMA.properties.ops.items, properties: { ...OPS_SCHEMA.properties.ops.items.properties, key: { type: "string" }, value: { type: ["number", "string", "boolean", "null"] } }, }, }, }, }; const shortQuote = (q: string, words = 12) => { const w = q.split(/\s+/).filter(Boolean); return w.length > words ? `${w.slice(0, words - 4).join(" ")} …` : q; }; export type ReviseVideoInput = { article: string; n: number; model?: string; feedback?: string; origin: string; maxUsd: number; projectsRoot: string; web?: boolean; webSearchMaxUses?: number; maxTurns?: number; }; export async function reviseVideo(input: ReviseVideoInput, deps: TaskDeps): Promise { return runOnIteration({ article: input.article, n: input.n, deps, maxUsd: input.maxUsd, kinds: ["revise-video"] }, (h) => reviseVideoBody(h, input), ); } // The nearest iteration up `n`'s parents whose project has a manifest. async function parentProject(h: TaskHandle, projectsRoot: string): Promise<{ it: Iteration; dir: string; manifest: VideoManifest } | null> { let at = h.iteration.parent; while (at !== null) { const it = await readIteration(h.article, at, h.paths); if (!it) return null; const dir = projectDirOf(it, projectsRoot); const manifest = await readManifest(dir); if (manifest) return { it, dir, manifest }; at = it.parent; } return null; } async function reviseVideoBody(h: TaskHandle, input: ReviseVideoInput): Promise { const { deps, iteration } = h; const model = input.model ?? iteration.model; const feedback = (input.feedback ?? iteration.feedback ?? "").trim(); if (!feedback) throw new TaskInputError("a revision needs feedback"); const parent = await parentProject(h, input.projectsRoot); if (!parent) throw new TaskInputError(`"${h.article}" i${h.n}: no iteration it revises has a video cut (run the chain to its manifest first)`); const report = (await readProjectReport(parent.dir)) as ReportForVideo | null; if (!report) throw new TaskInputError(`${parent.dir} has no report.json beside its manifest`); const origin = input.origin.replace(/\/+$/, ""); const channels = [...new Set(Object.values(report.citations ?? {}).map((c) => c?.channel).filter((c): c is string => !!c))]; const resolver = slugResolver(deps.corpus, channels); const rewrite = (t: string) => rewriteMomentBases(t, resolver, origin); let manifest: VideoManifest = structuredClone(parent.manifest); const applied: AppliedVideoOp[] = []; const refused: RefusedVideoOp[] = []; const cites = Object.entries(report.citations ?? {}) .map(([cid, c]) => `${cid}: ${c?.channel}/${c?.id} @ ${Math.floor(c?.start ?? 0)} s "${String(c?.quote ?? "").slice(0, 160)}"`) .join("\n"); const view = () => `${cutView(manifest)}\n\nREPORT CITATIONS (add_clip takes these ids):\n${cites}`; const applyOps = (ops: unknown[]) => { const r = applyVideoOps(manifest, ops, { report, parent: parent.manifest, feedback }); manifest = r.manifest; applied.push(...r.applied); refused.push(...r.refused); h.log(`ops: ${r.applied.length} applied, ${r.refused.length} refused`); return r; }; h.log(`revising the cut of i${parent.it.n} on ${model}`); const tools: AgentTool[] = [ ...reviseCorpusTools(deps, rewrite), ...(input.web === false ? [] : (deps.web ?? [])), { name: "read_doc", description: "The cut as it is now, and the report's citations.", inputSchema: { type: "object", properties: {} }, run: async () => view() }, { name: "apply_ops", description: "Apply edit operations (see the system prompt). Returns what was applied and refused, and the cut after.", inputSchema: VIDEO_OPS_SCHEMA, run: async (inp: { ops?: unknown }) => { const r = applyOps(Array.isArray(inp?.ops) ? inp.ops : []); return ( JSON.stringify({ applied: r.applied.map((a) => ({ index: a.index, op: a.op.op, ...(a.warnings ? { warnings: a.warnings } : {}) })), refused: r.refused.map((x) => ({ index: x.index, op: x.op.op, why: x.why })), }) + `\n\nNow:\n${cutView(manifest)}` ); }, }, ]; const what = "video cut (an evidence video: cards with spoken narration between clips of what was said)"; if (providerOf(model) === "local") { // Release 28 Q3: one ops batch over the cut trimmed to the prompt cap. const citeRows = Object.entries(report.citations ?? {}).map(([cid, c]) => ({ cid, line: `${cid}: ${c?.channel}/${c?.id} @ ${Math.floor(c?.start ?? 0)} s "${shortQuote(String(c?.quote ?? ""))}"`, })); const named = (cid: string) => new RegExp(`\\b${cid}\\b`).test(feedback); const citeOrder = [...citeRows].sort((a, b) => Number(named(b.cid)) - Number(named(a.cid))); await localOpsBatch(h, { model, system: `${LOCAL_REVISE_RULES(what)}\n\n${VIDEO_OPS_TEXT.replace("objects for apply_ops", "objects in the `ops` list")}`, what: "cut", schema: VIDEO_OPS_SCHEMA, build: (maxChars) => { const budget = maxChars - feedback.length - 400; const cut = trimmedCutView(manifest, { maxChars: Math.floor(budget * 0.7), feedback }); let left = budget - cut.text.length; const shown: string[] = []; for (const c of citeOrder) { if (c.line.length + 1 > left) continue; left -= c.line.length + 1; shown.push(c.cid); } const lines = citeRows.filter((c) => shown.includes(c.cid)).map((c) => c.line); const more = citeRows.length - lines.length; return ( `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW (quotes shortened in this view only):\n${cut.text}\n\n` + `REPORT CITATIONS (add_clip takes these ids${more ? `; ${more} more not shown` : ""}):\n${lines.join("\n")}\n\n` + `THE REPORT IT IS CUT FROM: ${String(report.title ?? "")}\n\nAnswer with the ops batch that carries out the feedback.` ); }, apply: async (ops) => applyOps(ops), }); } else { const system = `${COMMON_REVISE_RULES(what)}\n\n${VIDEO_OPS_TEXT}`; const run = await runAgent({ llm: deps.llm, model, system, user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nTHE REPORT IT IS CUT FROM: ${String(report.title ?? "")}`, tools, meter: h.meter, maxUsd: input.maxUsd, maxTurns: input.maxTurns ?? 30, ...(input.web !== false ? { serverWebSearch: { maxUses: input.webSearchMaxUses ?? 3 } } : {}), signal: deps.signal, onEvent: (e) => { if (e.type !== "turn") return; h.progress({ metric: "turns", current: e.turn + 1, total: input.maxTurns ?? 30 }); h.log(`turn ${e.turn}: ${e.calls.join(", ") || "done"} — ~$${h.meter.usd.toFixed(2)}`); }, }); h.turns(run.transcript); if (run.stopReason === "cancelled") return { status: "failed", summary: "cancelled" }; // A model that ends without calling apply_ops gets ONE schema-bound ask for // the batch; nothing at all after that is a failing check, not a quiet "0 // applied". if (applied.length + refused.length === 0) { const asked = await structuredAnswer<{ ops?: unknown[] }>({ llm: deps.llm, model, system, user: `OPERATOR FEEDBACK:\n${feedback}\n\nTHE VIDEO NOW:\n${view()}\n\nAnswer with the ops batch that carries out the feedback.`, schema: VIDEO_OPS_SCHEMA, meter: h.meter, signal: deps.signal, }).catch((e: unknown) => { h.log(`the ops ask failed: ${(e as Error).message}`); return null; }); if (asked && Array.isArray(asked.ops) && asked.ops.length) { h.log(`no apply_ops call: asked for the batch, ${asked.ops.length} op(s)`); applyOps(asked.ops); } } } if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" }; h.check({ name: "ops", ok: applied.length + refused.length > 0, detail: applied.length + refused.length > 0 ? `${applied.length} applied, ${refused.length} refused` : "the model proposed no edits", }); const ops = { applied: applied.map((a) => (a.warnings ? { ...a.op, warnings: a.warnings } : a.op)), refused: refused.map((r) => ({ ...r.op, why: r.why })), }; // Release 28 (the M9 ruling): ops that change the cut's order make that // order a model's draft — reviewable as the cut's row, and redrafted by the // cut task only with force. An order they leave as it was keeps the // parent's mark (or none). if (timelineOrderChanged(parent.manifest, manifest)) { const m = manifest as VideoManifest & { drafted?: Record }; m.drafted = { ...(m.drafted ?? {}), timeline: makeProvenance({ task: "revise-video", model, iteration: h.n, attempt: 1 }) }; h.log(`the cut's order changed: marked a draft of revise-video on ${model}`); } const dir = projectDirOf(iteration, input.projectsRoot); const seeded = await seedProject(parent.dir, dir, manifest); await writeManifest(dir, manifest); h.check({ name: "cut", ok: true, detail: `${manifest.timeline.length} timeline entries; from i${parent.it.n}: ${seeded.voices} voice(s) linked, ${seeded.stills} still(s)` }); return { status: "done", summary: `${ops.applied.length} op(s) applied, ${ops.refused.length} refused — the cut in ${dir}`, patch: { ops, projectDir: dir }, }; } /** Whether the timeline's order (its entries' ids, the cut's drafted field) differs between two manifests. */ export function timelineOrderChanged(before: unknown, after: unknown): boolean { return stableStringify(fieldSignature(before, { field: "timeline" })) !== stableStringify(fieldSignature(after, { field: "timeline" })); }