commit 7fe411b671ee154c6aae2050f9a0180e6fd1b8ff
parent 451536a00163d4b21904c7f4c527912652572d1c
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 12 Nov 2026 08:38:27 -0500
refresh, revise-report: a local refresh sweeps in the settings' claim form, and a revision keeps a neutral report neutral and its claims' flags (D2 round b review)
A local REFRESH dropped both settings of generation.localSweep: its
restricted sweep ran on the pipeline's defaults (sentence form, no
read-aloud check), so a neutral report's recurring update got "He says…"
findings. The refresh job now carries generation.localSweep into the sweep.
What a revision did with a neutral report (before this): it rebuilds
report.json from sweep.md, and a claim's `flag` (the read-aloud "check by
ear: may be read aloud") is in report.json only -- every flag was lost; the
"Check by ear:" words and the "To check by ear" section stayed in the text. A
`claim` op could rewrite a code-written line into anything ("She says…"), an
`add` took the model's line as given, and `section`, `title` and `summary`
took the model's words.
Now: a report whose coverage line says its lines are code's
(NEUTRAL_LINES_NOTE, isNeutralSweep) is revised under reportOps' `neutral`
rules -- `claim` and a merge's text are refused; an `add` must give
"[Check by ear: ]In <title> (<date>), on <topic>:", its topic held like a
label (grounded in the quote, the recording's title, the question) and the
line written again by code from the recording's own title and date; a new or
renamed section title must pass the heading rule (grounded in the report);
`title` is refused; a summary is refused when it has a pronoun, a word of
saying or judging, or the host's name. The revision carries every flag of
the parent's claims (and of a refresh sweep's own report) to the claim that
cites the same words of the same recording.
Tests: a local refresh end to end (fake ollama): the sweep's extract is the
neutral one, the added finding's line is code's, a rewrite, an attributing
heading, a sentence-form add and a title refused, the parent's read-aloud
flag kept; the ops' neutral rules one by one; carryClaimFlags.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
7 files changed, 479 insertions(+), 19 deletions(-)
diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -455,7 +455,16 @@ async function runRefreshJob(
let result: Awaited<ReturnType<typeof refreshTask>> | null = null;
try {
result = await refreshTask(
- { article: body.article, n, model, extractorModel: o.extractor, maxUsd: o.capUsd ?? Number.POSITIVE_INFINITY, ...(body.fetch === false ? { fetch: false } : {}), ...(body.ids?.length ? { ids: body.ids } : {}) },
+ {
+ article: body.article,
+ n,
+ model,
+ extractorModel: o.extractor,
+ maxUsd: o.capUsd ?? Number.POSITIVE_INFINITY,
+ localSweep: gen.localSweep,
+ ...(body.fetch === false ? { fetch: false } : {}),
+ ...(body.ids?.length ? { ids: body.ids } : {}),
+ },
taskDeps,
);
} catch (e) {
diff --git a/common/lib/report/draft/refresh/task.ts b/common/lib/report/draft/refresh/task.ts
@@ -30,6 +30,7 @@
// failed or cancelled. A done refresh without a report is never offered as
// current (it has nothing to offer).
+import type { GenerationLocalSweep } from "../../../generationSettings";
import { providerOf } from "../../../llm";
import { iterationLabel, readIteration, readIterationFile, writeIterationFile } from "../../iterations";
import { reviseReportBody } from "../tasks/revise-report";
@@ -71,6 +72,10 @@ export type RefreshInput = {
// instead of the new and changed ones; the update runs even when the delta
// found nothing else.
ids?: string[];
+ // A local update's sweep: its claim form and read-aloud rule
+ // (settings.generation.localSweep, as a first sweep on the local route has
+ // them). Absent: the pipeline's own defaults (sentence, off).
+ localSweep?: GenerationLocalSweep;
};
// ─── the estimate ───
@@ -307,7 +312,11 @@ async function refreshBody(h: TaskHandle, input: RefreshInput): Promise<TaskOutc
const capped = Number.isFinite(input.maxUsd) ? input.maxUsd * 0.7 : Number.POSITIVE_INFINITY;
const out = isApi
? await sweepAgentBody(h, { ...sweepIn, extractorModel: input.extractorModel, maxUsd: capped })
- : await sweepPipelineBody(h, { ...sweepIn, ...(Number.isFinite(capped) ? { maxUsd: capped } : {}) });
+ : await sweepPipelineBody(h, {
+ ...sweepIn,
+ ...(Number.isFinite(capped) ? { maxUsd: capped } : {}),
+ ...(input.localSweep ? { claimForm: input.localSweep.claimForm, readAloud: input.localSweep.readAloud } : {}),
+ });
if (deps.signal?.aborted) return { status: "failed", summary: "cancelled" };
const md = out.status === "done" ? await readIterationFile(h.article, h.n, "sweep.md", h.paths) : null;
findings = md ? findingsOf(md) : null;
diff --git a/common/lib/report/draft/reportOps.test.ts b/common/lib/report/draft/reportOps.test.ts
@@ -217,3 +217,53 @@ test("add: a fragment quote is refused, and the refusal carries the full sentenc
const words = await strictCheckerOver(cuesOf, { fragments: false })({ channel: "synth-kitchen", id: "pie-stream-02", second: 40, quote: "my lawyer told me not to" });
assert.deepEqual(words, { ok: true });
});
+
+// A speaker-neutral report (review of round b, 12 Nov 2026): its lines,
+// headings and title stay code's through a revision.
+test("a neutral report: a line is not rewritten, an added line is code's, a heading or summary that attributes is refused, the title is code's", async () => {
+ const doc = await load("basic");
+ const before = claims(doc);
+ const seen: string[] = [];
+ const neutral: ReportOpsContext["neutral"] = {
+ line: async (o) => {
+ seen.push(o.text);
+ return o.text.startsWith("In ") ? { line: `In Contest results, on ${o.text.split(", on ")[1]}` } : { why: "not the neutral shape" };
+ },
+ heading: (t) => (/\b(?:her|says|reaction)\b/i.test(t) ? `“${t}” attributes` : null),
+ summary: (t) => (/\bshe\b/i.test(t) ? "a pronoun" : null),
+ };
+ const add = (text: string, section = "The contest") => ({ op: "add", section, text, quote: "I did not enter the contest this year", link: momentHref("synth-kitchen", "pie-stream-02", 10) });
+ const r = await applyReportOps(doc, [
+ { op: "claim", n: 1, text: "She says she would never sell" },
+ { op: "merge", n: 2, into: 3, text: "She denies it all" },
+ { op: "merge", n: 2, into: 3 },
+ { op: "move", n: 4, section: "Her reaction" },
+ { op: "move", n: 4, section: "The pie contest" },
+ { op: "section", section: "The bakery", text: "What she says about the bakery" },
+ add("She did not enter"),
+ add("In Whatever, on entering the contest:"),
+ add("In Whatever, on entering the contest:", "Her reaction"),
+ { op: "title", text: "The baker slams the contest" },
+ { op: "summary", text: "She hates it." },
+ { op: "summary", text: "Two recordings were since removed from the platform." },
+ ], { ...ctx, neutral });
+ assert.deepEqual(
+ r.refused.map((x) => [x.index, x.why.split(":")[0]]),
+ [
+ [0, "a speaker-neutral report's lines are written by code"],
+ [1, "a speaker-neutral report's lines are written by code"],
+ [3, "a speaker-neutral report's heading is a topic"],
+ [5, "a speaker-neutral report's heading is a topic"],
+ [6, "not the neutral shape"],
+ [8, "a speaker-neutral report's heading is a topic"],
+ [9, "a speaker-neutral report's title is written by code"],
+ [10, "a speaker-neutral report's summary says where the words are, not who says what"],
+ ],
+ );
+ assert.equal(claims(r.doc)[0], before[0], "the line stands");
+ assert.ok(claims(r.doc).includes("In Contest results, on entering the contest:"), "the added line is the one code wrote");
+ assert.deepEqual(seen, ["She did not enter", "In Whatever, on entering the contest:"], "a refused section title stops an add before its line is written");
+ assert.ok(renderSweep(r.doc).includes('In Contest results, on entering the contest: "I did not enter the contest this year"'), "a line ending on a colon takes no second one");
+ assert.ok(r.doc.sections.some((s) => s.title === "The pie contest"));
+ assert.match(r.doc.preamble.join("\n"), /since removed/);
+});
diff --git a/common/lib/report/draft/reportOps.ts b/common/lib/report/draft/reportOps.ts
@@ -26,6 +26,12 @@
// - 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";
@@ -62,8 +68,22 @@ export type ReportOpsContext = {
// 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
@@ -205,6 +225,12 @@ export async function applyReportOps(
};
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;
@@ -223,6 +249,7 @@ export async function applyReportOps(
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);
@@ -238,6 +265,7 @@ export async function applyReportOps(
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);
}
@@ -256,6 +284,7 @@ export async function applyReportOps(
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);
@@ -266,7 +295,8 @@ export async function applyReportOps(
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");
+ 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() : "";
@@ -280,12 +310,18 @@ export async function applyReportOps(
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,
- sep: ": ",
+ // A neutral line ends on its own colon.
+ sep: claim.endsWith(":") ? " " : ": ",
rest: `"${quote}" [${name} @ ${mmss(at_!.second)}](${link})`,
continued: [],
added: true,
@@ -300,15 +336,25 @@ export async function applyReportOps(
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": {
- doc.preamble = ["", text(op.text, "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:
diff --git a/common/lib/report/draft/tasks/neutralClaim.test.ts b/common/lib/report/draft/tasks/neutralClaim.test.ts
@@ -2,7 +2,7 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { attributes, humanDate, neutralHeading, neutralSentence, neutralTitle, plainTitle, topicLabel } from "./neutralClaim";
+import { attributes, cleanLabel, humanDate, isNeutralSweep, labelProblem, neutralHeading, neutralSentence, neutralTitle, NEUTRAL_LINES_NOTE, plainTitle, runTopicOf, topicLabel } from "./neutralClaim";
import { quotedIn } from "../../convertShared";
const ground = ["the acolyte now I think we finally hit rock bottom at a 15% audience score", "ratings numbers viewership numbers", "The Acolyte Hits ROCK BOTTOM", "What has Jeremy said about the Star Wars show The Acolyte?", "the acolyte"];
@@ -25,15 +25,15 @@ test("a topic label: the model's when it is a grounded noun phrase", () => {
assert.deepEqual(label("the acolyte's audience score"), { label: "the acolyte's audience score", from: "model" });
assert.deepEqual(label('On "The Acolyte ratings".'), { label: "The Acolyte ratings", from: "model" });
// Function words need no grounding.
- assert.equal(label("why the acolyte has no audience").from, "model");
+ assert.equal(label("the acolyte and its audience").from, "model");
// A plural or an inflection of a word that is there.
assert.equal(label("acolyte viewership number").from, "model");
});
test("a topic label that attributes, runs long, or uses words from nowhere is the run's topic", () => {
- assert.deepEqual(label("Jeremy's view of the acolyte"), { label: "the acolyte", from: "fallback", why: "the label says who says or thinks something" });
- assert.equal(label("the quartering on the acolyte").why, "the label says who says or thinks something");
- assert.equal(label("he says the acolyte hit rock bottom").why, "the label says who says or thinks something");
+ assert.deepEqual(label("Jeremy's view of the acolyte"), { label: "the acolyte", from: "fallback", why: "“view” is a word of saying, thinking or judging" });
+ assert.equal(label("the quartering on the acolyte").why, "it names quartering");
+ assert.equal(label("he says the acolyte hit rock bottom").why, "“he” is a pronoun: a label names what the words are about, not a person");
assert.equal(label("the acolyte's racist fan backlash").why, "“racist” is not in the quote, the transcript before it, the title or the question");
assert.equal(label("the acolyte audience score at rock bottom now finally here").why, "a label of 10 words (at most 8)");
assert.equal(label("").why, "no label");
@@ -41,12 +41,134 @@ test("a topic label that attributes, runs long, or uses words from nowhere is th
assert.equal(label("of the").why, "a label of no content words");
});
-test("the title and the headings are code's when the model's attribute", () => {
+test("the title is code's; a heading is kept only when it is a grounded noun-phrase topic", () => {
assert.equal(neutralTitle("the acolyte", ["TheQuartering"]), "The acolyte: quotes from TheQuartering");
assert.equal(neutralTitle("", []), "Quotes: quotes from the archive");
- assert.equal(neutralHeading("Audience scores and reviews", ["a", "b"]), "Audience scores and reviews");
- assert.equal(neutralHeading("Jeremy's criticism of the show", ["the acolyte's reviews", "The Acolyte's reviews", "the budget"], ["jeremy"]), "The acolyte's reviews");
- assert.equal(neutralHeading("What he thinks of the lore", []), "Quotes");
+ const o = { labels: ["the acolyte's reviews", "The Acolyte's reviews", "the budget"], ground: ["the reviews and the budget of the acolyte", "The Acolyte Hits ROCK BOTTOM"], topic: "the acolyte", hosts: ["jeremy"] };
+ assert.deepEqual(neutralHeading("Reviews and budget", o), { heading: "Reviews and budget", from: "model" });
+ assert.deepEqual(neutralHeading("Jeremy's criticism of the show", o), { heading: "The acolyte's reviews", from: "code", why: "“criticism” is a word of saying, thinking or judging" });
+ // Not grounded: a word in none of its quotes, labels or titles, nor the question.
+ const racist = neutralHeading("Racist backlash to the acolyte", o);
+ assert.equal(racist.from, "code");
+ assert.match(racist.why!, /“racist” is in none of/);
+ assert.equal(neutralHeading("What he thinks of the lore", { ...o, labels: [] }).heading, "The acolyte");
+ // A heading an earlier section has gets an ordinal; never two sections of one name.
+ const used = new Set<string>();
+ assert.equal(neutralHeading("Reviews and budget", { ...o, used }).heading, "Reviews and budget");
+ assert.equal(neutralHeading("Main Actress's Comments", { ...o, used }).heading, "The acolyte's reviews");
+ assert.equal(neutralHeading("Fan Reactions", { ...o, used }).heading, "The acolyte's reviews (2)");
+ assert.equal(neutralHeading("reviews and budget", { ...o, used }).heading, "The acolyte's reviews (3)");
assert.equal(attributes("Reviews and ratings"), false);
assert.equal(attributes("Fans' reaction"), true);
});
+
+// The review of round b (12 Nov 2026): headings and labels from the shipped
+// runs, and constructed labels that passed when the quote had the word.
+const REFUSED_HEADINGS = ["Main Actress's Comments", "Showrunner's Comments", "Wizards of the Coast's Response", "Public Statements and Accusations", "Fan Reactions"];
+const REFUSED_LABELS = [
+ "acolyte writer blames filon",
+ "The Acolyte hates white people",
+ "DCI ban for defending free speech",
+ "his love of the show",
+ "he loves the show",
+ "why he hates disney",
+ "his hate for disney",
+ "his admission that the ban was a lie",
+ "she is guilty of fraud",
+ "the disney confession",
+ // and more of the same shapes
+ "Disney lying about promotional piece",
+ "the showrunner's budget",
+ "it's the acolyte",
+ "they're cancelling the acolyte",
+ "the acolyte isn't canceled",
+ "Disney's take on the acolyte",
+ "the acolyte was cancelled",
+ "fans' reaction to the acolyte",
+ "Jeremy's ban",
+];
+// A ground with every word of them: grounding does not save a label that attributes.
+const everyWord = [...REFUSED_LABELS, ...REFUSED_HEADINGS].join(" ");
+
+test("labels and headings that attribute, assert or name a person are refused, whatever the quote holds", () => {
+ for (const l of [...REFUSED_LABELS, ...REFUSED_HEADINGS]) {
+ assert.ok(labelProblem(cleanLabel(l), ["jeremy", "quartering"]), `refused: ${l}`);
+ const r = topicLabel(l, { fallback: "RUN", hosts: ["jeremy", "quartering"], ground: [everyWord] });
+ assert.equal(r.from, "fallback", `label refused: ${l}`);
+ assert.equal(r.label, "RUN");
+ }
+ for (const hd of REFUSED_HEADINGS) {
+ assert.equal(neutralHeading(hd, { labels: ["the acolyte ratings"], ground: [everyWord], topic: "the acolyte" }).from, "code", `heading replaced: ${hd}`);
+ }
+ // Curly apostrophes are the same apostrophe.
+ assert.ok(labelProblem("Jeremy’s ban", ["jeremy"]));
+ assert.ok(labelProblem("the actress’s comments"));
+});
+
+test("noun-phrase topics still pass", () => {
+ const ground = ["the acolyte ratings were the lowest", "disney star wars budget", "wizards of the coast changed its ban policy", "What has Jeremy said about being banned from Magic: The Gathering events and his dispute with Wizards of the Coast?"];
+ for (const l of ["the acolyte ratings", "disney star wars budget", "wizards of the coast ban policy", "the acolyte's audience score", "the ban from sanctioned events"]) {
+ assert.equal(labelProblem(l), null, l);
+ }
+ for (const l of ["the acolyte ratings", "disney star wars budget", "wizards of the coast ban policy"]) {
+ assert.deepEqual(topicLabel(l, { fallback: "RUN", hosts: ["jeremy"], ground }), { label: l, from: "model" }, l);
+ }
+ // "viewership" is not "view"; "statement" is refused, "states" alone is not in the list.
+ assert.equal(labelProblem("acolyte viewership numbers"), null);
+ assert.equal(labelProblem("united states release"), null);
+});
+
+test("the run's topic: the model's when it passes the label rules, never its raw words unchecked", () => {
+ const ground = ["What has Jeremy said about the Star Wars show The Acolyte?", "the acolyte", "leslye headland"];
+ assert.equal(runTopicOf(["star wars the acolyte"], { hosts: ["jeremy"], ground }).topic, "star wars the acolyte");
+ const r = runTopicOf(["Jeremy's hatred of the acolyte", "the acolyte"], { hosts: ["jeremy"], ground });
+ assert.equal(r.topic, "the acolyte");
+ assert.deepEqual(r.refused.map((x) => x.candidate), ["Jeremy's hatred of the acolyte"]);
+ assert.equal(runTopicOf(["he hates it", "", 7], { ground }).topic, "the question's subject");
+});
+
+test("a neutral sweep says so in its coverage line", () => {
+ assert.ok(isNeutralSweep(`## Coverage\n\nThe quotes were picked by m; ${NEUTRAL_LINES_NOTE}; every quote checked.`));
+ assert.equal(isNeutralSweep("## Coverage\n\nDrafted by m."), false);
+});
+
+// Every function over text a model or a transcript wrote runs in linear time
+// (the review of round b found a pattern that never returned on 60 letters).
+const slow = (f: () => unknown) => {
+ const t0 = performance.now();
+ f();
+ return performance.now() - t0;
+};
+const ADVERSARIAL = ["a".repeat(200), "x".repeat(150), "ha".repeat(75), "7".repeat(150)];
+const big = (s: string) => s.repeat(Math.ceil(100_000 / s.length)).slice(0, 100_000);
+const BIG = [".".repeat(100_000) + "x", big(" ."), big(".:"), big("a "), big("a'"), big("1,"), big("'s "), big("jeremy "), "a".repeat(100_000)];
+
+test("the label, heading, title and date functions are linear on long and adversarial text", () => {
+ const ground = ["the acolyte", "a".repeat(200)];
+ for (const s of [...ADVERSARIAL, ...BIG]) {
+ const what = `${JSON.stringify(s.slice(0, 12))}×${s.length}`;
+ for (const [name, f] of [
+ ["topicLabel", () => topicLabel(s, { fallback: "f", hosts: ["jeremy", "the quartering"], ground: [s, ...ground] })],
+ ["labelProblem", () => labelProblem(s, ["jeremy"])],
+ ["cleanLabel", () => cleanLabel(s)],
+ ["neutralHeading", () => neutralHeading(s, { labels: [s.slice(0, 200)], ground: [s], topic: "t", hosts: ["jeremy"] })],
+ ["runTopicOf", () => runTopicOf([s, s], { ground: [s] })],
+ ["neutralSentence", () => neutralSentence({ title: s, date: s, topic: s.slice(0, 200) })],
+ ["neutralTitle", () => neutralTitle(s, [s])],
+ ["plainTitle", () => plainTitle(s)],
+ ["humanDate", () => humanDate(s)],
+ ] as const) {
+ const ms = slow(f);
+ assert.ok(ms < 50, `${name} on ${what}: ${ms.toFixed(1)} ms`);
+ }
+ }
+});
+
+test("a revision of a neutral report: the parent's claim flags are carried to the claims that cite the same words", async () => {
+ const { carryClaimFlags } = await import("./revise-report");
+ const cite = (id: string, quote: string) => ({ kind: "video" as const, channel: "c", id, start: 1, quote });
+ const parent = { sections: [{ id: "s", title: "S", claims: [{ id: "k1", text: "a", citations: ["c1"], flag: "check by ear: may be read aloud" }, { id: "k2", text: "b", citations: ["c2"] }] }], citations: { c1: cite("v1", "The judges were friends."), c2: cite("v1", "I did not enter") } };
+ const revised = { sections: [{ id: "t", title: "T", claims: [{ id: "k1", text: "b", citations: ["c1"] }, { id: "k2", text: "a", citations: ["c9"] }, { id: "k3", text: "x", citations: ["c3"] }] }], citations: { c1: cite("v1", "I did not enter"), c9: cite("v1", "the judges were friends"), c3: cite("v2", "the judges were friends") } };
+ assert.equal(carryClaimFlags(revised as never, [parent as never, null]), 1);
+ assert.deepEqual(revised.sections[0]!.claims.map((k) => (k as { flag?: string }).flag ?? null), [null, "check by ear: may be read aloud", null]);
+});
diff --git a/common/lib/report/draft/tasks/revise-report.ts b/common/lib/report/draft/tasks/revise-report.ts
@@ -9,6 +9,14 @@
// Then the link backstop, convert and the quote check: a NEW finding whose
// quote fails is dropped, never repaired.
//
+// A SPEAKER-NEUTRAL report (the local sweep's neutral form, ./neutralClaim.ts,
+// known by its coverage line) stays neutral: its lines, headings and title are
+// code's, and the ops keep them so (reportOps' `neutral` rules: a line is not
+// rewritten, an added finding's line is written by code from its topic and
+// its recording, a heading or a summary that attributes is refused). A claim's
+// FLAG (a read-aloud "check by ear") lives in report.json, not sweep.md: the
+// revision carries it to the claim that still cites the same words.
+//
// ON A LOCAL MODEL (release 28 Q3) there is no tool loop: one schema-bound
// ask (`structuredAnswer`) for the whole ops batch, over the numbered view
// trimmed to the model's prompt cap (sweepModel trimmedNumberedView: the
@@ -31,6 +39,11 @@ import { CLAIM_QUOTES_RULE, UNATTENDED_RULE, VERBATIM_QUOTES_RULE, WHOLE_SENTENC
import { applyReportOps, strictCheckerOver, type AppliedOp, type RefusedOp } from "../reportOps";
import { numberedView, parseSweep, renderSweep, trimmedNumberedView, type SweepDoc } from "../sweepModel";
import { extractJsonObject } from "../../../parseStdoutJson";
+import { strictNormalize } from "../../../citations/verify";
+import type { Report } from "../../schema";
+import { isNeutralSweep, labelProblem, neutralSentence, topicLabel, ungrounded } from "./neutralClaim";
+import { subjectNames } from "./selection";
+import type { NeutralOpsRules } from "../reportOps";
import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
import { checkQuotes, convertSweepText, dropFailedFindings, titleOfSweep } from "./quotes";
import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
@@ -184,23 +197,36 @@ export async function reviseReportBody(h: TaskHandle, input: ReviseReportInput):
const channels = input.channels ?? cited;
const resolver = slugResolver(deps.corpus, channels);
const rewrite = (t: string) => rewriteMomentBases(t, resolver, origin);
- const titleOf = async (channel: string, id: string) => {
+ const metaOf = async (channel: string, id: string): Promise<{ title?: unknown; uploadDate?: unknown; date?: unknown } | null> => {
try {
- const meta = extractJsonObject(await deps.corpus.call("get_video_metadata", { channel, video_id: id })) as { title?: unknown } | null;
- return typeof meta?.title === "string" ? meta.title : null;
+ return extractJsonObject(await deps.corpus.call("get_video_metadata", { channel, video_id: id })) as { title?: unknown } | null;
} catch {
return null;
}
};
+ const titleOf = async (channel: string, id: string) => {
+ const meta = await metaOf(channel, id);
+ return typeof meta?.title === "string" ? meta.title : null;
+ };
const checkQuote = strictCheckerOver(deps.cuesOf);
let doc: SweepDoc = parseSweep(parent.md);
const applied: AppliedOp[] = [];
const refused: RefusedOp[] = [];
const added: string[] = [];
const local = providerOf(model) === "local";
- h.log(`revising the report of i${parent.from} on ${model}${local ? " (one ops batch)" : ""}`);
+ const neutral = isNeutralSweep(parent.md) ? neutralRules(parent.md, channels, metaOf) : undefined;
+ h.log(`revising the report of i${parent.from} on ${model}${local ? " (one ops batch)" : ""}${neutral ? "; speaker-neutral: its lines, headings and title stay code's" : ""}`);
+ // The flags the claims carried: the parent's, and those of a sweep this
+ // iteration already ran (a refresh's, whose findings it adds).
+ const flagSources = [parentReport, await readIterationFile(h.article, h.n, "report.json", h.paths)].map((t) => {
+ try {
+ return t ? (JSON.parse(t) as Report) : null;
+ } catch {
+ return null;
+ }
+ });
const applyOps = async (ops: unknown[]) => {
- const r = await applyReportOps(doc, ops, { checkQuote, titleOf, origin });
+ const r = await applyReportOps(doc, ops, { checkQuote, titleOf, origin, ...(neutral ? { neutral } : {}) });
doc = r.doc;
applied.push(...r.applied);
refused.push(...r.refused);
@@ -332,6 +358,8 @@ export async function reviseReportBody(h: TaskHandle, input: ReviseReportInput):
? `${failing.length} quote(s) fail the strict check (from the iteration revised): ${failing.map((p) => p.why).slice(0, 3).join("; ")}${warn}`
: `every quote verbatim (strict)${warn}`,
});
+ const carried = carryClaimFlags(c.report as Report, flagSources);
+ if (carried) h.log(`${carried} claim flag(s) carried over (a flag lives in report.json, not in sweep.md)`);
await writeIterationFile(h.article, h.n, "report.json", c.report, h.paths);
return {
status: "done",
@@ -369,3 +397,73 @@ export async function localOpsBatch(
h.progress({ metric: "turns", current: 1, total: 1 });
if (asked && Array.isArray(asked.ops) && asked.ops.length) await o.apply(asked.ops);
}
+
+// A claim's flags are not in sweep.md: each claim of the revised report whose
+// citation quotes the same words of the same recording as a flagged claim of
+// `from` gets that flag (the first found). Returns how many claims got one.
+export function carryClaimFlags(report: Report, from: readonly (Report | null)[]): number {
+ const keyOf = (c: { kind?: string; id?: string; quote?: string } | undefined) => (c?.id && c.quote ? `${c.kind ?? ""}|${c.id}|${strictNormalize(c.quote)}` : null);
+ const flags = new Map<string, string>();
+ for (const r of from) {
+ if (!r) continue;
+ for (const s of r.sections ?? []) {
+ for (const k of s.claims ?? []) {
+ if (!k.flag) continue;
+ for (const cid of k.citations ?? []) {
+ const key = keyOf(r.citations?.[cid] as { kind?: string; id?: string; quote?: string } | undefined);
+ if (key && !flags.has(key)) flags.set(key, k.flag);
+ }
+ }
+ }
+ }
+ let n = 0;
+ if (!flags.size) return 0;
+ for (const s of report.sections ?? []) {
+ for (const k of s.claims ?? []) {
+ if (k.flag) continue;
+ const flag = (k.citations ?? []).map((cid) => keyOf(report.citations?.[cid] as { kind?: string; id?: string; quote?: string } | undefined)).find((key) => key && flags.has(key));
+ if (flag) {
+ k.flag = flags.get(flag)!;
+ n++;
+ }
+ }
+ }
+ return n;
+}
+
+// The neutral form's rules over a revision's ops (reportOps' NeutralOpsRules):
+// the report's question names whose report it is; its whole text is what a
+// heading's words must be found in.
+export function neutralRules(
+ md: string,
+ channels: readonly string[],
+ metaOf: (channel: string, id: string) => Promise<{ title?: unknown; uploadDate?: unknown; date?: unknown } | null>,
+): NeutralOpsRules {
+ const question = /^Question:\s*(.+)$/m.exec(md)?.[1]?.trim() ?? "";
+ const hosts = [...subjectNames({ question, channels: channels.map((slug) => ({ slug })) })];
+ return {
+ async line({ text, quote, channel, id }) {
+ // "[Check by ear: ]In <title> (<date>), on <topic>:" — the topic is the
+ // model's (held down like a label); the rest is written again by code.
+ const ear = /^check by ear:\s*/i.exec(text);
+ const body = ear ? text.slice(ear[0].length) : text;
+ const at = body.lastIndexOf(", on ");
+ if (!/^In /.test(body) || at < 0 || !body.endsWith(":")) return { why: "a speaker-neutral report's line is “In <title> (<date>), on <topic>:” — code writes it; give the topic in that shape" };
+ const meta = await metaOf(channel, id);
+ const title = typeof meta?.title === "string" ? meta.title : "";
+ const date = typeof meta?.uploadDate === "string" ? meta.uploadDate : typeof meta?.date === "string" ? meta.date : "";
+ const label = topicLabel(body.slice(at + 5, -1), { fallback: "", hosts, ground: [quote, title, question] });
+ if (label.from !== "model") return { why: `the topic label is refused: ${label.why}` };
+ return { line: `${ear ? "Check by ear: " : ""}${neutralSentence({ title, date, topic: label.label })}` };
+ },
+ heading(text) {
+ const bad = labelProblem(text, hosts);
+ if (bad) return bad;
+ const loose = ungrounded(text, md.split("\n"));
+ return loose ? `“${loose}” is nowhere in the report` : null;
+ },
+ summary(text) {
+ return labelProblem(text, hosts, { sentence: true });
+ },
+ };
+}
diff --git a/mcp/src/refreshTask.test.ts b/mcp/src/refreshTask.test.ts
@@ -14,6 +14,10 @@ import os from "node:os";
import path from "node:path";
import { LATE_RECORD, ORIGIN, POSTS, withRecords, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs";
import { FAKE_KEY, startFakeAnthropic, textTurn, toolTurn, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs";
+import { jsonReply, startFakeOllama, type FakeOllama } from "yt-dlp-transcript-common/testing/llm/fakeOllama.mjs";
+import { NEUTRAL_LINES_NOTE } from "yt-dlp-transcript-common/lib/report/draft/tasks/neutralClaim";
+import { READ_ALOUD_FLAG } from "yt-dlp-transcript-common/lib/report/draft/tasks/readAloud";
+import { convertSweepText } from "yt-dlp-transcript-common/lib/report/draft/tasks/quotes";
import { createIteration, readIteration, readIterationFile, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations";
import { runTask, type TaskDeps } from "yt-dlp-transcript-common/lib/report/draft/tasks/index";
import { corpusCuesOf } from "yt-dlp-transcript-common/lib/report/draft/tasks/corpusCues";
@@ -25,8 +29,10 @@ const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../
let tmp: string;
let later: CorpusTools;
let api: FakeAnthropic;
+let ol: FakeOllama;
before(async () => {
+ ol = await startFakeOllama();
tmp = await mkdtemp(path.join(os.tmpdir(), "refresh-task-"));
const dir = await writeDraftCorpus(path.join(tmp, "later"), { channels: withRecords([LATE_RECORD]) });
later = await createCorpusTools({ source: `local:${dir}` });
@@ -36,6 +42,7 @@ before(async () => {
after(async () => {
await later.close();
await api.close();
+ await ol.close();
await rm(tmp, { recursive: true, force: true });
});
@@ -115,3 +122,122 @@ test("refresh: the new recording found, a sweep restricted to it, the report rev
assert.equal(it?.status, "done");
assert.deepEqual((it as { refresh?: unknown }).refresh, { status: "updated", newIds: 1, changed: 0, drifted: 0, deleted: 0, summary: f.summary });
});
+
+// A LOCAL refresh of a speaker-neutral report (review of round b, 12 Nov
+// 2026): the restricted sweep runs with settings.generation.localSweep (here
+// neutral + flag) — not the pipeline's defaults — and the revision keeps the
+// report neutral: an added finding's line is code's, a rewrite of a line and a
+// heading that attributes are refused, and the read-aloud flag of a parent's
+// claim survives (it lives in report.json, which a revision rebuilds).
+test("refresh on a local model: the sweep in the settings' claim form, the revision keeps the neutral form and the claims' flags", async () => {
+ const paths = { articlesDir: path.join(tmp, "reports-local"), exportIndexDir: path.join(tmp, "idx-local") };
+ const art = "synth-neutral-refresh";
+ const question = "What has the baker said about the contest?";
+ const link = (id: string, t: number) => `${ORIGIN}/?v=synth-kitchen%2F${id}&t=${t}`;
+ const md = [
+ "# The contest: quotes from Synth Kitchen",
+ "",
+ `Question: ${question}`,
+ "",
+ "## The contest",
+ "",
+ `- In Pie stream (10 February 2026), on entering the contest: "I did not enter the contest this year" — [Pie stream @ 0:10](${link("pie-stream-02", 10)})`,
+ "",
+ "## To check by ear",
+ "",
+ `- Check by ear: In Pie stream (10 February 2026), on the contest: "the judges were friends of mine so it felt wrong" — [Pie stream @ 0:15](${link("pie-stream-02", 15)})`,
+ "",
+ "## Coverage",
+ "",
+ `Searched synth-kitchen for contest. The quotes were picked and their topics labelled by qwen3:8b; ${NEUTRAL_LINES_NOTE}; every quote was checked word for word against its transcript.`,
+ "",
+ ].join("\n");
+ await createIteration(art, { kind: "sweep", model: "qwen3:8b", question, scope: { channels: ["synth-kitchen"] } }, paths);
+ await writeIterationFile(art, 1, "sweep.md", md, paths);
+ const c = await convertSweepText(md, { id: art });
+ assert.ok(c.ok);
+ const parent = c.report as { sections: { claims?: { text: string; flag?: string }[] }[] };
+ for (const s of parent.sections) for (const k of s.claims ?? []) if (k.text.startsWith("Check by ear")) k.flag = READ_ALOUD_FLAG;
+ await writeIterationFile(art, 1, "report.json", parent, paths);
+ const trace = [
+ { t: "run", run: 1, phase: "start", task: "sweep-pipeline", model: "qwen3:8b" },
+ { t: "scope", run: 1, source: "local:/the/first/build", channels: ["synth-kitchen"], question },
+ { t: "enumerate", run: 1, query: "contest", n: 1, ids: ["pie-stream-02"], partial: false, unreached: [], counts: { "pie-stream-02": 2 } },
+ ];
+ await writeIterationFile(art, 1, "trace.jsonl", trace.map((e) => JSON.stringify(e)).join("\n") + "\n", paths);
+ await updateIteration(art, 1, { status: "done" }, paths);
+ await createIteration(art, { kind: "refresh", model: "qwen3:8b", parent: 1 }, paths);
+
+ const late = link("contest-stream-04", 5);
+ ol.push(
+ // The restricted sweep (its terms are the parent's queries: no terms call): one extract, in the NEUTRAL form, and the grouping.
+ jsonReply({ relevant: true, items: [{ quote: "I was not a judge at the contest this year either", topic: "the contest results", on_topic: true, strength: 3 }] }),
+ // (one section holding every quote: the grouping is asked twice)
+ jsonReply({ title: "x", sections: [{ heading: "The contest results", findings: [1] }] }),
+ jsonReply({ title: "x", sections: [{ heading: "The contest results", findings: [1] }] }),
+ // The revision's one ops batch.
+ jsonReply({
+ ops: [
+ { op: "add", section: "The contest", text: "In Some other title (1 January 2020), on the contest results:", quote: "I was not a judge at the contest this year either", link: late },
+ { op: "claim", n: 1, text: "She says she did not enter" },
+ { op: "section", section: "The contest", text: "Her reaction to the contest" },
+ { op: "add", section: "The contest", text: "She says she was not a judge", quote: "I was not a judge at the contest this year either", link: late },
+ { op: "title", text: "The baker slams the contest" },
+ ],
+ }),
+ );
+ const lines: string[] = [];
+ const deps: TaskDeps = {
+ llm: { anthropic: { baseUrl: "http://127.0.0.1:9", env: {} }, ollama: { baseUrl: ol.url } },
+ corpus: later,
+ cuesOf: corpusCuesOf(later),
+ paths,
+ log: (l) => lines.push(l),
+ refresh: {
+ editor: { run: async () => assert.fail("fetch: false runs no editor action") },
+ jobOf: async () => null,
+ channelOf: async () => null,
+ siteOf: async () => ({ site: null }),
+ openCorpus: async () => ({ source: later.source, origin: ORIGIN, build: "later" }),
+ capRefusal: async () => null,
+ },
+ };
+ const out = await runTask(
+ { task: "refresh", article: art, n: 2, model: "qwen3:8b", extractorModel: "qwen3:8b", maxUsd: Number.POSITIVE_INFINITY, fetch: false, localSweep: { claimForm: "neutral", readAloud: "flag" } },
+ deps,
+ );
+ assert.equal(out.status, "done", `${out.summary}\n${lines.join("\n")}`);
+ assert.equal(ol.remaining(), 0, "every scripted turn was used");
+ const f = JSON.parse((await readIterationFile(art, 2, "refresh.json", paths))!) as RefreshFile;
+ assert.equal(f.status, "updated", lines.join("\n"));
+ // The sweep ran in the neutral form: its extract asked for a topic label, and its items say so.
+ assert.ok(ol.requests.some((q: { messages?: unknown }) => /Each topic is a label of two to six words/.test(JSON.stringify(q.messages ?? ""))));
+ const items = (await readIterationFile(art, 2, "items.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l));
+ assert.deepEqual(items.map((x) => [x.form, x.topic]), [["neutral", "the contest results"]]);
+ // The revision: the added finding's line written by code from its recording (its title and date), the rest refused.
+ const revised = (await readIterationFile(art, 2, "sweep.md", paths))!;
+ assert.ok(revised.includes(`- In Contest results (12 October 2026), on the contest results: "I was not a judge at the contest this year either" [Contest results @ 0:05](${late})`), revised);
+ assert.ok(!/Some other title|She says|Her reaction|slams/.test(revised), revised);
+ assert.match(revised, /^# The contest: quotes from Synth Kitchen$/m, "the title is code's");
+ const ops = (await readIteration(art, 2, paths)) as unknown as { ops?: { refused: { op: string; why: string }[] } };
+ assert.deepEqual(
+ ops.ops?.refused.map((r) => [r.op, r.why.split(":")[0]]),
+ [
+ ["claim", "a speaker-neutral report's lines are written by code"],
+ ["section", "a speaker-neutral report's heading is a topic"],
+ ["add", "a speaker-neutral report's line is “In <title> (<date>), on <topic>"],
+ ["title", "a speaker-neutral report's title is written by code"],
+ ],
+ );
+ // The parent's read-aloud flag is on its claim still.
+ const report = JSON.parse((await readIterationFile(art, 2, "report.json", paths))!);
+ const claims = report.sections.flatMap((x: { claims?: { text: string; flag?: string }[] }) => x.claims ?? []);
+ assert.deepEqual(
+ claims.map((k: { text: string; flag?: string }) => [k.text.slice(0, 30), k.flag ?? null]),
+ [
+ ["In Pie stream (10 February 202", null],
+ ["In Contest results (12 October", null],
+ ["Check by ear: In Pie stream (1", READ_ALOUD_FLAG],
+ ],
+ );
+});