// REPORT OPS — a revision of a sweep report, as checked edit operations a // model asks for and code applies (the stopgap's revise.py, release 27 S2). // // drop {n} remove finding n // claim {n, text} rewrite finding n's claim (its quotes and links stay) // merge {n, into, text?} fold n into another finding: it keeps every quote with // its own link; `text` (optional) is its new claim // move {n, section} move n to a section (a new title makes a section, before Coverage) // add {section, text, quote, link} a new finding; the quote is STRICT-checked (ctx.checkQuote) // section {section, text} rename a section // title {text} / summary {text} // // The rules, in code: // - A batch numbers against the document AT THE START of the batch: "drop 3, // drop 5" means the 3 and the 5 the model saw, whatever the drop of 3 did. // - Merges chain: an op on a finding merged away follows it to the finding it // went into (merge 1 into 2, then 2 into 3: an op on 1 lands on 3). Dropping // a finding merged away is refused — drop the one it went into. // - Every refusal carries its reason, and refuses that op only. // - A claim never carries quoted words or a link: convertSweep makes every // quoted span before a link THAT link's quote, so a claim quoting another // moment's words breaks its citation. An op that would put one in is // refused (testing/draft/sweeps/quotes-in-claims.md is the shape it stops). // - Quotes are never edited: no op reaches a finding's `rest`, except merge, // which appends one finding's quotes and links, verbatim, to another's. // - An `add` carries the transcript's exact words; they are checked through // the injected strict checker before the finding exists (no checker, no // add). // - A SPEAKER-NEUTRAL report (ctx.neutral; ./tasks/neutralClaim.ts) keeps its // form: its lines are code's, so `claim` and a merge's `text` are refused, // an `add`'s line is written again by code (ctx.neutral.line) or refused, // a new or renamed section's title must pass ctx.neutral.heading, `title` // is refused (the title is code's) and `summary` must pass // ctx.neutral.summary. import { STRICT_QUOTE_WINDOW_SECONDS, strictQuoteCheck } from "../../citations/verify"; import { fragmentHint, fragmentOf, fullSentenceFor } from "../../citations/fragment"; import { LINK_RE, QUOTE_MARK_RE, evidenceOf, findingsOf, isCoverage, numberFindings, type Finding, type SweepDoc, type SweepSection, } from "./sweepModel"; export const REPORT_OP_NAMES = ["drop", "claim", "merge", "move", "add", "section", "title", "summary"] as const; export type ReportOpName = (typeof REPORT_OP_NAMES)[number]; // What a model sends: loosely typed, every field checked here. export type ReportOp = { op: string } & Record; export type AppliedOp = { index: number; op: ReportOp }; export type RefusedOp = { index: number; op: ReportOp; why: string }; export type QuoteCheckRequest = { channel: string; id: string; second: number; quote: string }; export type QuoteCheckAnswer = { ok: boolean; why?: string }; export type ReportOpsContext = { // The strict check for an `add`'s quote (e.g. strictCheckerOver below). // Without it every `add` is refused. checkQuote?: (q: QuoteCheckRequest) => Promise; // A recording's title, for the new finding's link label. titleOf?: (channel: string, id: string) => Promise; // When set, an `add`'s link must start with this origin (the article's // citation origin) — moment links never depend on a build's moment_base. origin?: string; // A speaker-neutral report: what code says of the model's words. neutral?: NeutralOpsRules; }; export type NeutralOpsRules = { // An added finding's line, from the model's text, its quote and its // recording: the line code writes, or why it is refused. line: (o: { text: string; quote: string; channel: string; id: string }) => Promise<{ line: string } | { why: string }>; // Why a section title (new or renamed) is refused, or null. heading: (text: string) => string | null; // Why a summary is refused, or null. summary: (text: string) => string | null; }; const NEUTRAL_LINE_REFUSAL = "a speaker-neutral report's lines are written by code: a line is not rewritten (drop, move or merge it without text)"; // The strict checker over a cue reader (testing/draft/corpus.mjs cuesOf, or // the MCP's transcript read): every fragment verbatim within ±90 s, and the // quote not a FRAGMENT (release 28 Q2: under four words, or stopping on a // function word) — the refusal then carries the full sentence to quote. // `fragments: false` checks the words only. export function strictCheckerOver( cuesOf: (channel: string, id: string) => Promise, opts: { windowSeconds?: number; fragments?: boolean } = {}, ): (q: QuoteCheckRequest) => Promise { const windowSeconds = opts.windowSeconds ?? STRICT_QUOTE_WINDOW_SECONDS; return async ({ channel, id, second, quote }) => { const cues = await cuesOf(channel, id); if (!cues || cues.length === 0) return { ok: false, why: `no transcript cues for ${channel}/${id}` }; const r = strictQuoteCheck(quote, cues, second, { windowSeconds }); if (!r.ok) return { ok: false, why: `"${r.failed}" is not there` }; const frag = opts.fragments === false ? null : fragmentOf(quote); if (frag) return { ok: false, why: fragmentHint(frag, fullSentenceFor(frag.part, cues, second, { windowSeconds })) }; return { ok: true }; }; } export type ReportOpsResult = { doc: SweepDoc; applied: AppliedOp[]; refused: RefusedOp[] }; class Refusal extends Error {} const refuse = (why: string): never => { throw new Refusal(why); }; // A claim's text, checked: no quotation marks, no link, not empty. export function claimProblem(text: unknown): string | null { if (typeof text !== "string" || !text.trim()) return "a claim needs its text"; if (QUOTE_MARK_RE.test(text)) { return "a claim carries no quotation marks or quoted words — quoted words live only in a finding's quote"; } if (new RegExp(LINK_RE.source).test(text)) return "a claim carries no link — the finding's link is in its quote"; return null; } const MOMENT_LINK_RE = /[?&]v=([^&%/]+)(?:%2F|\/)([^&]+)&t=(\d+)s?(?:&|$)/i; export function parseMomentLink(link: string): { channel: string; id: string; second: number } | null { if (!/^https?:\/\//.test(link)) return null; const m = MOMENT_LINK_RE.exec(link); if (!m) return null; return { channel: decodeURIComponent(m[1]!), id: decodeURIComponent(m[2]!), second: Number(m[3]) }; } export function mmss(seconds: number): string { const s = Math.max(0, Math.floor(seconds)); const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); const ss = String(s % 60).padStart(2, "0"); return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`; } function num(v: unknown): number | null { const n = typeof v === "number" ? v : typeof v === "string" && /^\s*\d+\s*$/.test(v) ? Number(v) : NaN; return Number.isInteger(n) ? n : null; } const blank = (): { type: "line"; text: string } => ({ type: "line", text: "" }); const isBlank = (b: SweepSection["body"][number]) => b.type === "line" && !b.text.trim(); // Remove a block, and one of two blank lines it leaves side by side. function removeBlock(section: SweepSection, block: Finding) { const i = section.body.indexOf(block); if (i < 0) return; section.body.splice(i, 1); const prev = section.body[i - 1]; const next = section.body[i]; if (prev && next && isBlank(prev) && isBlank(next)) section.body.splice(i, 1); } // A finding into a section: after its last finding, else after its text // with a blank line between. function insertFinding(section: SweepSection, f: Finding) { const body = section.body; for (let i = body.length - 1; i >= 0; i--) { if (body[i]!.type === "finding") { body.splice(i + 1, 0, f); return; } } let j = body.length; while (j > 0 && isBlank(body[j - 1]!)) j--; body.splice(j, 0, blank(), f); if (j + 2 >= body.length) body.push(blank()); } // The section of that title, or a new one before Coverage (else last). function sectionFor(doc: SweepDoc, title: string): SweepSection { const found = doc.sections.find((s) => s.title === title.trim()); if (found) return found; const made: SweepSection = { title: title.trim(), body: [] }; const cov = doc.sections.findIndex(isCoverage); doc.sections.splice(cov >= 0 ? cov : doc.sections.length, 0, made); return made; } function sectionOf(doc: SweepDoc, f: Finding): SweepSection { return doc.sections.find((s) => s.body.includes(f)) ?? refuse("that finding is no longer in the document"); } const clone = (doc: SweepDoc): SweepDoc => structuredClone(doc); export async function applyReportOps( input: SweepDoc, ops: readonly unknown[], ctx: ReportOpsContext = {}, ): Promise { const doc = clone(input); const applied: AppliedOp[] = []; const refused: RefusedOp[] = []; // ONE numbering for the whole batch. const start = numberFindings(doc); const byN = new Map(start.map((x) => [x.n, x.finding])); const nOf = new Map(start.map((x) => [x.finding, x.n])); const hadFindings = new Set(start.map((x) => x.section)); const mergedInto = new Map(); const dropped = new Set(); const label = (f: Finding) => (nOf.has(f) ? `finding ${nOf.get(f)}` : "the finding added in this batch"); const original = (v: unknown, what = "n"): Finding => { const n = num(v); if (n === null) return refuse(`${what} must be a finding number`); return byN.get(n) ?? refuse(`no finding ${n} (the document has ${start.length})`); }; // A finding by its batch-start number, following merges. const at = (v: unknown, what = "n"): Finding => { let f = original(v, what); const seen = new Set(); while (mergedInto.has(f)) { if (seen.has(f)) refuse("a merge cycle"); seen.add(f); f = mergedInto.get(f)!; } if (dropped.has(f)) refuse(`${label(f)} was dropped earlier in this batch`); return f; }; const text = (v: unknown, what: string): string => typeof v === "string" && v.trim() ? v.trim() : refuse(`${what} needs "text"`); // A section title a neutral report does not have yet must pass the heading rule. const neutralSection = (title: string) => { if (!ctx.neutral || doc.sections.some((x) => x.title === title.trim())) return; const why = ctx.neutral.heading(title.trim()); if (why) refuse(`a speaker-neutral report's heading is a topic: ${why}`); }; for (const [index, raw] of ops.entries()) { const op = (raw && typeof raw === "object" ? raw : { op: String(raw) }) as ReportOp; try { switch (op.op) { case "drop": { const f = original(op.n); if (mergedInto.has(f)) { let to = f; while (mergedInto.has(to)) to = mergedInto.get(to)!; refuse(`finding ${nOf.get(f)} was merged into ${label(to)}; drop that one`); } if (dropped.has(f)) refuse(`finding ${nOf.get(f)} was already dropped in this batch`); removeBlock(sectionOf(doc, f), f); dropped.add(f); break; } case "claim": { if (ctx.neutral) refuse(NEUTRAL_LINE_REFUSAL); const f = at(op.n); const t = text(op.text, "claim"); const bad = claimProblem(t); if (bad) refuse(bad); f.claim = t; if (!f.sep && f.rest) f.sep = " "; break; } case "merge": { const src = at(op.n); const target = op.into ?? op.id ?? op.after; if (target === undefined) refuse('merge needs "into": the finding to fold it into'); const dst = at(target, "into"); if (src === dst) refuse("a finding cannot merge into itself"); if (op.text !== undefined && op.text !== "") { if (ctx.neutral) refuse(NEUTRAL_LINE_REFUSAL); const bad = claimProblem(op.text); if (bad) refuse(bad); } if (typeof op.text === "string" && op.text.trim()) { dst.claim = op.text.trim(); } // Every quote keeps its own link: the rest is appended verbatim. dst.rest = [dst.rest.trimEnd(), src.rest.trim()].filter(Boolean).join(" "); if (!dst.sep && dst.rest) dst.sep = " "; dst.continued.push(...src.continued); removeBlock(sectionOf(doc, src), src); mergedInto.set(src, dst); break; } case "move": { const f = at(op.n); const title = typeof op.section === "string" && op.section.trim() ? op.section : refuse('move needs "section"'); const from = sectionOf(doc, f); neutralSection(title); const to = sectionFor(doc, title); if (from === to) refuse(`finding ${nOf.get(f)} is already in "${to.title}"`); removeBlock(from, f); insertFinding(to, f); hadFindings.add(to); break; } case "add": { if (!ctx.checkQuote) refuse("adding a finding needs the quote checker, and this run has none"); const title = typeof op.section === "string" && op.section.trim() ? op.section : refuse('add needs "section"'); neutralSection(title); let claim = text(op.text, "add"); const bad = claimProblem(claim); if (bad) refuse(`${bad} (put the words in "quote")`); const quote = typeof op.quote === "string" ? op.quote.trim().replace(/^["“”]+|["“”]+$/g, "").trim() : ""; if (!quote) refuse("add needs the quote: the transcript's exact words"); if (QUOTE_MARK_RE.test(quote) || quote.includes("\n")) refuse("a quote is one passage, with no quotation marks inside"); const link = typeof op.link === "string" ? op.link.trim() : ""; const at_ = parseMomentLink(link); if (!at_) refuse("add needs a moment link: /?v=%2F&t="); if (ctx.origin && !link.startsWith(ctx.origin)) refuse(`the link must be on the article's origin ${ctx.origin}`); const check = await ctx.checkQuote!({ ...at_!, quote }); if (!check.ok) { refuse(`the quote is not the transcript's words within 90 s of ${at_!.second} s${check.why ? `: ${check.why}` : ""}`); } if (ctx.neutral) { const r = await ctx.neutral.line({ text: claim, quote, channel: at_!.channel, id: at_!.id }); if ("why" in r) refuse(r.why); else claim = r.line; } const name = ((await ctx.titleOf?.(at_!.channel, at_!.id)) ?? at_!.id).replace(/[[\]()]/g, "").trim().slice(0, 80); const f: Finding = { type: "finding", bullet: "- ", claim, // A neutral line ends on its own colon. sep: claim.endsWith(":") ? " " : ": ", rest: `"${quote}" [${name} @ ${mmss(at_!.second)}](${link})`, continued: [], added: true, }; const to = sectionFor(doc, title); insertFinding(to, f); hadFindings.add(to); break; } case "section": { const old = typeof op.section === "string" ? op.section.trim() : ""; const s = doc.sections.find((x) => x.title === old) ?? refuse(`no section "${old}"`); const t = text(op.text, "section"); if (t !== old && doc.sections.some((x) => x.title === t)) refuse(`there is already a section "${t}"`); if (ctx.neutral && t !== old) { const why = ctx.neutral.heading(t); if (why) refuse(`a speaker-neutral report's heading is a topic: ${why}`); } s.title = t; break; } case "title": if (ctx.neutral) refuse("a speaker-neutral report's title is written by code"); doc.title = text(op.text, "title"); doc.hasTitle = true; break; case "summary": { const t = text(op.text, "summary"); if (ctx.neutral) { const why = ctx.neutral.summary(t); if (why) refuse(`a speaker-neutral report's summary says where the words are, not who says what: ${why}`); } doc.preamble = ["", t, ""]; break; } default: refuse(`no op "${String(op.op)}" — the ops are ${REPORT_OP_NAMES.join(", ")}`); } applied.push({ index, op }); } catch (e) { if (!(e instanceof Refusal)) throw e; refused.push({ index, op, why: e.message }); } } // A section this batch emptied of findings, with no text left, goes. doc.sections = doc.sections.filter( (s) => !hadFindings.has(s) || findingsOf(s).length > 0 || s.body.some((b) => b.type === "line" && b.text.trim()), ); return { doc, applied, refused }; } // Findings whose quoted run carries words between its quotes that are not a // joiner — a claim's words inside the quote (the quotes-in-claims shape: // `She "would never" sell the bakery, she says: "…" [link]`). A lint for a // generated sweep before it is converted; the ops never make one. export function quotedClaimProblems(doc: SweepDoc): { n: number; why: string }[] { const out: { n: number; why: string }[] = []; const JOINER = /^\s*(?:…|\.\.\.|,|;|—|-|and|and then|then|or)?\s*$/i; for (const { n, finding } of numberFindings(doc)) { // Each link's quoted run: the text from the previous link to it. const rest = evidenceOf(finding); let from = 0; for (const link of rest.matchAll(new RegExp(LINK_RE.source, "g"))) { const run = rest.slice(from, link.index); from = link.index! + link[0].length; const spans = [...run.matchAll(/"[^"\n]*"|“[^”\n]*”/g)]; for (let i = 1; i < spans.length; i++) { const between = run.slice(spans[i - 1]!.index! + spans[i - 1]![0].length, spans[i]!.index); if (!JOINER.test(between)) { out.push({ n, why: `words outside the quotes ("${between.trim().slice(0, 60)}") are inside a link's quoted run` }); break; } } } } return out; }