// TASK narrate — card narration for an iteration's video cut (release 27, S5; // the stopgap's local_narrate.py). A STEP on a done iteration (its `steps`), // never an iteration of its own. // // For each title and chapter card the model drafts the words from that card's // own evidence (the section's claims and quotes) under the authoring rules — // the narration hard rule, the writing rules without their examples or the // tag rule, the house taste. Code checks every draft (./grounding.ts: no tags, // no stock phrases, every number and name in the report, no quote read out); // a failing draft is re-asked once and the better attempt kept; one still // failing a hard check loses its failing sentences, and a card with nothing // left is not written. The manifest is snapshotted, then written whole; every // draft and its checks go to the project's narration-draft.json. // // Release 28 (M0): a spec on the media task scaffold (./media.ts). A narration // it writes carries its drafted mark (`entry.drafted.narration`), and a card // whose narration is the operator's (words with no mark) is never replaced, // even with `force`: the draft goes to narration-draft.json's alternatives. import { entriesWithId } from "../../drafted.mjs"; import { NARRATION_HARD_RULE, NARRATION_TASTE, NARRATION_WRITING_RULES, rulesForModel } from "../authoringRules"; import { checkNarration, groundingInputOf, sentencesOf, type GroundingInput } from "../grounding"; import type { ManifestEntry } from "../videoOps"; import { runMediaTask, type MediaSkip, type MediaTaskInput, type MediaTaskSpec, type MediaUnit } from "./media"; import type { TaskDeps, TaskResult } from "./types"; export const TITLE_WORDS = 35; export const CHAPTER_WORDS = 45; // A draft this far over its limit is refused outright. export const OVER_LIMIT_SLACK = 10; export type NarrateInput = MediaTaskInput & { // Only these card ids (default: every title and chapter card). cards?: string[]; }; type Section = { title?: string; body?: string | null; claims?: { text?: string; citations?: string[] }[] | null }; type ReportLike = { title?: string; summary?: string | null; sections?: Section[]; citations?: Record | null; }; export function narrationSystem(limit: number): string { const rules = rulesForModel(NARRATION_WRITING_RULES, { tags: false }); return ( "You write the spoken narration for one card of a short evidence video; a stock synthetic voice reads it aloud. " + `${NARRATION_HARD_RULE} Rules for the ear: ${rules.map((r, i) => `(${i + 1}) ${r}`).join(" ")} ` + `House style: ${NARRATION_TASTE.join(" ")} At most ${limit} words, one short paragraph, plain text.` ); } const stripCites = (s: string) => s.replace(/\[([^\]]+)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, ""); // A card's evidence and the quotes it must not read out; null when the card // matches no section of the report. export function cardContext(card: ManifestEntry, report: ReportLike): { text: string; quotes: string[] } | null { const cites = report.citations ?? {}; if (card.style === "title") { const claims = (report.sections ?? []).flatMap((s) => (s.claims ?? []).map((c) => stripCites(c.text ?? ""))).slice(0, 6); return { text: "This is the OPENING card: set up what the video looks at in one or two short sentences, as a hook. Do not list " + `the sections and do not give the findings away.\nReport title: ${report.title ?? ""}` + (report.summary ? `\n${report.summary}` : "") + `\nSome of what it found:\n${claims.map((c) => `- ${c}`).join("\n")}`, quotes: Object.values(cites).map((c) => c?.quote ?? "").filter(Boolean), }; } const s = (report.sections ?? []).find((x) => x.title === card.heading); if (!s) return null; const lines = [`Section: ${s.title}`]; const quotes: string[] = []; if (s.body) lines.push(`Section text: ${stripCites(s.body)}`); for (const c of (s.claims ?? []).slice(0, 12)) { const ids = (c.citations ?? []).filter((i) => cites[i]); const q = ids.map((i) => cites[i]?.quote ?? "").filter(Boolean).join(" … "); const dates = [...new Set(ids.map((i) => cites[i]?.date ?? "").filter(Boolean))].sort(); lines.push(`- Claim: ${stripCites(c.text ?? "")}${dates.length ? ` (${dates.join(", ")})` : ""}${q ? `\n Quote: ${q}` : ""}`); if (q) quotes.push(q); } return { text: lines.join("\n"), quotes }; } type Attempt = { text: string; hard: string[]; soft: string[] }; function checkDraft(text: string, g: GroundingInput, limit: number): Attempt { const r = checkNarration(text, g); const hard = [...r.hard]; const words = text.split(/\s+/).filter(Boolean).length; if (words > limit + OVER_LIMIT_SLACK) hard.push(`${words} words (limit ${limit})`); if (!text) hard.push("empty"); return { text, hard, soft: r.soft }; } // The best of the attempts; when it still fails a hard check, the attempts // with their failing sentences REMOVED (never rewritten) and cut to the limit. export function chooseDraft(attempts: Attempt[], g: GroundingInput, limit: number): Attempt { const rank = [...attempts].sort((a, b) => a.hard.length - b.hard.length || a.soft.length - b.soft.length); const best = rank[0] ?? { text: "", hard: ["no draft"], soft: [] }; if (!best.hard.length) return best; for (const cand of rank) { const sents = sentencesOf(cand.text).filter((t) => !checkNarration(t, g).hard.length); while (sents.length && sents.join(" ").split(/\s+/).length > limit) sents.pop(); const text = sents.join(" ").trim(); if (text.split(/\s+/).filter(Boolean).length < 5) continue; const again = checkDraft(text, g, limit); if (!again.hard.length) return { text, hard: [], soft: [...again.soft, "trimmed: failing or overlong sentences removed"] }; } return best; } // A unit: one card, its limit and evidence. type NarrateUnit = MediaUnit & { card: ManifestEntry; limit: number; g: GroundingInput; ctxText: string }; /** Narrate as a media task (./media.ts): one unit per title and chapter card. */ export const NARRATE_SPEC: MediaTaskSpec = { task: "narrate", // Its audit file kept its release 27 name. draftFile: "narration-draft.json", snapshotOp: "narration", checkName: "narration", turnKind: "narration", noun: "card", verb: "narrated", progressMetric: "cards", units(ctx) { const out: (NarrateUnit | MediaSkip)[] = []; const only = ctx.input.cards?.length ? new Set(ctx.input.cards) : null; const seen = new Set(); for (const card of ctx.manifest.timeline) { if (card.type !== "card" || (card.style !== "title" && card.style !== "chapter")) continue; if (only && !only.has(card.id)) continue; if (seen.has(card.id)) continue; seen.add(card.id); if ((card.heading ?? "").trim().toLowerCase() === "coverage") { out.push({ id: card.id, skipped: "the Coverage card is not narrated (its numbers are on the page)" }); continue; } const c = cardContext(card, ctx.report as ReportLike); if (!c) { out.push({ id: card.id, skipped: "no section in the report matches this card's heading" }); continue; } const limit = card.style === "title" ? TITLE_WORDS : CHAPTER_WORDS; out.push({ id: card.id, target: { entry: card.id, field: "narration" }, label: card.heading, card, limit, g: { ...ctx.grounding, quotes: c.quotes }, ctxText: c.text, }); } return out; }, schema: () => ({ type: "object", properties: { text: { type: "string" } }, required: ["text"] }), system: (u) => narrationSystem(u.limit), user: (u) => `Card heading on screen: ${u.card.heading ?? ""}\n\nEvidence for this card (the only facts you may use):\n${u.ctxText}\n\nWrite this card's narration.`, parse: (answer) => String((answer as { text?: unknown } | null)?.text ?? "") .replace(/\s+/g, " ") .trim() .replace(/^"+|"+$/g, ""), check(text, u) { const a = checkDraft(text, u.g, u.limit); return { hard: a.hard, soft: a.soft }; }, repair(attempts, u) { const chosen = chooseDraft( attempts.map((a) => ({ text: a.value ?? "", hard: a.hard, soft: a.soft })), u.g, u.limit, ); return chosen.hard.length ? null : { value: chosen.text, hard: [], soft: chosen.soft }; }, toField(text, u, manifest) { const cur = entriesWithId(manifest, u.card.id)[0]?.narration; return { ...(cur && typeof cur === "object" ? cur : {}), text }; }, afterApply(manifest, u) { for (const e of entriesWithId(manifest, u.card.id)) e.seconds = "auto"; }, describe: (text) => text, }; export async function narrate(input: NarrateInput, deps: TaskDeps): Promise { return runMediaTask(NARRATE_SPEC, input, deps); }