Archilyzer · Source

archilyzer

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

commit 51bbc9b1a105cfe04d50993ff41bbafa72e1d6f1
parent b72d3fe572b28969f52a0a14c52269e29595d6c7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 12 Nov 2026 03:57:33 -0500

sweep-pipeline: a speaker-neutral claim form written by code, and read-aloud cues (D2 round b)

Round a's bar (90% of kept claims supported, none reversed) was missed on
qwen3:8b for one reason: attribution. The model cannot tell the host reading
a tweet, a headline or a review aloud from the host speaking, and wrote
"Jeremy says ..." about words he was quoting (34 kept, 16 supported, 1
reversed on The Acolyte).

Two levers, both code:

- claimForm "neutral" (neutralClaim.ts): the model's job per item is the
  quote and a topic label of a few words; code writes the line -- In <title>
  (<date>), on <topic>: "<quote>" -- with the citation and the link. No
  sentence is drafted, so there is no meaning check (one call an item less).
  The label is held down: at most eight words, no name of the host, no verb
  of saying or thinking, every content word found in the quote, the 300
  characters before it, the title or the question; one that fails is the
  run's topic. The title is code's, and a section heading that attributes is
  the commonest label of its quotes.
- readAloud "flag" | "drop" | "off" (readAloud.ts): patterns in the 400
  characters before a quote, the quote and the 150 after -- a tweet, likes
  read out, an article or headline being introduced, a letter, a clip,
  "according to", "X writes / it says / also added", "saying" or "quote"
  right before it, "this is from ... shout out good take" or "this is a lie"
  after it, the host named in the third person (not his sign-on), a chat
  line. Derived from the 214 graded quotes of D0 and round a that have their
  context (67 not the host's words: 45 caught; 147 his own: 26 cued). flag
  keeps the quote in "To check by ear", its line starting "Check by ear:",
  its claim carrying the flag "check by ear: may be read aloud", the cue in
  items.jsonl and the trace; drop leaves it out with the cue as the reason.
  It works in the sentence form too (before the meaning check).

settings.generation.localSweep {claimForm, readAloud} (default neutral, flag)
is what the controller passes to a local sweep; the task's own defaults stay
sentence / off, so a refresh's update and every existing caller are as they
were. The Claude routes do not run this task.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MSETTINGS.md | 12++++++++++++
Mcommon/controller/reportDraft.ts | 2+-
Mcommon/lib/generationSettings.test.ts | 9+++++++++
Mcommon/lib/generationSettings.ts | 37+++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/neutralClaim.test.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/neutralClaim.ts | 170+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/readAloud.test.ts | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/report/draft/tasks/readAloud.ts | 145+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/report/draft/tasks/sweep-pipeline.ts | 167++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/lib/settingsDocs.ts | 2++
Mcommon/lib/settingsSchema.ts | 1+
Mmcp/src/draftTasks.test.ts | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msettings.json.example | 4++++
13 files changed, 746 insertions(+), 24 deletions(-)

diff --git a/SETTINGS.md b/SETTINGS.md @@ -1147,6 +1147,7 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `verdicts` | object — see below | The verdict bench's bar and the models that cleared it (below), set on umtool's /bench after reading a run (`archilyzer reports bench-verdicts`). Verdict proposals run only on `models`. | | `triage` | object — see below | Triage first (umtool R6): the cheap pass a recurring report runs before its sweep when it asks for one (a watch always does) — the model it judges on, when it escalates to an API sweep of what it flagged, and how often a day it may (below). | | `frames` | object — see below | The frame scan (`pnpm ops frame-scan`): the vision model each route reads a saved stream's frames on, a scan's spend cap and its sampling step (below). | +| `localSweep` | object — see below | The `local` route's sweep (a pipeline of code around the local model): who writes a finding's line and what happens to a quote that may be read aloud (below). `archilyzer gen local-sweep` sets both; the Claude routes' sweeps are not affected. | #### `generation.routes` @@ -1254,6 +1255,13 @@ Report and video generation (release 27): where each task runs (`code` = Claude | `maxUsd` | `5` | A scan's API cap when the job names none (at most `caps.max`): the scan stops before an ask that would pass it, and keeps what it read. | | `everySeconds` | `10` | Seconds between two sampled frames when the job names none (1 to 600). | +#### `generation.localSweep` + +| Key | Default | Description | +|---|---|---| +| `claimForm` | `"neutral"` | `neutral`: code writes each finding — `In <recording's title> (<date>), on <topic>: "<quote>"` — and the model only copies the quote and labels its topic in a few words (a label that names the speaker, has a verb of saying or thinking, or uses words found in neither the quote, the transcript before it, the title nor the question is replaced by the question's topic); the line says where the words are, never who is speaking. `sentence`: the model drafts a one-line claim ("He says …") and a meaning check, one more call an item, judges it against the transcript around the quote. | +| `readAloud` | `"flag"` | A quote whose transcript has a sign of reading aloud around it — a tweet, likes and retweets, a headline or article being introduced, "it says", "he writes", "according to", a clip, a chat message, the host named in the third person: `flag` keeps it in a last section "To check by ear", its line starting `Check by ear:` and its claim carrying the flag `check by ear: may be read aloud`; `drop` leaves it out (counted in the coverage line); `off` does not look. The patterns are code's (`common/lib/report/draft/tasks/readAloud.ts`) and miss a reading nothing in the transcript announces. | + Default: ```json @@ -1335,6 +1343,10 @@ Default: "localModel": "qwen2.5vl:7b", "maxUsd": 5, "everySeconds": 10 + }, + "localSweep": { + "claimForm": "neutral", + "readAloud": "flag" } } ``` diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts @@ -875,7 +875,7 @@ async function runReportDraft( input = provider === "api" ? { task: "sweep-agent", article: body.article, n, extractorModel: extractor, origin: where.origin, maxUsd: cap } - : { task: "sweep-pipeline", article: body.article, n, origin: where.origin }; + : { task: "sweep-pipeline", article: body.article, n, origin: where.origin, claimForm: gen.localSweep.claimForm, readAloud: gen.localSweep.readAloud }; break; case "revise-report": input = { task: "revise-report", article: body.article, n, origin: where.origin, maxUsd: cap }; diff --git a/common/lib/generationSettings.test.ts b/common/lib/generationSettings.test.ts @@ -196,3 +196,12 @@ test("claim groups for a cut (lane L4): local in every preset but api; a file fr } assert.equal(sanitizeGeneration({}).routes["propose-groups"], "local"); }); + +test("generation.localSweep: the claim form and the read-aloud rule, each one of its values or the default", async () => { + const { DEFAULT_GENERATION_LOCAL_SWEEP, sanitizeLocalSweep } = await import("./generationSettings"); + assert.deepEqual(sanitizeGeneration({}).localSweep, DEFAULT_GENERATION_LOCAL_SWEEP); + assert.deepEqual(sanitizeGeneration({ localSweep: { claimForm: "sentence", readAloud: "drop" } }).localSweep, { claimForm: "sentence", readAloud: "drop" }); + assert.deepEqual(sanitizeLocalSweep({ claimForm: "poem", readAloud: true }), DEFAULT_GENERATION_LOCAL_SWEEP); + assert.deepEqual(sanitizeLocalSweep({ readAloud: "off" }), { ...DEFAULT_GENERATION_LOCAL_SWEEP, readAloud: "off" }); + assert.deepEqual(sanitizeLocalSweep("neutral"), DEFAULT_GENERATION_LOCAL_SWEEP); +}); diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts @@ -107,6 +107,22 @@ export const DEFAULT_GENERATION_TRIAGE: GenerationTriage = { model: "local", str export type GenerationFrames = { apiModel: string; localModel: string; maxUsd: number; everySeconds: number }; export const DEFAULT_GENERATION_FRAMES: GenerationFrames = { apiModel: "claude-haiku-4-5", localModel: "qwen2.5vl:7b", maxUsd: 5, everySeconds: 10 }; +// The local sweep (demo epic D2, round b): the `local` route's sweep is a +// pipeline of code around a small model (report/draft/tasks/sweep-pipeline.ts). +// `claimForm`: who writes a finding's line — `neutral` (code: "In <title> +// (<date>), on <topic>: "<quote>"", the model only picks the quote and labels +// its topic) or `sentence` (the model drafts "He says …" and a meaning check +// judges it). `readAloud`: what happens to a quote whose transcript has a sign +// of reading aloud around it (a tweet, a headline, "it says"; code's patterns, +// report/draft/tasks/readAloud.ts) — `flag` (kept, marked "check by ear"), +// `drop`, or `off`. +export const CLAIM_FORMS = ["sentence", "neutral"] as const; +export type ClaimForm = (typeof CLAIM_FORMS)[number]; +export const READ_ALOUD_MODES = ["off", "flag", "drop"] as const; +export type ReadAloudMode = (typeof READ_ALOUD_MODES)[number]; +export type GenerationLocalSweep = { claimForm: ClaimForm; readAloud: ReadAloudMode }; +export const DEFAULT_GENERATION_LOCAL_SWEEP: GenerationLocalSweep = { claimForm: "neutral", readAloud: "flag" }; + export type GenerationSettings = { preset: GenerationPreset | "custom"; routes: GenerationRoutes; @@ -124,6 +140,7 @@ export type GenerationSettings = { verdicts: GenerationVerdicts; triage: GenerationTriage; frames: GenerationFrames; + localSweep: GenerationLocalSweep; }; export const DEFAULT_GENERATION_VERDICT_WINDOW: GenerationVerdictWindow = { mode: "seconds", seconds: 60 }; @@ -150,6 +167,7 @@ export const DEFAULT_GENERATION_SETTINGS: GenerationSettings = { verdicts: { bar: { ...DEFAULT_GENERATION_VERDICTS.bar }, models: [], window: { ...DEFAULT_GENERATION_VERDICT_WINDOW } }, triage: { ...DEFAULT_GENERATION_TRIAGE }, frames: { ...DEFAULT_GENERATION_FRAMES }, + localSweep: { ...DEFAULT_GENERATION_LOCAL_SWEEP }, }; export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { @@ -175,6 +193,15 @@ export const GENERATION_SETTINGS_FIELD_DOCS: FieldDocs<GenerationSettings> = { triage: "Triage first (umtool R6): the cheap pass a recurring report runs before its sweep when it asks for one (a watch always does) — the model it judges on, when it escalates to an API sweep of what it flagged, and how often a day it may (below).", frames: "The frame scan (`pnpm ops frame-scan`): the vision model each route reads a saved stream's frames on, a scan's spend cap and its sampling step (below).", + localSweep: + "The `local` route's sweep (a pipeline of code around the local model): who writes a finding's line and what happens to a quote that may be read aloud (below). `archilyzer gen local-sweep` sets both; the Claude routes' sweeps are not affected.", +}; + +export const GENERATION_LOCAL_SWEEP_FIELD_DOCS: FieldDocs<GenerationLocalSweep> = { + claimForm: + "`neutral`: code writes each finding — `In <recording's title> (<date>), on <topic>: \"<quote>\"` — and the model only copies the quote and labels its topic in a few words (a label that names the speaker, has a verb of saying or thinking, or uses words found in neither the quote, the transcript before it, the title nor the question is replaced by the question's topic); the line says where the words are, never who is speaking. `sentence`: the model drafts a one-line claim (\"He says …\") and a meaning check, one more call an item, judges it against the transcript around the quote.", + readAloud: + "A quote whose transcript has a sign of reading aloud around it — a tweet, likes and retweets, a headline or article being introduced, \"it says\", \"he writes\", \"according to\", a clip, a chat message, the host named in the third person: `flag` keeps it in a last section \"To check by ear\", its line starting `Check by ear:` and its claim carrying the flag `check by ear: may be read aloud`; `drop` leaves it out (counted in the coverage line); `off` does not look. The patterns are code's (`common/lib/report/draft/tasks/readAloud.ts`) and miss a reading nothing in the transcript announces.", }; export const GENERATION_FRAMES_FIELD_DOCS: FieldDocs<GenerationFrames> = { @@ -358,6 +385,16 @@ export function sanitizeGeneration(value: unknown): GenerationSettings { verdicts: sanitizeVerdicts(r.verdicts), triage: sanitizeTriage(r.triage), frames: sanitizeFrames(r.frames, model), + localSweep: sanitizeLocalSweep(r.localSweep), + }; +} + +export function sanitizeLocalSweep(v: unknown): GenerationLocalSweep { + const d = DEFAULT_GENERATION_LOCAL_SWEEP; + const o = v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {}; + return { + claimForm: (CLAIM_FORMS as readonly unknown[]).includes(o.claimForm) ? (o.claimForm as ClaimForm) : d.claimForm, + readAloud: (READ_ALOUD_MODES as readonly unknown[]).includes(o.readAloud) ? (o.readAloud as ReadAloudMode) : d.readAloud, }; } diff --git a/common/lib/report/draft/tasks/neutralClaim.test.ts b/common/lib/report/draft/tasks/neutralClaim.test.ts @@ -0,0 +1,50 @@ +// The speaker-neutral claim form (demo epic D2, round b): the line is code's. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { attributes, humanDate, neutralHeading, neutralSentence, neutralTitle, plainTitle, 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"]; +const label = (raw: unknown, hosts = ["jeremy", "quartering"]) => topicLabel(raw, { fallback: "the acolyte", hosts, ground }); + +test("the line: In <title> (<date>), on <topic>: — no speaker, no verb of saying", () => { + const s = neutralSentence({ title: 'The Acolyte Hits "ROCK BOTTOM" [it\'s over] (finally)', date: "2024-06-17", topic: "the acolyte's audience score" }); + assert.equal(s, "In The Acolyte Hits ROCK BOTTOM it's over finally (17 June 2024), on the acolyte's audience score:"); + // The converter reads the quoted words before a link as the citation's quote: + // the line carries exactly one quoted run, the quote. + assert.equal(quotedIn(`${s} "we finally hit rock bottom at a 15% audience score"`), "we finally hit rock bottom at a 15% audience score"); + assert.equal(neutralSentence({ title: "", date: "", topic: "the ban" }), "In a recording, on the ban:"); + assert.equal(humanDate("20240605"), "5 June 2024"); + assert.equal(humanDate("2024-13-05"), "2024-13-05"); + assert.equal(humanDate("last week"), "last week"); + assert.ok(plainTitle("x".repeat(40) + " " + "y".repeat(80)).endsWith("…")); +}); + +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" }); + // 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.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"); + assert.equal(label(42).why, "no label"); + 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", () => { + 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"); + assert.equal(attributes("Reviews and ratings"), false); + assert.equal(attributes("Fans' reaction"), true); +}); diff --git a/common/lib/report/draft/tasks/neutralClaim.ts b/common/lib/report/draft/tasks/neutralClaim.ts @@ -0,0 +1,170 @@ +// THE SPEAKER-NEUTRAL CLAIM FORM of a local sweep (demo epic D2, round b): +// the report's line is written by CODE, never by the model — +// +// In <video title> (<5 June 2024>), on <topic>: "<quote>" — [title @ mm:ss](link) +// +// The model's whole job per item is to copy the quote and label its topic in +// a few words. No "he said / he believes" sentence is generated at all: a +// small model cannot tell the host reading a tweet, a headline or a review +// aloud from the host speaking (round a, 11 Nov 2026: 34 kept, 16 supported, +// 1 reversed on qwen3:8b — every miss an attribution), and a sentence that +// attributes nothing cannot attribute wrongly. What the line says is where +// the words are (the recording, its date, the second) and what they are +// about; who is speaking is for the ear (./readAloud.ts flags the likely +// readings). +// +// The label is the one thing the model writes, so code holds it down: a few +// words, no name of the host, no verb of saying or thinking, and GROUNDED — +// every content word of it is in the quote, the transcript just before it, +// the recording's title or the question's own terms. A label that fails is +// replaced by the run's topic. + +import { strictNormalize } from "../../../citations/verify"; + +export { CLAIM_FORMS, type ClaimForm } from "../../../generationSettings"; + +export const MAX_TOPIC_WORDS = 8; + +export const NEUTRAL_EXTRACT_SYSTEM = + "You read excerpts of an automatic transcript and pick out passages that bear on a research question. Rules: (1) " + + "Only use the excerpt. (2) Each quote is copied EXACTLY, character for character, from consecutive transcript lines, " + + "without the bracketed timestamps; at least 8 and at most 40 words, a whole sentence or clause; do not fix grammar, " + + "spelling or names. (3) Each topic is a label of two to six words naming what the quote is ABOUT, using words from " + + "the quote or the question (\"the acolyte's audience score\", \"the ban from sanctioned events\"). A label is a noun " + + "phrase: no verb of saying or thinking, no name of the speaker, no opinion, no judgement. Do not say who is " + + "speaking and do not summarise what is said. Set on_topic to true only when the quote itself is about the " + + "question's subject. Strength: 3 = the quote directly answers the question, 2 = it bears on it, 1 = it only " + + "mentions a search word. (4) If the excerpt does not bear on the question, set relevant to false and return no " + + "items. (5) Return at most three items, the strongest first."; + +export function neutralExtractSchema(maxItems: number) { + return { + type: "object", + properties: { + relevant: { type: "boolean" }, + items: { + type: "array", + maxItems, + items: { + type: "object", + properties: { + quote: { type: "string" }, + topic: { type: "string" }, + on_topic: { type: "boolean" }, + strength: { type: "integer", minimum: 1, maximum: 3 }, + }, + required: ["quote", "topic", "on_topic", "strength"], + }, + }, + }, + required: ["relevant", "items"], + }; +} + +export const NEUTRAL_GROUP_SYSTEM = + "You organise numbered quotes into a short report. Each quote comes with a label of its topic. Return a title and " + + "between one and six sections. Each section has a short heading (at most 60 characters) naming the subject its " + + "quotes have in common, and the numbers of the quotes it holds, each number in exactly one section. A heading is a " + + "noun phrase about the subject matter: it never says who said something, what anyone thinks, or whether anything is " + + "true or good."; + +// A verb (or noun) of saying or thinking: a label or heading that has one +// attributes, and the neutral form attributes nothing. +const ATTRIBUTES = + /\b(?:says?|said|saying|tells?|told|thinks?|thought|thoughts|believes?|belie[fv]s?|claims?|claimed|argues?|argued|states?|stated|admits?|admitted|insists?|calls?|called|slams?|blasts?|mocks?|mocked|rants?|opinions?|views?|stance|takes?|reacts?|reaction|responds?|feels?|feelings?|according)\b/i; + +const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +// Does this text name the host or say who thinks what? +export function attributes(text: string, hosts: readonly string[] = []): boolean { + if (ATTRIBUTES.test(text)) return true; + const t = ` ${strictNormalize(text)} `; + return hosts.some((h) => { + const k = strictNormalize(h); + return k.length >= 3 && new RegExp(` ${esc(k)}s? `).test(t); + }); +} + +const LABEL_STOP = new Set( + "the a an of on in at to for and or with from by about its his her their this that these those is are was were be being as it into over new".split(" "), +); +const stem = (w: string) => (w.length > 5 ? w.slice(0, 5) : w.replace(/s$/, "")); +const contentWords = (s: string) => + strictNormalize(s) + .split(" ") + .filter((w) => w.length >= 3 && !LABEL_STOP.has(w)); + +export type TopicLabel = { label: string; from: "model" | "fallback"; why?: string }; + +// The model's topic label, held down by code; the run's topic when it fails. +// `ground`: the texts a label's words may come from (the quote, the +// transcript before it, the recording's title, the question's terms). +export function topicLabel(raw: unknown, o: { fallback: string; hosts?: readonly string[]; ground: readonly string[] }): TopicLabel { + const fb = (why: string): TopicLabel => ({ label: o.fallback, from: "fallback", why }); + let s = typeof raw === "string" ? raw : ""; + s = s + .replace(/["“”‘’'`*_#[\]()<>|]/g, (c) => (c === "'" || c === "’" ? "'" : " ")) + .replace(/\s+/g, " ") + .trim() + .replace(/^(?:on|about|re|regarding|topic)\b[:\s]*/i, "") + .replace(/[\s.:;,!?—–-]+$/g, "") + .trim(); + if (!s) return fb("no label"); + const n = s.split(" ").length; + if (n > MAX_TOPIC_WORDS) return fb(`a label of ${n} words (at most ${MAX_TOPIC_WORDS})`); + if (attributes(s, o.hosts)) return fb("the label says who says or thinks something"); + const words = contentWords(s); + if (!words.length) return fb("a label of no content words"); + const have = new Set(o.ground.flatMap((g) => contentWords(g)).map(stem)); + const loose = words.find((w) => !have.has(stem(w))); + if (loose) return fb(`“${loose}” is not in the quote, the transcript before it, the title or the question`); + return { label: s, from: "model" }; +} + +const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + +// "2024-06-05" (or "20240605") → "5 June 2024"; anything else as it is. +export function humanDate(date: string): string { + const m = /^(\d{4})-?(\d{2})-?(\d{2})$/.exec(date.trim()); + if (!m) return date.trim(); + const mo = Number(m[2]); + const d = Number(m[3]); + if (mo < 1 || mo > 12 || d < 1 || d > 31) return date.trim(); + return `${d} ${MONTHS[mo - 1]} ${m[1]}`; +} + +// A title as plain words inside a markdown list item: no quote marks (the +// converter reads quoted words before a link as the citation's quote), no +// markup, no brackets. +export function plainTitle(title: string, max = 90): string { + const t = title + .replace(/["“”«»]/g, "") + .replace(/[[\]()<>*_`#|]/g, " ") + .replace(/\s+/g, " ") + .trim(); + return t.length > max ? `${t.slice(0, max).replace(/\s\S*$/, "")}…` : t; +} + +// The line's words before its quote: "In <title> (<date>), on <topic>:". +export function neutralSentence(o: { title: string; date: string; topic: string }): string { + const date = humanDate(o.date); + return `In ${plainTitle(o.title) || "a recording"}${date ? ` (${date})` : ""}, on ${o.topic}:`; +} + +// The report's title, by code: "<Topic>: quotes from <channel>". +export function neutralTitle(topic: string, channels: readonly string[]): string { + const t = topic.trim(); + const head = t ? t[0]!.toUpperCase() + t.slice(1) : "Quotes"; + const from = channels.filter(Boolean).slice(0, 3).join(", "); + return `${head}: quotes from ${from || "the archive"}`.slice(0, 90); +} + +// A section heading the grouping call wrote: kept unless it attributes; then +// the commonest label of its items. +export function neutralHeading(heading: string, labels: readonly string[], hosts: readonly string[] = []): string { + if (heading && !attributes(heading, hosts)) return heading; + const count = new Map<string, number>(); + for (const l of labels) count.set(l.toLowerCase(), (count.get(l.toLowerCase()) ?? 0) + 1); + const best = [...count.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]; + return best ? best[0]!.toUpperCase() + best.slice(1) : "Quotes"; +} diff --git a/common/lib/report/draft/tasks/readAloud.test.ts b/common/lib/report/draft/tasks/readAloud.test.ts @@ -0,0 +1,74 @@ +// Read-aloud cues (demo epic D2, round b), on the transcripts of the claims +// the grader marked "not his words" in D0 and round a (11 Nov 2026), and on +// ones that are his own. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { cuesLine, READ_ALOUD_FLAG, readAloudCues } from "./readAloud"; + +const cues = (before: string, quote: string, after = "", hosts: string[] = ["jeremy", "quartering"]) => readAloudCues({ before, quote, after, hosts }).map((c) => c.cue); + +test("a tweet being introduced, its likes read out, 'writes', 'here you have': the quote is read aloud", () => { + // i123-d-q25 k06: Shad's tweet. + assert.deepEqual( + cues( + "there's one thing I want to one way that put one tweet that put it really good I want to give them credit for it because um you know I need to do better about that but like here Shad uh writes from", + "Shad adversity the acolyte episode 5 doesn't understand power scaling at all which is crucial if you want consistency and investment in a fight", + ), + ["tweet", "writes"], + ); + // i123-d-q25 k05: the End Wokeness tweet, its likes read out. + assert.deepEqual( + cues( + "even polygon which is a you know extremely left leaning uh publication is turning on it here you have n wokeness 19,000 likes here it is", + "Disney's latest episode of Star Wars the acolyte has a they them pronoun scene the pronouns of the acolyte are garbage", + ), + ["likes", "here"], + ); +}); + +test("an article, a clip, a rumour, a letter, 'also added', 'saying' right before the quote", () => { + assert.ok(cues("eight percent is a non-starter i did see this article out via bounding in the comics it said", "new rumor details that disney encouraged individuals to delete twitter accounts").includes("article")); + assert.deepEqual(cues("and you see see this clip from Looper which they only deleted after massive backlash some audience members have issues with the show's diversity", "they do however viewers should genuinely examine the legitimate criticisms the acolyte has received"), ["clip", "here"]); + assert.deepEqual(cues("and even hinted at her desire to join the franchise in the past according to some", "larson is set to be involved in an animated spin-off show"), ["according to"]); + assert.ok(cues("this is not just a problem for alan dean foster who wrote this to disney dear mickey we have a lot in common this is the letter he wrote them", "you acquired and acquired the rights to some books that i wrote").includes("letter")); + assert.deepEqual(cues("that's what it seems like they're saying interestingly enough wwe pro also added", "kathleen kennedy while in charge of lucasfilm for the next three years is being stripped of any control over star wars"), ["writes"]); + assert.deepEqual(cues("he went on to find humor in the situation saying", "can we please appreciate the irony of youtube accusing papa of using this word"), ["saying"]); +}); + +test("what he says AFTER it: 'this is from … shout out good take', 'this is a lie', 'what a shame'", () => { + // i123-d-q25 k04: nothing before the quote says it is read. + assert.deepEqual(cues("she's an attention seeking dless celebrity the truth is Star Wars", "the acolyte sucks and her performance is terrible", "it's not racism her performance is just weak in the RO in the role this is from Roar Ashley shout out good take and I r"), ["from (after)"]); + // D0 a k01: the review he reads to deny it. + assert.ok(cues("", "the reason for the ban was constant sexual harassment", "this is a lie this is liable this is slanderous").includes("reaction (after)")); + // i123-d-q3b k27: a critic's review. + assert.deepEqual(cues("in fact", "the acolyte keeps reminding me of the prequel trilogy in all the worst ways", "ah well what a shame I'll keep watching obviously"), ["reaction (after)"]); +}); + +test("the quote names the host in the third person — but not his own sign-on; a chat line; reported speech inside it", () => { + assert.deepEqual(cues("", "Jeremy Hambly was banned by Wizards of the coast from attending sanctioned events for the company's games"), ["names the host"]); + assert.deepEqual(cues("", "what's going on everyone Jeremy here from the quartering and I don't think many people would disagree"), []); + assert.deepEqual(cues("", "Jeremy are from the quartering and it's a tale as old as time"), [], "the transcript's mis-hearing of the sign-on"); + assert.deepEqual(cues("", "you'll find my name Jeremy Hambly as a lifetime banned player"), []); + assert.deepEqual(cues("", "sologamer5 says hey jeremy been a while glad to see your work ethic hasn't slacked off"), ["names the host", "chat"]); + assert.deepEqual(cues("", "the one thing they can use now they're saying if you rely upon misinformation then it tells me you're afraid of the truth"), ["saying"]); +}); + +test("his own words with nothing around them that says reading: no cue", () => { + // i123-d-q3b k01, k09, k20 (graded supported, his own). + assert.deepEqual(cues("so the show is out and", "the reviews are absolutely bottoming out the last review I saw for it was a 2.2 on IMDb and a certified rotten review score on Rotten Tomatoes", "everybody is absolutely"), []); + assert.deepEqual(cues("and I think that", "the acolyte you know has single-handedly removed has destroyed uh the lore of Star Wars", "and that is something"), []); + assert.deepEqual(cues("what's going on everyone", "the acolyte has been soundly rejected by any respectable Star Wars fan", "and today"), []); +}); + +test("a cue far back does not count for the near ones; each cue is reported once, with the words that matched", () => { + const far = `he also added ${"and then we went on with the show and nothing else was read at all ".repeat(5)}`; + assert.deepEqual(cues(far, "I think the show is bad and I have said so from the first trailer"), []); + const got = readAloudCues({ before: "one tweet here another tweet 371 likes", quote: "you people are making a mistake nothing was offensive", after: "" }); + assert.deepEqual(got, [ + { cue: "tweet", where: "before", match: "tweet" }, + { cue: "likes", where: "before", match: "371 likes" }, + ]); + assert.equal(cuesLine(got), "tweet (“tweet”), likes (“371 likes”)"); + assert.ok(READ_ALOUD_FLAG.length <= 60, "a claim's flag is at most 60 characters"); +}); diff --git a/common/lib/report/draft/tasks/readAloud.ts b/common/lib/report/draft/tasks/readAloud.ts @@ -0,0 +1,145 @@ +// READ-ALOUD CUES (demo epic D2, round b): what the transcript around a quote +// says about whose words it is, read by CODE. +// +// A host who covers news reads tweets, headlines, articles, reviews, chat and +// letters aloud, and plays clips; an automatic transcript has no quotation +// marks, and a small model cannot tell the reading from the speaking (D0 and +// round a, 11 Nov 2026: 60 of 185 graded quotes were not the host's words; the +// model's own speaker/stance answer missed most of them). The words that +// introduce a reading are in the transcript, though: "one tweet that put it +// really good", "19,000 likes here it is", "you see this clip from", "he +// writes", "according to", "this is from … shout out good take". This module +// looks for them: in the 400 characters before the quote, in the quote, and +// in the 150 after. +// +// A cue is evidence, not a verdict: the caller drops the item or keeps it +// flagged "check by ear" (settings: generation.localSweep.readAloud). +// +// The list is derived from the graded claims of D0 and round a (the grader's +// `not_him`), not from a guess; each pattern's comment names a claim it reads. + +// What a sweep does with a quote that has a cue: nothing (`off`), keep it +// marked "check by ear" (`flag`), or leave it out (`drop`). +export { READ_ALOUD_MODES, type ReadAloudMode } from "../../../generationSettings"; + +// The claim's flag in report.json (a pill on its card; at most 60 characters). +export const READ_ALOUD_FLAG = "check by ear: may be read aloud"; + +export type ReadAloudCue = { + // The pattern's name (stable: stored beside the item, shown in the trace). + cue: string; + where: "before" | "quote" | "after"; + // The transcript's words that matched. + match: string; +}; + +type Pattern = { cue: string; re: RegExp; near?: number }; + +// Before the quote. `near`: only in the last N characters (an attribution verb +// far back introduces something else). +const BEFORE: Pattern[] = [ + // "one tweet that put it really good", "kurt tweeted along", "retweets" + { cue: "tweet", re: /\b(?:re)?tweet(?:s|ed|ing)?\b|\bquote tweet/, near: 250 }, + // "453 comments 371 likes", "19,000 likes here it is" + { cue: "likes", re: /\b\d[\d,.]*\s*(?:k|thousand|million)?\s*(?:likes|retweets|replies|comments|reposts|upvotes)\b/ }, + // "here's another article", "you can see the article from just a few hours ago" + { cue: "article", re: /\b(?:here'?s|see|saw|seen|read|reading|reads|whole|another|according to) (?:\w+ ){0,2}(?:article|headline|op-?ed|press release|blog post|write-?up|story|report)s?\b/ }, + // "oh another comment mods made … made it clear that", "left a slanderous libel review" + { cue: "comment", re: /\b(?:another|this|that|one|top|first|next) (?:comment|reply|review|post)\b|\b(?:leave|left|leaves|wrote|writes|posted) an? (?:\w+ ){0,3}(?:comment|review|reply)\b/, near: 300 }, + // "this is the letter he wrote them", "in his statement", "another comment mod made" + { cue: "letter", re: /\b(?:letter|statement|email|e-mail|memo|announcement)\b/, near: 200 }, + // "you see this clip from looper", "here's the clip", "queue up the audio" + { cue: "clip", re: /\b(?:clip|audio|footage|trailer)\b/, near: 300 }, + // "according to some", "according to persistent rumors" + { cue: "according to", re: /\baccording to\b/, near: 300 }, + // "here shad writes from", "he wrote", "it says", "she replies", "wwe pro also added", + // "the customer goes on to say", "their reports allege", "producer claims" + { + cue: "writes", + re: /\b(?:he|she|they|it|who|which|that|this|\w+ also|[a-z]+ [a-z]+) (?:writes?|wrote|replies|replied|tweeted|posted|added|adds|alleges?|goes on to say|went on to say|responds|responded)\b|\b(?:it|he|she|this|that|which|article|headline|tweet|post|review|comment|caption|title) (?:says|said|reads|read|states|stated|claims|claimed)\b/, + near: 300, + }, + // "… he went on to find humor in the situation saying", "to which he replies", "quote" + { cue: "saying", re: /\b(?:saying(?: that)?|to which (?:he|she|they) repl\w+|quote|unquote|and i quote|titled|entitled|captioned|headlined|reads)\s*$/ }, + { cue: "quote", re: /\bquote\b/, near: 200 }, + // "this is via sputnik", "this is from", "here from", "from polygon" + { cue: "via", re: /\b(?:this is|it'?s|that'?s) (?:via|from|by|over at|on)\b|\bvia\b/, near: 300 }, + // "here you have end wokeness", "here's polygon again", "you see this from lucas", + // "here it is", "you can see" + { cue: "here", re: /\bhere (?:you have|you got|we have|we got|it is|is)\b|\bhere'?s\b|\byou (?:can )?(?:see )+(?:this|here|from|that|the)\b|\b(?:take|taking) a look\b|\blisten to this\b|\bcheck this out\b|\blook at this\b/, near: 300 }, + // "shout out dally here's bonfire legend" + { cue: "shout out", re: /\bshout ?-?out\b/, near: 300 }, + // chat: "sologamer5 says hey jeremy" + { cue: "chat", re: /\b(?:super ?chat|superchat|donation|donated|chat says|in the chat|commenter|subreddit|reddit)\b/, near: 300 }, + // an @handle, a hashtag read out + { cue: "handle", re: /(?:^|\s)@\w{2,}|\bat symbol\b|\bhashtag\b/ }, +]; + +// After the quote, in its first characters: his reaction to what he just read. +const AFTER: Pattern[] = [ + // "… this is from roar ashley shout out good take" + { cue: "from (after)", re: /\b(?:this is (?:from|via|by)|shout ?-?out|good take|great take|liked this|likes this|\d[\d,.]*\s*(?:likes|retweets))\b/, near: 120 }, + // "this is a lie this is libel", "that is a really disingenuous interpretation of what he said", + // "oh okay it's not productive", "what a shame", "imagine that" + { + cue: "reaction (after)", + re: /^(?:this is a lie|that is a (?:really |very |completely )?(?:disingenuous|dishonest|ridiculous|insane|wild|crazy)|what a shame|imagine that|oh+ ?okay|okay so (?:he|she|they)|mm+ that'?s|(?:he|she|they|it) (?:goes|go) on|(?:he|she|they) (?:also )?(?:say|says|said|write|writes|wrote)\b)|^(?:\W*\w+){0,10}?\W+(?:what a shame|imagine that|go(?:es|ing) on to say|went on to say)\b/, + near: 120, + }, +]; + +const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +const lower = (s: string) => s.toLowerCase().replace(/[’‘]/g, "'").replace(/\s+/g, " ").trim(); + +export const READ_ALOUD_BEFORE = 400; +export const READ_ALOUD_AFTER = 150; + +// The cues around one quote: none = nothing says it is read aloud. +// `hosts`: the names of the person the report is about (lowercase); a quote +// that names him in the third person is somebody else's words about him. +export function readAloudCues(o: { before: string; quote: string; after: string; hosts?: readonly string[] }): ReadAloudCue[] { + const out: ReadAloudCue[] = []; + const before = lower(o.before).slice(-READ_ALOUD_BEFORE); + const after = lower(o.after).slice(0, READ_ALOUD_AFTER); + const quote = lower(o.quote); + const add = (cue: string, where: ReadAloudCue["where"], match: string) => { + if (!out.some((c) => c.cue === cue)) out.push({ cue, where, match: match.trim() }); + }; + for (const p of BEFORE) { + const text = p.near ? before.slice(-p.near) : before; + const m = p.re.exec(text); + if (m) add(p.cue, "before", m[0]); + } + for (const p of AFTER) { + const m = p.re.exec(p.near ? after.slice(0, p.near) : after); + if (m) add(p.cue, "after", m[0]); + } + // In the quote: the host named in the third person ("jeremy hambly was + // banned by wizards", "hambly has in the past gone after"), a chat line + // ("sologamer5 says hey jeremy"), a "quote" spoken inside it. + const names = (o.hosts ?? []).map((h) => lower(h)).filter((h) => h.length >= 3); + for (const h of names) { + const re = new RegExp(`\\b${esc(h)}(?:'s)?\\b`); + const m = re.exec(quote); + if (!m) continue; + // His own sign-on: "jeremy here from the quartering", "i'm jeremy", "my name is". + // (the transcript hears "jeremy here from" as "jeremy are from", "jeremy hair from") + const self = new RegExp( + `\\b(?:i'?m|i am|my name(?: is)?|it'?s|this is|papa|here from|here with)\\s+(?:\\w+\\s+){0,2}${esc(h)}\\b|\\b${esc(h)}(?:\\s+\\w+){0,2}\\s+(?:here|hear|hair|are) (?:from|with|and)\\b|\\b(?:from|on|at|to|of|with) (?:the )?${esc(h)}\\b`, + ).test(quote); + if (!self) add("names the host", "quote", m[0]); + } + const chat = /^\w+ says\b/.exec(quote) ?? /\bhey (?:\w+ )?(?:been a while|love (?:the|your)|big fan)\b/.exec(quote); + if (chat) add("chat", "quote", chat[0]); + const q = /\bquote\b/.exec(quote); + if (q) add("quote", "quote", q[0]); + // Reported speech inside the quote: "now they're saying if you rely upon misinformation". + const rs = /\b(?:they'?re|they are|he'?s|she'?s|he is|she is|it'?s|is|are) saying\b|\b(?:it|article|headline|tweet|post|review) (?:says|reads)\b/.exec(quote); + if (rs) add("saying", "quote", rs[0]); + return out; +} + +// One line for a log, a trace or a reason: `tweet (“one tweet”), likes (“19,000 likes”)`. +export function cuesLine(cues: readonly ReadAloudCue[]): string { + return cues.map((c) => `${c.cue} (${c.where === "before" ? "" : `${c.where}: `}“${c.match}”)`).join(", "); +} diff --git a/common/lib/report/draft/tasks/sweep-pipeline.ts b/common/lib/report/draft/tasks/sweep-pipeline.ts @@ -11,6 +11,14 @@ // Every prompt fits the local cap; one that would not is never sent (the // ollama module refuses it) and that chunk is logged as failed. // +// TWO CLAIM FORMS (demo epic D2, round b; `claimForm`): `sentence` — the model +// drafts a one-line claim and a meaning check judges it — and `neutral` — the +// model only copies the quote and labels its topic, and CODE writes the line: +// "In <title> (<date>), on <topic>: "<quote>"" (./neutralClaim.ts; no meaning +// check, there is no drafted sentence). And READ-ALOUD CUES (`readAloud`, +// ./readAloud.ts): a quote whose transcript says it is being read aloud (a +// tweet, a headline, "it says") is dropped, or kept marked "check by ear". +// // The run is TRACED (trace.jsonl, ./trace.ts; umtool R3): the scope, the // terms, each term's enumeration, each read batch with the model's lines, // every quote kept or dropped and why, the findings; the iteration's @@ -26,8 +34,10 @@ import { momentHref } from "./links"; import { checkQuotes, convertSweepText, dropFailedFindings } from "./quotes"; import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run"; import { CoverageTally, enumerateOf, traceReport } from "./trace"; -import { lintClaim, MIN_KEPT, onTopicBy, quoteContext } from "./claimChecks"; +import { GATE_CHARS, lintClaim, MIN_KEPT, onTopicBy, quoteContext } from "./claimChecks"; import { CHECK_BY_EAR, decideMeaning, MEANING_SCHEMA, MEANING_SYSTEM, meaningPrompt, readMeaning, type MeaningAnswer, type MeaningDecision } from "./meaning"; +import { NEUTRAL_EXTRACT_SYSTEM, NEUTRAL_GROUP_SYSTEM, neutralExtractSchema, neutralHeading, neutralSentence, neutralTitle, topicLabel, type ClaimForm, type TopicLabel } from "./neutralClaim"; +import { cuesLine, READ_ALOUD_FLAG, readAloudCues, type ReadAloudCue, type ReadAloudMode } from "./readAloud"; export { lintClaim }; import { @@ -157,6 +167,14 @@ export type SweepPipelineInput = { secondsPerCall?: number; // The subject's host names (a channel's context note): never search terms. hosts?: string[]; + // The claim form (round b): `sentence` (the model drafts each claim; the + // default here) or `neutral` (code writes "In <title> (<date>), on <topic>:" + // around the quote). settings.generation.localSweep.claimForm, passed by + // the controller. + claimForm?: ClaimForm; + // A quote with a read-aloud cue around it: `off` (the default here), `flag` + // (kept, marked "check by ear") or `drop`. settings.generation.localSweep.readAloud. + readAloud?: ReadAloudMode; // Only these recordings (umtool R4; a general sweep option): the worklist is // the enumeration's rows of these ids, and any of them the terms did not // find is read too. Default: the iteration's scope.ids. @@ -294,6 +312,10 @@ type Kept = { // kept, "check by ear". meaning?: { answer: MeaningAnswer; decision: MeaningDecision; seconds: number; drafted: string }; mark?: boolean; + // The neutral form's topic label (the model's, or the run's topic when code + // refused it) and the read-aloud cues found around the quote (round b). + label?: TopicLabel; + readAloud?: ReadAloudCue[]; }; export async function sweepPipeline(input: SweepPipelineInput, deps: TaskDeps): Promise<TaskResult> { @@ -328,10 +350,13 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const origin = input.origin.replace(/\/+$/, ""); const maxClaims = input.maxClaims ?? 40; const only = input.ids ?? iteration.scope?.ids; + const form: ClaimForm = input.claimForm ?? "sentence"; + const neutral = form === "neutral"; + const raMode: ReadAloudMode = input.readAloud ?? "off"; if (!question) throw new TaskInputError("a sweep needs its question"); if (!channels.length) throw new TaskInputError("a sweep needs its channels"); const event = (e: Record<string, unknown>) => h.turns([e]); - h.log(`pipeline sweep on ${model}, corpus ${deps.corpus.source}, links on ${origin}`); + h.log(`pipeline sweep on ${model}, corpus ${deps.corpus.source}, links on ${origin}${neutral ? "; claims in the speaker-neutral form (written by code)" : ""}${raMode !== "off" ? `; read-aloud cues: ${raMode}` : ""}`); const cov = new CoverageTally(); h.setCoverage(() => cov.value()); h.trace({ t: "scope", source: deps.corpus.source, channels, ...(since ? { from: since } : {}), ...(until ? { to: until } : {}), question, model, origin, ...(only?.length ? { ids: only } : {}) }); @@ -342,9 +367,12 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const names = subjectNames({ question, channels: channelNames, hosts: input.hosts }); const droppedTerms: DroppedTerm[] = []; let topic = ""; + // The topic as the model wrote it (the neutral form shows it). + let topicShown = ""; const proposeTerms = async (user: string, what: string) => { const ans = await ask<{ terms?: unknown; topic?: unknown }>(h, model, TERMS_SYSTEM, user, TERMS_SCHEMA, what, true); if (!topic && typeof ans.topic === "string") topic = ans.topic.replace(/["“”]/g, "").trim().slice(0, 60); + if (!topicShown) topicShown = topic.replace(/[[\]()<>*_`#|]/g, " ").replace(/\s+/g, " ").trim(); const c = cleanTerms(Array.isArray(ans.terms) ? ans.terms : [], { names }); droppedTerms.push(...c.dropped); return c.kept; @@ -443,6 +471,10 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T // The topic the model named, as the gate reads it (the subject's names off). topic = normalizeTerm(topic, names); const rare = rareTermsOf(usable); + // The neutral form's fallback label: the topic the model named for the + // question, else the rarest term. + const hostNames = [...names]; + const runTopic = topicShown || topic || rare[0] || terms[0]!; h.trace({ t: "note", text: `scope ${scopeSize} recording(s); terms by rarity: ${usable.map((st) => `${st.term} ${st.videos}${st.partial ? "+" : ""} (${(st.share * 100).toFixed(1)}%, idf ${st.idf.toFixed(2)}${st.nominates ? "" : ", scores only"})`).join("; ")}; rare: ${rare.join(", ")}`, @@ -565,7 +597,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const user = `Research question: ${question}\n\nVideo: ${title} (${v.channel}, ${v.date})\n\nTranscript excerpt:\n${excerpt}`; let ans: { relevant?: unknown; items?: unknown }; try { - ans = await ask(h, model, EXTRACT_SYSTEM, user, EXTRACT_SCHEMA, `extract ${v.id}@${ch[0]![0]}`); + ans = await ask(h, model, neutral ? NEUTRAL_EXTRACT_SYSTEM : EXTRACT_SYSTEM, user, neutral ? neutralExtractSchema(MAX_ITEMS_PER_CHUNK) : EXTRACT_SCHEMA, `extract ${v.id}@${ch[0]![0]}`); } catch (e) { if (deps.signal?.aborted) throw e; event({ kind: "chunk-failed", video: v.id, at: ch[0]![0], error: (e as Error).message }); @@ -576,13 +608,14 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T if (!ans.relevant) continue; nRelevant++; const items = Array.isArray(ans.items) ? ans.items.slice(0, MAX_ITEMS_PER_CHUNK) : []; - for (const raw of items as { quote?: unknown; claim?: unknown; on_topic?: unknown; strength?: unknown }[]) { + for (const raw of items as { quote?: unknown; claim?: unknown; topic?: unknown; on_topic?: unknown; strength?: unknown }[]) { let quote = String(raw.quote ?? "") .replace(/["“”]/g, "") .replace(/\s+/g, " ") .trim() .replace(/^\[[\d:]+\]\s*/, ""); - const claim = String(raw.claim ?? "").replace(/\s+/g, " ").trim().replace(/"/g, "'").replace(/[“”]/g, "'"); + // The neutral form has no drafted claim: code writes the line below. + let claim = neutral ? "" : String(raw.claim ?? "").replace(/\s+/g, " ").trim().replace(/"/g, "'").replace(/[“”]/g, "'"); const sec = locate(quote, ch); // A quote that stops mid-thought (Q2) becomes its whole sentence // when the window has one: code copies the words, still verbatim. @@ -602,7 +635,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T else if (stillFragment) why = `a fragment (${stillFragment.why})`; else if (wc < MIN_QUOTE_WORDS) why = `too short (${wc} words)`; else if (wc > MAX_QUOTE_WORDS) why = `too long (${wc} words)`; - else if (!claim) why = "no claim"; + else if (!neutral && !claim) why = "no claim"; else if (raw.on_topic === false || (Number(raw.strength) || 2) < 2) why = "model: not on topic"; const key = norm(quote); if (!why && kept.some((k) => k.video === v.id && (norm(k.quote).includes(key) || key.includes(norm(k.quote))))) why = "duplicate"; @@ -612,6 +645,17 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const around = !why ? quoteContext(win, quote, { before: 400, after: 150 }) : null; const gate = around ? onTopicBy({ quote, before: around.before, terms: rare, ...(topic ? { topic } : {}) }) : null; if (!why && !gate) why = `off the question: no ${rare.map((t) => `“${t}”`).join(" or ")}${topic && !rare.includes(topic) ? ` or “${topic}”` : ""} in the quote or the 300 characters before it`; + // Read-aloud cues (round b): what the transcript around the quote + // says about whose words it is. Dropped, or kept to check by ear. + const cues = !why && raMode !== "off" ? readAloudCues({ before: around!.before, quote, after: around!.after, hosts: hostNames }) : []; + if (cues.length && raMode === "drop") why = `read aloud: ${cuesLine(cues)}`; + // The neutral form: the model's topic label, held down by code, + // and the line code writes around the quote. + let label: TopicLabel | undefined; + if (neutral && !why) { + label = topicLabel(raw.topic, { fallback: runTopic, hosts: hostNames, ground: [quote, around!.before.slice(-GATE_CHARS), title, question, runTopic, ...terms] }); + claim = neutralSentence({ title, date: v.date, topic: label.label }); + } const at = sec ?? ch[0]![0]; batchLines.push(`${v.id} @ ${mmss(at)} “${quote}” — ${claim || "(no claim)"}${why ? ` [dropped: ${why}]` : ""}`); if (why) { @@ -620,7 +664,16 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T h.trace({ t: "check", quote, cite: { channel: slug, video: v.id, start: at }, ok: false, reason: why, stage: "extract", dropped: true, claim }); continue; } - h.trace({ t: "check", quote, cite: { channel: slug, video: v.id, start: at }, ok: true, reason: "verbatim in its window", stage: "extract", claim }); + h.trace({ + t: "check", + quote, + cite: { channel: slug, video: v.id, start: at }, + ok: true, + reason: `verbatim in its window${cues.length ? `; read-aloud cue: ${cuesLine(cues)} — to check by ear` : ""}${label?.from === "fallback" ? `; topic label refused (${label.why}), the run's topic used` : ""}`, + stage: "extract", + claim, + }); + if (cues.length) event({ kind: "read-aloud", video: v.id, quote, cues }); kept.push({ video: v.id, title, @@ -631,10 +684,12 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T claim, sec: sec!, strength: Math.round(Number(raw.strength) || 2), - flags: lintClaim(claim, quote), + flags: neutral ? [] : lintClaim(claim, quote), before: around!.before, after: around!.after, gate: gate!, + ...(label ? { label } : {}), + ...(cues.length ? { readAloud: cues, mark: true } : {}), }); } } @@ -689,8 +744,10 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T // the seconds). kept.sort((a, b) => b.strength - a.strength || a.date.localeCompare(b.date) || a.video.localeCompare(b.video) || a.sec - b.sec); const host = askedAboutName(question) ?? "the channel's host (its own voice)"; - const toCheck = kept.slice(0, MAX_MEANING_CHECKS); - const unchecked = kept.length - toCheck.length; + // The neutral form has no drafted sentence to check: no call. Its items + // are stored the same way (items.jsonl), with the label and the cues. + const toCheck = neutral ? [] : kept.slice(0, MAX_MEANING_CHECKS); + const unchecked = neutral ? 0 : kept.length - toCheck.length; const items: Record<string, unknown>[] = []; const tally: Record<string, number> = {}; const passed: Kept[] = []; @@ -711,21 +768,48 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const seconds = Math.round((Date.now() - t0) / 100) / 10; const decision = decideMeaning(answer, { sentence: r.claim, quote: r.quote, before: r.before, after: r.after }); tally[decision.action] = (tally[decision.action] ?? 0) + 1; - items.push({ video: r.video, sec: r.sec, quote: r.quote, claim: r.claim, gate: r.gate, before: r.before, after: r.after, prompt: user, answer, decision, seconds }); + items.push({ video: r.video, sec: r.sec, quote: r.quote, claim: r.claim, gate: r.gate, before: r.before, after: r.after, prompt: user, answer, decision, seconds, ...(r.readAloud ? { readAloud: r.readAloud } : {}) }); h.trace({ t: "meaning", video: r.video, sec: r.sec, quote: r.quote, answer, action: decision.action, why: decision.why, ...(decision.action !== "drop" && decision.sentence !== r.claim ? { from: r.claim, to: decision.sentence } : {}), seconds }); if (decision.action === "drop") { dropped.push({ video: r.video, quote: r.quote, why: `meaning check: ${decision.why}` }); event({ kind: "dropped", why: `meaning check: ${decision.why}`, video: r.video, quote: r.quote, claim: r.claim }); continue; } - passed.push({ ...r, claim: decision.sentence.replace(/"/g, "'"), meaning: { answer, decision, seconds, drafted: r.claim }, ...(decision.action === "mark" ? { mark: true } : {}) }); + passed.push({ ...r, claim: decision.sentence.replace(/"/g, "'"), meaning: { answer, decision, seconds, drafted: r.claim }, ...(decision.action === "mark" || r.mark ? { mark: true } : {}) }); + } + if (neutral) { + for (const r of kept) { + items.push({ + video: r.video, + sec: r.sec, + quote: r.quote, + claim: r.claim, + form: "neutral", + topic: r.label?.label, + ...(r.label?.from === "fallback" ? { topicRefused: r.label.why } : {}), + gate: r.gate, + before: r.before, + after: r.after, + ...(r.readAloud ? { readAloud: r.readAloud } : {}), + decision: r.mark ? { action: "mark", why: `read-aloud cue: ${cuesLine(r.readAloud ?? [])}` } : { action: "keep", why: "verbatim, on the question, no read-aloud cue" }, + }); + } } await writeIterationFile(h.article, h.n, "items.jsonl", items.map((x) => JSON.stringify(x)).join("\n") + (items.length ? "\n" : ""), h.paths); - const tallyLine = Object.entries(tally).map(([k, n]) => `${n} ${k === "mark" ? "marked check by ear" : k === "keep" ? "kept" : k === "rewrite" ? "rewritten" : k === "drop" ? "dropped" : k}`).join(", "); - h.log(`meaning check: ${toCheck.length} item(s): ${tallyLine}${unchecked ? `; ${unchecked} past the budget of ${MAX_MEANING_CHECKS} not checked (left out)` : ""}`); - h.check({ name: "meaning", ok: !tally["check failed"], detail: `${toCheck.length} checked: ${tallyLine}${unchecked ? `; ${unchecked} not checked` : ""}` }); - kept.splice(0, kept.length, ...passed); - if (kept.length < minKept) return nothingFound("were verbatim, on the question and passed the meaning check"); + if (!neutral) { + const tallyLine = Object.entries(tally).map(([k, n]) => `${n} ${k === "mark" ? "marked check by ear" : k === "keep" ? "kept" : k === "rewrite" ? "rewritten" : k === "drop" ? "dropped" : k}`).join(", "); + h.log(`meaning check: ${toCheck.length} item(s): ${tallyLine}${unchecked ? `; ${unchecked} past the budget of ${MAX_MEANING_CHECKS} not checked (left out)` : ""}`); + h.check({ name: "meaning", ok: !tally["check failed"], detail: `${toCheck.length} checked: ${tallyLine}${unchecked ? `; ${unchecked} not checked` : ""}` }); + kept.splice(0, kept.length, ...passed); + if (kept.length < minKept) return nothingFound("were verbatim, on the question and passed the meaning check"); + } + const nReadAloud = dropped.filter((d) => d.why.startsWith("read aloud")).length; + const nByEar = kept.filter((r) => r.readAloud?.length).length; + if (raMode !== "off") { + const line = `read-aloud cues (${raMode}): ${raMode === "drop" ? `${nReadAloud} quote(s) dropped` : `${nByEar} quote(s) kept to check by ear`}`; + h.log(line); + h.check({ name: "read-aloud", ok: true, detail: line }); + } // 4. group and title (the model); counts, balance and caps in code // "Check by ear" items are never grouped (never in the first section): @@ -739,12 +823,12 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T const pool = trimmed .slice(0, MAX_CLAIMS_TOTAL) .sort((a, b) => a.date.localeCompare(b.date) || a.video.localeCompare(b.video) || a.sec - b.sec); - const listing = pool.map((r, i) => `${i + 1}. (${r.date}) ${r.claim}`).join("\n"); + const listing = pool.map((r, i) => (neutral ? `${i + 1}. (${r.date}) ${r.label!.label}: ${r.quote.split(" ").slice(0, 24).join(" ")}` : `${i + 1}. (${r.date}) ${r.claim}`)).join("\n"); let best: { score: number; g: { title?: unknown; sections?: unknown } } | null = null; for (let attempt = 0; attempt < (pool.length ? 2 : 0); attempt++) { let g: { title?: unknown; sections?: unknown }; try { - g = await ask(h, model, GROUP_SYSTEM, `Research question: ${question}\n\nFindings:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`, true); + g = await ask(h, model, neutral ? NEUTRAL_GROUP_SYSTEM : GROUP_SYSTEM, `Research question: ${question}\n\n${neutral ? "Quotes" : "Findings"}:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`, true); } catch (e) { if (deps.signal?.aborted) throw e; event({ kind: "group-failed", error: (e as Error).message }); @@ -760,7 +844,10 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T if (placed.size >= pool.length * 0.8 && biggest <= 0.7 * pool.length) break; } const g = best?.g ?? { title: question, sections: [] }; - const title = (String(g.title ?? "") || question).replace(/["“”#]/g, "").trim().slice(0, 90) || question.slice(0, 90); + // The neutral form's title is code's too: the topic and whose recordings. + const title = neutral + ? neutralTitle(runTopic, channelNames.map((c) => c.name || c.slug)) + : (String(g.title ?? "") || question).replace(/["“”#]/g, "").trim().slice(0, 90) || question.slice(0, 90); const raw = ((Array.isArray(g.sections) ? g.sections : []) as { heading?: unknown; findings?: unknown }[]) .slice(0, MAX_SECTIONS) .map((s) => ({ @@ -775,7 +862,10 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T }); let sections = raw.map((s, i) => ({ heading: s.heading, nums: s.nums.filter((n) => home.get(n) === i) })); const rest = pool.map((_, i) => i + 1).filter((n) => !home.has(n)); - if (rest.length) sections.push({ heading: "Other findings", nums: rest }); + // A heading that says who said or thinks something is not the neutral + // form's: the commonest label of its quotes instead. + if (neutral) sections = sections.map((s) => ({ ...s, heading: neutralHeading(s.heading, s.nums.map((n) => pool[n - 1]!.label!.label), hostNames).slice(0, 60) })); + if (rest.length) sections.push({ heading: neutral ? "Other quotes" : "Other findings", nums: rest }); sections = sections.filter((s) => s.nums.length); let leftOut = kept.length - pool.length - marked.length + unchecked; for (const s of sections) { @@ -820,6 +910,9 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T leftOut, partial, todo: todo.length, + neutral, + readAloud: raMode, + nReadAloud, }; let md = writeMarkdown(secs, { ...ctx, dropped: dropped.length }); await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths); @@ -878,14 +971,31 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T ? `${flagged.length} claim(s) to read against their quote: ${flagged.slice(0, 3).map((r) => `${r.claim.slice(0, 50)} (${r.flags[0]})`).join("; ")}` : "no claim flagged", }); + // A quote kept on a read-aloud cue carries the flag in the report's data + // (a pill on the claim's card), not only in its words. + const byEar = cited.filter((r) => r.readAloud?.length); + if (byEar.length) flagReadAloud(report as Report, byEar); await writeIterationFile(h.article, h.n, "report.json", report, h.paths); traceReport(h.trace, report as Report); return { status: "done", - summary: `“${title}”: ${cited.length} claim(s) in ${secs.length} section(s) from ${new Set(cited.map((r) => r.video)).size} video(s); ${dropped.length} dropped, ${flagged.length} flagged`, + summary: + `“${title}”: ${cited.length} claim(s) in ${secs.length} section(s) from ${new Set(cited.map((r) => r.video)).size} video(s); ${dropped.length} dropped, ${flagged.length} flagged` + + (raMode === "flag" ? `, ${byEar.length} to check by ear (read-aloud cue)` : raMode === "drop" ? `, ${nReadAloud} of the dropped on a read-aloud cue` : ""), }; } +// The claims whose citation is one of these records' quotes get the flag. +function flagReadAloud(report: Report, recs: readonly Kept[]): void { + const keys = new Set(recs.map((r) => `${r.video}|${norm(r.quote)}`)); + const hit = new Set<string>(); + for (const [cid, c] of Object.entries(report.citations ?? {})) { + const q = (c as { quote?: string }).quote; + if ((c.kind === "video" || c.kind === "audio") && q && keys.has(`${c.id}|${norm(q)}`)) hit.add(cid); + } + for (const s of report.sections ?? []) for (const k of s.claims ?? []) if ((k.citations ?? []).some((c) => hit.has(c))) k.flag = READ_ALOUD_FLAG; +} + function citeLabel(r: Kept): string { return `${r.title.replace(/[[\]()]/g, "").trim().slice(0, 80)} @ ${mmss(r.sec)}`; } @@ -911,10 +1021,14 @@ function writeMarkdown( leftOut: number; partial: string[]; todo: number; + neutral?: boolean; + readAloud?: ReadAloudMode; + nReadAloud?: number; }, ): string { const cited = secs.flatMap((s) => s.recs); const md = [`# ${c.title}`, "", `Question: ${c.question}`, ""]; + const byEar = cited.filter((r) => r.readAloud?.length).length; for (const s of secs) { md.push(`## ${s.heading}`, ""); for (const r of s.recs) md.push(`- ${r.mark ? `${CHECK_BY_EAR} ` : ""}${r.claim} "${r.quote}" — [${citeLabel(r)}](${momentHref(c.origin, r.slug, r.video, r.sec)})`); @@ -927,7 +1041,14 @@ function writeMarkdown( `Searched ${scope} for ${c.terms.join(", ")}. ${c.nEnum} video(s) matched; ${c.read} read (${c.nChunks} excerpt(s), ` + `${c.nRelevant} judged relevant); ${new Set(cited.map((r) => r.video)).size} cited, ${cited.length} quote(s). Quotes ` + `found ${c.kept}, dropped ${c.dropped} (not verbatim, unusable, or not passing the quote check), ${c.leftOut} left out ` + - `by the caps. Drafted by ${c.model}; every quote was checked word for word against its transcript.` + + `by the caps. ` + + (c.neutral + ? `The quotes were picked and their topics labelled by ${c.model}; each line, its citation and its link are written by code and say where the words are, not who is speaking; every quote was checked word for word against its transcript.` + : `Drafted by ${c.model}; every quote was checked word for word against its transcript.`) + + (c.readAloud === "flag" && byEar + ? ` ${byEar} quote(s) are marked to check by ear: the transcript around them has a sign of reading aloud (a tweet, a headline, an article, “it says”), so the words may not be the speaker's own.` + : "") + + (c.readAloud === "drop" && c.nReadAloud ? ` ${c.nReadAloud} of the dropped quote(s) had a sign of reading aloud around them (a tweet, a headline, an article, “it says”).` : "") + (c.partial.length ? ` COVERAGE PARTIAL for: ${c.partial.join(", ")}.` : "") + (c.nEnum > c.todo ? ` Only ${c.todo} of the ${c.nEnum} matching videos were read.` : ""), "", diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -42,6 +42,7 @@ import { GENERATION_CUT_FIELD_DOCS, GENERATION_TRIAGE_FIELD_DOCS, GENERATION_FRAMES_FIELD_DOCS, + GENERATION_LOCAL_SWEEP_FIELD_DOCS, GENERATION_SETTINGS_FIELD_DOCS, GENERATION_WEB_FIELD_DOCS, GENERATION_VERDICTS_FIELD_DOCS, @@ -340,6 +341,7 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, { path: "generation.verdicts.window", docs: GENERATION_VERDICT_WINDOW_FIELD_DOCS, defaults: fromObject(d.generation.verdicts.window) }, { path: "generation.triage", docs: GENERATION_TRIAGE_FIELD_DOCS, defaults: fromObject(d.generation.triage) }, { path: "generation.frames", docs: GENERATION_FRAMES_FIELD_DOCS, defaults: fromObject(d.generation.frames) }, + { path: "generation.localSweep", docs: GENERATION_LOCAL_SWEEP_FIELD_DOCS, defaults: fromObject(d.generation.localSweep) }, ], clips: [ { diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -101,6 +101,7 @@ export { GENERATION_VERDICT_WINDOW_FIELD_DOCS, GENERATION_TRIAGE_FIELD_DOCS, GENERATION_FRAMES_FIELD_DOCS, + GENERATION_LOCAL_SWEEP_FIELD_DOCS, type GenerationSettings, } from "./generationSettings"; export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings"; diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts @@ -392,6 +392,103 @@ test("sweep-pipeline gate (D2 item 2): an item with no rare term in its quote or assert.equal(Object.keys(report.citations ?? {}).length, 0); }); +// The neutral form's model answers: the terms with the topic, one extract of +// quotes with topic labels (no claim), one grouping. No meaning check. +const neutralTurns = async () => { + const r = await run("sweep-pipeline"); + const turns = [structuredClone(r.turns[0]), structuredClone(r.turns[1]), structuredClone(r.turns.at(-1))]; + turns[0].message.content = JSON.stringify({ terms: ["contest", "judges"], topic: "the pie contest" }); + turns[1].message.content = JSON.stringify({ + relevant: true, + items: [ + { quote: "I did not enter the contest this year", topic: "entering the pie contest", on_topic: true, strength: 3 }, + // A label that says who thinks what: code uses the run's topic. + { quote: "the judges were friends of mine so it felt wrong", topic: "the baker says the judges are corrupt", on_topic: true, strength: 3 }, + { quote: "I have never met the other finalist", topic: "meeting the finalist", on_topic: true, strength: 2 }, + ], + }); + // A heading that attributes, and a title: both replaced by code. + turns[2].message.content = JSON.stringify({ title: "The baker slams the judges", sections: [{ heading: "What the baker thinks of the judges", findings: [1, 2] }] }); + return { r, turns }; +}; + +test("sweep-pipeline, the speaker-neutral form (D2 round b): code writes 'In <title> (<date>), on <topic>:' around each quote; no claim is drafted and no meaning check is called; a quote with a read-aloud cue is kept flagged, in the words and in the data", async () => { + const { r, turns } = await neutralTurns(); + ol.push(...turns); + const it = await createIteration("synth-neutral", { kind: "sweep", model: r.model, question: "What has the baker said about the pie contest?", scope: { channels: r.channels } }, paths); + const d = deps(); + // "finalist" stands for the host's name: a quote that names the host in the third person is a read-aloud cue. + const out = await runTask({ task: "sweep-pipeline", article: "synth-neutral", n: it.n, origin: ORIGIN, claimForm: "neutral", readAloud: "flag", hosts: ["finalist"] }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + assert.equal(ol.remaining(), 0); + const after = (await readIteration("synth-neutral", it.n, paths))!; + assert.equal(after.usage["qwen3:8b"]!.calls, 3, "terms, one extract, one grouping — no meaning check"); + // The extract call asked for a topic label, not a claim. + const extract = ol.requests.findLast((q: { messages?: unknown }) => /Each topic is a label of two to six words/.test(JSON.stringify(q.messages ?? ""))); + assert.ok(extract, "the neutral extract prompt was sent"); + assert.deepEqual(extract.format.properties.items.items.required, ["quote", "topic", "on_topic", "strength"]); + const md = (await readIterationFile("synth-neutral", it.n, "sweep.md", paths))!; + assert.match(md, /^# The pie contest: quotes from Synth Kitchen\n/, "the title is code's"); + assert.ok(md.includes(`- In Pie stream (10 February 2026), on entering the pie contest: "I did not enter the contest this year" — [Pie stream @ 0:10](${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=10)`), md); + assert.ok(md.includes('- In Pie stream (10 February 2026), on the pie contest: "the judges were friends of mine so it felt wrong"'), "a label that attributes is the run's topic"); + assert.ok(!/\b(says|said|thinks|believes|slams)\b/i.test(md.split("## Coverage")[0]!.replace(/^Question: .*$/m, "")), "no verb of saying anywhere in the findings"); + assert.match(md, /## Entering the pie contest\n/, "an attributing heading is the commonest label"); + assert.match(md, /## To check by ear\n\n- Check by ear: In Pie stream \(10 February 2026\), on the pie contest: "I have never met the other finalist"/); + assert.match(md, /each line, its citation and its link are written by code and say where the words are, not who is speaking/); + assert.match(md, /1 quote\(s\) are marked to check by ear: the transcript around them has a sign of reading aloud/); + assert.match(out.summary, /3 claim\(s\) in 2 section\(s\) from 1 video\(s\); 0 dropped, 0 flagged, 1 to check by ear \(read-aloud cue\)$/); + // The data: the claim's flag, the item's cue, the checks. + const report = JSON.parse((await readIterationFile("synth-neutral", it.n, "report.json", paths))!); + const claims = report.sections.flatMap((x: { claims?: { text: string; flag?: string }[] }) => x.claims ?? []); + assert.deepEqual(claims.map((c: { flag?: string }) => c.flag ?? null), [null, null, "check by ear: may be read aloud"]); + assert.equal(Object.keys(report.citations).length, 3); + const items = (await readIterationFile("synth-neutral", it.n, "items.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l)); + assert.deepEqual(items.map((x) => [x.form, x.topic, x.decision.action]), [ + ["neutral", "entering the pie contest", "keep"], + ["neutral", "the pie contest", "keep"], + ["neutral", "the pie contest", "mark"], + ]); + assert.equal(items[1].topicRefused, "the label says who says or thinks something"); + assert.deepEqual(items[2].readAloud, [{ cue: "names the host", where: "quote", match: "finalist" }]); + assert.deepEqual(after.checks?.map((c) => [c.name, c.ok]), [["read-aloud", true], ["convert", true], ["quotes", true], ["lint", true]]); + const trace = await traceOf("synth-neutral", it.n); + assert.ok(!trace.some((e) => e.t === "meaning")); + assert.match(trace.find((e) => e.t === "check" && e.quote === "I have never met the other finalist")!.reason, /read-aloud cue: names the host \(quote: “finalist”\) — to check by ear/); +}); + +test("sweep-pipeline read-aloud cues, drop (D2 round b): the quote is left out, with the cue as the reason", async () => { + const { r, turns } = await neutralTurns(); + ol.push(...turns.slice(0, 2)); + const it = await createIteration("synth-neutral-drop", { kind: "sweep", model: r.model, question: "What has the baker said about the pie contest?", scope: { channels: r.channels } }, paths); + const d = deps(); + const out = await runTask({ task: "sweep-pipeline", article: "synth-neutral-drop", n: it.n, origin: ORIGIN, claimForm: "neutral", readAloud: "drop", hosts: ["finalist"] }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const trace = await traceOf("synth-neutral-drop", it.n); + assert.deepEqual( + trace.filter((e) => e.t === "check" && e.dropped).map((e) => [e.quote, e.reason]), + [["I have never met the other finalist", "read aloud: names the host (quote: “finalist”)"]], + ); + // Two left: fewer than a report needs, said so (never padded with the dropped one). + assert.match(out.summary, /^Nothing usable found: .* 2 passage\(s\) were verbatim and on the question/); + assert.equal(ol.remaining(), 0, "no grouping call"); +}); + +test("sweep-pipeline read-aloud cues in the sentence form (D2 round b): a cued quote goes through the meaning check and stays marked to check by ear", async () => { + const r = await run("sweep-pipeline"); + ol.push(...r.turns); + const it = await createIteration("synth-sentence-flag", { kind: "sweep", model: r.model, question: r.question, scope: { channels: r.channels } }, paths); + const d = deps(); + // "friends" stands for the host's name. + const out = await runTask({ task: "sweep-pipeline", article: "synth-sentence-flag", n: it.n, origin: ORIGIN, readAloud: "flag", hosts: ["friends"] }, d); + assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`); + const md = (await readIterationFile("synth-sentence-flag", it.n, "sweep.md", paths))!; + assert.match(md, /## To check by ear\n\n- Check by ear: She says the judges were friends of hers, so entering felt wrong to her\. "the judges were friends of mine so it felt wrong"/); + const report = JSON.parse((await readIterationFile("synth-sentence-flag", it.n, "report.json", paths))!); + const flags = report.sections.flatMap((x: { claims?: { text: string; flag?: string }[] }) => x.claims ?? []).filter((c: { flag?: string }) => c.flag); + assert.equal(flags.length, 1, "the meaning check's own mark carries no flag; the read-aloud one does"); + assert.match(flags[0].text, /the judges were friends of hers/); +}); + test("sweep-pipeline selection (D2 item 1): the subject's own name and generic words are never searched; the read is traced with its reasons", async () => { const r = await run("sweep-pipeline"); const turns = structuredClone(r.turns); diff --git a/settings.json.example b/settings.json.example @@ -359,6 +359,10 @@ "localModel": "qwen2.5vl:7b", "maxUsd": 5, "everySeconds": 10 + }, + "localSweep": { + "claimForm": "neutral", + "readAloud": "flag" } }, "clips": {