// GROUNDING — the code checks every drafted narration line passes before it // is used (the stopgap's local_narrate.py `checks`, release 27 S2), plus the // Q0 lints. // // HARD (the line is refused): // - a tag in angle brackets (no expressive tags or stage directions); // - a stock phrase from BANNED_PHRASES; // - a number — digits or a number word — the report does not have; // - a capitalised name the report does not have (the first word of a // sentence and the COMMON_CAPS words aside); // - text in quotation marks: a narrator does not read quotes out; // - six or more consecutive words of a cited quote: the clip says it; // - a first-person word (I, me, my, we, us, our, … — FIRST_PERSON_WORDS) // outside quotation marks: the narrator is third person (release 28 Q1). // When the sentence restates a cited quote, the reason names whose line it // is and where it was cited. // // SOFT (a warning; the line may be used, flagged for review) — the Q0 lints, // for what the hard checks cannot see (plans/local-llm-report-media.md, Q0): // - a NEGATION MISMATCH: the line shares its content with an evidence line // (a claim or a quote) but one of them is negated and the other is not // ("I have never met the finalist" → "she met the finalist"); // - a DROPPED HEDGE: the evidence line hedges ("maybe", "allegedly", "I // think") and the line that restates it does not. // // Pure: the report's text and quotes are the inputs. import { strictNormalize } from "../../citations/verify"; export const BANNED_PHRASES = [ "that's an allegation, not a ruling", "that is an allegation", "worth being precise", "here's the thing", "let's dive in", "let's dive", "dive in", "dive into", "delve", "buckle up", "in conclusion", "it's worth noting", "it is worth noting", "let's unpack", "unpack", "at the end of the day", "a testament to", "in a world where", "make no mistake", "the plot thickens", "stay tuned", "game-changer", "navigate the", "tapestry", "let that sink in", ] as const; const NUM_WORDS: Record = { zero: 0, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17, eighteen: 18, nineteen: 19, twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90, hundred: 100, thousand: 1000, million: 1000000, dozen: 12, }; // Capitalised words that are not names. export const COMMON_CAPS = new Set( `I I'm I've I'd I'll A An The And But So Or Yet Then Now Here There This That These Those It It's He She They We You His Her Their Our Your What When Where Why How Who Which One No Not Yes Just Still Also Even Only First Next Last Again Some Many Most All Every Each Nothing Something Everything Anyone Someone Today Tomorrow Yesterday Oh Okay Ok Well Plus Because If Once While Since Before After Later Meanwhile Monday Tuesday Wednesday Thursday Friday Saturday Sunday January February March April May June July August September October November December Twice Different Same Another Both Either Neither Over Under`.split(/\s+/), ); export const QUOTE_RUN_WORDS = 6; export const QUOTE_RUN_MESSAGE = "repeats 6+ words of a quote: the clip says it; do not read quotes out"; export type GroundingInput = { // Everything the report says (reportText), where numbers and names must be. reference: string; // The cited quotes the line must not read out. quotes: readonly string[]; // The evidence lines (claims and quotes) the Q0 lints compare against; // default: the quotes. evidence?: readonly string[]; // Every cited quote with who said it and where it is cited, for the // first-person reason (default: none — the reason names no line). sources?: readonly QuoteSource[]; }; export type QuoteSource = { quote: string; speaker?: string; citation?: string }; export type GroundingResult = { hard: string[]; soft: string[] }; type ReportLike = { title?: string; summary?: string | null; sections?: readonly { title?: string; body?: string | null; claims?: readonly { text?: string; title?: string }[] | null }[]; citations?: | Record< string, { quote?: string; label?: string; date?: string; speaker?: string; channel?: string; id?: string; start?: number } | undefined > | null; }; // Every text of a report a narration may draw on: title, summary, section // titles and bodies, claims, and each citation's quote, label and date. export function reportText(report: ReportLike): string { const bits: string[] = [report.title ?? "", report.summary ?? ""]; for (const s of report.sections ?? []) { bits.push(s.title ?? "", s.body ?? ""); for (const c of s.claims ?? []) bits.push(c.text ?? "", c.title ?? ""); } for (const c of Object.values(report.citations ?? {})) bits.push(c?.quote ?? "", c?.label ?? "", c?.date ?? ""); return bits.filter(Boolean).join("\n"); } // The report's cited quotes. export function reportQuotes(report: ReportLike): string[] { return Object.values(report.citations ?? {}) .map((c) => c?.quote ?? "") .filter(Boolean); } // The evidence lines of a report: each claim (its citation markers // stripped) and each quote. export function reportEvidence(report: ReportLike): string[] { const out: string[] = []; for (const s of report.sections ?? []) { for (const c of s.claims ?? []) if (c.text) out.push(c.text.replace(/\[([^\]]*)\]\(cite:[^)]+\)|\(cite:[^)]+\)/g, "$1")); } return [...out, ...reportQuotes(report)]; } const mmssOf = (s: number) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`; // Each cited quote with its speaker and its citation, as the first-person // reason names them: `c03 (Pie stream @ 0:30)`. export function reportQuoteSources(report: ReportLike): QuoteSource[] { const out: QuoteSource[] = []; for (const [cid, c] of Object.entries(report.citations ?? {})) { if (!c?.quote) continue; const where = c.label ?? (c.channel && c.id ? `${c.channel}/${c.id}` : ""); const at = typeof c.start === "number" ? ` @ ${mmssOf(c.start)}` : ""; out.push({ quote: c.quote, ...(c.speaker ? { speaker: c.speaker } : {}), citation: where ? `${cid} (${where}${at})` : cid }); } return out; } export function groundingInputOf(report: ReportLike): GroundingInput { return { reference: reportText(report), quotes: reportQuotes(report), evidence: reportEvidence(report), sources: reportQuoteSources(report), }; } // ─── the narrator is third person (release 28 Q1) ─── // Word-bounded and case-insensitive: "Iowa", "myth" and "mineral" are not // hits. Two kinds of collateral are accepted: "mine" the noun (a gold mine) // and a roman numeral I; the all-caps "US" (the country) is not a hit. export const FIRST_PERSON_WORDS = [ "i", "i'm", "i've", "i'd", "i'll", "me", "my", "mine", "myself", "we", "we're", "we've", "we'd", "we'll", "us", "our", "ours", "ourselves", ] as const; export const THIRD_PERSON_MESSAGE = "the narrator is third person"; const FIRST_PERSON = new Set(FIRST_PERSON_WORDS); // A sentence's first-person words outside quotation marks, as written. export function firstPersonWords(sentence: string): string[] { const outside = sentence .replace(/[’‘ʼ]/g, "'") .replace(/"[^"]*"|“[^”]*”/g, " "); const out: string[] = []; for (const m of outside.matchAll(/[A-Za-z]+(?:'[A-Za-z]+)?/g)) { const w = m[0]; if (w === "US") continue; if (FIRST_PERSON.has(w.toLowerCase())) out.push(w); } return out; } // The hard problem for each first-person sentence: the rule, and — when the // sentence restates a cited quote — whose line it is and where it is cited. export function firstPersonProblems(text: string, sources: readonly QuoteSource[] = []): string[] { const out: string[] = []; for (const sent of sentencesOf(text)) { const words = firstPersonWords(sent); if (!words.length) continue; const said = [...new Set(words)].map((w) => `“${w}”`).join(", "); const line = sources.length ? closest(strictNormalize(sent), sources.map((s) => s.quote)) : null; const src = line === null ? undefined : sources.find((s) => s.quote === line); out.push( src ? `${THIRD_PERSON_MESSAGE} (${said}): this is ${src.speaker ? `${src.speaker}'s` : "the speaker's"} line from ${src.citation ?? "a citation"}, “${src.quote.slice(0, 80)}”` : `${THIRD_PERSON_MESSAGE} (${said}): say what the speaker said, not as the speaker`, ); } return out; } const SENTENCE_SPLIT = /(?<=[.!?…])\s+/; export function sentencesOf(text: string): string[] { return text.split(SENTENCE_SPLIT).map((s) => s.trim()).filter(Boolean); } const hasWord = (normText: string, w: string) => ` ${normText} `.includes(` ${w} `); /** * The numbers (digits or words) and names (a capitalised word past a * sentence's first that is not a common one) in `text` that `reference` does * not have, as sentences naming `where` ("the report"; a media task's own * evidence). What checkNarration grounds; release 28's on-screen and teaser * drafts ground the same way. */ export function groundedProblems(text: string, reference: string, where = "the report"): string[] { const out = new Set(); const low = text.toLowerCase(); const refNorm = strictNormalize(reference); const refNums = new Set(reference.replace(/,/g, "").match(/\d+/g) ?? []); // A number the reference spells out ("about four ferrets") is that number in digits too. for (const w of refNorm.split(/\s+/)) if (NUM_WORDS[w] !== undefined) refNums.add(String(NUM_WORDS[w])); for (const d of text.match(/\d[\d,]*/g) ?? []) { if (!refNums.has(d.replace(/,/g, ""))) out.add(`number ${d} is not in ${where}`); } for (const w of low.match(/[a-z]+/g) ?? []) { const n = NUM_WORDS[w]; if (n === undefined) continue; if (!hasWord(refNorm, w) && !refNums.has(String(n))) out.add(`number “${w}” is not in ${where}`); } for (const sent of sentencesOf(text)) { const toks = sent.match(/[A-Za-z][A-Za-z'’.-]*/g) ?? []; for (const raw of toks.slice(1)) { const t = raw.replace(/^[.\-’']+|[.\-’']+$/g, ""); if (!/^[A-Z]/.test(t) || COMMON_CAPS.has(t)) continue; const n = strictNormalize(t.replace(/['’]s$/, "")); if (n && !refNorm.includes(n)) out.add(`name “${t}” is not in ${where}`); } } return [...out]; } export function checkNarration(text: string, input: GroundingInput): GroundingResult { const hard = new Set(); const soft = new Set(); const low = text.toLowerCase(); if (/<[^>]+>/.test(text)) hard.add("has a tag in angle brackets"); for (const b of BANNED_PHRASES) if (low.includes(b)) hard.add(`stock phrase “${b}”`); for (const p of groundedProblems(text, input.reference)) hard.add(p); if (/(^|\s)'[^']+(\s[^']+){3,}'/.test(text) || /["“”]/.test(text)) { hard.add("text in quotation marks: no quotes in narration"); } const said = ` ${strictNormalize(text)} `; for (const q of input.quotes) { const qw = strictNormalize(q).split(" ").filter(Boolean); for (let k = 0; k + QUOTE_RUN_WORDS <= qw.length; k++) { if (said.includes(` ${qw.slice(k, k + QUOTE_RUN_WORDS).join(" ")} `)) { hard.add(QUOTE_RUN_MESSAGE); break; } } } for (const p of firstPersonProblems(text, input.sources)) hard.add(p); for (const w of lintNarration(text, input.evidence ?? input.quotes)) soft.add(w); return { hard: [...hard].sort(), soft: [...soft].sort() }; } // ─── the Q0 lints ─── const NEGATIONS = new Set([ "not", "no", "never", "nobody", "nothing", "none", "neither", "nor", "cannot", "dont", "doesnt", "didnt", "wont", "wouldnt", "isnt", "arent", "wasnt", "werent", "cant", "couldnt", "shouldnt", "havent", "hasnt", "hadnt", "aint", ]); const HEDGES = [ "maybe", "perhaps", "possibly", "probably", "allegedly", "reportedly", "apparently", "might", "may", "could", "seems", "seemed", "i think", "i believe", "i guess", "kind of", "sort of", "not sure", "rumor", "rumour", ]; const STOP = new Set( `a an the and but or so of to in on at by for with from as is are was were be been being it its this that these those i me my we our you your he him his she her they them their there here what which who whom when where why how do does did done have has had will would shall should can could may might must just very really also too about into over under than then out up down off all any some more most such only own same other again s t ll re ve d m o y said says say saying`.split(/\s+/), ); function content(normText: string): Set { return new Set(normText.split(" ").filter((w) => w && !STOP.has(w) && !NEGATIONS.has(w))); } const negated = (normText: string) => normText.split(" ").some((w) => NEGATIONS.has(w)); const hedged = (normText: string) => HEDGES.some((h) => hasWord(normText, h)); // The evidence line a sentence restates: the one sharing the most content // words, when it shares at least two and half the sentence's. function closest(sentNorm: string, evidence: readonly string[]): string | null { const mine = content(sentNorm); if (mine.size === 0) return null; let best: { line: string; shared: number } | null = null; for (const line of evidence) { const theirs = content(strictNormalize(line)); let shared = 0; for (const w of mine) if (theirs.has(w)) shared++; if (!best || shared > best.shared) best = { line, shared }; } return best && best.shared >= 2 && best.shared * 2 >= mine.size ? best.line : null; } export function lintNarration(text: string, evidence: readonly string[]): string[] { const out: string[] = []; for (const sent of sentencesOf(text)) { const sn = strictNormalize(sent); const line = closest(sn, evidence); if (!line) continue; const ln = strictNormalize(line); if (negated(ln) !== negated(sn)) { out.push(`negation mismatch: “${sent.slice(0, 80)}” against “${line.slice(0, 80)}” — check the meaning is not reversed`); } if (hedged(ln) && !hedged(sn)) { out.push(`dropped hedge: “${line.slice(0, 80)}” hedges, “${sent.slice(0, 80)}” does not`); } } return out; }