// What the flips, threads and youtube drafts read (release 28, M4–M6): the // cut's clips as facts code can check against — each clip's quote, the claim // it stands for (and that claim's verdict), the chapter it sits under, and // the date its recording was made — and the one check of a short line of // text (a topic, a label, a title) against the report. // // THE DATE is code's, never the model's: the entry's own `date` (the // operator's, what the clip's header shows), else the recording's upload date // from the corpus record (`get_video_metadata`, the reader the other tasks // use), else the citation's `date`. A clip with none is in no pair. import { strictNormalize } from "../../../citations/verify"; import { extractJsonObject } from "../../../parseStdoutJson"; import { checkNarration, type GroundingInput, type GroundingResult } from "../grounding"; import type { ManifestEntry, VideoManifest } from "../videoOps"; import type { MediaReport } from "./media"; import { isTitleCase, titleAsSentence } from "./onscreen"; import type { CorpusToolsLike } from "./types"; export type ClipClaim = { id?: string; text: string; verdict?: string }; /** One clip of the cut, as the media drafts read it. */ export type ClipFact = { id: string; // The clip's first place in the timeline. index: number; quote: string; claim: ClipClaim | null; // The chapter card it sits under (its heading), if any. section: string | null; // YYYY-MM-DD, or null when nothing says. date: string | null; dateFrom: "entry" | "record" | "citation" | null; }; const stripCites = (s: string) => s.replace(/\[([^\]]*)\]\(cite:[^)]+\)/g, "$1").replace(/\(cite:[^)]+\)/g, "").replace(/\s+/g, " ").trim(); /** `20260105`, `2026-01-05` or an ISO stamp → `2026-01-05`; else null. */ export function isoDay(v: unknown): string | null { if (typeof v !== "string") return null; const t = v.trim(); let m = /^(\d{4})(\d{2})(\d{2})$/.exec(t); if (m) return `${m[1]}-${m[2]}-${m[3]}`; m = /^(\d{4})-(\d{2})-(\d{2})(?:$|T)/.exec(t); return m ? `${m[1]}-${m[2]}-${m[3]}` : null; } const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; /** A side's `when`, written by code from its date: `Jan 2026`. */ export const whenOf = (day: string) => `${MONTHS[Number(day.slice(5, 7)) - 1] ?? ""} ${day.slice(0, 4)}`.trim(); // Every claim of the report by id, and by the citations it cites. function claimIndex(report: MediaReport) { const byId = new Map(); const byCite = new Map(); for (const s of (report.sections ?? []) as { claims?: { id?: string; text?: string; citations?: string[]; verdict?: string }[] }[]) { for (const c of s.claims ?? []) { const claim: ClipClaim = { ...(c.id ? { id: c.id } : {}), text: stripCites(c.text ?? ""), ...(c.verdict ? { verdict: c.verdict } : {}) }; if (c.id) byId.set(c.id, claim); for (const cid of c.citations ?? []) if (!byCite.has(cid)) byCite.set(cid, claim); } } return { byId, byCite }; } /** * The cut's clips (every clip of the timeline once, in timeline order), with * their claims, chapters and dates. `corpus` is asked for the dates the * entries do not carry; a failed read leaves the date to the citation's. */ export async function clipFacts( manifest: VideoManifest, report: MediaReport, corpus: Pick | null, { dates = true }: { dates?: boolean } = {}, ): Promise { const { byId, byCite } = claimIndex(report); const cites = (report.citations ?? {}) as Record; const prov = (manifest.provenance ?? {}) as { channelSlug?: string }; const recordDates = new Map>(); const recordDate = (channel: string, video: string) => { const key = `${channel}/${video}`; let p = recordDates.get(key); if (!p) { p = (corpus ? corpus.call("get_video_metadata", { channel, video_id: video }) : Promise.resolve("")) .then((t) => isoDay((extractJsonObject(t) as { uploadDate?: unknown } | null)?.uploadDate)) .catch(() => null); recordDates.set(key, p); } return p; }; const out: ClipFact[] = []; const seen = new Set(); let section: string | null = null; for (const [index, e] of manifest.timeline.entries()) { if (e.type === "card" && e.style === "chapter") section = e.heading ?? null; if (e.type !== "clip" || seen.has(e.id)) continue; seen.add(e.id); const claimRef = (e.claim ?? null) as { id?: string; verdict?: string } | null; const base = (claimRef?.id ? byId.get(claimRef.id) : undefined) ?? byCite.get(e.id) ?? null; const claim = base || claimRef?.verdict ? { ...(base ?? { text: "" }), ...(claimRef?.verdict ? { verdict: claimRef.verdict } : {}) } : null; const channel = String(e.siteChannel ?? e.channel ?? prov.channelSlug ?? ""); const video = String(e.siteVideo ?? e.video ?? ""); let date = dates ? isoDay(e.date) : null; let dateFrom: ClipFact["dateFrom"] = date ? "entry" : null; if (dates && !date && channel && video) { date = await recordDate(channel, video); if (date) dateFrom = "record"; } if (dates && !date) { date = isoDay(cites[e.id]?.date); if (date) dateFrom = "citation"; } out.push({ id: e.id, index, quote: String(e.quote ?? "").trim(), claim, section, date, dateFrom }); } return out; } /** A clip's evidence line for a prompt (its quote and claim cut to `max` characters each). */ export function clipLine(c: ClipFact, { max = 160, date = true }: { max?: number; date?: boolean } = {}): string { const cut = (s: string) => (s.length > max ? `${s.slice(0, max - 1)}…` : s); return ( `- ${c.id}` + (date ? ` [${c.date ?? "date unknown"}]` : "") + (c.section ? ` (chapter: ${c.section})` : "") + (c.quote ? `: "${cut(c.quote)}"` : "") + (c.claim?.text ? ` — claim: ${cut(c.claim.text)}` : "") ); } /** Lines that fit a character budget, in order; the rest counted. */ export function fitLines(lines: string[], budget: number): { text: string; omitted: number } { const kept: string[] = []; let used = 0; for (const l of lines) { if (used + l.length + 1 > budget) break; kept.push(l); used += l.length + 1; } return { text: kept.join("\n"), omitted: lines.length - kept.length }; } const FIT_SMALL = new Set(["a", "an", "the", "and", "or", "of", "to", "in", "on", "for", "with", "at", "by", "from", "as", "but"]); /** * A short line (a flip's topic, a thread's label) fitted to `max` characters * in code, never by asking again: a line over it keeps the part before a colon * or a dash when that part fits, else drops words from its end — and a small * word left dangling — until it fits. A line that fits is returned as it is. */ export function fitShortLine(text: string, max: number): string { const t = text.trim(); if (t.length <= max) return t; const head = t.split(/\s*[:—–]\s*|\s+-\s+/)[0]!.trim(); if (head && head.length <= max && head !== t) return head; const words = t.split(/\s+/); while (words.length > 1 && (words.join(" ").length > max || FIT_SMALL.has(words.at(-1)!.toLowerCase()))) words.pop(); return words.join(" ").replace(/[\s,;:.]+$/, ""); } const QUOTED = /“([^”]+)”|"([^"]+)"/g; /** * A short line's problems (a topic, a label, a title or a summary), by the * narration's grounding (./grounding.ts): every name and number in the * report, no stock phrase, no first person, no tag. With `quotes`, words in * quotation marks are allowed only when a cited quote says them verbatim * (they are then left out of the other checks); without, any quotation marks * or a run of a quote's words is refused, as in narration. */ export function checkLine(text: string, g: GroundingInput, { quotes = false }: { quotes?: boolean } = {}): GroundingResult { // A Title Case line is checked in its sentence case, and a capital left over // that the report lacks is soft (./onscreen.ts titleLineGrounding says why). if (isTitleCase(text)) { const r = checkLineAsIs(titleAsSentence(text, g.reference), g, quotes); const names = r.hard.filter((h) => h.startsWith("name “")); return { hard: r.hard.filter((h) => !h.startsWith("name “")), soft: [...r.soft, ...names.map((h) => `${h} (a Title Case word — check it is not a name)`)], }; } return checkLineAsIs(text, g, quotes); } function checkLineAsIs(text: string, g: GroundingInput, quotes: boolean): GroundingResult { if (!quotes) return checkNarration(text, g); const hard: string[] = []; const said = g.quotes.map((q) => ` ${strictNormalize(q)} `); const stripped = text.replace(QUOTED, (_m, a: string | undefined, b: string | undefined) => { const words = strictNormalize(a ?? b ?? ""); if (!words || !said.some((q) => q.includes(` ${words} `))) hard.push(`“${(a ?? b ?? "").slice(0, 80)}” is not what a cited clip says, word for word`); return " "; }); const r = checkNarration(stripped, { ...g, quotes: [] }); return { hard: [...new Set([...hard, ...r.hard])].sort(), soft: r.soft }; } /** The clips in a manifest by id (the first entry with each id). */ export function clipsById(manifest: VideoManifest): Map { const m = new Map(); for (const e of manifest.timeline) if (e.type === "clip" && !m.has(e.id)) m.set(e.id, e); return m; }