Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit f17a4c3c8937d05512e60b3952bd54ac10a1489a
parent c721c02f1041b22a26054b6698bca74a61f7a624
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 13 Oct 2026 10:40:20 -0400

common: release 27 S2 — the strict quote check, verify-quotes `inexact`, the sweep.md model and the report/video op engines

- citations/verify.ts: strictQuoteCheck / strictTextCheck — every quoted fragment
  (split on the ellipsis convertSweep joins with) verbatim after normalisation
  (case, punctuation, whitespace, curly quotes) within ±90 s of the cited second,
  on word boundaries.
- reports verify-quotes: a new status `inexact` (recall passes, the strict check
  does not) — printed as a warning, counted, never a failure (D3); compose and
  publish unchanged.
- report/draft/sweepModel.ts: parseSweep / renderSweep, byte-identical over every
  fixture; findings split into claim / sep / rest at the first quote.
- report/draft/reportOps.ts: drop, claim, merge, move, add, section, title,
  summary — batches number against their start, merges chain, every refusal
  carries its reason, claims never carry quoted words, quotes are never edited,
  an add's quote goes through an injected strict checker.
- report/draft/videoOps.ts: drop, move, heading, narration, trim, add_clip,
  title, subtitle — trims within the parent window ±3 s, clips only from the
  report's video citations, narration through grounding.
- report/draft/grounding.ts: the stopgap's narration checks plus the Q0 lints
  (negation mismatch, dropped hedge) as warnings.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mcommon/bin/reports-check.test.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/bin/reports-check.ts | 69++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/lib/citations/verify.test.ts | 67+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/citations/verify.ts | 100+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/grounding.test.ts | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/grounding.ts | 237+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/reportOps.test.ts | 181+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/reportOps.ts | 347+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/sweepModel.test.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/sweepModel.ts | 193+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/videoOps.test.ts | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/videoOps.ts | 212+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
12 files changed, 1755 insertions(+), 7 deletions(-)

diff --git a/common/bin/reports-check.test.ts b/common/bin/reports-check.test.ts @@ -30,6 +30,8 @@ const { getPaths } = await import("../lib/paths"); const { checkMain, verifyQuotesMain } = await import("./reports-check"); const { attachVideoMain } = await import("./reports-attach-video"); const { encodePlan, encodeArgs } = await import("../publish/reportVideo"); +const { CHANNELS } = await import("../testing/draft/corpus.mjs"); +const { convertFixture } = await import("../testing/draft/derive"); const paths = getPaths(); const CHAN = "chan"; @@ -191,6 +193,62 @@ test("verify-quotes: a clean report exits 0, in words", async () => { assert.match(c.text(), /1 quote\(s\): 1 ok/); }); +test("verify-quotes: `inexact` — recall passes, the strict check does not — is a warning (testing/draft/sweeps/inexact.md)", async () => { + // The synthetic kitchen channel, its records as served `en` tracks. + writeJson(path.join(paths.channelsDir, "synth-kitchen", "config.json"), { + handling: "youtube", + name: "Synth Kitchen", + url: "https://video.example/@synth-kitchen", + }); + const kitchen = CHANNELS.find((ch) => ch.slug === "synth-kitchen")!; + for (const r of kitchen.records) { + const dir = path.join(paths.channelsDir, "synth-kitchen", "data", r.id); + writeJson(path.join(dir, "metadata.info.json"), { + id: r.id, + title: r.title, + channel: r.channel, + upload_date: r.uploadDate, + duration: r.duration, + webpage_url: r.webpageUrl, + extractor_key: "Youtube", + }); + writeText(path.join(dir, "transcript.en.vtt"), vtt(r.cues.map((q) => [q.start, q.end, q.text]))); + } + const { report } = await convertFixture("inexact"); + const file = path.join(ROOT, "inexact.report.json"); + writeJson(file, report); + + const c = capture(); + const code = await verifyQuotesMain({ file, json: true, paths }, c.out); + const { results } = JSON.parse(c.text()) as { + results: { citation: string; status: string; score?: number; strict?: { ok: boolean; failed?: string } }[]; + }; + const by = Object.fromEntries(results.map((r) => [r.citation, r])); + // Reversed: every token is in the cue, so recall passes at 1 — but the + // words are not what was said. + assert.equal(by.c01.status, "inexact"); + assert.equal(by.c01.score, 1); + assert.deepEqual(by.c01.strict, { ok: false, failed: "I would sell the bakery to a chain" }); + // Two hundred seconds from its link: recall fails it already (its ±5 s + // window shares only "the"), so it is a drift, the stronger status. + assert.equal(by.c02.status, "drift"); + assert.equal(by.c02.strict, undefined); + // Exact. + assert.equal(by.c03.status, "ok"); + assert.deepEqual(by.c03.strict, { ok: true }); + assert.equal(code, 1, "the drift fails it; the inexact alone would not"); + + // Without the drift, an inexact quote is a warning: exit 0, in words. + const warnOnly = { ...report, citations: { c01: report.citations!.c01, c03: report.citations!.c03 } }; + warnOnly.sections = [{ id: "s", title: "S", body: "Said [this](cite:c01) and [that](cite:c03)." }]; + writeJson(file, warnOnly); + const w = capture(); + assert.equal(await verifyQuotesMain({ file, paths }, w.out), 0); + assert.match(w.text(), /INEXACT \(warning\) c01 {2}video synth-kitchen\/bread-day-01 15–19\.8 s {2}1\.00 transcript\.en\.vtt/); + assert.match(w.text(), /"I would sell the bakery to a chain" is not verbatim within ±90 s/); + assert.match(w.text(), /2 quote\(s\): 1 inexact, 1 ok \(inexact is a warning\)/); +}); + // ─── attach-video ─── test("encodePlan: remux an H.264 mp4 under the limit; encode the rest to fit; refuse what cannot", () => { diff --git a/common/bin/reports-check.ts b/common/bin/reports-check.ts @@ -19,6 +19,12 @@ // `en-orig` is not what the speaker said, and is reported as such, even // though compose (which takes the best track) would pass it. // +// A quote that passes compose's recall check but is not VERBATIM within +// ±90 s of its second (the strict check, lib/citations/verify.ts +// strictQuoteCheck — release 27 D3) is `inexact`: a WARNING. It is printed +// and counted, and does not change the exit code; compose and publish do not +// use it. +// // `--article <id>` checks one ARTICLE (release 26: transcripts/reports/<id>/, // published or a draft) as the homepage's compose would — any channel of the // corpus citable, the articles' prepared media. @@ -36,7 +42,15 @@ import { readAllPosts } from "../lib/posts-server"; import { parseReport } from "../lib/report/validate"; import type { Report } from "../lib/report/schema"; import { reportCitationNumbers } from "../lib/report/uses"; -import { QUOTE_DRIFT_THRESHOLD, quoteDrifted, quoteVerification, roundScore } from "../lib/citations/verify"; +import { + QUOTE_DRIFT_THRESHOLD, + quoteDrifted, + quoteVerification, + roundScore, + strictQuoteCheck, + strictTextCheck, + type StrictQuoteResult, +} from "../lib/citations/verify"; import { ComposeReportsError, checkSpanQuote, @@ -126,6 +140,8 @@ export type QuoteStatus = | "ok" | "drift" | "en-orig-drift" + // Recall passes, the strict check does not: a warning (release 27 D3). + | "inexact" | "missing-record" | "no-cues" | "missing-post" @@ -146,9 +162,25 @@ export type QuoteResult = { // Every track's score; and the en-orig track's, when the record has one. tracks?: { name: string; score: number }[]; enOrig?: number; + // The strict check (verbatim within ±90 s): whether it passed, and the + // first fragment it did not find. Absent where recall already failed. + strict?: { ok: boolean; failed?: string }; message?: string; }; +// Statuses that are warnings: printed and counted, never a failure. +export const QUOTE_WARNING_STATUSES: ReadonlySet<QuoteStatus> = new Set<QuoteStatus>(["inexact"]); + +const strictOf = (r: StrictQuoteResult): NonNullable<QuoteResult["strict"]> => + r.ok ? { ok: true } : { ok: false, ...(r.failed !== undefined ? { failed: r.failed } : {}) }; + +export function inexactMessage(failed: string | undefined): string { + return ( + `recall passes, but ${failed ? `"${failed.slice(0, 120)}"` : "the quote"} is not verbatim within ±90 s ` + + `of the cited second (the strict check generated quotes must pass) — a warning; compose is unchanged` + ); +} + export const EN_ORIG_TRACK = "transcript.en-orig.vtt"; // Every video, audio and post citation of a report, checked against the @@ -200,12 +232,19 @@ export async function verifyReportQuotes( continue; } const v = quoteVerification(c.quote, postText, now); + const strict = quoteDrifted(v) ? null : strictTextCheck(c.quote, postText); + const status: QuoteStatus = quoteDrifted(v) ? "drift" : strict && !strict.ok ? "inexact" : "ok"; results.push({ ...base, score: v.quoteScore, track: "post", - status: quoteDrifted(v) ? "drift" : "ok", - ...(quoteDrifted(v) ? { message: quoteDriftMessage(v.quoteScore) } : {}), + status, + ...(strict ? { strict: strictOf(strict) } : {}), + ...(status === "drift" + ? { message: quoteDriftMessage(v.quoteScore) } + : status === "inexact" + ? { message: inexactMessage(strict?.failed) } + : {}), }); continue; } @@ -227,6 +266,17 @@ export async function verifyReportQuotes( const enOrig = checked.tracks.find((t) => t.name === EN_ORIG_TRACK)?.score; let status: QuoteStatus = "ok"; let message: string | undefined; + // The strict check passes when any track has the quote verbatim near + // the cited second (as recall takes the best track). + let strict: StrictQuoteResult | null = null; + if (!quoteDrifted(checked.verification)) { + const tracks = record.tracks.length ? record.tracks.map((t) => t.cues) : [record.cues]; + for (const cues of tracks) { + const r = strictQuoteCheck(c.quote, cues, c.start); + if (!strict || r.ok) strict = r; + if (r.ok) break; + } + } if (quoteDrifted(checked.verification)) { status = "drift"; message = quoteDriftMessage(score); @@ -235,6 +285,9 @@ export async function verifyReportQuotes( message = `the quote matches ${best?.name ?? "a track"} (${score.toFixed(2)}) but only ${Math.round(enOrig * 100)}% of ` + `the en-orig track, the words as spoken — a served \`en\` track can rewrite them: quote en-orig, or check the audio`; + } else if (strict && !strict.ok) { + status = "inexact"; + message = inexactMessage(strict.failed); } results.push({ ...base, @@ -242,6 +295,7 @@ export async function verifyReportQuotes( ...(best ? { track: best.name } : {}), tracks: checked.tracks, ...(enOrig !== undefined ? { enOrig } : {}), + ...(strict ? { strict: strictOf(strict) } : {}), status, ...(message ? { message } : {}), }); @@ -253,7 +307,7 @@ function describe(r: QuoteResult): string { const where = r.kind === "post" ? `${r.channel}/${r.id}` : `${r.channel}/${r.id} ${r.start}–${r.end} s`; const score = r.score === undefined ? "" : ` ${r.score.toFixed(2)}${r.track ? ` ${r.track}` : ""}`; const orig = r.enOrig === undefined || r.track === EN_ORIG_TRACK ? "" : ` · en-orig ${r.enOrig.toFixed(2)}`; - const label = r.status === "ok" ? "ok" : r.status.toUpperCase(); + const label = r.status === "ok" ? "ok" : QUOTE_WARNING_STATUSES.has(r.status) ? `${r.status.toUpperCase()} (warning)` : r.status.toUpperCase(); return ` ${label.padEnd(14)} ${r.citation}${r.cited ? "" : " (not cited)"} ${r.kind} ${where}${score}${orig}` + (r.message ? `\n${" ".repeat(17)}${r.message}` : ""); } @@ -277,18 +331,19 @@ export async function verifyQuotesMain( return 1; } const results = await verifyReportQuotes(parsed.value, { paths, ...(opts.now ? { now: opts.now } : {}) }); - const bad = results.filter((r) => r.status !== "ok"); + const bad = results.filter((r) => r.status !== "ok" && !QUOTE_WARNING_STATUSES.has(r.status)); if (opts.json) { out.log(JSON.stringify({ file: opts.file, problems: parsed.problems, results }, null, 2)); } else { for (const p of parsed.problems) out.error(` invalid: ${p.path}: ${p.message}`); - for (const r of results) (r.status === "ok" ? out.log : out.error)(describe(r)); + for (const r of results) (r.status === "ok" || QUOTE_WARNING_STATUSES.has(r.status) ? out.log : out.error)(describe(r)); const counts = new Map<QuoteStatus, number>(); for (const r of results) counts.set(r.status, (counts.get(r.status) ?? 0) + 1); out.log( `reports verify-quotes: ${results.length} quote(s): ` + [...counts].map(([s, n]) => `${n} ${s}`).join(", ") + - (parsed.problems.length ? `; ${parsed.problems.length} validation problem(s)` : ""), + (parsed.problems.length ? `; ${parsed.problems.length} validation problem(s)` : "") + + (results.some((r) => QUOTE_WARNING_STATUSES.has(r.status)) ? " (inexact is a warning)" : ""), ); } return bad.length > 0 || parsed.problems.length > 0 ? 1 : 0; diff --git a/common/lib/citations/verify.test.ts b/common/lib/citations/verify.test.ts @@ -8,7 +8,13 @@ import { quoteTokens, quoteVerification, tokenRecall, + STRICT_QUOTE_WINDOW_SECONDS, + quoteFragments, + strictNormalize, + strictQuoteCheck, + strictTextCheck, } from "./verify"; +import { cuesOf } from "../../testing/draft/corpus.mjs"; test("tokens: lowercased, punctuation stripped, split on whitespace", () => { assert.deepEqual(quoteTokens("Don't stop — the U.S. bridge, OK?"), ["dont", "stop", "the", "us", "bridge", "ok"]); @@ -47,3 +53,64 @@ test("the block: rounded score, the time, the method; drift below the threshold" assert.equal(quoteDrifted({}), true); assert.ok(!("voiceChecked" in v), "a voice is never vouched for"); }); + +// ─── the strict check (release 27 D3) ─── + +test("strict normalisation: case, punctuation, whitespace, curly quotes and apostrophes", () => { + assert.equal(strictNormalize(" Don’t STOP — the “U.S.” bridge,\nOK?"), "dont stop the u s bridge ok"); + assert.equal(strictNormalize("don't"), strictNormalize("Don’t")); +}); + +test("strict fragments: split on the ellipsis convertSweep joins with", () => { + assert.deepEqual(quoteFragments("a lot of you asked … I did not enter"), ["a lot of you asked", "I did not enter"]); + assert.deepEqual(quoteFragments("one... two"), ["one", "two"]); + assert.deepEqual(quoteFragments(" … "), []); +}); + +test("strict: a reversed quote recall passes is refused; the exact one passes", async () => { + const cues = (await cuesOf("synth-kitchen", "bread-day-01"))!; + // Recall passes it — every token of the reversed quote is in the cue. + assert.equal(tokenRecall("I would sell the bakery to a chain", cueWindowText(cues, 15, 19.8)), 1); + const reversed = strictQuoteCheck("I would sell the bakery to a chain", cues, 15); + assert.equal(reversed.ok, false); + assert.equal(reversed.failed, "I would sell the bakery to a chain"); + assert.equal(strictQuoteCheck("I would never sell the bakery to a chain", cues, 15).ok, true); + // Case, punctuation and curly quotes do not matter. + assert.equal(strictQuoteCheck("I WOULD never sell the bakery, to a chain!", cues, 15).ok, true); +}); + +test("strict: every fragment must be found; a quote spanning two cues passes", async () => { + const cues = (await cuesOf("synth-kitchen", "bread-day-01"))!; + const two = strictQuoteCheck("we never said that about the old oven … the oven was fine it just ran hot", cues, 25); + assert.equal(two.ok, true); + assert.deepEqual(two.fragments.map((f) => f.ok), [true, true]); + const across = strictQuoteCheck("about the old oven the oven was fine", cues, 25); + assert.equal(across.ok, true); + const oneBad = strictQuoteCheck("we never said that about the old oven … the oven was broken", cues, 25); + assert.equal(oneBad.ok, false); + assert.equal(oneBad.failed, "the oven was broken"); +}); + +test("strict: on word boundaries — a fragment inside a longer word does not pass", async () => { + const cues = (await cuesOf("synth-kitchen", "bread-day-01"))!; + assert.equal(strictQuoteCheck("he oven", cues, 25).ok, false); + assert.equal(strictQuoteCheck("the oven", cues, 25).ok, true); +}); + +test("strict: within ±90 s of the cited second, and no further", async () => { + const cues = (await cuesOf("synth-kitchen", "qa-long-03"))!; + const q = "we opened the second shop in the spring"; // said at 205 s + assert.equal(STRICT_QUOTE_WINDOW_SECONDS, 90); + assert.equal(strictQuoteCheck(q, cues, 205).ok, true); + assert.equal(strictQuoteCheck(q, cues, 120).ok, true); + assert.equal(strictQuoteCheck(q, cues, 5).ok, false, "two hundred seconds from its link"); + assert.equal(strictQuoteCheck(q, cues, 100).ok, false); + assert.equal(strictQuoteCheck(q, cues, 5, { windowSeconds: 300 }).ok, true); +}); + +test("strict: an empty quote never passes; a post is checked against its text", () => { + assert.equal(strictTextCheck("", "anything").ok, false); + const post = "No, I did not enter the pie contest. The judges are my friends."; + assert.equal(strictTextCheck("No, I did not enter the pie contest.", post).ok, true); + assert.equal(strictTextCheck("I did enter the pie contest", post).ok, false); +}); diff --git a/common/lib/citations/verify.ts b/common/lib/citations/verify.ts @@ -95,3 +95,103 @@ export function quoteVerification(quote: string, text: string, checkedAt: string export function quoteDrifted(v: Pick<CitationVerification, "quoteScore">): boolean { return (v.quoteScore ?? 0) < QUOTE_DRIFT_THRESHOLD; } + +// ─── the STRICT check (release 27, D3) ─── +// +// Token recall passes a quote whose meaning is reversed: "I would sell" scores +// 1.0 against a record that says "I would never sell", and a quote with two +// words reversed in meaning passed at 0.85. A GENERATED quote is held to +// more: every quoted fragment — the fragments convertSweep joins with an +// ellipsis — must be in the record's text VERBATIM after normalisation +// (strictNormalize: case, punctuation, whitespace, curly quotes), within +// ±STRICT_QUOTE_WINDOW_SECONDS of the cited second, on word boundaries. +// +// verify-quotes reports a quote that passes recall and fails this as +// `inexact` — a WARNING for existing reports; compose and publish do not use +// it (release 27 D3). The generation tasks refuse a quote that fails it. + +export const STRICT_QUOTE_WINDOW_SECONDS = 90; + +export const STRICT_QUOTE_METHOD = + "strict v1: every fragment verbatim (case, punctuation, whitespace and curly quotes normalised) within ±90 s of the cited second"; + +// The text both sides are compared as: NFKC, lowercased, curly quotes made +// straight, apostrophes removed ("don't" is "dont"), every other character +// that is not a letter, a digit or whitespace made a space, whitespace +// collapsed. +export function strictNormalize(text: string): string { + return text + .normalize("NFKC") + .toLowerCase() + .replace(/[‘’ʼ]/g, "'") + .replace(/[“”]/g, '"') + .replace(/[^\p{L}\p{N}\s']/gu, " ") + .replace(/'/g, "") + .replace(/\s+/g, " ") + .trim(); +} + +// A quote's fragments: split on the ellipsis convertSweep joins quoted runs +// with (`…`, or three dots), blanks dropped. +export function quoteFragments(quote: string): string[] { + return quote + .split(/…|\.\.\./) + .map((f) => f.trim()) + .filter((f) => strictNormalize(f).length > 0); +} + +export type StrictFragmentResult = { fragment: string; ok: boolean }; + +export type StrictQuoteResult = { + // Every fragment found; false for a quote with no words. + ok: boolean; + fragments: StrictFragmentResult[]; + // The first fragment that was not found, as quoted. + failed?: string; + method: string; +}; + +// Whether `needle` occurs in `hay` on word boundaries (both normalised). +function containsWords(hay: string, needle: string): boolean { + return needle.length > 0 && ` ${hay} `.includes(` ${needle} `); +} + +function strictAgainst(quote: string, text: string): StrictQuoteResult { + const hay = strictNormalize(text); + const fragments = quoteFragments(quote).map((fragment) => ({ + fragment, + ok: containsWords(hay, strictNormalize(fragment)), + })); + const failed = fragments.find((f) => !f.ok)?.fragment; + return { + ok: fragments.length > 0 && failed === undefined, + fragments, + ...(failed !== undefined ? { failed } : fragments.length === 0 ? { failed: quote } : {}), + method: STRICT_QUOTE_METHOD, + }; +} + +// The text of every cue overlapping [second − window, second + window]. +export function strictWindowText( + cues: readonly TimedText[], + second: number, + windowSeconds = STRICT_QUOTE_WINDOW_SECONDS, +): string { + return cueWindowText(cues, second, second, windowSeconds); +} + +// A span quote, strictly: each fragment verbatim in the cues within +// ±windowSeconds of `second` (the cited second — a citation's `start`). +export function strictQuoteCheck( + quote: string, + cues: readonly TimedText[], + second: number, + opts: { windowSeconds?: number } = {}, +): StrictQuoteResult { + return strictAgainst(quote, strictWindowText(cues, second, opts.windowSeconds ?? STRICT_QUOTE_WINDOW_SECONDS)); +} + +// A post quote, strictly: each fragment verbatim in the post's text. +export function strictTextCheck(quote: string, text: string): StrictQuoteResult { + return strictAgainst(quote, text); +} diff --git a/common/lib/report/draft/grounding.test.ts b/common/lib/report/draft/grounding.test.ts @@ -0,0 +1,77 @@ +// Grounding: the hard checks every narration line passes, and the Q0 lints. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { checkNarration, groundingInputOf, lintNarration, reportText, QUOTE_RUN_MESSAGE } from "./grounding"; + +const REPORTS = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft/reports"); +const basic = JSON.parse(await readFile(path.join(REPORTS, "basic.report.json"), "utf8")); +const input = groundingInputOf(basic); + +test("the report's text: title, sections, claims, quotes and labels", () => { + const t = reportText(basic); + assert.match(t, /Synth Kitchen — what the baker says about the bakery/); + assert.match(t, /The contest/); + assert.match(t, /I paid for the new mixer myself/); + assert.match(t, /Bread day/); +}); + +test("a grounded line passes clean", () => { + assert.deepEqual(checkNarration("She talks about the bakery, the oven and the contest. Here's what she said.", input), { + hard: [], + soft: [], + }); +}); + +test("hard: numbers and names the report lacks", () => { + const r = checkNarration("She sold 7 bakeries to Megacorp in twenty minutes.", input); + assert.ok(r.hard.includes("number 7 is not in the report"), r.hard.join("|")); + assert.ok(r.hard.includes("name “Megacorp” is not in the report"), r.hard.join("|")); + assert.ok(r.hard.includes("number “twenty” is not in the report"), r.hard.join("|")); + // A name the report has passes, possessive or not; the first word of a sentence is not a name. + assert.deepEqual(checkNarration("Kitchen talk. Bread day is where Synth Kitchen's baker speaks.", input).hard, []); +}); + +test("hard: tags, stock phrases, quotation marks, quotes read out", () => { + assert.deepEqual(checkNarration("<laugh> So she did.", input).hard, ["has a tag in angle brackets"]); + assert.deepEqual(checkNarration("Let's dive in to the bakery.", input).hard, [ + "stock phrase “dive in”", + "stock phrase “let's dive in”", + "stock phrase “let's dive”", + ]); + assert.deepEqual(checkNarration("She said “no” to the bakery.", input).hard, [ + "text in quotation marks: no quotes in narration", + ]); + // Six words of a quote, said as the narrator's own. + assert.deepEqual(checkNarration("She says she would never sell the bakery to a chain.", input).hard, [QUOTE_RUN_MESSAGE]); + // Five words are not a quote run. + assert.deepEqual(checkNarration("She would never sell the bakery.", input).hard, []); +}); + +test("soft (Q0): a negation mismatch — the meaning reversed against its evidence", () => { + const ev = ["I have never met the other finalist", "She says she paid for the new mixer herself"]; + const w = lintNarration("She met the other finalist backstage.", ev); + assert.equal(w.length, 1); + assert.match(w[0]!, /^negation mismatch: “She met the other finalist backstage\.” against “I have never met the other finalist”/); + assert.deepEqual(lintNarration("She has never met the other finalist.", ev), []); + // A line about something else is not compared. + assert.deepEqual(lintNarration("The pie needs an hour.", ev), []); +}); + +test("soft (Q0): a dropped hedge", () => { + const ev = ["next year maybe I will enter the contest again"]; + const w = lintNarration("Next year she will enter the contest again.", ev); + assert.equal(w.length, 1); + assert.match(w[0]!, /^dropped hedge: /); + assert.deepEqual(lintNarration("Maybe she will enter the contest again next year.", ev), []); +}); + +test("checkNarration carries the lints as soft warnings", () => { + const r = checkNarration("She paid nothing for the new mixer.", input); + assert.deepEqual(r.hard, []); + assert.equal(r.soft.length, 1); + assert.match(r.soft[0]!, /negation mismatch/); +}); diff --git a/common/lib/report/draft/grounding.ts b/common/lib/report/draft/grounding.ts @@ -0,0 +1,237 @@ +// 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. +// +// 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<string, number> = { + 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[]; +}; + +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 } | 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)]; +} + +export function groundingInputOf(report: ReportLike): GroundingInput { + return { reference: reportText(report), quotes: reportQuotes(report), evidence: reportEvidence(report) }; +} + +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} `); + +export function checkNarration(text: string, input: GroundingInput): GroundingResult { + const hard = new Set<string>(); + const soft = new Set<string>(); + 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}”`); + + const ref = input.reference; + const refNorm = strictNormalize(ref); + const refNums = new Set(ref.replace(/,/g, "").match(/\d+/g) ?? []); + for (const d of text.match(/\d[\d,]*/g) ?? []) { + if (!refNums.has(d.replace(/,/g, ""))) hard.add(`number ${d} is not in the report`); + } + 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))) hard.add(`number “${w}” is not in the report`); + } + 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)) hard.add(`name “${t}” is not in the report`); + } + } + 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 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<string> { + 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; +} diff --git a/common/lib/report/draft/reportOps.test.ts b/common/lib/report/draft/reportOps.test.ts @@ -0,0 +1,181 @@ +// Report ops over the fixture sweeps: batch numbering, merge chains, reasons +// on every refusal, no quoted words in claims, quotes untouched, a strict +// check on every added quote. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { sweepToReport } from "../convertSweep"; +import { cuesOf, momentHref, recordOf } from "../../../testing/draft/corpus.mjs"; +import { readSweep } from "../../../testing/draft/derive"; +import { numberFindings, parseSweep, renderSweep, type SweepDoc } from "./sweepModel"; +import { applyReportOps, quotedClaimProblems, strictCheckerOver, type ReportOpsContext } from "./reportOps"; + +const load = async (name: Parameters<typeof readSweep>[0]) => parseSweep(await readSweep(name)); +const claims = (doc: SweepDoc) => numberFindings(doc).map((x) => x.finding.claim); +const ctx: ReportOpsContext = { + checkQuote: strictCheckerOver(cuesOf), + titleOf: async (c, id) => recordOf(c, id)?.title ?? null, + origin: "https://synth.example", +}; +const quotesOfReport = async (md: string) => + Object.values((await sweepToReport(md, { cuesOf })).report.citations ?? {}) + .map((c) => ("quote" in c ? c.quote : "")) + .sort(); + +test("a batch numbers against the document at its START: drop 1 then drop 3 drops the 1 and 3 the model saw", async () => { + const doc = await load("basic"); + const before = claims(doc); + const r = await applyReportOps(doc, [{ op: "drop", n: 1 }, { op: "drop", n: 3 }, { op: "claim", n: 4, text: "She did not enter" }]); + assert.deepEqual(r.refused, []); + assert.deepEqual(claims(r.doc), [before[1], "She did not enter", before[4], before[5]]); + // The input is not touched. + assert.deepEqual(claims(doc), before); + // A second batch numbers afresh. + const r2 = await applyReportOps(r.doc, [{ op: "drop", n: 1 }]); + assert.deepEqual(claims(r2.doc), ["She did not enter", before[4], before[5]]); +}); + +test("merge chains resolve: merge 1→2, 2→3, then an op on 1 lands on 3; dropping 1 is refused with its reason", async () => { + const doc = await load("basic"); + const r = await applyReportOps(doc, [ + { op: "merge", n: 1, into: 2 }, + { op: "merge", n: 2, into: 3, text: "She denies three stories" }, + { op: "claim", n: 1, text: "She denies all three" }, + { op: "drop", n: 1 }, + { op: "merge", n: 3, into: 1 }, + ]); + assert.deepEqual(r.applied.map((a) => a.index), [0, 1, 2]); + assert.equal(r.refused.length, 2); + assert.match(r.refused[0]!.why, /finding 1 was merged into finding 3; drop that one/); + assert.match(r.refused[1]!.why, /cannot merge into itself/); + const fs = numberFindings(r.doc).map((x) => x.finding); + assert.equal(fs.length, 4); + assert.equal(fs[0]!.claim, "She denies all three"); + // Every quote kept its own link, in order. + const links = [...fs[0]!.rest.matchAll(/&t=(\d+)\)/g)].map((m) => Number(m[1])); + assert.deepEqual(links, [45, 25, 15]); + // Converted, the quotes are the original quotes — none edited. + assert.deepEqual(await quotesOfReport(renderSweep(r.doc)), await quotesOfReport(await readSweep("basic"))); +}); + +test("every refusal carries a reason, and refuses that op only", async () => { + const doc = await load("basic"); + const r = await applyReportOps(doc, [ + { op: "drop", n: 99 }, + { op: "drop" }, + { op: "explode", n: 1 }, + { op: "claim", n: 2 }, + { op: "move", n: 2 }, + { op: "section", section: "Nope", text: "x" }, + { op: "section", section: "The bakery", text: "The contest" }, + { op: "title", text: " " }, + "nonsense", + { op: "drop", n: 2 }, + { op: "drop", n: 2 }, + { op: "claim", n: 2, text: "after the drop" }, + ]); + assert.deepEqual(r.applied.map((a) => a.index), [9]); + assert.equal(r.refused.length, 11); + for (const x of r.refused) assert.ok(x.why.length > 8, JSON.stringify(x)); + const why = r.refused.map((x) => x.why); + assert.match(why[0]!, /no finding 99 \(the document has 6\)/); + assert.match(why[2]!, /no op "explode"/); + assert.match(why[5]!, /no section "Nope"/); + assert.match(why[6]!, /already a section "The contest"/); + assert.match(why[9]!, /already dropped/); + assert.match(why[10]!, /dropped earlier in this batch/); +}); + +test("claims never carry quoted words or a link: the op that would put one in is refused (quotes-in-claims.md)", async () => { + const doc = await load("quotes-in-claims"); + // The fixture breaks the rule; the lint names each finding. + assert.deepEqual(quotedClaimProblems(doc).map((p) => p.n), [1, 2, 3]); + const r = await applyReportOps(doc, [ + { op: "claim", n: 1, text: 'She "would never" sell the bakery' }, + { op: "claim", n: 2, text: "The “old oven” story is denied" }, + { op: "merge", n: 3, into: 1, text: 'She says "nobody"' }, + { op: "claim", n: 1, text: "See [this](https://synth.example/?v=a%2Fb&t=1)" }, + { op: "add", section: "Findings", text: 'She "sold"', quote: "I would never sell the bakery to a chain", link: momentHref("synth-kitchen", "bread-day-01", 15) }, + { op: "claim", n: 1, text: "She says she would never sell the bakery" }, + ], ctx); + assert.deepEqual(r.applied.map((a) => a.index), [5]); + for (const x of r.refused.slice(0, 3)) assert.match(x.why, /no quotation marks/); + assert.match(r.refused[3]!.why, /no link/); + assert.match(r.refused[4]!.why, /no quotation marks.*put the words in "quote"/); + // The clean basic and multi-quote sweeps pass the lint. + assert.deepEqual(quotedClaimProblems(await load("basic")), []); + assert.deepEqual(quotedClaimProblems(await load("multi-quote")), []); +}); + +test("move: to a new section before Coverage, and the document still converts", async () => { + const doc = await load("paragraphs"); + const r = await applyReportOps(doc, [{ op: "move", n: 2, section: "The recipe" }, { op: "move", n: 1, section: "The second shop" }]); + assert.match(r.refused[0]!.why, /already in "The second shop"/); + assert.deepEqual(r.doc.sections.map((s) => s.title), ["The second shop", "The recipe", "Coverage"]); + const md = renderSweep(r.doc); + assert.match(md, /\n## The recipe\n\n- The other kitchen tried the recipe: "we tried the sourdough recipe from last week" \[The flat loaf @ 0:05\]\([^)]+\)\n\n## Coverage\n/); + const { report, problems } = await sweepToReport(md, { cuesOf }); + assert.deepEqual(problems, []); + assert.deepEqual(report.sections.map((s) => s.title), ["The second shop", "The recipe", "Coverage"]); +}); + +test("a section a batch empties goes; one with text left stays", async () => { + const basic = await load("basic"); + const r = await applyReportOps(basic, [{ op: "drop", n: 4 }, { op: "drop", n: 5 }, { op: "drop", n: 6 }]); + assert.deepEqual(r.doc.sections.map((s) => s.title), ["The bakery"]); + assert.ok(renderSweep(r.doc).endsWith("&t=45)\n")); + const para = await load("paragraphs"); + const r2 = await applyReportOps(para, [{ op: "drop", n: 1 }, { op: "drop", n: 2 }]); + assert.deepEqual(r2.doc.sections.map((s) => s.title), ["The second shop", "Coverage"]); +}); + +test("add: the quote is strict-checked; exact words in, a reversed quote out; no checker, no add", async () => { + const doc = await load("basic"); + const link = (s: number) => momentHref("synth-kitchen", "bread-day-01", s); + const r = await applyReportOps( + doc, + [ + { op: "add", section: "The oven", text: "She says the oven ran hot", quote: "“the oven was fine it just ran hot”", link: link(30) }, + { op: "add", section: "The oven", text: "She says she would sell", quote: "I would sell the bakery to a chain", link: link(15) }, + { op: "add", section: "The oven", text: "Far away", quote: "thanks for watching see you next week", link: momentHref("synth-kitchen", "qa-long-03", 205) }, + { op: "add", section: "The oven", text: "No link", quote: "the oven was fine it just ran hot", link: "https://video.example/watch?v=x" }, + { op: "add", section: "The oven", text: "Other origin", quote: "the oven was fine it just ran hot", link: "https://elsewhere.example/?v=synth-kitchen%2Fbread-day-01&t=30" }, + { op: "add", section: "The oven", text: "Inner quote", quote: 'the "oven"', link: link(30) }, + ], + ctx, + ); + assert.deepEqual(r.applied.map((a) => a.index), [0]); + assert.match(r.refused[0]!.why, /not the transcript's words within 90 s of 15 s: "I would sell the bakery to a chain" is not there/); + assert.match(r.refused[1]!.why, /not the transcript's words/); + assert.match(r.refused[2]!.why, /needs a moment link/); + assert.match(r.refused[3]!.why, /origin https:\/\/synth\.example/); + assert.match(r.refused[4]!.why, /no quotation marks inside/); + const added = numberFindings(r.doc).map((x) => x.finding).find((f) => f.added)!; + assert.equal( + `- ${added.claim}${added.sep}${added.rest}`, + `- She says the oven ran hot: "the oven was fine it just ran hot" [Bread day @ 0:30](${link(30)})`, + ); + assert.deepEqual(r.doc.sections.map((s) => s.title), ["The bakery", "The contest", "The oven"]); + const conv = await sweepToReport(renderSweep(r.doc), { cuesOf }); + assert.deepEqual(conv.problems, []); + assert.ok(Object.values(conv.report.citations ?? {}).some((c) => "quote" in c && c.quote === "the oven was fine it just ran hot")); + + const none = await applyReportOps(doc, [{ op: "add", section: "X", text: "y", quote: "the oven was fine it just ran hot", link: link(30) }]); + assert.match(none.refused[0]!.why, /needs the quote checker/); +}); + +test("section, title and summary", async () => { + const doc = await load("basic"); + const r = await applyReportOps(doc, [ + { op: "section", section: "The contest", text: "The pie contest" }, + { op: "title", text: "What the baker says" }, + { op: "summary", text: "Six findings from two recordings." }, + ]); + assert.deepEqual(r.refused, []); + const md = renderSweep(r.doc); + assert.ok(md.startsWith("# What the baker says\n\nSix findings from two recordings.\n\n## The bakery\n")); + assert.match(md, /\n## The pie contest\n/); + const { report } = await sweepToReport(md, { cuesOf }); + assert.equal(report.title, "What the baker says"); + assert.equal(report.summary, "Six findings from two recordings."); +}); diff --git a/common/lib/report/draft/reportOps.ts b/common/lib/report/draft/reportOps.ts @@ -0,0 +1,347 @@ +// 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). + +import { STRICT_QUOTE_WINDOW_SECONDS, strictQuoteCheck } from "../../citations/verify"; +import { + LINK_RE, + QUOTE_MARK_RE, + 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<string, unknown>; + +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<QuoteCheckAnswer>; + // A recording's title, for the new finding's link label. + titleOf?: (channel: string, id: string) => Promise<string | null>; + // 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; +}; + +// The strict checker over a cue reader (testing/draft/corpus.mjs cuesOf, or +// the MCP's transcript read): every fragment verbatim within ±90 s. +export function strictCheckerOver( + cuesOf: (channel: string, id: string) => Promise<readonly { start: number; end: number; text: string }[] | null>, + opts: { windowSeconds?: number } = {}, +): (q: QuoteCheckRequest) => Promise<QuoteCheckAnswer> { + 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 }); + return r.ok ? { ok: true } : { ok: false, why: `"${r.failed}" is not there` }; + }; +} + +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<ReportOpsResult> { + 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<Finding, Finding>(); + const dropped = new Set<Finding>(); + + 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<Finding>(); + 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"`); + + 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": { + 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.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 !== "") { + const bad = claimProblem(op.text); + if (bad) refuse(bad); + } + if (typeof op.text === "string" && op.text.trim()) { + dst.claim = op.text.trim(); + if (!dst.sep) dst.sep = " "; + } + // Every quote keeps its own link: the rest is appended verbatim. + dst.rest = `${dst.rest.trimEnd()} ${src.rest.trim()}`; + 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); + 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"'); + const 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: <origin>/?v=<channel>%2F<id>&t=<seconds>"); + 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}` : ""}`); + } + const name = ((await ctx.titleOf?.(at_!.channel, at_!.id)) ?? at_!.id).replace(/[[\]()]/g, "").trim().slice(0, 80); + const f: Finding = { + type: "finding", + bullet: "- ", + claim, + sep: ": ", + 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}"`); + s.title = t; + break; + } + case "title": + doc.title = text(op.text, "title"); + doc.hasTitle = true; + break; + case "summary": { + doc.preamble = ["", text(op.text, "summary"), ""]; + 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 = finding.rest; + 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; +} diff --git a/common/lib/report/draft/sweepModel.test.ts b/common/lib/report/draft/sweepModel.test.ts @@ -0,0 +1,88 @@ +// The sweep.md model: byte-identical round trip over every fixture sweep, +// and the claim / sep / rest split at the first quote. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readdir, readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { numberFindings, numberedView, parseSweep, quotesOf, renderSweep, splitFinding } from "./sweepModel"; + +const SWEEPS = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft/sweeps"); + +test("round trip: parseSweep → renderSweep is byte-identical over every fixture sweep", async () => { + const files = (await readdir(SWEEPS)).filter((f) => f.endsWith(".md")); + assert.ok(files.length >= 6, files.join(",")); + for (const f of files) { + const md = await readFile(path.join(SWEEPS, f), "utf8"); + assert.equal(renderSweep(parseSweep(md)), md, f); + // And without the final newline. + assert.equal(renderSweep(parseSweep(md.trimEnd())), md.trimEnd(), `${f} (no final newline)`); + } +}); + +test("round trip: odd shapes — no title, lines before it, indented continuations, headings with extra spaces", () => { + for (const md of [ + "", + "no title at all\n", + "intro\n# Title\n\n## A\n\n- x: \"q\" [l](https://a.example/?v=c%2Fv&t=1)\n continued line\n\ntext\n", + "# Spaced title \n\n## Spaced section \n\n* star: “curly” [l](https://a.example/?v=c%2Fv&t=2)\n", + "# T\n\n## S\n\n- \"starts with a quote\" [l](https://a.example/?v=c%2Fv&t=3)\n- a plain list item, no link\n", + ]) { + assert.equal(renderSweep(parseSweep(md)), md, JSON.stringify(md)); + } +}); + +test("the model: title, preamble, sections in body order; findings only where a link is", async () => { + const doc = parseSweep(await readFile(path.join(SWEEPS, "paragraphs.md"), "utf8")); + assert.equal(doc.title, "Paragraphs between findings"); + // The preamble's bullets have no links: they are preamble lines, not findings. + assert.ok(doc.preamble.some((l) => l.startsWith("- **The second shop"))); + assert.deepEqual(doc.sections.map((s) => s.title), ["The second shop", "Coverage"]); + const shop = doc.sections[0]!; + assert.deepEqual( + shop.body.filter((b) => b.type === "line" ? b.text.trim() : true).map((b) => (b.type === "line" ? b.text : `[F] ${b.claim}`)), + [ + "She talks about it near the end of a long episode.", + "[F] She says it opened in the spring", + "### A sub-heading inside a section", + "The other kitchen mentions the recipe, not the shop.", + "[F] The other kitchen tried the recipe", + ], + ); + assert.equal(numberFindings(doc).length, 2); +}); + +test("split: the claim, the separator, and the rest from the first quote before the first link", () => { + assert.deepEqual(splitFinding('She says she would not sell: "I would never sell" [Bread day @ 0:15](https://s.example/?v=a%2Fb&t=15)'), { + claim: "She says she would not sell", + sep: ": ", + rest: '"I would never sell" [Bread day @ 0:15](https://s.example/?v=a%2Fb&t=15)', + }); + // No quote: cut at the link. + assert.deepEqual(splitFinding("A claim — [x @ 0:01](https://s.example/?v=a%2Fb&t=1)"), { + claim: "A claim", + sep: " — ", + rest: "[x @ 0:01](https://s.example/?v=a%2Fb&t=1)", + }); + // A quote AFTER the first link does not move the cut. + assert.equal(splitFinding('Claim [x](https://s.example/?v=a%2Fb&t=1) then "late"').claim, "Claim"); +}); + +test("quotes-in-claims: the split puts the claim's quoted words in the rest, never in the claim", async () => { + const doc = parseSweep(await readFile(path.join(SWEEPS, "quotes-in-claims.md"), "utf8")); + const fs = numberFindings(doc).map((x) => x.finding); + assert.deepEqual(fs.map((f) => f.claim), ["She", "The", "She says"]); + for (const f of fs) assert.doesNotMatch(f.claim, /["“”]/); + assert.deepEqual(quotesOf(fs[2]!), ["nobody sponsored", "nobody sponsored this kitchen"]); +}); + +test("the numbered view a model reads", async () => { + const doc = parseSweep(await readFile(path.join(SWEEPS, "basic.md"), "utf8")); + const view = numberedView(doc); + assert.match(view, /^TITLE: Synth Kitchen — what the baker says about the bakery\nSUMMARY: Scope: channel/); + assert.match(view, /\n## The bakery\n\[1\] She says she would not sell: "I would never sell the bakery to a chain" \[Bread day @ 0:15\]/); + assert.match(view, /\n\[6\] She will not discuss the lease: /); + const p = numberedView(parseSweep(await readFile(path.join(SWEEPS, "paragraphs.md"), "utf8"))); + assert.match(p, /## Coverage {2}\(coverage — keep\)/); +}); diff --git a/common/lib/report/draft/sweepModel.ts b/common/lib/report/draft/sweepModel.ts @@ -0,0 +1,193 @@ +// THE SWEEP.MD MODEL — a /sweep report as a document a revision can edit +// with checked operations (./reportOps.ts), and write back unchanged where it +// was not edited. +// +// The shape (what /sweep writes and convertSweep reads, +// lib/report/convertSweep.ts): +// +// # <title> +// <preamble: the summary, any lines before the first section> +// ## <section> +// - <claim>: "<quoted words>" [<label>](<link>) ← a FINDING +// <paragraphs, sub-headings, blank lines> ← kept, in body order +// +// A FINDING is a list item (`- ` or `* `) inside a section that carries at +// least one citing link. It is split at its FIRST quoted span before the +// first link (or at the link when nothing is quoted): the CLAIM before it, +// the separator, and the REST — the quotes and links — kept verbatim. That +// cut is the rule convertSweep imposes: every quoted span between the +// previous link and a link becomes that link's quote, so no quoted word may +// sit in the editable claim, and nothing an op does touches a quote. +// +// `parseSweep` → `renderSweep` is BYTE-IDENTICAL for any input (every line, +// blank lines and the final newline included; a test holds it over every +// fixture sweep). Ops change the parts they name and nothing else. + +export type Finding = { + type: "finding"; + // The list marker as written (`- `, `* `, with any indent). + bullet: string; + claim: string; + // What sat between the claim and the first quote (`: `, ` — `, ` `); may + // be empty. + sep: string; + // From the first quote (or link) to the end of the line, verbatim. + rest: string; + // Indented lines that continue the item, verbatim. + continued: string[]; + // Set by the `add` op: a finding this revision wrote (its quote is checked + // again after convert, and dropped — never repaired — if it fails). + added?: true; +}; + +export type SweepLine = { type: "line"; text: string }; + +export type SweepBlock = Finding | SweepLine; + +export type SweepSection = { + title: string; + // The heading line as written, when it is not exactly `## <title>`. + rawHeading?: string; + body: SweepBlock[]; +}; + +export type SweepDoc = { + // Lines before the `# ` title (normally none). + lead: string[]; + // The title, without `# `; empty when the document has no `# ` line. + title: string; + hasTitle: boolean; + rawTitle?: string; + // Every line between the title and the first section, verbatim. + preamble: string[]; + sections: SweepSection[]; +}; + +// A quoted span: straight or curly double quotes. +export const QUOTED_RE = /"[^"\n]*"|“[^”\n]*”/g; +// A citing link: a markdown link to an http(s) URL. +export const LINK_RE = /\[[^\]\n]*\]\(https?:\/\/[^)\s]+\)/g; +// Any quotation mark a claim may not carry. +export const QUOTE_MARK_RE = /["“”]/; + +const BULLET_RE = /^(\s{0,3}[-*] )(.*)$/; +const CONTINUED_RE = /^\s{2,}\S/; + +function firstMatch(re: RegExp, text: string, from = 0, to = text.length): RegExpExecArray | null { + const r = new RegExp(re.source, re.flags.includes("g") ? re.flags : `${re.flags}g`); + r.lastIndex = from; + const m = r.exec(text); + return m && m.index < to ? m : null; +} + +export function hasLink(text: string): boolean { + return firstMatch(LINK_RE, text) !== null; +} + +// A finding's text split at its first quote before its first link (the +// stopgap's split_item): the claim (trailing ` :—-` moved into the +// separator), the separator, and the rest. +export function splitFinding(text: string): { claim: string; sep: string; rest: string } { + const link = firstMatch(LINK_RE, text); + const quote = link ? firstMatch(QUOTED_RE, text, 0, link.index) : null; + const cut = quote ? quote.index : link ? link.index : text.length; + const head = text.slice(0, cut); + const claim = head.replace(/[ :—-]+$/u, ""); + return { claim, sep: head.slice(claim.length), rest: text.slice(cut) }; +} + +export function parseSweep(md: string): SweepDoc { + const lines = md.split("\n"); + const doc: SweepDoc = { lead: [], title: "", hasTitle: false, preamble: [], sections: [] }; + let section: SweepSection | null = null; + let last: Finding | null = null; + for (const line of lines) { + if (section === null && !doc.hasTitle && line.startsWith("# ")) { + doc.hasTitle = true; + doc.title = line.slice(2).trim(); + if (line !== `# ${doc.title}`) doc.rawTitle = line; + continue; + } + if (line.startsWith("## ")) { + const title = line.slice(3).trim(); + section = { title, body: [], ...(line !== `## ${title}` ? { rawHeading: line } : {}) }; + doc.sections.push(section); + last = null; + continue; + } + if (section === null) { + (doc.hasTitle ? doc.preamble : doc.lead).push(line); + continue; + } + if (last && CONTINUED_RE.test(line)) { + last.continued.push(line); + continue; + } + const b = BULLET_RE.exec(line); + if (b && hasLink(b[2]!)) { + last = { type: "finding", bullet: b[1]!, ...splitFinding(b[2]!), continued: [] }; + section.body.push(last); + continue; + } + last = null; + section.body.push({ type: "line", text: line }); + } + return doc; +} + +export function findingLines(f: Finding): string[] { + return [`${f.bullet}${f.claim}${f.sep}${f.rest}`, ...f.continued]; +} + +export function renderSweep(doc: SweepDoc): string { + const out: string[] = [...doc.lead]; + if (doc.hasTitle) { + out.push(doc.rawTitle !== undefined && doc.rawTitle.slice(2).trim() === doc.title ? doc.rawTitle : `# ${doc.title}`); + } + out.push(...doc.preamble); + for (const s of doc.sections) { + out.push(s.rawHeading !== undefined && s.rawHeading.slice(3).trim() === s.title ? s.rawHeading : `## ${s.title}`); + for (const b of s.body) { + if (b.type === "line") out.push(b.text); + else out.push(...findingLines(b)); + } + } + return out.join("\n"); +} + +export function findingsOf(section: SweepSection): Finding[] { + return section.body.filter((b): b is Finding => b.type === "finding"); +} + +// Every finding in document order, numbered from 1 — the numbering an op +// batch is written against. +export function numberFindings(doc: SweepDoc): { n: number; section: SweepSection; finding: Finding }[] { + const out: { n: number; section: SweepSection; finding: Finding }[] = []; + for (const section of doc.sections) { + for (const finding of findingsOf(section)) out.push({ n: out.length + 1, section, finding }); + } + return out; +} + +export const isCoverage = (s: SweepSection) => s.title.trim().toLowerCase() === "coverage"; + +// The document as a model reads it: the title, the summary, each section +// and each finding numbered `[n]` (the numbers an op batch uses). +export function numberedView(doc: SweepDoc): string { + const numbers = new Map(numberFindings(doc).map((x) => [x.finding, x.n])); + const summary = doc.preamble.map((l) => l.trim()).filter(Boolean).join(" "); + const lines = [`TITLE: ${doc.title}`, `SUMMARY: ${summary}`]; + for (const s of doc.sections) { + lines.push(`## ${s.title}${isCoverage(s) ? " (coverage — keep)" : ""}`); + for (const b of s.body) { + if (b.type === "finding") lines.push(`[${numbers.get(b)}] ${b.claim}${b.sep}${b.rest}`); + else if (b.text.trim()) lines.push(b.text); + } + } + return lines.join("\n"); +} + +// The quoted spans of a finding's rest, in order (without their marks). +export function quotesOf(f: Finding): string[] { + return [...f.rest.matchAll(new RegExp(QUOTED_RE.source, "g"))].map((m) => m[0].slice(1, -1)); +} diff --git a/common/lib/report/draft/videoOps.test.ts b/common/lib/report/draft/videoOps.test.ts @@ -0,0 +1,133 @@ +// Video ops over the fixture manifests: trims within the fetched window, +// clips only from the report's citations, narration through grounding. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { applyVideoOps, cutView, TRIM_SLACK_SECONDS, type VideoManifest } from "./videoOps"; + +const DRAFT = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../testing/draft"); +const json = async (p: string) => JSON.parse(await readFile(path.join(DRAFT, p), "utf8")); +const manifest: VideoManifest = await json("manifests/basic.video.manifest.json"); +const report = await json("reports/basic.report.json"); +const ids = (m: VideoManifest) => m.timeline.map((e) => e.id); + +test("drop, move (after an entry, or to the start), heading, title, subtitle", () => { + const r = applyVideoOps( + manifest, + [ + { op: "drop", id: "c02" }, + { op: "move", id: "c06", after: "the-bakery" }, + { op: "move", id: "the-contest", after: "start" }, + { op: "heading", id: "the-bakery", text: "The shop" }, + { op: "title", text: "The baker, in her words" }, + { op: "subtitle", text: "Two recordings" }, + ], + { report }, + ); + assert.deepEqual(r.refused, []); + assert.deepEqual(ids(r.manifest), ["the-contest", "title", "the-bakery", "c06", "c01", "c03", "c04", "c05"]); + assert.equal(r.manifest.timeline.find((e) => e.id === "the-bakery")!.heading, "The shop"); + assert.equal(r.manifest.title, "The baker, in her words"); + assert.equal(r.manifest.subtitle, "Two recordings"); + // The input is not touched. + assert.equal(manifest.timeline.length, 9); +}); + +test("trim: within the parent's window ±3 s; outside it is refused with the window", () => { + assert.equal(TRIM_SLACK_SECONDS, 3); + const r = applyVideoOps( + manifest, + [ + { op: "trim", id: "c01", start: 12.5, end: 22 }, + { op: "trim", id: "c03", start: 41, end: 49 }, + { op: "trim", id: "c04", start: 11, end: 10 }, + { op: "trim", id: "the-bakery", start: 1, end: 2 }, + { op: "trim", id: "c05", start: "x", end: 3 }, + ], + { report }, + ); + assert.deepEqual(r.applied.map((a) => a.index), [0]); + const c01 = r.manifest.timeline.find((e) => e.id === "c01")!; + assert.deepEqual([c01.start, c01.end], [12.5, 22]); + assert.match(r.refused[0]!.why, /outside the fetched window \(42\.00–52\.80 s\)/); + assert.match(r.refused[1]!.why, /start is before its end/); + assert.match(r.refused[2]!.why, /is a card, not a clip/); + assert.match(r.refused[3]!.why, /start and end in seconds/); + // A second revision is bounded by the PARENT cut, not by the trimmed one. + const again = applyVideoOps(r.manifest, [{ op: "trim", id: "c01", start: 11.5, end: 22.5 }], { report, parent: manifest }); + assert.match(again.refused[0]!.why, /12\.00–22\.80/); +}); + +test("add_clip: only the report's own video citations, once each", () => { + const r = applyVideoOps( + manifest, + [ + { op: "drop", id: "c02" }, + { op: "add_clip", citation: "c02", after: "c01" }, + { op: "add_clip", citation: "c03" }, + { op: "add_clip", citation: "c99" }, + { op: "trim", id: "c02", start: 22, end: 30 }, + ], + { report: { ...report, citations: { ...report.citations, p01: { kind: "post", channel: "s", id: "1", quote: "x" } } } }, + ); + assert.deepEqual(r.applied.map((a) => a.index), [0, 1, 4]); + assert.match(r.refused[0]!.why, /"c03" is already in the cut/); + assert.match(r.refused[1]!.why, /no citation "c99"/); + assert.deepEqual(ids(r.manifest).slice(0, 4), ["title", "the-bakery", "c01", "c02"]); + const c02 = r.manifest.timeline.find((e) => e.id === "c02")!; + assert.deepEqual( + { channel: c02.channel, video: c02.video, start: c02.start, end: c02.end, quote: c02.quote }, + { channel: "synth-kitchen", video: "bread-day-01", start: 22, end: 30, quote: "we never said that about the old oven" }, + ); + const post = applyVideoOps(manifest, [{ op: "add_clip", citation: "p01" }], { + report: { ...report, citations: { p01: { kind: "post", channel: "s", id: "1", quote: "x" } } }, + }); + assert.match(post.refused[0]!.why, /only a video citation becomes a clip/); +}); + +test("narration: through grounding — refused with its reasons, flagged with the lints, removed with an empty text", () => { + const r = applyVideoOps( + manifest, + [ + { op: "narration", id: "the-bakery", text: "First, the bakery and the oven." }, + { op: "narration", id: "the-contest", text: "She sold 7 pies to Megacorp. <sigh>" }, + { op: "narration", id: "the-contest", text: "She says she would never sell the bakery to a chain." }, + { op: "narration", id: "c01", text: "A clip." }, + { op: "narration", id: "the-contest", text: "She did enter the contest this year." }, + { op: "narration", id: "title", text: "" }, + ], + { report }, + ); + assert.deepEqual(r.applied.map((a) => a.index), [0, 4, 5]); + assert.equal(r.manifest.timeline.find((e) => e.id === "the-bakery")!.narration!.text, "First, the bakery and the oven."); + assert.match(r.refused[0]!.why, /^narration refused: .*has a tag.*name “Megacorp”.*number 7/); + assert.match(r.refused[1]!.why, /repeats 6\+ words of a quote/); + assert.match(r.refused[2]!.why, /"c01" is a clip, not a card/); + // A reversed meaning is applied, and flagged. + assert.match(r.applied[1]!.warnings![0]!, /^negation mismatch/); + assert.equal(r.manifest.timeline.find((e) => e.id === "title")!.narration, undefined); +}); + +test("unknown ops and entries are refused with a reason", () => { + const r = applyVideoOps(manifest, [{ op: "spin" }, { op: "drop", id: "nope" }, { op: "move", id: "c01", after: "c01" }], { + report, + }); + assert.deepEqual(r.applied, []); + assert.deepEqual( + r.refused.map((x) => x.why), + [ + 'no op "spin" — the ops are drop, move, heading, narration, trim, add_clip, title, subtitle', + 'no entry "nope" in the cut', + "an entry cannot move after itself", + ], + ); +}); + +test("the cut as a model reads it", () => { + const v = cutView(manifest); + assert.match(v, /^TITLE: Synth Kitchen — what the baker says about the bakery\nSUBTITLE: \n- card title \(title\) heading: /); + assert.match(v, /\n- clip c01 synth-kitchen\/bread-day-01 15–19\.8 s quote: "I would never sell the bakery to a chain"/); +}); diff --git a/common/lib/report/draft/videoOps.ts b/common/lib/report/draft/videoOps.ts @@ -0,0 +1,212 @@ +// VIDEO OPS — a revision of a report video's cut (`video.manifest.json`), as +// checked edit operations a model asks for and code applies (the stopgap's +// revise.py, release 27 S2). +// +// drop {id} remove an entry +// move {id, after} reorder: after another entry, or "start" +// heading {id, text} a card's on-screen heading +// narration {id, text} a card's spoken narration ("" removes it) — through grounding +// trim {id, start, end} a clip's in/out, within the fetched window ±3 s +// add_clip {citation, after?} a clip for a video citation of the report not in the cut +// title {text} / subtitle {text} +// +// The rules, in code: +// - A narration passes ./grounding.ts's hard checks, or the op is refused +// with them; its soft warnings come back with the result. +// - A trim stays within the window already fetched: the PARENT cut's clip +// (the one the revision started from) ±TRIM_SLACK_SECONDS. A clip added in +// this revision is bounded by its own citation's span. +// - add_clip only takes the report's own VIDEO citations, once each. +// - Every refusal carries its reason, and refuses that op only. Ops name +// entries by id, so a batch is not renumbered by its own drops. +// +// Pure: the manifest in, a new one out. + +import { checkNarration, groundingInputOf, type GroundingInput } from "./grounding"; + +export const VIDEO_OP_NAMES = ["drop", "move", "heading", "narration", "trim", "add_clip", "title", "subtitle"] as const; + +export const TRIM_SLACK_SECONDS = 3; + +export type ManifestEntry = { + type: string; + id: string; + style?: string; + heading?: string; + narration?: { text: string } & Record<string, unknown>; + channel?: string; + video?: string; + start?: number; + end?: number; + cite?: number; + quote?: string; +} & Record<string, unknown>; + +export type VideoManifest = { title?: string; subtitle?: string; timeline: ManifestEntry[] } & Record<string, unknown>; + +type CitationLike = { kind: string; channel?: string; id?: string; start?: number; end?: number; quote?: string }; + +export type ReportForVideo = Parameters<typeof groundingInputOf>[0] & { + citations?: Record<string, CitationLike | undefined> | null; +}; + +export type VideoOp = { op: string } & Record<string, unknown>; +export type AppliedVideoOp = { index: number; op: VideoOp; warnings?: string[] }; +export type RefusedVideoOp = { index: number; op: VideoOp; why: string }; + +export type VideoOpsContext = { + // The report the cut is made from: its citations, and the text grounding + // checks a narration against. + report: ReportForVideo; + // The cut the revision started from (its clips' windows bound a trim); + // default: the manifest passed in. + parent?: VideoManifest; + // Grounding's input; default: from the report. + grounding?: GroundingInput; +}; + +export type VideoOpsResult = { manifest: VideoManifest; applied: AppliedVideoOp[]; refused: RefusedVideoOp[] }; + +class Refusal extends Error {} +const refuse = (why: string): never => { + throw new Refusal(why); +}; + +const str = (v: unknown, what: string): string => + typeof v === "string" ? v : refuse(`${what} must be text`); + +export function applyVideoOps(input: VideoManifest, ops: readonly unknown[], ctx: VideoOpsContext): VideoOpsResult { + const manifest = structuredClone(input); + if (!Array.isArray(manifest.timeline)) manifest.timeline = []; + const parent = ctx.parent ?? input; + const parentClips = new Map( + (parent.timeline ?? []).filter((e) => e.type === "clip").map((e) => [e.id, e] as const), + ); + const grounding = ctx.grounding ?? groundingInputOf(ctx.report); + const citations = ctx.report.citations ?? {}; + const applied: AppliedVideoOp[] = []; + const refused: RefusedVideoOp[] = []; + + for (const [index, raw] of ops.entries()) { + const op = (raw && typeof raw === "object" ? raw : { op: String(raw) }) as VideoOp; + const tl = manifest.timeline; + const entry = (v: unknown): ManifestEntry => { + const id = str(v, "id"); + return tl.find((e) => e.id === id) ?? refuse(`no entry "${id}" in the cut`); + }; + const card = (v: unknown): ManifestEntry => { + const e = entry(v); + return e.type === "card" ? e : refuse(`"${e.id}" is a ${e.type}, not a card`); + }; + let warnings: string[] | undefined; + try { + switch (op.op) { + case "drop": + tl.splice(tl.indexOf(entry(op.id)), 1); + break; + case "move": { + const e = entry(op.id); + const after = str(op.after, "after"); + if (after === e.id) refuse("an entry cannot move after itself"); + const anchor = after === "start" ? null : entry(after); + tl.splice(tl.indexOf(e), 1); + tl.splice(anchor ? tl.indexOf(anchor) + 1 : 0, 0, e); + break; + } + case "heading": { + const c = card(op.id); + const t = str(op.text, "text").trim(); + if (!t) refuse("a heading needs its text"); + c.heading = t; + break; + } + case "narration": { + const c = card(op.id); + const t = str(op.text, "text").replace(/\s+/g, " ").trim(); + if (!t) { + delete c.narration; + break; + } + const g = checkNarration(t, grounding); + if (g.hard.length) refuse(`narration refused: ${g.hard.join("; ")}`); + c.narration = { text: t }; + if (g.soft.length) warnings = g.soft; + break; + } + case "trim": { + const e = entry(op.id); + if (e.type !== "clip") refuse(`"${e.id}" is a ${e.type}, not a clip`); + const s = Number(op.start); + const en = Number(op.end); + if (!Number.isFinite(s) || !Number.isFinite(en)) refuse("trim needs start and end in seconds"); + if (!(s < en)) refuse("a trim's start is before its end"); + const bound = parentClips.get(e.id) ?? e; + const lo = (bound.start ?? 0) - TRIM_SLACK_SECONDS; + const hi = (bound.end ?? 0) + TRIM_SLACK_SECONDS; + if (s < lo || en > hi) refuse(`outside the fetched window (${lo.toFixed(2)}–${hi.toFixed(2)} s)`); + e.start = s; + e.end = en; + break; + } + case "add_clip": { + const cid = str(op.citation, "citation"); + const c = citations[cid] ?? refuse(`no citation "${cid}" in the report`); + if (c.kind !== "video") refuse(`only a video citation becomes a clip ("${cid}" is a ${c.kind})`); + if (tl.some((x) => x.id === cid)) refuse(`"${cid}" is already in the cut`); + if (typeof c.start !== "number" || typeof c.end !== "number" || !c.channel || !c.id) { + refuse(`citation "${cid}" has no span`); + } + const e: ManifestEntry = { + type: "clip", + id: cid, + channel: c.channel!, + video: c.id!, + start: c.start!, + end: c.end!, + cite: Math.floor(c.start!), + quote: c.quote ?? "", + }; + const after = op.after === undefined || op.after === null || op.after === "" ? null : str(op.after, "after"); + const anchor = after === null || after === "end" ? null : after === "start" ? "start" : entry(after); + tl.splice(anchor === null ? tl.length : anchor === "start" ? 0 : tl.indexOf(anchor) + 1, 0, e); + // A clip added here is bounded by its own citation. + parentClips.set(cid, e); + break; + } + case "title": + case "subtitle": { + const t = str(op.text, "text").trim(); + if (op.op === "title" && !t) refuse("a title needs its text"); + manifest[op.op] = t; + break; + } + default: + refuse(`no op "${String(op.op)}" — the ops are ${VIDEO_OP_NAMES.join(", ")}`); + } + applied.push({ index, op, ...(warnings ? { warnings } : {}) }); + } catch (e) { + if (!(e instanceof Refusal)) throw e; + refused.push({ index, op, why: e.message }); + } + } + return { manifest, applied, refused }; +} + +// The cut as a model reads it. +export function cutView(m: VideoManifest): string { + const lines = [`TITLE: ${m.title ?? ""}`, `SUBTITLE: ${m.subtitle ?? ""}`]; + for (const e of m.timeline ?? []) { + if (e.type === "card") { + const n = e.narration?.text ?? ""; + lines.push( + `- card ${e.id} (${e.style ?? ""}) heading: ${JSON.stringify(e.heading ?? "")}` + + (n ? ` narration: ${JSON.stringify(n)}` : ""), + ); + } else if (e.type === "clip") { + lines.push(`- clip ${e.id} ${e.channel}/${e.video} ${e.start}–${e.end} s quote: ${JSON.stringify(e.quote ?? "")}`); + } else { + lines.push(`- ${e.type} ${e.id}`); + } + } + return lines.join("\n"); +}