commit 19b847b14cbf9fab9cede81b684441473706dff6
parent d58e3a16f125a406481b60999d0af51007252b29
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 12 Nov 2026 10:49:17 -0500
Merge main (42d362f4) into lane/characters-c3: editor/CHANGELOG.md keeps both sides; SETTINGS.md, COMMANDS.md regenerated
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
54 files changed, 3543 insertions(+), 199 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -44,6 +44,7 @@ Run from the repo root (in the container: `docker compose exec editor pnpm archi
| `archilyzer gen policy` | `[--json]` | the generation policy: where each task runs (code = Claude Code, api = the Claude API, local = the local model), the models, the caps and the day's Claude API spend — from the editor, or settings.json when none answers |
| `archilyzer gen preset` | `<code\|balanced\|api\|local>` | route every generation task by a preset (its routes are written; settings.generation.routes) |
| `archilyzer gen set` | `<task> <code\|api\|local>` | route one generation task (sweep, revise-report, revise-video, research; the media drafts cut, onscreen, teaser, flips, threads, narrate, youtube, social) |
+| `archilyzer gen local-sweep` | `[--form neutral\|sentence] [--read-aloud flag\|drop\|off]` | the local route's sweep (settings.generation.localSweep): who writes a finding's line — neutral: code (In <title> (<date>), on <topic>: "<quote>"; the model only picks the quote and labels its topic), sentence: the model, judged by a meaning check — and what happens to a quote whose transcript has a sign of reading aloud around it (a tweet, a headline, "it says"): flag keeps it marked to check by ear, drop leaves it out, off does not look; bare, what they are |
| `archilyzer gen run` | `<task> [<question\|feedback>] --article <id> [--via api\|local\|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--entries a,b] [--force] [--autonomy propose\|limits\|auto] [--source <handle>\|--build <id>] [--wait]` | enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube, social) is a step on --iteration <n>, takes no words, --entries limits it, --force re-drafts only fields a model drafted; EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once) |
| `archilyzer reports move-to-articles` | `[--keep <site>/<id>,…] [--drafts] [--apply]` | ONE-OFF (release 26): every report a site lists, but the pages named by --keep, moved to transcripts/reports/ as an article — audience private, published in reports/index.json in the sites' order (a report with problems as a draft), dropped from its site; --drafts moves unlisted ones too. A dry run printing the plan unless --apply *(passthrough)* |
| `archilyzer reports convert` | `<sweep\|ask\|manifest> <in> --out <report.json> [--channels-dir <dir>] [--id <id>] [--title <title>]` | a /sweep report (markdown), an /ask answer or a report-to-video manifest as a report.json, written only when it validates (--channels-dir: widen spans from the cues, find posts' channels) |
diff --git a/OPERATING.md b/OPERATING.md
@@ -907,6 +907,24 @@ pnpm ops get generation-usage
while a transcription or a synthesis runs, and the model is unloaded when its job ends. A local sweep is the
code-driven pipeline (the model proposes terms, judges, extracts and groups; code reads, cites and checks). It
reads the web through the editor's paced `web-search` / `web-fetch`; a Claude model uses its own web search.
+- **A local sweep's findings are written by code and say where the words are, not who said them:**
+ `In <recording's title> (<date>), on <topic>: "<quote>"`. The model copies the quote and labels its topic; a small
+ model cannot tell the host reading a tweet or a headline aloud from the host speaking, so it drafts no "He says …"
+ sentence. A quote whose transcript has a sign of reading aloud around it (a tweet, likes read out, an article being
+ introduced, "it says", "according to", a clip, the host named in the third person) is kept in a last section,
+ **To check by ear**, with the flag `check by ear: may be read aloud` on its claim — listen to those before
+ filming; a reading nothing in the transcript announces is not caught. A topic label and a section heading are
+ noun-phrase topics held by code — no pronoun, no word of saying, feeling or judging ("comments", "reaction",
+ "blames", "hates"), no "is / was / has", no "the actress's …", every word found in the quotes, the titles or the
+ question — else code writes them. A refresh sweeps in the same form, and a revision keeps the lines, headings and
+ title code's and the flags on their claims. Both are `settings.generation.localSweep`:
+
+ ```sh
+ pnpm archilyzer gen local-sweep # what they are
+ pnpm archilyzer gen local-sweep --form neutral --read-aloud flag # the defaults
+ pnpm archilyzer gen local-sweep --read-aloud drop # leave such quotes out instead
+ pnpm archilyzer gen local-sweep --form sentence # the drafted sentence and its meaning check
+ ```
- The stopgap (`~/reports/local-reports`) is retired: its kept runs were imported (release 27,
`pnpm archilyzer reports import-local-runs`) and the directory deleted (release 28). The repo's
`.claude/commands/gen.md` is the one `/gen` (the stopgap's user-level copy is deleted too).
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`
@@ -1255,6 +1256,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
@@ -1337,6 +1345,10 @@ Default:
"localModel": "qwen2.5vl:7b",
"maxUsd": 5,
"everySeconds": 10
+ },
+ "localSweep": {
+ "claimForm": "neutral",
+ "readAloud": "flag"
}
}
```
diff --git a/common/bin/archilyzer.ts b/common/bin/archilyzer.ts
@@ -483,6 +483,14 @@ export const COMMANDS: Command[] = [
run: async (ctx) => (await import("./gen")).genSetRow(ctx),
},
{
+ path: ["gen", "local-sweep"],
+ usage:
+ "[--form neutral|sentence] [--read-aloud flag|drop|off] the local route's sweep (settings.generation.localSweep): who writes a finding's line — neutral: code (In <title> (<date>), on <topic>: \"<quote>\"; the model only picks the quote and labels its topic), sentence: the model, judged by a meaning check — and what happens to a quote whose transcript has a sign of reading aloud around it (a tweet, a headline, \"it says\"): flag keeps it marked to check by ear, drop leaves it out, off does not look; bare, what they are",
+ flags: { form: "string", "read-aloud": "string" },
+ maxPositionals: 0,
+ run: async (ctx) => (await import("./gen")).genLocalSweepRow(ctx),
+ },
+ {
path: ["gen", "run"],
usage:
"<task> [<question|feedback>] --article <id> [--via api|local|code] [--model <m>] [--iteration <n>] [--channels a,b] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--copy-of <n>] [--max-usd <usd>] [--cards a,b] [--entries a,b] [--force] [--autonomy propose|limits|auto] [--source <handle>|--build <id>] [--wait] enqueue a report-draft job as `pnpm ops report-draft` does (--wait follows it; `sweep --iteration <n>` continues research run n); a media draft (cut, onscreen, teaser, flips, threads, narrate, youtube, social) is a step on --iteration <n>, takes no words, --entries limits it, --force re-drafts only fields a model drafted; EXITS 3 and runs nothing when the task is routed to code (Claude Code does it; --via overrides once)",
diff --git a/common/bin/gen.test.ts b/common/bin/gen.test.ts
@@ -32,11 +32,13 @@ const BALANCED: GenPolicy = {
routes: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api" },
models: { api: "claude-sonnet-5-5", local: "qwen3:8b", extractor: "claude-haiku-4-5" },
caps: { sweep: 5, revision: 2, narration: 1, daily: 20, max: 10 },
+ localSweep: { claimForm: "neutral", readAloud: "flag" },
};
// A store in memory, recording what it was asked to write.
function memoryStore(policy: GenPolicy = BALANCED, offline = false) {
const written: Record<string, string>[] = [];
+ const localSweeps: NonNullable<GenPolicy["localSweep"]>[] = [];
let p = structuredClone(policy);
const store: GenStore = {
where: offline ? "settings.json (test)" : "the editor at http://editor.test",
@@ -48,8 +50,13 @@ function memoryStore(policy: GenPolicy = BALANCED, offline = false) {
p = { ...p, routes, preset: "custom" };
return p;
},
+ writeLocalSweep: async (ls) => {
+ localSweeps.push(ls);
+ p = { ...p, localSweep: ls };
+ return p;
+ },
};
- return { store, written };
+ return { store, written, localSweeps };
}
test("gen policy prints the routes, models, caps and today's spend", async () => {
@@ -85,6 +92,27 @@ test("gen preset writes the preset's routes; gen set writes one; nonsense is a u
assert.equal(m.written.length, 2);
});
+test("gen local-sweep shows the claim form and the read-aloud rule, writes one or both, and refuses a value it does not know", async () => {
+ const c = capture();
+ const m = memoryStore();
+ const deps = { store: async () => m.store, runOps: async () => 0, out: c.out };
+ assert.equal(await gen.localSweepMain({}, deps), 0);
+ assert.match(c.lines[0]!, /^local sweep: claim form neutral \(code writes each line/);
+ assert.match(c.lines[1]!, /a quote that may be read aloud: flag \(kept, marked to check by ear\)/);
+ assert.equal(m.localSweeps.length, 0, "a bare call writes nothing");
+ assert.equal(await gen.localSweepMain({ readAloud: "drop" }, deps), 0);
+ assert.deepEqual(m.localSweeps[0], { claimForm: "neutral", readAloud: "drop" });
+ assert.equal(await gen.localSweepMain({ form: "sentence", readAloud: "off" }, deps), 0);
+ assert.deepEqual(m.localSweeps[1], { claimForm: "sentence", readAloud: "off" });
+ assert.ok(c.lines.includes("(written to the editor at http://editor.test)"));
+ for (const o of [{ form: "poem" }, { readAloud: "maybe" }]) assert.equal(await gen.localSweepMain(o, deps), 2, JSON.stringify(o));
+ assert.equal(m.localSweeps.length, 2);
+ // The policy shows it too.
+ const p = capture();
+ await gen.policyMain({ json: false }, { ...deps, out: p.out });
+ assert.ok(p.lines.some((l) => l.startsWith("local sweep: claim form sentence")));
+});
+
test("gen run exits 3 and runs nothing when the task is routed to code", async () => {
const c = capture();
const ran: string[][] = [];
@@ -198,6 +226,10 @@ test("the offline store reads and writes settings.json through the settings writ
const c = capture();
assert.equal(await gen.setMain({ preset: "api" }, { store: async () => store, runOps: async () => 0, out: c.out }), 0);
assert.equal((await store.read()).preset, "api");
+ // The local sweep's two knobs: the defaults, then written through the same writer.
+ assert.deepEqual((await store.read()).localSweep, { claimForm: "neutral", readAloud: "flag" });
+ assert.equal(await gen.localSweepMain({ form: "sentence", readAloud: "drop" }, { store: async () => store, runOps: async () => 0, out: c.out }), 0);
+ assert.deepEqual(JSON.parse(readFileSync(path.join(ROOT, "settings.json"), "utf8")).generation.localSweep, { claimForm: "sentence", readAloud: "drop" });
});
test("gen run research takes --autonomy; nothing else does", async () => {
diff --git a/common/bin/gen.ts b/common/bin/gen.ts
@@ -4,6 +4,9 @@
// archilyzer gen policy [--json] the routes, models, caps and the day's API spend
// archilyzer gen preset code|balanced|api|local route every task at once
// archilyzer gen set <task> code|api|local route one task
+// archilyzer gen local-sweep [--form neutral|sentence] [--read-aloud flag|drop|off]
+// the local sweep's claim form and read-aloud rule
+// (settings.generation.localSweep); bare: what they are
// archilyzer gen run <task> [<question|feedback>] --article <id> [--via api|local|code] […] [--wait]
// enqueue a report-draft job (`pnpm ops report-draft`);
// a media draft (cut, onscreen, teaser, flips, threads,
@@ -32,6 +35,11 @@ import type { CommandContext } from "./_cli";
import type { FlagValue } from "./_parseFlags";
import { REPO_ROOT, runChild } from "./_spawnBin";
import {
+ CLAIM_FORMS,
+ READ_ALOUD_MODES,
+ type ClaimForm,
+ type GenerationLocalSweep,
+ type ReadAloudMode,
GENERATION_PRESETS,
GENERATION_PRESET_NAMES,
GENERATION_ROUTES,
@@ -49,6 +57,7 @@ export type GenPolicy = {
routes: Record<string, GenerationRoute>;
models: { api: string; local: string; extractor?: string };
caps?: Record<string, number>;
+ localSweep?: GenerationLocalSweep;
};
export type GenUsage = { day: string; usd: number; jobs: number; daily: number };
@@ -60,6 +69,7 @@ export type GenStore = {
read(): Promise<GenPolicy>;
usage(): Promise<GenUsage | null>;
writeRoutes(routes: Record<string, GenerationRoute>): Promise<GenPolicy>;
+ writeLocalSweep(localSweep: GenerationLocalSweep): Promise<GenPolicy>;
};
export type GenDeps = {
@@ -85,9 +95,29 @@ export function policyFrom(value: unknown): GenPolicy | null {
routes,
models: { api: m.api, local: m.local, ...(typeof m.extractor === "string" ? { extractor: m.extractor } : {}) },
...(v.caps && typeof v.caps === "object" ? { caps: v.caps as Record<string, number> } : {}),
+ ...(localSweepFrom(v.localSweep) ? { localSweep: localSweepFrom(v.localSweep)! } : {}),
};
}
+function localSweepFrom(value: unknown): GenerationLocalSweep | null {
+ const v = value && typeof value === "object" ? (value as Record<string, unknown>) : null;
+ if (!v || !(CLAIM_FORMS as readonly unknown[]).includes(v.claimForm) || !(READ_ALOUD_MODES as readonly unknown[]).includes(v.readAloud)) return null;
+ return { claimForm: v.claimForm as ClaimForm, readAloud: v.readAloud as ReadAloudMode };
+}
+
+const FORM_WORDS: Record<ClaimForm, string> = {
+ neutral: "neutral (code writes each line: In <title> (<date>), on <topic>: \"<quote>\")",
+ sentence: "sentence (the model drafts each claim; a meaning check judges it)",
+};
+const READ_ALOUD_WORDS: Record<ReadAloudMode, string> = {
+ flag: "flag (kept, marked to check by ear)",
+ drop: "drop (left out)",
+ off: "off (not looked for)",
+};
+export function formatLocalSweep(ls: GenerationLocalSweep): string[] {
+ return [`local sweep: claim form ${FORM_WORDS[ls.claimForm]}`, ` a quote that may be read aloud: ${READ_ALOUD_WORDS[ls.readAloud]}`];
+}
+
const usd = (n: number) => `$${n.toFixed(2)}`;
export function formatPolicy(p: GenPolicy, usage: GenUsage | null): string[] {
@@ -102,6 +132,7 @@ export function formatPolicy(p: GenPolicy, usage: GenUsage | null): string[] {
(typeof c.daily === "number" ? ` · ${c.daily > 0 ? `daily ${usd(c.daily)}` : "no daily cap"}` : ""),
);
}
+ if (p.localSweep) lines.push(...formatLocalSweep(p.localSweep));
if (usage) lines.push(`today ${usage.day} (UTC): ${usd(usage.usd)} on the Claude API in ${usage.jobs} job(s)`);
return lines;
}
@@ -171,6 +202,13 @@ export async function editorStore(env: NodeJS.ProcessEnv = process.env, fetchImp
if (!p) throw new Error("the editor's answer carried no generation block");
return p;
},
+ async writeLocalSweep(localSweep) {
+ const a = await call("POST", "/api/ops/settings", { patch: { generation: { localSweep } } });
+ if (a.kind !== "ok") throw fail(a);
+ const p = policyFrom((a.body.value as Record<string, unknown> | undefined)?.generation);
+ if (!p) throw new Error("the editor's answer carried no generation block");
+ return p;
+ },
};
}
@@ -194,6 +232,11 @@ export async function offlineStore(): Promise<GenStore> {
await writeSettings({ ...s, generation: { ...s.generation, routes: { ...s.generation.routes, ...routes } as typeof s.generation.routes } });
return read();
},
+ async writeLocalSweep(localSweep) {
+ const s = getSettings();
+ await writeSettings({ ...s, generation: { ...s.generation, localSweep } });
+ return read();
+ },
};
}
@@ -201,7 +244,7 @@ export async function defaultStore(env: NodeJS.ProcessEnv = process.env): Promis
return (await editorStore(env)) ?? (await offlineStore());
}
-// ─── The four verbs ───
+// ─── The verbs ───
export async function policyMain(o: { json: boolean }, deps: GenDeps): Promise<number> {
const out = deps.out ?? console;
@@ -247,6 +290,41 @@ export async function setMain(o: { preset?: string; task?: string; route?: strin
return 0;
}
+// `gen local-sweep`: the local sweep's claim form and what it does with a
+// quote that may be read aloud (settings.generation.localSweep). Bare: what
+// they are.
+export async function localSweepMain(o: { form?: string; readAloud?: string }, deps: GenDeps): Promise<number> {
+ const out = deps.out ?? console;
+ if (o.form !== undefined && !(CLAIM_FORMS as readonly string[]).includes(o.form)) {
+ out.error(`gen local-sweep: --form is one of ${CLAIM_FORMS.join(", ")}`);
+ return 2;
+ }
+ if (o.readAloud !== undefined && !(READ_ALOUD_MODES as readonly string[]).includes(o.readAloud)) {
+ out.error(`gen local-sweep: --read-aloud is one of ${READ_ALOUD_MODES.join(", ")}`);
+ return 2;
+ }
+ const store = await deps.store();
+ if ("error" in store) {
+ out.error(`gen local-sweep: ${store.error}`);
+ return 1;
+ }
+ const p = await store.read();
+ if (!p.localSweep) {
+ out.error(`gen local-sweep: ${store.where} carries no generation.localSweep (an editor older than this checkout?)`);
+ return 1;
+ }
+ if (o.form === undefined && o.readAloud === undefined) {
+ for (const l of [...formatLocalSweep(p.localSweep), `(from ${store.where})`]) out.log(l);
+ return 0;
+ }
+ const saved = await store.writeLocalSweep({
+ claimForm: (o.form as ClaimForm | undefined) ?? p.localSweep.claimForm,
+ readAloud: (o.readAloud as ReadAloudMode | undefined) ?? p.localSweep.readAloud,
+ });
+ for (const l of [...formatLocalSweep(saved.localSweep ?? p.localSweep), `(written to ${store.where})`]) out.log(l);
+ return 0;
+}
+
// The report-draft body from `gen run`'s words, or why not. The editor judges
// the rest (controller/reportDraft.ts parseReportDraftBody).
export function runBody(task: string, text: string | undefined, flags: Record<string, FlagValue>): Record<string, unknown> | { error: string } {
@@ -360,6 +438,12 @@ export async function genSetRow(ctx: CommandContext): Promise<number> {
const [task, route] = ctx.positionals;
return setMain({ ...(task ? { task } : {}), ...(route ? { route } : {}) }, defaultDeps(ctx));
}
+export async function genLocalSweepRow(ctx: CommandContext): Promise<number> {
+ const str = (k: string) => (typeof ctx.flags[k] === "string" ? (ctx.flags[k] as string).trim() : undefined);
+ const form = str("form");
+ const readAloud = str("read-aloud");
+ return localSweepMain({ ...(form !== undefined ? { form } : {}), ...(readAloud !== undefined ? { readAloud } : {}) }, defaultDeps(ctx));
+}
export async function genRunRow(ctx: CommandContext): Promise<number> {
const [task, text] = ctx.positionals;
return runMain({ ...(task ? { task } : {}), ...(text ? { text } : {}), flags: ctx.flags }, defaultDeps(ctx));
diff --git a/common/controller/buildIndexLocalRecording.test.ts b/common/controller/buildIndexLocalRecording.test.ts
@@ -39,7 +39,7 @@ const writeJson = (file: string, value: unknown) => {
};
const channel = "classroom";
const dataDirectory = path.join(paths.channelsDir, channel, "data");
-const transcript = "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nSynthetic classroom discovery phrase\n";
+const transcript = "WEBVTT\n\n00:00.000 --> 00:02.000\nSynthetic classroom discovery phrase\n";
const first = "local-" + "a".repeat(32), second = "local-" + "b".repeat(32);
const metadata = (id: string, recordedDate?: string) => prepareManualLocalRecordingMetadata({id,
filename: "Lesson 2020-01-01.mp4", recordedDate});
diff --git a/common/controller/localMediaImport.test.ts b/common/controller/localMediaImport.test.ts
@@ -17,7 +17,7 @@ async function fixture(t: TestContext) {
async function add(name: string, id = name) {
await writeFile(path.join(source, name + ".mp4"), "synthetic video");
await writeFile(path.join(source, name + ".info.json"), JSON.stringify({ id, title: "Synthetic", duration: 3, upload_date: "20261030", webpage_url: `https://www.youtube.com/watch?v=${id}` }));
- await writeFile(path.join(source, name + ".vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nSynthetic cue\n");
+ await writeFile(path.join(source, name + ".vtt"), "WEBVTT\n\n00:01.000 --> 00:02.000\nSynthetic cue\n");
}
return { root, source, paths, channel, config, add };
}
@@ -48,7 +48,7 @@ test("preview creates nothing; import then rescan detects additions without chan
});
test("changed transcript after preview is stale and no record is written", async (t) => {
const f=await fixture(t); await f.add("first"); const p=await previewLocalMedia(f.paths,"sample");
- await writeFile(path.join(f.source,"first.vtt"),"WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nChanged text\n");
+ await writeFile(path.join(f.source,"first.vtt"),"WEBVTT\n\n00:01.000 --> 00:02.000\nChanged text\n");
const result=await importLocalMedia(f.paths,"sample",selection(p));
assert.equal(result.records[0].status,"stale"); assert.equal(result.needsIndexUpdate,false);
assert.deepEqual(await readdir(f.channel),["config.json"]);
@@ -173,7 +173,7 @@ test("managed job fails honestly for a stale selection after publishing another
const f = await fixture(t); await f.add("first"); await f.add("second");
const p = await previewLocalMedia(f.paths, "sample");
const job = localMediaJobOptions(f.paths as Paths, "sample", selection(p));
- await writeFile(path.join(f.source, "second.vtt"), "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nChanged\n");
+ await writeFile(path.join(f.source, "second.vtt"), "WEBVTT\n\n00:01.000 --> 00:02.000\nChanged\n");
const log: string[] = [];
await assert.rejects(job.fn(line => log.push(line), new AbortController().signal, () => {}, jobContext()), /require review/);
assert.deepEqual(await readdir(path.join(f.channel, "data")), ["first"]);
diff --git a/common/controller/reportDraft.ts b/common/controller/reportDraft.ts
@@ -915,7 +915,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/controller/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -456,7 +456,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/generationSettings.test.ts b/common/lib/generationSettings.test.ts
@@ -197,6 +197,15 @@ 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);
+});
+
test("plannedModelOf (demo epic D3): a task's route and the model it will run on; code has none; a frame scan's vision model; the API needs a key", async () => {
const { plannedModelOf, sanitizeGeneration } = await import("./generationSettings");
const gen = sanitizeGeneration({ routes: { sweep: "code", narrate: "local", "revise-report": "api", frames: "local" }, models: { api: "claude-sonnet-5-5", local: "qwen2.5:7b" } });
diff --git a/common/lib/generationSettings.ts b/common/lib/generationSettings.ts
@@ -113,6 +113,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;
@@ -130,6 +146,7 @@ export type GenerationSettings = {
verdicts: GenerationVerdicts;
triage: GenerationTriage;
frames: GenerationFrames;
+ localSweep: GenerationLocalSweep;
};
export const DEFAULT_GENERATION_VERDICT_WINDOW: GenerationVerdictWindow = { mode: "seconds", seconds: 60 };
@@ -156,6 +173,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> = {
@@ -181,6 +199,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> = {
@@ -366,6 +393,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/localMedia.ts b/common/lib/localMedia.ts
@@ -32,16 +32,22 @@ export function coerceLocalMediaConfig(value: unknown): LocalMediaConfig | undef
return { sourceId: value.sourceId, directory,
...(value.playback === true ? { playback: true as const } : {}) };
}
+// Whether a library-relative path can be stored in a reference. Literal
+// filenames with '/' separators, never URL-decoded; both OSes' escape syntax
+// (\ and :) and control characters are refused regardless of the machine doing
+// the read. No path normalization: it would conceal traversal or change a
+// source name. The scan asks this too, so a recording whose name a reference
+// cannot hold is an issue in its preview, not a failed import.
+export function isExternalMediaRelativePath(relativePath: string): boolean {
+ return !!relativePath && relativePath.length <= 4096 && !/[\\:\x00-\x1f\x7f]/.test(relativePath)
+ && !relativePath.split("/").some((part) => !part || part === "." || part === "..")
+ && /\.mp4$/i.test(relativePath);
+}
export function coerceExternalMediaReference(value: unknown): ExternalMediaReference | null {
if (!record(value) || value.version !== 1 || value.kind !== "external"
|| !isLocalMediaSourceId(value.sourceId) || typeof value.relativePath !== "string") return null;
const relativePath = value.relativePath;
- // Store literal filenames using '/' separators, never URL-decode them.
- // Reject both OSes' escape syntax regardless of the machine doing the read.
- // No path normalization: it would conceal traversal or change a source name.
- if (!relativePath || relativePath.length > 4096 || /[\\:\x00-\x1f\x7f]/.test(relativePath)
- || relativePath.split("/").some((part) => !part || part === "." || part === "..")
- || !/\.mp4$/i.test(relativePath)) return null;
+ if (!isExternalMediaRelativePath(relativePath)) return null;
return { version: 1, kind: "external", sourceId: value.sourceId, relativePath };
}
diff --git a/common/lib/localMediaCommit-server.test.ts b/common/lib/localMediaCommit-server.test.ts
@@ -11,7 +11,7 @@ async function fixture(t: TestContext) {
const dataDirectory = path.join(root, "data"); await mkdir(dataDirectory);
const input = { dataDirectory, directoryId: "test-id",
metadata: JSON.stringify({ id: "test-id", title: "Synthetic", duration: 3, upload_date: "20261030", webpage_url: "https://www.youtube.com/watch?v=test-id" }),
- transcript: "WEBVTT\r\n\r\n00:00:01.000 --> 00:00:02.000\r\nSynthetic cue\r\n",
+ transcript: "WEBVTT\r\n\r\n00:01.000 --> 00:02.000\r\nSynthetic cue\r\n",
reference: { version: 1, kind: "external", sourceId: "library-1", relativePath: "Original ⧸ $title.mp4" } };
return { root, input, target: path.join(dataDirectory, "test-id") };
}
diff --git a/common/lib/localMediaScan.test.ts b/common/lib/localMediaScan.test.ts
@@ -145,22 +145,19 @@ test("read-only source files remain readable and unchanged", async (t) => {
} finally { for (const file of files) await chmod(path.join(root, file), 0o644); }
});
-// The parser reads only hh:mm:ss.mmm cue timings until slice 2 lands its
-// short-form support (with a corpus regression check). Until then a short-form
-// VTT is held for review, never imported with missing or misread cues.
-test("short-form timestamps are held for review, not imported", async (t) => {
+test("short timestamps produce index-compatible cues", async (t) => {
const root = await fixture(t);
await add(root, "short");
await writeFile(path.join(root, "short.vtt"), "WEBVTT\n\n00:00.250 --> 00:01.910\nShort cue\n");
const row = (await scan(root)).candidates[0];
- assert.equal(row.status, "issue");
- assert.match(row.issues.join(), /no usable cues/);
- assert.equal(row.fingerprint, undefined);
+ assert.equal(row.status, "new");
+ assert.equal(row.cueCount, 1);
+ assert.deepEqual(row.warnings, []);
});
test("isolated zero-duration cues warn without changing source; all-point transcripts remain blocked", async (t) => {
const root = await fixture(t);
await add(root, "mixed"); await add(root, "points");
- const point = "00:00:03.000 --> 00:00:03.000\nPoint cue\n";
+ const point = "00:03.000 --> 00:03.000\nPoint cue\n";
const mixed = VTT + "\n" + point;
await writeFile(path.join(root, "mixed.vtt"), mixed);
await writeFile(path.join(root, "points.vtt"), "WEBVTT\n\n" + point);
@@ -172,3 +169,21 @@ test("isolated zero-duration cues warn without changing source; all-point transc
assert.match(result.candidates[1].issues.join(), /no positive-duration/);
assert.equal(await readFile(path.join(root, "mixed.vtt"), "utf8"), mixed);
});
+// A name a library reference cannot hold (coerceExternalMediaReference refuses
+// a control character, \ or :) is an issue in the preview: offered as new, its
+// import could only fail. No fingerprint of any kind is offered for it.
+test("a recording whose file name a reference cannot hold is held for review", async (t) => {
+ const root = await fixture(t);
+ for (const name of ["colon:name", "back\\slash", "tab\tname", "line\nbreak"]) await add(root, name, "id-" + name.length);
+ await writeFile(path.join(root, "bare\u0001.mp4"), "synthetic video bytes");
+ await writeFile(path.join(root, "bare\u0001.vtt"), VTT);
+ const result = await scan(root);
+ assert.equal(result.candidates.length, 5);
+ for (const row of result.candidates) {
+ assert.equal(row.status, "issue", JSON.stringify(row.media));
+ assert.match(row.issues[0], /^Media: the file name has a control character/);
+ assert.equal(row.fingerprint, undefined);
+ assert.equal(row.preparationFingerprint, undefined);
+ assert.equal(row.transcriptionFingerprint, undefined);
+ }
+});
diff --git a/common/lib/localMediaScan.ts b/common/lib/localMediaScan.ts
@@ -4,6 +4,7 @@ import type { Stats } from "node:fs";
import path from "node:path";
import { lstat, open, readdir, realpath } from "node:fs/promises";
import { extractVideoId } from "./videoId";
+import { isExternalMediaRelativePath } from "./localMedia";
import { parseVtt } from "./vtt";
// Read-only discovery, not an executable import plan. The caller supplies the
@@ -114,8 +115,14 @@ export async function scanLocalMedia(options: {
let metadataMissing = false;
let transcriptText = "";
let metadataUsable = false;
- try { mediaStat = await lstat(await regularFile(root, media)); }
- catch (error) { row.issues.push(`Media: ${reason(error)}`); }
+ // A name the library reference cannot hold (a control character, \ or :)
+ // is held here: offered as new, its import could only fail.
+ if (!isExternalMediaRelativePath(media)) {
+ row.issues.push("Media: the file name has a control character, \\ or :, which a library reference cannot hold; rename the file");
+ } else {
+ try { mediaStat = await lstat(await regularFile(root, media)); }
+ catch (error) { row.issues.push(`Media: ${reason(error)}`); }
+ }
try {
metadataText = await readLocalMediaText(root, row.metadata);
const meta = JSON.parse(metadataText.replace(/^\uFEFF/, ""));
diff --git a/common/lib/localMediaTranscript.test.ts b/common/lib/localMediaTranscript.test.ts
@@ -7,7 +7,7 @@ test("SRT preserves multiline Unicode dialogue, emphasis, overlaps and milliseco
assert.equal(srtToVtt(input), "WEBVTT\n\n00:00:01.001 --> 00:00:03.999\n<i>Hello</i> & welcome\n録画\n\n00:00:02.050 --> 00:00:04.500\nSecond line\n");
});
test("VTT remains byte-for-byte text and SRT freshness includes unconverted source", () => {
- const vtt = "\uFEFFWEBVTT\r\n\r\n00:00:01.000 --> 00:00:02.000\r\nHi\r\n";
+ const vtt = "\uFEFFWEBVTT\r\n\r\n00:01.000 --> 00:02.000\r\nHi\r\n";
assert.equal(localTranscriptVtt("lesson.vtt", vtt), vtt);
assert.equal(localTranscriptFingerprint("lesson.vtt",vtt), vtt);
const srt = "1\n00:00:01,000 --> 00:00:02,000\nHi\n";
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/claimChecks.test.ts b/common/lib/report/draft/tasks/claimChecks.test.ts
@@ -0,0 +1,36 @@
+// Item 2's gate and the text around a quote (demo epic D2), on cases from the
+// D0 sample.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { onTopicBy, quoteContext } from "./claimChecks";
+
+const WIN: [number, string][] = [
+ [0, "so let's check in on the Rotten Tomato score for the acolyte"],
+ [3, "we see it is sitting at a Wonder"],
+ [8, "26% audience score not shocking at all"],
+ [12, "um the show is you know basically"],
+ [15, "getting mocked into Oblivion by anybody"],
+];
+
+test("quoteContext: the transcript's own words before and after a verbatim quote, cut at a word", () => {
+ const c = quoteContext(WIN, "26% audience score not shocking at all um the show", { before: 40, after: 20 })!;
+ assert.equal(c.before, "acolyte we see it is sitting at a Wonder");
+ assert.equal(c.after, "is you know");
+ // Punctuation and case do not matter; a quote that is not there is null.
+ assert.ok(quoteContext(WIN, "Getting mocked into oblivion"));
+ assert.equal(quoteContext(WIN, "never said this"), null);
+});
+
+test("onTopicBy: the rare term in the quote or the 300 characters before it; the topic counts too", () => {
+ const before = quoteContext(WIN, "26% audience score not shocking at all")!.before;
+ assert.equal(onTopicBy({ quote: "26% audience score not shocking at all", before, terms: ["acolyte"] }), "acolyte");
+ // 300 characters of something else in between: off the question.
+ const far = `the acolyte ${"word ".repeat(70)}`;
+ assert.equal(onTopicBy({ quote: "26% audience score not shocking at all", before: far, terms: ["acolyte"] }), null);
+ // A 2019 Ghostbusters video naming Star Wars in passing (D0 d k01): no.
+ assert.equal(onTopicBy({ quote: "maybe it was Jurassic Park maybe it was Star Wars", before: "think about your favorite film franchise", terms: ["acolyte"] }), null);
+ assert.equal(onTopicBy({ quote: "Disney's new show The Acolyte is out", before: "", terms: ["lightsaber"], topic: "the acolyte" }), "the acolyte");
+ // Words, not substrings.
+ assert.equal(onTopicBy({ quote: "the acolytes of the cult", before: "", terms: ["acolyte"] }), null);
+});
diff --git a/common/lib/report/draft/tasks/claimChecks.ts b/common/lib/report/draft/tasks/claimChecks.ts
@@ -0,0 +1,128 @@
+// What code checks of a local sweep's item once its quote is verbatim (demo
+// epic D2): the text around the quote in its transcript window, and whether
+// the item is ON the question (item 2's gate).
+//
+// D0 (11 Nov 2026): with nothing on the subject read, the extractor still
+// marked 100-200 items on topic, and grouping named sections for them; 39 of
+// the Acolyte run's 40 kept claims were off the question. The model's own
+// `on_topic` is advisory: an item is kept only when its quote, or the 300
+// characters before it, holds one of the question's rare terms (or the topic
+// the model named) — what code can see.
+
+import { strictNormalize } from "../../../citations/verify";
+
+type Win = readonly (readonly [number, string])[];
+
+// The window's words, each with its normalized tokens (a raw word may
+// normalize to none, or to two: "rock-bottom").
+function tokensOf(win: Win): { raw: string[]; norm: string[]; owner: number[] } {
+ const raw: string[] = [];
+ const norm: string[] = [];
+ const owner: number[] = [];
+ for (const [, text] of win) {
+ for (const w of text.split(/\s+/)) {
+ if (!w) continue;
+ raw.push(w);
+ for (const t of strictNormalize(w).split(" ")) {
+ if (!t) continue;
+ norm.push(t);
+ owner.push(raw.length - 1);
+ }
+ }
+ }
+ return { raw, norm, owner };
+}
+
+export type QuoteContext = { before: string; after: string };
+
+// The transcript's own words before and after a verbatim quote in its window
+// (at most `before` / `after` characters, cut at a word); null when the quote
+// is not in it.
+export function quoteContext(win: Win, quote: string, o: { before?: number; after?: number } = {}): QuoteContext | null {
+ const q = strictNormalize(quote).split(" ").filter(Boolean);
+ if (!q.length) return null;
+ const { raw, norm, owner } = tokensOf(win);
+ let at = -1;
+ for (let i = 0; i + q.length <= norm.length && at < 0; i++) {
+ let ok = true;
+ for (let j = 0; j < q.length && ok; j++) ok = norm[i + j] === q[j];
+ if (ok) at = i;
+ }
+ if (at < 0) return null;
+ const first = owner[at]!;
+ const last = owner[at + q.length - 1]!;
+ const take = (words: string[], max: number, fromEnd: boolean) => {
+ const out: string[] = [];
+ let n = 0;
+ const list = fromEnd ? [...words].reverse() : words;
+ for (const w of list) {
+ if (n + w.length + (out.length ? 1 : 0) > max) break;
+ out.push(w);
+ n += w.length + (out.length > 1 ? 1 : 0);
+ }
+ return (fromEnd ? out.reverse() : out).join(" ");
+ };
+ return { before: take(raw.slice(0, first), o.before ?? 400, true), after: take(raw.slice(last + 1), o.after ?? 150, false) };
+}
+
+export const GATE_CHARS = 300;
+
+// The question's term (or the topic) the item shows, in its quote or the
+// GATE_CHARS before it; null when it shows none — the item is off the question.
+export function onTopicBy(o: { quote: string; before: string; terms: readonly string[]; topic?: string }): string | null {
+ const before = o.before.length > GATE_CHARS ? o.before.slice(o.before.length - GATE_CHARS).replace(/^\S*\s/, "") : o.before;
+ const text = ` ${strictNormalize(`${before} ${o.quote}`)} `;
+ for (const t of [...o.terms, ...(o.topic ? [o.topic] : [])]) {
+ const k = strictNormalize(t);
+ if (k && text.includes(` ${k} `)) return t;
+ }
+ return null;
+}
+
+// A full sweep needs this many items on the question to be a report; fewer is
+// "nothing usable found" (never padded).
+export const MIN_KEPT = 3;
+
+const HEDGES = ["allegedly", "reportedly", "claims", "claimed", "may", "might", "maybe", "if", "probably", "likely", "i think", "apparently", "supposedly", "rumor", "rumour"];
+// A hedge is kept when the sentence says it in its own words: "I think" is
+// "he thinks"; "maybe" is "may", "might" or "perhaps".
+const MAYBE = ["maybe", "may", "might", "perhaps", "possibly", "could"];
+const HEDGE_KEPT_BY: Record<string, string[]> = {
+ "i think": ["i think", "thinks?", "believes?", "feels?", "guess(?:es)?", "suspects?", "in his (?:view|opinion)"],
+ maybe: MAYBE,
+ may: MAYBE,
+ might: MAYBE,
+ probably: ["probably", "likely", "thinks?", "believes?", "expects?"],
+ likely: ["probably", "likely", "thinks?", "believes?", "expects?"],
+ allegedly: ["allegedly", "reportedly", "claims?", "claimed", "accused", "accusations?"],
+ reportedly: ["reportedly", "allegedly", "reports?", "claims?", "according to"],
+ apparently: ["apparently", "reportedly", "seems?", "appears?"],
+ supposedly: ["supposedly", "allegedly", "reportedly", "claims?"],
+};
+const NEGATIONS = /\b(never|not|no|nobody|nothing|none|neither|nor|cannot|without)\b|n't\b/i;
+
+// The drafted sentence against its quote: a negation or hedge lost or added,
+// a number not in the quote. Flags, never drops (the meaning check's fix of an
+// overstated sentence must pass it).
+export function lintClaim(claim: string, quote: string): string[] {
+ const flags: string[] = [];
+ const qn = quote.toLowerCase();
+ const cn = claim.toLowerCase();
+ if (NEGATIONS.test(qn) && !NEGATIONS.test(cn)) flags.push("negation: the quote has a not/never/no the claim does not");
+ if (!NEGATIONS.test(qn) && NEGATIONS.test(cn)) flags.push("negation: the claim has a not/never/no the quote does not");
+ for (const h of HEDGES) {
+ const re = new RegExp(`\\b${h.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`);
+ const kept = new RegExp(`\\b(${(HEDGE_KEPT_BY[h] ?? [h]).join("|")})\\b`);
+ if (re.test(qn) && !kept.test(cn)) {
+ flags.push(`hedge dropped: the quote says “${h}”`);
+ break;
+ }
+ }
+ for (const num of claim.match(/\d[\d,.]*/g) ?? []) {
+ if (!quote.includes(num.replace(/[.,]+$/, ""))) {
+ flags.push(`number ${num} is not in the quote`);
+ break;
+ }
+ }
+ return flags;
+}
diff --git a/common/lib/report/draft/tasks/meaning.test.ts b/common/lib/report/draft/tasks/meaning.test.ts
@@ -0,0 +1,90 @@
+// The meaning check's rules in code (demo epic D2, item 3), on D0's own
+// cases.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { decideMeaning, hasBothHalves, meaningPrompt, readMeaning, type MeaningAnswer } from "./meaning";
+
+const A = (o: Partial<MeaningAnswer>): MeaningAnswer => ({ speaker: "host", stance: "asserts", sentence: "supported", fix: null, ...o });
+
+// D0 a-qwen3-8b k01, reversed on both models: he reads a hostile business
+// review aloud and says at once "this is a lie this is liable this is slanderous".
+const REVIEW = {
+ sentence: "Jeremy Hambly was banned by Wizards of the Coast from sanctioned events due to constant sexual harassment.",
+ quote: "was banned by Wizards of the Coast from attending sanctioned events due to constant sexual harassment",
+ before: "let's look at the reviews of the coffee company one star it says Jeremy Hambly",
+ after: "this is a lie this is liable this is slanderous",
+};
+
+test("not his words / he rebuts it: rewritten only when the fix says what he reads AND what he says of it", () => {
+ const fix = "He reads a business review that says Wizards banned him for constant sexual harassment; he calls it a lie and slander.";
+ const d = decideMeaning(A({ speaker: "someone he reads or plays", stance: "rebuts it", sentence: "reversed", fix }), REVIEW);
+ assert.equal(d.action, "drop", "reversed comes first: the drafted sentence is gone either way");
+ const r = decideMeaning(A({ speaker: "someone he reads or plays", stance: "rebuts it", sentence: "overstated", fix }), REVIEW);
+ assert.deepEqual([r.action, r.action !== "drop" && r.sentence], ["rewrite", fix]);
+ const half = decideMeaning(A({ speaker: "someone he reads or plays", stance: "reads it out", sentence: "overstated", fix: "Jeremy reads a review saying he was banned for harassment." }), REVIEW);
+ assert.equal(half.action, "drop");
+ assert.match(half.action === "drop" ? half.why : "", /^not his words, and no sentence says both/);
+ // Sarcasm is the same rule.
+ assert.equal(decideMeaning(A({ stance: "sarcastic", fix: null }), REVIEW).action, "drop");
+ // A drafted sentence that already carries both halves stands.
+ const both = "He reads a tweet that says the show is a hit; he says nobody watched it.";
+ const k = decideMeaning(A({ speaker: "someone he reads or plays", stance: "rebuts it", sentence: "supported", fix: null }), { sentence: both, quote: "the show is a hit", before: "a tweet", after: "nobody watched this garbage" });
+ assert.deepEqual([k.action, k.action !== "drop" && k.sentence], ["rewrite", both]);
+ // What he says of it must be in the transcript around the quote, not a
+ // restatement of what he reads (D2 run i123-d-q25, the power-scaling tweet).
+ const shad = {
+ sentence: "Jeremy says episode 5 does not understand power scaling.",
+ quote: "the acolyte episode 5 doesn't understand power scaling at all which is crucial if you want consistency",
+ before: "Shad adversity",
+ after: "and investment in a fight great point",
+ };
+ const restated = decideMeaning(A({ speaker: "someone he reads or plays", sentence: "overstated", fix: "He reads a tweet that says episode 5 misses power scaling; he calls it crucial for consistency." }), shad);
+ assert.equal(restated.action, "drop");
+ assert.match(restated.action === "drop" ? restated.why : "", /not in the transcript around the quote/);
+ const grounded = decideMeaning(A({ speaker: "someone he reads or plays", sentence: "overstated", fix: "The host reads a tweet that says episode 5 misses power scaling; he calls it a great point." }), shad);
+ assert.deepEqual([grounded.action, grounded.action !== "drop" && grounded.sentence], ["rewrite", "He reads a tweet that says episode 5 misses power scaling; he calls it a great point."]);
+ // "reads it out" is reading: the same rule, even when the model says "host".
+ assert.equal(decideMeaning(A({ stance: "reads it out", sentence: "supported" }), shad).action, "drop");
+});
+
+test("reversed: dropped (D0 a k09: 'his coffee company dropped a sponsorship' — Trade Coffee dropped its sponsorship of him)", () => {
+ const d = decideMeaning(A({ sentence: "reversed", fix: "He says Trade Coffee dropped its sponsorship of him." }), {
+ sentence: "Jeremy states that his coffee company dropped a sponsorship worth thousands of dollars.",
+ quote: "trade coffees dropped a sponsorship",
+ });
+ assert.equal(d.action, "drop");
+});
+
+test("overstated: the fix replaces the sentence when the lint passes, else dropped", () => {
+ const o = { sentence: "Jeremy says the show will be cancelled.", quote: "I think the show is going to get cancelled" };
+ const good = decideMeaning(A({ sentence: "overstated", fix: "He says he thinks the show is going to get cancelled." }), o);
+ assert.deepEqual([good.action, good.action !== "drop" && good.sentence], ["rewrite", "He says he thinks the show is going to get cancelled."]);
+ // A fix that drops the hedge fails the lint.
+ const bad = decideMeaning(A({ sentence: "overstated", fix: "He says the show is going to get cancelled maybe." }), { ...o, quote: "I think the show might get cancelled" });
+ assert.equal(bad.action, "drop");
+ assert.equal(decideMeaning(A({ sentence: "overstated", fix: null }), o).action, "drop");
+ assert.equal(decideMeaning(A({ sentence: "overstated", fix: "word ".repeat(31).trim() }), o).action, "drop");
+});
+
+test("unclear: kept, marked check by ear; supported and his own: kept as drafted", () => {
+ const o = { sentence: "Jeremy says the show is tanking.", quote: "the show is tanking in the ratings" };
+ assert.deepEqual(decideMeaning(A({ speaker: "unclear" }), o), { action: "mark", sentence: o.sentence, why: "speaker unclear: check by ear" });
+ assert.equal(decideMeaning(A({ stance: "unclear" }), o).action, "mark");
+ assert.deepEqual(decideMeaning(A({}), o), { action: "keep", sentence: o.sentence, why: "supported, his own words" });
+
+});
+
+test("readMeaning: strict — an unknown value is unclear / overstated; an empty or 'null' fix is null", () => {
+ assert.deepEqual(readMeaning({ speaker: "Jeremy", stance: "maybe", sentence: "fine", fix: "null" }), { speaker: "unclear", stance: "unclear", sentence: "overstated", fix: null });
+ assert.deepEqual(readMeaning(null), { speaker: "unclear", stance: "unclear", sentence: "overstated", fix: null });
+ assert.equal(readMeaning({ speaker: "host", stance: "asserts", sentence: "supported", fix: ' He says "no". ' }).fix, "He says 'no'.");
+});
+
+test("hasBothHalves and the prompt", () => {
+ assert.ok(hasBothHalves("He plays a clip of Disney's CEO that says ratings are up; he says they are lying."));
+ assert.ok(!hasBothHalves("He reads a review that says it is bad."));
+ assert.ok(!hasBothHalves("He says it is bad; he calls it bad."));
+ const p = meaningPrompt({ question: "Q?", host: "Jeremy", before: "it says", quote: "the quote", after: "this is a lie", sentence: "S." });
+ assert.equal(p, "Question: Q?\n\nThe host: Jeremy\n\nBefore the quote: …it says\n\nQUOTE: the quote\n\nAfter the quote: this is a lie…\n\nDrafted sentence: S.");
+});
diff --git a/common/lib/report/draft/tasks/meaning.ts b/common/lib/report/draft/tasks/meaning.ts
@@ -0,0 +1,169 @@
+// The MEANING CHECK of a local sweep (demo epic D2, item 3): one small model
+// call per kept item, WITH the transcript around its quote, and rules in code
+// over the answer.
+//
+// D0 (11 Nov 2026): 46 of 177 kept quotes were not the host's words — an
+// article, a review, a tweet, a letter, a clip or chat he reads aloud — and the
+// sentence said "Jeremy claims". Reading an accusation to rebut it became a
+// reversal (the "banned for sexual harassment" line, wrong on both models).
+// The evidence is almost always in the ~300 characters BEFORE the quote, which
+// the lint cannot see. So the check reads 400 characters before, the quote,
+// 150 after and the drafted sentence, and answers four fields; code decides.
+
+import { lintClaim } from "./claimChecks";
+
+export const SPEAKERS = ["host", "someone he reads or plays", "unclear"] as const;
+export const STANCES = ["asserts", "reads it out", "rebuts it", "sarcastic", "unclear"] as const;
+export const SENTENCES = ["supported", "overstated", "reversed"] as const;
+export type Speaker = (typeof SPEAKERS)[number];
+export type Stance = (typeof STANCES)[number];
+export type SentenceVerdict = (typeof SENTENCES)[number];
+export type MeaningAnswer = { speaker: Speaker; stance: Stance; sentence: SentenceVerdict; fix: string | null };
+
+export const MEANING_SYSTEM =
+ "You check one finding of a report on what a streamer (the host) has said. You get the question, the transcript just " +
+ "BEFORE the quote, the QUOTE, the transcript just AFTER it, and the drafted sentence. The transcript is automatic and " +
+ "has no punctuation. Answer four things. speaker: is the QUOTE the host's own words (host), or words of someone else " +
+ "he reads aloud or plays — an article, review, post, tweet, letter, chat message, donation, a clip of another person " +
+ "(someone he reads or plays), or can you not tell (unclear)? Look for \"it says\", \"he wrote\", \"they said\", " +
+ "\"listen to this\", a title read out, before the quote. stance: does the host assert it as his own view (asserts), " +
+ "only read it out (reads it out), quote it to reject or mock it (rebuts it), say it sarcastically, meaning the " +
+ "opposite (sarcastic), or unclear? sentence: does the drafted sentence say what the host means here (supported), say " +
+ "more than the quote does — a dropped maybe or I think, someone else's words given as his, a guess stated as fact " +
+ "(overstated), or the opposite of what he means (reversed)? fix: when the sentence is not supported or the words " +
+ "are not his, a corrected sentence of at most 30 words in the third person (\"He says …\"); for words he reads or " +
+ "plays, write both halves: \"He reads a <review/post/letter/article/clip> that says …; he calls it …\" (what he says " +
+ "of it, from the transcript). Use only what the transcript says. Otherwise an empty string.";
+
+export const MEANING_SCHEMA = {
+ type: "object",
+ properties: {
+ speaker: { type: "string", enum: [...SPEAKERS] },
+ stance: { type: "string", enum: [...STANCES] },
+ sentence: { type: "string", enum: [...SENTENCES] },
+ fix: { type: "string" },
+ },
+ required: ["speaker", "stance", "sentence", "fix"],
+};
+
+export function meaningPrompt(o: { question: string; host: string; before: string; quote: string; after: string; sentence: string }): string {
+ return [
+ `Question: ${o.question}`,
+ `The host: ${o.host}`,
+ `Before the quote: …${o.before}`,
+ `QUOTE: ${o.quote}`,
+ `After the quote: ${o.after}…`,
+ `Drafted sentence: ${o.sentence}`,
+ ].join("\n\n");
+}
+
+// The model's answer, read strictly: an unknown value is "unclear" (speaker,
+// stance) or "overstated" (sentence); an empty fix is null.
+export function readMeaning(raw: unknown): MeaningAnswer {
+ const r = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>;
+ const pick = <T extends string>(v: unknown, all: readonly T[], d: T): T => (typeof v === "string" && (all as readonly string[]).includes(v.trim()) ? (v.trim() as T) : d);
+ const fix = typeof r.fix === "string" ? r.fix.replace(/\s+/g, " ").replace(/["“”]/g, "'").trim() : "";
+ return {
+ speaker: pick(r.speaker, SPEAKERS, "unclear"),
+ stance: pick(r.stance, STANCES, "unclear"),
+ sentence: pick(r.sentence, SENTENCES, "overstated"),
+ fix: fix && !/^(null|none|n\/a)$/i.test(fix) ? fix : null,
+ };
+}
+
+export const MAX_FIX_WORDS = 30;
+const words = (s: string) => s.split(/\s+/).filter(Boolean).length;
+
+// "He reads a review that says …; he calls it …": a reading half (reads,
+// plays, quotes, shows) and, after the semicolon, what he says of it.
+export function hasBothHalves(s: string): boolean {
+ const parts = s.split(";").map((p) => p.trim());
+ if (parts.length < 2 || !parts[0] || !parts[1]) return false;
+ const reading = /\b(reads?|reading|plays?|playing|quotes?|quoting|shows?|showing|cites?|citing)\b/i.test(parts[0]);
+ const reaction = /^(he|she|they|and he|but he|then he)\b/i.test(parts[1]) && words(parts[1]) >= 3;
+ return reading && reaction;
+}
+
+// What he says of what he reads must come from the transcript AROUND the
+// quote: the reaction half carries at least one word (four letters or more,
+// not a common one) found before or after the quote and not in it. A half that
+// only restates the read text, or invents a reaction, has none (D2 run
+// i123-d-q25: "he calls it crucial for consistency" of a tweet that said
+// "crucial … consistency").
+const COMMON = new Set(
+ "that this they them their there what when with from have says said calls call reads read thinks think about would could should just like really very also than then into over only more most much some such were been being does doesn't isn't it's he's she's".split(" "),
+);
+const contentWords = (s: string) =>
+ s
+ .toLowerCase()
+ .replace(/[^a-z0-9' ]+/g, " ")
+ .split(/\s+/)
+ .map((w) => w.replace(/'s$/, ""))
+ .filter((w) => w.length >= 4 && !COMMON.has(w));
+export function reactionGrounded(sentence: string, o: { quote: string; before: string; after: string }): boolean {
+ const reaction = sentence.split(";").slice(1).join(";");
+ // Compared by their first five letters ("slander" / "slanderous").
+ const stem = (w: string) => w.slice(0, 5);
+ const inQuote = new Set(contentWords(o.quote).map(stem));
+ const around = new Set([...contentWords(o.before), ...contentWords(o.after)].map(stem));
+ return contentWords(reaction).some((w) => around.has(stem(w)) && !inQuote.has(stem(w)));
+}
+
+// "The host reads …" → "He reads …".
+export function heSentence(s: string): string {
+ return s.replace(/^(the host|the streamer|the speaker)\b/i, "He").replace(/;\s*(the host|the streamer|the speaker)\b/gi, "; he");
+}
+
+export type MeaningDecision =
+ | { action: "keep"; sentence: string; why: string }
+ | { action: "rewrite"; sentence: string; why: string }
+ | { action: "mark"; sentence: string; why: string }
+ | { action: "drop"; why: string };
+
+// The rules, in code (spec D2 item 3):
+// - reversed → dropped;
+// - not his words, or he rebuts it or is sarcastic → rewritten as "He reads a
+// … that says …; he calls it …" ONLY if the fix (or the draft) carries both
+// halves, else dropped;
+// - overstated → the fix replaces the sentence if the lint passes, else dropped;
+// - speaker or stance unclear → kept, marked "check by ear" (and never in the
+// first section: the pipeline's grouping);
+// - else kept as drafted.
+export function decideMeaning(a: MeaningAnswer, o: { sentence: string; quote: string; before?: string; after?: string }): MeaningDecision {
+ if (a.sentence === "reversed") return { action: "drop", why: "reversed: the sentence says the opposite of what he means" };
+ // "reads it out" is reading too: words he voices, not his view (D2 run
+ // i123-d-q25: the model called the reader "host" with the stance "reads it
+ // out" on 7 of 21 items, every one a headline or a tweet).
+ const notHis = a.speaker === "someone he reads or plays" || a.stance === "reads it out";
+ if (notHis || a.stance === "rebuts it" || a.stance === "sarcastic") {
+ const why = notHis ? "not his words" : a.stance === "sarcastic" ? "he is sarcastic" : "he rebuts it";
+ const ctx = { quote: o.quote, before: o.before ?? "", after: o.after ?? "" };
+ let ungrounded = false;
+ for (const raw of [a.fix, o.sentence]) {
+ const s = raw ? heSentence(raw) : raw;
+ if (!s || words(s) > MAX_FIX_WORDS + 10 || !hasBothHalves(s)) continue;
+ if (!reactionGrounded(s, ctx)) {
+ ungrounded = true;
+ continue;
+ }
+ return { action: "rewrite", sentence: s, why: `${why}: says what he reads and what he says of it` };
+ }
+ return {
+ action: "drop",
+ why: ungrounded ? `${why}; what he says of it is not in the transcript around the quote` : `${why}, and no sentence says both what he reads and what he says of it`,
+ };
+ }
+ let sentence = o.sentence;
+ let rewritten = false;
+ if (a.sentence === "overstated") {
+ if (!a.fix || words(a.fix) > MAX_FIX_WORDS) return { action: "drop", why: "overstated, with no usable fix" };
+ const flags = lintClaim(a.fix, o.quote);
+ if (flags.length) return { action: "drop", why: `overstated; the fix fails the lint (${flags[0]})` };
+ sentence = heSentence(a.fix);
+ rewritten = true;
+ }
+ if (a.speaker === "unclear" || a.stance === "unclear") return { action: "mark", sentence, why: `${a.speaker === "unclear" ? "speaker" : "stance"} unclear: check by ear` };
+ return rewritten ? { action: "rewrite", sentence, why: "overstated: the fix replaces it" } : { action: "keep", sentence, why: "supported, his own words" };
+}
+
+export const CHECK_BY_EAR = "Check by ear:";
diff --git a/common/lib/report/draft/tasks/neutralClaim.test.ts b/common/lib/report/draft/tasks/neutralClaim.test.ts
@@ -0,0 +1,177 @@
+// 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, 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"];
+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" });
+ // Function words need no grounding.
+ 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: "“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");
+ assert.equal(label(42).why, "no label");
+ assert.equal(label("of the").why, "a label of no content words");
+});
+
+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");
+ 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");
+ // One quote's label is not a heading over others: the run's topic.
+ assert.equal(neutralHeading("Fan Reactions", { ...o, labels: ["spin-offs confirmed", "the acolyte budget"] }).heading, "The acolyte");
+ assert.equal(neutralHeading("Fan Reactions", { ...o, labels: ["spin-offs confirmed"] }).heading, "Spin-offs confirmed");
+ // 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/neutralClaim.ts b/common/lib/report/draft/tasks/neutralClaim.ts
@@ -0,0 +1,321 @@
+// 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;
+
+// The words of a neutral report's coverage line that say its lines are code's
+// (a revision reads them: ./revise-report.ts keeps such a report neutral).
+export const NEUTRAL_LINES_NOTE = "each line, its citation and its link are written by code and say where the words are, not who is speaking";
+
+export function isNeutralSweep(md: string): boolean {
+ return md.includes(NEUTRAL_LINES_NOTE);
+}
+
+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.";
+
+// WHAT A LABEL OR A HEADING NEVER CARRIES. A label (and a section heading) is
+// a noun-phrase TOPIC — what the words are about — never a proposition about
+// who said, thought, did or is something. The rules are a few closed lists,
+// read token by token (review of round b, 12 Nov 2026: "Main Actress's
+// Comments" over twelve quotes none of them hers, "acolyte writer blames
+// filon", "The Acolyte hates white people", "his love of the show"):
+// (i) no personal or possessive pronoun (he, his, she, her, they, their, …);
+// (ii) no word of saying, thinking, feeling or judging, in any of its forms
+// (says, comments, reaction, blames, hates, loves, admission, lying, …);
+// (iii) no copula or auxiliary (is, are, was, were, be, been, being, has,
+// have, had, does, did, am) and no contracted verb (it's, they're,
+// isn't, …): those make it a statement;
+// (iv) no person-role in the possessive (the actress's …, the showrunner's …);
+// (v) no name of the host.
+// A possessive followed by a word of (ii) is refused by (ii) alone. Then the
+// content words must be GROUNDED (topicLabel, neutralHeading). Each list is
+// spelled out form by form, so what it refuses can be read here.
+const PRONOUNS = new Set(
+ "i me my mine myself we us our ours ourselves you your yours yourself yourselves he him his himself she her hers herself they them their theirs themselves themself".split(" "),
+);
+const COPULAS = new Set("am is are was were be been being has have had does did".split(" "));
+const ATTRIBUTION = new Set(
+ `
+ say says said saying sayings tell tells told telling talk talks talked talking speak speaks spoke spoken speaking speech speeches
+ ask asks asked asking explain explains explained explaining suggest suggests suggested suggesting suggestion suggestions
+ think thinks thought thoughts thinking believe believes believed believing belief beliefs
+ claim claims claimed claiming argue argues argued arguing argument arguments stated stating statement statements
+ admit admits admitted admitting admission admissions confess confesses confessed confessing confession confessions
+ insist insists insisted insisting call calls called calling slam slams slammed slamming blast blasts blasted blasting
+ mock mocks mocked mocking rant rants ranted ranting rave raves raved raving rip rips ripped ripping
+ trash trashes trashed trashing roast roasts roasted roasting expose exposes exposed exposing
+ opinion opinions view views stance stances position positions take takes took taking
+ react reacts reacted reacting reaction reactions respond responds responded responding response responses
+ reply replies replied replying feel feels felt feeling feelings according
+ comment comments commented commenting commentary remark remarks remarked remarking
+ accuse accuses accused accusing accusation accusations allege alleges alleged alleging allegation allegations
+ criticism criticisms criticize criticizes criticized criticizing criticise criticises criticised criticising critique critiques
+ blame blames blamed blaming hate hates hated hating hatred love loves loved loving despise despises despised
+ praise praises praised praising condemn condemns condemned condemning condemnation denounce denounces denounced denouncing
+ deny denies denied denying denial denials defend defends defended defending defense defence
+ apologize apologizes apologized apologizing apologise apologises apologised apologising apology apologies
+ agree agrees agreed agreeing agreement disagree disagrees disagreed disagreeing disagreement
+ complain complains complained complaining complaint complaints endorse endorses endorsed endorsing endorsement
+ oppose opposes opposed opposing attack attacks attacked attacking
+ lie lies lied lying liar liars guilt guilty judgement judgment judgements judgments verdict
+`
+ .split(/\s+/)
+ .filter(Boolean),
+);
+// The raw text a label is cleaned from, at most this long (the trailing
+// punctuation trim is linear, and nothing longer is a label anyway).
+export const MAX_RAW_LABEL_CHARS = 200;
+
+// Who a possessive may not be (iv): a person by role.
+const ROLES = new Set(
+ "actor actress actors actresses star stars showrunner showrunners writer writers director directors creator creators producer producers host hosts streamer streamers youtuber youtubers ceo ceos president owner owners boss employee employees staff fan fans critic critics reviewer reviewers journalist journalists reporter reporters spokesperson spokesman spokeswoman executive executives".split(
+ " ",
+ ),
+);
+// "it's", "that's", "there's": the 's is "is".
+const IS_CONTRACTED = new Set("it that there here what who where how when why".split(" "));
+
+const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+const tokensOf = (s: string) =>
+ s
+ .toLowerCase()
+ .replace(/[’‘`]/g, "'")
+ .split(/[^a-z0-9']+/)
+ .map((t) => t.replace(/^'+/, ""))
+ .filter(Boolean);
+
+// Why this label or heading is not a neutral topic, or null when it is one.
+// `sentence`: the text is a sentence (a revision's summary), so (iii) does not
+// apply and it may run to MAX_SENTENCE_CHARS; (i), (ii), (iv) and (v) do.
+export const MAX_SENTENCE_CHARS = 1000;
+export function labelProblem(text: string, hosts: readonly string[] = [], o: { sentence?: boolean } = {}): string | null {
+ const max = o.sentence ? MAX_SENTENCE_CHARS : MAX_RAW_LABEL_CHARS;
+ if (text.length > max) return `longer than ${max} characters`;
+ for (const tok of tokensOf(text)) {
+ const possessive = /'s?$/.test(tok) && !/'(?:re|ve|ll|d|m|t)$/.test(tok);
+ const base = tok.replace(/'s?$/, "");
+ if (!o.sentence && (/[a-z]'(?:re|ve|ll|d|m|t)$/.test(tok) || (tok.endsWith("'s") && IS_CONTRACTED.has(base)))) return `“${tok}” is a contracted verb: a label is a noun phrase, not a statement`;
+ if (PRONOUNS.has(base)) return `“${tok}” is a pronoun: a label names what the words are about, not a person`;
+ if (!o.sentence && COPULAS.has(base)) return `“${tok}” makes it a statement: a label is a noun phrase`;
+ if (ATTRIBUTION.has(base)) return `“${tok}” is a word of saying, thinking or judging`;
+ if (possessive && ROLES.has(base)) return `“${tok}” puts a person in the possessive`;
+ }
+ const t = ` ${strictNormalize(text)} `;
+ const host = hosts.find((h) => {
+ const k = strictNormalize(h);
+ return k.length >= 3 && new RegExp(` ${esc(k)}s? `).test(t);
+ });
+ return host ? `it names ${host}` : null;
+}
+
+// Does this text name the host or say who says, thinks or is what?
+export function attributes(text: string, hosts: readonly string[] = []): boolean {
+ return labelProblem(text, hosts) !== null;
+}
+
+const LABEL_STOP = new Set(
+ "the a an of on in at to for and or with from by about its this that these those as it into over new who whom what why how when where which someone something anyone not no more most than then also own other".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));
+
+// The first content word of `text` found in none of `ground`, or null.
+// (Each ground text is read to its first GROUND_CHARS: a quote, the
+// transcript before it, a title or the question is far shorter.)
+const GROUND_CHARS = 4000;
+export function ungrounded(text: string, ground: readonly string[]): string | null {
+ const have = new Set(ground.flatMap((g) => contentWords(g.slice(0, GROUND_CHARS))).map(stem));
+ return contentWords(text).find((w) => !have.has(stem(w))) ?? null;
+}
+
+export type TopicLabel = { label: string; from: "model" | "fallback"; why?: string };
+
+const TRAILING = new Set([..." .:;,!?—–-"]);
+
+// A model's label cleaned: no quotes or markup, no "on:"/"about", no trailing
+// punctuation, whitespace collapsed.
+export function cleanLabel(raw: unknown): string {
+ let s = typeof raw === "string" ? raw.slice(0, MAX_RAW_LABEL_CHARS) : "";
+ s = s
+ .replace(/["“”‘’'`*_#[\]()<>|~\\{}$]/g, (c) => (c === "'" || c === "’" ? "'" : " "))
+ .replace(/\s+/g, " ")
+ .trim()
+ .replace(/^(?:on|about|re|regarding|topic)\b[:\s]*/i, "");
+ let end = s.length;
+ while (end > 0 && TRAILING.has(s[end - 1]!)) end--;
+ return s.slice(0, end).trim();
+}
+
+// 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 });
+ const s = cleanLabel(raw);
+ 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})`);
+ const bad = labelProblem(s, o.hosts);
+ if (bad) return fb(bad);
+ if (!contentWords(s).length) return fb("a label of no content words");
+ const loose = ungrounded(s, o.ground);
+ if (loose) return fb(`“${loose}” is not in the quote, the transcript before it, the title or the question`);
+ return { label: s, from: "model" };
+}
+
+// The run's topic, the neutral form's fallback label and its report title: the
+// first candidate (the model's topic as it wrote it, then with the subject's
+// names off, then the rare terms) that passes the label rules, grounded in the
+// question and the terms; else "the question's subject".
+export function runTopicOf(candidates: readonly unknown[], o: { hosts?: readonly string[]; ground: readonly string[] }): { topic: string; refused: { candidate: string; why: string }[] } {
+ const refused: { candidate: string; why: string }[] = [];
+ for (const c of candidates) {
+ const s = cleanLabel(c);
+ if (!s) continue;
+ const r = topicLabel(s, { fallback: "", ...(o.hosts ? { hosts: o.hosts } : {}), ground: o.ground });
+ if (r.from === "model") return { topic: r.label, refused };
+ refused.push({ candidate: s, why: r.why! });
+ }
+ return { topic: "the question's subject", refused };
+}
+
+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
+ .slice(0, max * 4)
+ .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 when it passes the label
+// rules (labelProblem) AND every content word of it is grounded in the
+// section's own labels and quotes, its recordings' titles or the question.
+// Else code writes it: the label two or more of the section's quotes share
+// (labels are held down already), or the run's topic; a heading already used
+// gets an ordinal. `labels`: the section's labels the model wrote and code
+// kept; `used`: the headings of the sections before it (lowercase).
+export function neutralHeading(
+ heading: string,
+ o: { labels: readonly string[]; ground: readonly string[]; topic: string; hosts?: readonly string[]; used?: Set<string> },
+): { heading: string; from: "model" | "code"; why?: string } {
+ const h = cleanLabel(heading).slice(0, 60).trim();
+ const bad = h ? labelProblem(h, o.hosts) : "no heading";
+ const loose = bad ? null : ungrounded(h, [...o.labels, ...o.ground]);
+ const why = bad ?? (loose ? `“${loose}” is in none of its quotes, labels or titles, nor the question` : null);
+ const used = o.used ?? new Set<string>();
+ if (!why && !used.has(h.toLowerCase())) {
+ used.add(h.toLowerCase());
+ return { heading: h, from: "model" };
+ }
+ // The commonest label, when it is the label of two quotes or more (or of
+ // the section's only one): one quote's topic over a section of others
+ // would misname them. Else the run's topic.
+ const count = new Map<string, number>();
+ for (const l of o.labels) count.set(l.toLowerCase(), (count.get(l.toLowerCase()) ?? 0) + 1);
+ const top = [...count.entries()].sort((a, b) => b[1] - a[1])[0];
+ const best = top && (top[1] >= 2 || o.labels.length === 1) ? top[0] : o.topic.toLowerCase();
+ const base = (best ? best[0]!.toUpperCase() + best.slice(1) : "Quotes").slice(0, 54).trim();
+ let out = base;
+ for (let k = 2; used.has(out.toLowerCase()); k++) out = `${base} (${k})`;
+ used.add(out.toLowerCase());
+ return { heading: out, from: "code", why: why ?? "a heading an earlier section has" };
+}
diff --git a/common/lib/report/draft/tasks/readAloud.test.ts b/common/lib/report/draft/tasks/readAloud.test.ts
@@ -0,0 +1,143 @@
+// 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", "says", "saying"]);
+ 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("the words right before the quote, and 'this via' after it (round b's own runs)", () => {
+ // d-nf-1 k29: what the showrunner says, as he reports it.
+ assert.deepEqual(cues("i mean you see leslie hedland again harvey's best friend who heads up the show says", "the acolyte is the gayest Star Wars"), ["says"]);
+ // d-nf-1 k16: a tweet.
+ assert.deepEqual(cues("i wonder how many of those are people who are literally just hate watching now we have chris gore writing", "the acolyte episode 7 might be the most amateurish poorly written episode of TV ever"), ["says", "saying"]);
+ // d-nd-1 k08: "emon uh saying uh andy mayan so".
+ assert.deepEqual(cues("let's just get right to some of the reactions first we'll get uh emon uh saying uh andy mayan so", "the third episode of Star Wars the acolyte basically ruins the original films"), ["saying"]);
+ // d-nf-1 k02, k21, k17.
+ assert.deepEqual(cues("in terms of what makes a character uh good for you you can see", "the acolyte showrunner disney hadlon recently provided some"), ["says"]);
+ assert.deepEqual(cues("they marked the fresh on rotten tomatoes because they include phrases such as", "the acolyte doesn't offer anything new to the universe the way the Andor did and it feels forced"), ["says"]);
+ assert.deepEqual(cues("reprising his role as darth vader lucasfilm also revealed that", "the name and premise of the russian doll creator leslie hedland's disney plus series the acolyte"), ["says"]);
+ // d-nf-1 k05: the Forbes headline, named after it.
+ assert.deepEqual(cues("so we'll go and we'll cover another rag in forbes magazine", "the acolyte episode 3 review one the most disappointing Star Wars episodes ever made", "this via Eric Kane who is generally pretty even keeled in his reviews"), ["from (after)"]);
+ // b-nf-1 k19: a designer's tweet.
+ assert.deepEqual(cues("principal game designer at wizards of the coast pronouns in the bio going on to say", "hard week for my heart and many of yours still feeling raw today"), ["writes"]);
+ // His own: "and I said", "I'm just saying", "the writing on the wall", an email he was sent.
+ assert.deepEqual(cues("so i looked at the numbers and i said", "the acolyte is the worst rated Star Wars show there has ever been"), []);
+ assert.deepEqual(cues("look i'm just saying", "the acolyte is the worst rated Star Wars show there has ever been"), []);
+ assert.deepEqual(cues("because i saw the writing on the wall it was", "eventually barred from playing in any official Magic the Gathering events"), []);
+ assert.deepEqual(cues("there's a video on my channel that shows the actual email i got from wizards of the coast that showed why i was banned", "that's why people like oh isn't that the guy that got banned for harassing a cosplayer no"), []);
+});
+
+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");
+});
+
+// The review of round b (12 Nov 2026): the after-quote pattern backtracked
+// for ever on one long word ("a"×60 never returned). Every pattern, at every
+// place it reads, on long and adversarial text: under 50 ms.
+test("the cues are linear: long words, repeated syllables, digits, 100k-character text", () => {
+ const big = (s: string) => s.repeat(Math.ceil(100_000 / s.length)).slice(0, 100_000);
+ const inputs = [
+ "a".repeat(200),
+ "a".repeat(60),
+ "x".repeat(150),
+ "ha".repeat(75),
+ "7".repeat(150),
+ "1,".repeat(75),
+ big("a "),
+ big("a"),
+ big("see "),
+ big("you see "),
+ big("1, "),
+ big(" ."),
+ big("jeremy "),
+ big("i'm jeremy "),
+ big("hey "),
+ big("@a"),
+ big("says "),
+ big("oh"),
+ big("mm"),
+ "a".repeat(100_000) + " what a shame",
+ ];
+ for (const s of inputs) {
+ for (const where of ["before", "quote", "after"] as const) {
+ const o = { before: "", quote: "the quote", after: "", hosts: ["jeremy", "jeremy hambly", "the quartering"], [where]: s };
+ const t0 = performance.now();
+ readAloudCues(o);
+ const ms = performance.now() - t0;
+ assert.ok(ms < 50, `${where} = ${JSON.stringify(s.slice(0, 12))}×${s.length}: ${ms.toFixed(1)} ms`);
+ }
+ }
+});
+
+test("'what a shame', 'goes on to say' within the first ten words after the quote, and not past them", () => {
+ assert.deepEqual(cues("", "the show is bad", "ah well what a shame I'll keep watching"), ["reaction (after)"]);
+ assert.deepEqual(cues("", "the show is bad", "and then he goes on to say more"), ["reaction (after)"]);
+ assert.deepEqual(cues("", "the show is bad", "one two three four five six seven eight nine ten imagine that"), ["reaction (after)"]);
+ assert.deepEqual(cues("", "the show is bad", "one two three four five six seven eight nine ten eleven imagine that"), []);
+ assert.deepEqual(cues("", "the show is bad", "a".repeat(60) + " what a shame"), ["reaction (after)"]);
+ assert.equal(readAloudCues({ before: "", quote: "q", after: "ah well what a shame I'll" })[0]!.match, "ah well what a shame");
+});
diff --git a/common/lib/report/draft/tasks/readAloud.ts b/common/lib/report/draft/tasks/readAloud.ts
@@ -0,0 +1,180 @@
+// 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.
+// Round b's own first runs (12 Nov 2026, eight sweeps graded) added the words
+// said right before a quote ("the showrunner says", "chris gore writing", "you
+// can see", "lucasfilm also revealed that"), "this via <outlet>" after it and
+// "going on to say", and took "email" out (he talks about the emails Wizards
+// sent him in his own words). What no pattern catches is a headline or an
+// article read with nothing announcing it — about a third of the readings.
+
+// 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|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|going 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,
+ },
+ // "to which he replies", "quote", "titled" right before it
+ { cue: "titled", re: /\b(?:to which (?:he|she|they) repl\w+|quote|unquote|and i quote|titled|entitled|captioned|headlined|reads)\s*$/ },
+ // Right before the quote: "who heads up the show says", "he said", "now we have chris gore writing",
+ // "you can see", "when you see", "they include phrases such as" (round b's own runs, 12 Nov).
+ {
+ cue: "says",
+ re: /(?<!\bi )(?<!\band i )\b(?:(?:says|said|writes|wrote|writing|tweeted|tweets|posted|replied|replies|added|adds|claims|claimed|asks|asked|revealed|announced|reported|confirmed)(?: that)?|you (?:can )?see|(?:phrases?|headlines?|lines?|words?|comments?) (?:such as|like))\s*$/,
+ },
+ // A little before it: "emon uh saying uh andy mayan so", "we have chris gore writing".
+ { cue: "saying", re: /(?<!\bi'm )(?<!\bi am )(?<!\bjust )(?<!\bnot )(?<!\bthe )(?<!\bmy )\b(?:saying|writing|tweeting|posting)\b(?: that)?/, near: 60 },
+ { 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 ){1,3}(?: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 },
+ // Straight after it: "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)/,
+ near: 120,
+ },
+];
+
+// Within the first ten words after it: "ah well what a shame", "and he goes on to say". Read by
+// splitting the words, never by a regex that counts words: `(?:\W*\w+){0,10}` can cut one long
+// word into ten pieces and backtracks for ever on a run of letters (review of round b, 12 Nov).
+const AFTER_WORDS = 10;
+const AFTER_PHRASES: readonly (readonly string[])[] = ["what a shame", "imagine that", "goes on to say", "going on to say", "went on to say"].map((p) => p.split(" "));
+
+function phraseInFirstWords(after: string): string | null {
+ const words = after.split(/[^a-z0-9_]+/).filter(Boolean).slice(0, AFTER_WORDS + 4);
+ for (let i = 0; i <= Math.min(AFTER_WORDS, words.length - 1); i++) {
+ for (const p of AFTER_PHRASES) {
+ if (p.every((w, j) => words[i + j] === w)) return words.slice(0, i + p.length).join(" ");
+ }
+ }
+ return null;
+}
+
+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;
+// A quote is at most 40 words in a sweep; the cap keeps a caller's long text linear and short.
+export const READ_ALOUD_QUOTE = 2000;
+
+// 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[] = [];
+ // Sliced before `lower` too (whitespace runs collapse, so twice the window is read).
+ const before = lower(o.before.slice(-READ_ALOUD_BEFORE * 2)).slice(-READ_ALOUD_BEFORE);
+ const after = lower(o.after.slice(0, READ_ALOUD_AFTER * 2)).slice(0, READ_ALOUD_AFTER);
+ const quote = lower(o.quote.slice(0, READ_ALOUD_QUOTE * 2)).slice(0, READ_ALOUD_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]);
+ }
+ const said = phraseInFirstWords(after.slice(0, 120));
+ if (said) add("reaction (after)", "after", said);
+ // 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/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,13 @@ 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 { AppliedOp as Applied, NeutralOpsRules, RefusedOp as Refused } from "../reportOps";
+import type { CallItem } from "../../../llm/callLog";
+import { CallSlot } from "../../../llm/callLog-server";
import { rewriteLinks, rewriteMomentBases, slugResolver } from "./links";
import { checkQuotes, convertSweepText, dropFailedFindings, titleOfSweep } from "./quotes";
import { TaskInputError, runOnIteration, type TaskHandle, type TaskOutcome } from "./run";
@@ -184,23 +199,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 +360,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",
@@ -352,6 +382,7 @@ export async function localOpsBatch(
const fitted = fitLocalAsk({ llm: deps.llm, model: o.model, system: o.system, schema, build: o.build });
h.log(`one ops batch over the ${o.what} (~${fitted.tokens} of ${fitted.cap} prompt tokens)`);
const t0 = Date.now();
+ const slot = new CallSlot();
const asked = await structuredAnswer<{ ops?: unknown[] }>({
llm: deps.llm,
model: o.model,
@@ -360,6 +391,7 @@ export async function localOpsBatch(
schema,
meter: h.meter,
signal: deps.signal,
+ call: { phase: "revision", label: `ops batch (${o.what})`, slot },
}).catch((e: unknown) => {
if (deps.signal?.aborted) throw e;
h.log(`the ops ask failed: ${(e as Error).message}`);
@@ -367,5 +399,91 @@ export async function localOpsBatch(
});
h.turns([{ kind: "model", what: "ops batch", tokens: fitted.tokens, seconds: Math.round((Date.now() - t0) / 100) / 10, answer: asked }]);
h.progress({ metric: "turns", current: 1, total: 1 });
- if (asked && Array.isArray(asked.ops) && asked.ops.length) await o.apply(asked.ops);
+ if (!asked || !Array.isArray(asked.ops) || !asked.ops.length) {
+ if (asked) slot.decide("dropped", "no ops proposed");
+ return;
+ }
+ const r = (await o.apply(asked.ops)) as { applied?: Applied[]; refused?: Refused[] } | undefined;
+ // The model log: each op applied or refused, with code's reason (a neutral
+ // report's refusals among them).
+ if (r && Array.isArray(r.applied) && Array.isArray(r.refused)) {
+ const items: CallItem[] = [
+ ...r.applied.map((a): CallItem => ({ text: opText(a.op), outcome: "kept", why: "applied" })),
+ ...r.refused.map((x): CallItem => ({ text: opText(x.op), outcome: "dropped", why: `refused: ${x.why}` })),
+ ];
+ slot.decide(r.applied.length ? "kept" : "dropped", `${r.applied.length} op(s) applied, ${r.refused.length} refused`, items);
+ }
+}
+
+const opText = (op: { op: string } & Record<string, unknown>) =>
+ [op.op, op.n !== undefined ? `#${String(op.n)}` : "", typeof op.section === "string" ? `“${op.section}”` : "", typeof op.text === "string" ? op.text : ""].filter(Boolean).join(" ");
+
+// 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/common/lib/report/draft/tasks/selection.test.ts b/common/lib/report/draft/tasks/selection.test.ts
@@ -0,0 +1,123 @@
+// What a local sweep reads (demo epic D2, item 1), on the D0 baseline's own
+// cases: the Acolyte question's terms led with "jeremy" and "show"/"say", and
+// its 40 read held nothing from 2024.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ cleanTerms,
+ normalizeTerm,
+ quarterOf,
+ rareTermsOf,
+ readingSet,
+ readingSize,
+ scoreOf,
+ subjectNames,
+ termStats,
+ termsNear,
+ usableTerms,
+} from "./selection";
+
+const QUARTERING = [{ slug: "the-quartering", name: "TheQuartering" }];
+
+test("subjectNames: the person the question asks about and the channel's own words", () => {
+ const n = subjectNames({ question: "What has Jeremy said about the Star Wars show The Acolyte?", channels: QUARTERING });
+ for (const w of ["jeremy", "quartering", "thequartering"]) assert.ok(n.has(w), w);
+ for (const w of ["acolyte", "star", "wars", "the", "show"]) assert.ok(!n.has(w), w);
+ assert.ok(subjectNames({ question: "What does Jeremy Hambly think of Disney?", channels: [] }).has("hambly"));
+ assert.ok(subjectNames({ question: "Jeremy's views on Disney", channels: [] }).has("jeremy"));
+ assert.ok(subjectNames({ question: "anything", channels: [], hosts: ["Chrissie Mayr"] }).has("mayr"));
+});
+
+test("cleanTerms: D0's Acolyte terms lose the subject's name and the generic words; phrases stay phrases", () => {
+ const names = subjectNames({ question: "What has Jeremy said about the Star Wars show The Acolyte?", channels: QUARTERING });
+ const c = cleanTerms(["jeremy", "star wars", "acolyte", "show", "comment", "say"], { names });
+ assert.deepEqual(c.kept, ["star wars", "acolyte"]);
+ assert.deepEqual(
+ c.dropped.map((d) => [d.term, d.why]),
+ [
+ ["jeremy", "the subject's own name"],
+ ["show", "a generic word"],
+ ["comment", "a generic word"],
+ ["say", "a generic word"],
+ ],
+ );
+ // The coffee question's phrases: the name and the possessive come off.
+ const a = cleanTerms(["jeremy's coffee company", "company's performance", "the quartering"], { names });
+ assert.deepEqual(a.kept, ["coffee company", "company performance"]);
+ assert.equal(a.dropped[0]!.why, "the subject's own name");
+ assert.equal(normalizeTerm('"Wizards of the Coast"'), "wizards of the coast");
+ assert.equal(normalizeTerm("the acolyte"), "acolyte");
+ assert.deepEqual(cleanTerms(["contest", "contests"], { names }).kept, ["contest"]);
+ // qwen3:8b's Acolyte terms: the phrase that holds another term gives its remainder.
+ assert.deepEqual(cleanTerms(["star wars the acolyte", "star wars", "comments"], { names }).kept, ["star wars the acolyte", "star wars", "acolyte"]);
+});
+
+test("termStats: rarity over the scope; a term in > 25% is common; a capped list scores but never nominates", () => {
+ const s = termStats(
+ [
+ { term: "acolyte", videos: 48, partial: false },
+ { term: "star wars", videos: 755, partial: false },
+ { term: "twitter", videos: 2000, partial: true },
+ { term: "people", videos: 4000, partial: false },
+ { term: "nothing", videos: 0, partial: false },
+ ],
+ 11712,
+ );
+ const by = Object.fromEntries(s.map((x) => [x.term, x]));
+ assert.ok(by.acolyte!.idf > by["star wars"]!.idf);
+ assert.equal(by.people!.common, true);
+ assert.deepEqual([by.twitter!.common, by.twitter!.nominates], [false, false]);
+ assert.deepEqual(usableTerms(s).map((x) => x.term), ["acolyte", "star wars", "twitter"]);
+ assert.deepEqual(rareTermsOf(s), ["acolyte"]);
+ // A scope too small to say anything: nothing is common.
+ assert.equal(termStats([{ term: "contest", videos: 1, partial: false }], 3)[0]!.common, false);
+ // No term under 5%: the rarest nominating one is still the gate's.
+ assert.deepEqual(rareTermsOf(termStats([{ term: "elon musk", videos: 966, partial: false }, { term: "buy", videos: 1500, partial: false }], 11712)), ["elon musk"]);
+});
+
+test("scoreOf: rarity × saturated hits — 30 'star wars' no longer outrank 5 'acolyte'; two terms near = a bonus", () => {
+ const stats = new Map(termStats([{ term: "acolyte", videos: 48, partial: false }, { term: "star wars", videos: 755, partial: false }], 11712).map((x) => [x.term, x]));
+ assert.ok(scoreOf({ acolyte: 5, "star wars": 1 }, stats) > scoreOf({ "star wars": 30 }, stats));
+ assert.ok(scoreOf({ acolyte: 2 }, stats, true) > scoreOf({ acolyte: 2 }, stats));
+ assert.equal(scoreOf({ unknown: 9 }, stats), 0);
+});
+
+test("termsNear: two different terms within 90 s", () => {
+ const lines: ([number, string] | null)[] = [
+ [10, "the new star wars show"],
+ [70, "the acolyte is out"],
+ [400, "acolyte again"],
+ ];
+ assert.equal(termsNear(lines, ["acolyte", "star wars"]), true);
+ assert.equal(termsNear(lines.slice(1), ["acolyte", "star wars"]), false);
+ assert.equal(termsNear([[10, "star wars"], [200, "acolyte"]], ["acolyte", "star wars"]), false);
+});
+
+test("readingSet: the top n by score, plus the best of each quarter a rare term hits", () => {
+ const c = (id: string, date: string, score: number, rareHit = true) => ({ id, date, score, rareHit });
+ const ranked = [
+ c("sw2019a", "2019-12-01", 30, false),
+ c("sw2019b", "2019-12-02", 29, false),
+ c("aco2024a", "2024-06-05", 20),
+ c("aco2024b", "2024-06-06", 19),
+ c("aco2020", "2020-12-11", 3),
+ c("sw2018", "2018-01-01", 2, false),
+ ];
+ const s = readingSet(ranked, { n: 3, spreadable: (x) => x.rareHit });
+ assert.deepEqual(
+ s.read.map((x) => x.id),
+ ["sw2019a", "sw2019b", "aco2024a", "aco2020"],
+ );
+ assert.deepEqual(s.spread, ["aco2020"]);
+ assert.equal(quarterOf("2024-06-11"), "2024Q2");
+ assert.equal(quarterOf("20240611"), "2024Q2");
+ assert.equal(quarterOf(""), null);
+});
+
+test("readingSize: a time budget over the measured seconds a call; 40 by default", () => {
+ assert.equal(readingSize(), 40);
+ assert.equal(readingSize({ budgetMinutes: 20, secondsPerCall: 4.3 }), 121);
+ assert.equal(readingSize({ budgetMinutes: 20, secondsPerCall: 10.4 }), 50);
+ assert.equal(readingSize({ budgetMinutes: 1, secondsPerCall: 60 }), 5);
+});
diff --git a/common/lib/report/draft/tasks/selection.ts b/common/lib/report/draft/tasks/selection.ts
@@ -0,0 +1,259 @@
+// What a local sweep reads (demo epic D2, item 1): the search terms the model
+// proposes, cleaned by code; their rarity over the scope; each recording's
+// score; and the reading set — the best by score plus one recording per
+// year-quarter that has hits, so a 2024 subject is never answered from 2017.
+//
+// Pure: the pipeline (./sweep-pipeline.ts) does the calls and hands the
+// numbers in. Measured on the D0 baseline (11 Nov 2026): the model's terms led
+// with the subject's own name and generic words ("jeremy", "show", "say"),
+// were weighted by their position, and the 40 read of 3,000-6,800 matches held
+// nothing from the years asked about.
+
+import { strictNormalize } from "../../../citations/verify";
+
+// Words that never make a search term on their own: function words, and the
+// words a question ABOUT someone's talk is made of.
+export const GENERIC_WORDS = new Set(
+ (
+ "a an the and or but of to in on at by for from with without into onto over under about after before between " +
+ "is are was were be been being am do does did done has have had having will would shall should can could may might must " +
+ "i me my we us our you your he him his she her they them their it its this that these those there here " +
+ "what when where which who whom whose why how whether if then than so such also just like very really " +
+ "not no yes all any some more most many much other others own same each every both few " +
+ "say says said saying tell tells told talk talks talked talking speak speaks spoke discuss discussed discussion " +
+ "think thinks thought thoughts feel feels felt opinion opinions view views comment comments commented commentary " +
+ "statement statements mention mentions mentioned remark remarks claim claims claimed argue argued react reaction reacts " +
+ "show shows video videos channel channels stream streams streamer episode content " +
+ "thing things stuff people person someone something anything everything way ways time times year years day days " +
+ "get gets got make makes made making go goes went going come came take took give gave start started starting " +
+ "reason reasons why because issue issues topic topics subject question questions answer news story stories " +
+ "good bad new old big great best worst lot lots"
+ ).split(/\s+/),
+);
+
+export type ChannelName = { slug: string; name?: string | null };
+
+// "TheQuartering" → "the quartering"; "the-quartering" → "the quartering".
+function nameWords(s: string): string[] {
+ return s
+ .replace(/\(.*?\)/g, " ")
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
+ .replace(/[-_]+/g, " ")
+ .toLowerCase()
+ .split(/[^a-z0-9']+/)
+ .filter(Boolean);
+}
+
+// The person a question is about ("What has Jeremy said about …", "What does
+// Jeremy Hambly think of …", "Jeremy's views on …"): their name words.
+const ASKED_ABOUT =
+ /\b(?:what|how|why|when|where|has|have|does|do|did|is|was)\s+((?:[A-Z][\w'’.-]*\s+){0,2}[A-Z][\w'’.-]*?)(?:['’]s)?\s+(?:ever\s+|really\s+|publicly\s+)?(?:said|say|says|think|thinks|thought|felt|feel|feels|talked|talk|talks|claimed|claim|claims|argued|argue|revealed|reveal|told|tell|admitted|admit|stated|state|reacted|react|commented|comment|done|do)\b/;
+const POSSESSIVE = /\b([A-Z][\w-]*(?:\s+[A-Z][\w-]*){0,2})['’]s\s+(?:views?|take|takes|opinions?|thoughts|comments|words|stance|position|reaction)\b/;
+
+// The subject's own names: the channels' slugs and names, the person the
+// question asks about, and any host names the caller knows (a channel's
+// context note). A term that is one of these finds the speaker everywhere.
+export function subjectNames(o: { question: string; channels: readonly ChannelName[]; hosts?: readonly string[] }): Set<string> {
+ const out = new Set<string>();
+ const add = (s: string) => {
+ const words = nameWords(s).filter((w) => !GENERIC_WORDS.has(w));
+ for (const w of words) out.add(w);
+ const joined = words.join(" ");
+ if (joined) out.add(joined);
+ const solid = s.toLowerCase().replace(/[^a-z0-9]+/g, "");
+ if (solid.length >= 4) out.add(solid);
+ };
+ for (const c of o.channels) {
+ add(c.slug);
+ if (c.name) add(c.name);
+ }
+ for (const h of o.hosts ?? []) add(h);
+ for (const re of [ASKED_ABOUT, POSSESSIVE]) {
+ const m = re.exec(o.question);
+ if (m) add(m[1]!);
+ }
+ return out;
+}
+
+export type DroppedTerm = { term: string; why: string };
+
+// A proposed term as a search phrase: lowercase, no quotes or operators, the
+// generic words trimmed from its ends (a phrase stays a phrase).
+// A possessive is its noun ("company's" → "company"); `names`' words come
+// off a phrase's ends too ("jeremy's coffee company" → "coffee company").
+export function normalizeTerm(raw: unknown, names: ReadonlySet<string> = new Set()): string {
+ let words = String(raw ?? "")
+ .toLowerCase()
+ .replace(/[’‘`]/g, "'")
+ .replace(/["“”]/g, "")
+ .replace(/[^a-z0-9'\- ]+/g, " ")
+ .split(/\s+/)
+ .map((w) => w.replace(/'s$|s'$|^'+|'+$/g, (m) => (m === "s'" ? "s" : "")))
+ .filter(Boolean);
+ const edge = (w: string) => GENERIC_WORDS.has(w) || names.has(w);
+ while (words.length > 1 && edge(words[0]!)) words = words.slice(1);
+ while (words.length > 1 && edge(words.at(-1)!)) words = words.slice(0, -1);
+ return words.join(" ");
+}
+
+// The model's terms, cleaned: the subject's own names, generic words, too
+// long and repeats dropped, each with its reason. Phrases are kept whole.
+export function cleanTerms(proposed: readonly unknown[], o: { names: ReadonlySet<string>; max?: number }): { kept: string[]; dropped: DroppedTerm[] } {
+ const kept: string[] = [];
+ const dropped: DroppedTerm[] = [];
+ for (const raw of proposed) {
+ const t = normalizeTerm(raw, o.names);
+ if (!t) continue;
+ const words = t.split(" ");
+ if (t.length > 40) dropped.push({ term: t, why: "too long" });
+ else if (words.every((w) => GENERIC_WORDS.has(w))) dropped.push({ term: t, why: "a generic word" });
+ else if (o.names.has(t) || words.every((w) => o.names.has(w) || GENERIC_WORDS.has(w))) dropped.push({ term: t, why: "the subject's own name" });
+ else if (t.length < 3) dropped.push({ term: t, why: "too short" });
+ else if (kept.includes(t)) continue;
+ else if (kept.some((k) => k === `${t}s` || `${k}s` === t)) dropped.push({ term: t, why: "a plural of another term" });
+ else kept.push(t);
+ }
+ // A phrase that holds another term ("star wars the acolyte" and "star
+ // wars"): its remainder is a term too ("acolyte"; qwen3:8b on the Acolyte
+ // question proposed only the two, and "acolyte" alone was never searched).
+ for (const t of [...kept]) {
+ for (const k of kept) {
+ if (k === t || !t.startsWith(`${k} `) && !t.endsWith(` ${k}`)) continue;
+ const rest = normalizeTerm(t.startsWith(`${k} `) ? t.slice(k.length + 1) : t.slice(0, t.length - k.length - 1), o.names);
+ const rw = rest.split(" ");
+ if (rest.length >= 4 && !kept.includes(rest) && !rw.every((w) => GENERIC_WORDS.has(w) || o.names.has(w))) kept.push(rest);
+ }
+ }
+ const max = o.max ?? 6;
+ for (const t of kept.slice(max)) dropped.push({ term: t, why: `more than ${max} terms` });
+ return { kept: kept.slice(0, max), dropped };
+}
+
+// A term's enumeration as the pipeline saw it.
+export type TermCount = { term: string; videos: number; partial: boolean };
+
+export type TermStat = TermCount & {
+ // Of the scope's recordings (a partial count is a lower bound).
+ share: number;
+ // ln(scope / videos): an upper bound for a partial count.
+ idf: number;
+ // Matches more than COMMON_SHARE of the scope: dropped.
+ common: boolean;
+ // Its list nominates recordings. A capped (partial) list is a sample in the
+ // corpus's page order, not by relevance: it only scores the nominated.
+ nominates: boolean;
+};
+
+export const COMMON_SHARE = 0.25;
+// Below this many recordings a share says nothing (one of three is 33%).
+export const MIN_SCOPE_FOR_SHARE = 40;
+// The gate's rare terms (item 2): at most this share of the scope.
+export const RARE_SHARE = 0.05;
+
+export function termStats(counts: readonly TermCount[], scopeSize: number): TermStat[] {
+ const n = Math.max(1, scopeSize, ...counts.map((c) => c.videos));
+ return counts.map((c) => {
+ const share = c.videos / n;
+ const common = share > COMMON_SHARE && n >= MIN_SCOPE_FOR_SHARE;
+ return { ...c, share, idf: c.videos > 0 ? Math.log(n / c.videos) : 0, common, nominates: c.videos > 0 && !common && !c.partial };
+ });
+}
+
+// The usable terms: matched something and not common.
+export const usableTerms = (stats: readonly TermStat[]) => stats.filter((s) => s.videos > 0 && !s.common);
+
+// The terms a kept item must show (item 2's gate): the nominating terms at
+// most RARE_SHARE of the scope, and always the rarest nominating one(s).
+export function rareTermsOf(stats: readonly TermStat[]): string[] {
+ const nom = stats.filter((s) => s.nominates);
+ const rare = nom.filter((s) => s.share <= RARE_SHARE).map((s) => s.term);
+ const least = Math.min(...nom.map((s) => s.videos));
+ for (const s of nom) if (s.videos === least && !rare.includes(s.term)) rare.push(s.term);
+ return rare;
+}
+
+// Two different terms within `seconds` of each other in a recording's lines.
+export function termsNear(lines: readonly ([number, string] | null)[], terms: readonly string[], seconds = 90): boolean {
+ const keys = terms.map((t) => ` ${strictNormalize(t)} `).filter((k) => k.trim());
+ const hits: [number, number][] = [];
+ for (const l of lines) {
+ if (!l) continue;
+ const text = ` ${strictNormalize(l[1])} `;
+ keys.forEach((k, i) => {
+ if (text.includes(k)) hits.push([l[0], i]);
+ });
+ }
+ hits.sort((a, b) => a[0] - b[0]);
+ for (let i = 0; i < hits.length; i++) {
+ for (let j = i + 1; j < hits.length && hits[j]![0] - hits[i]![0] <= seconds; j++) if (hits[j]![1] !== hits[i]![1]) return true;
+ }
+ return false;
+}
+
+export const NEAR_BONUS = 1.5;
+
+// A recording's score: Σ rarity × hits over the usable terms, × NEAR_BONUS
+// when two terms hit within 90 s. Hits count saturated (log2(1 + hits), as
+// BM25 does): on D0's Acolyte question raw hits let 30 "star wars" outrank 5
+// "acolyte" (19 of the top 40 held the subject's word); saturated, 35 of 40.
+export function scoreOf(hits: Readonly<Record<string, number>>, stats: ReadonlyMap<string, TermStat>, near = false): number {
+ let s = 0;
+ for (const [t, h] of Object.entries(hits)) {
+ const st = stats.get(t);
+ if (!st || st.common) continue;
+ s += st.idf * Math.log2(1 + Math.max(0, h));
+ }
+ return near ? s * NEAR_BONUS : s;
+}
+
+// "2024-06-11" → "2024Q2"; null when the date does not read.
+export function quarterOf(date: string | null | undefined): string | null {
+ const m = /^(\d{4})-?(\d{2})/.exec(date ?? "");
+ if (!m) return null;
+ const q = Math.floor((Number(m[2]) - 1) / 3) + 1;
+ return q >= 1 && q <= 4 ? `${m[1]}Q${q}` : null;
+}
+
+export type Candidate = { id: string; date: string; score: number };
+
+// The reading set: the top `n` by score, plus the best of every year-quarter
+// that has a (spreadable) candidate (at most `spreadMax` of them, the quarters whose best
+// scores highest), in score order. `spread` names the ones the date spread
+// added.
+// Only a candidate `spreadable` passes (one a rare term hits: a quarter where
+// only a common word hits has nothing on the subject).
+export function readingSet<C extends Candidate>(
+ ranked: readonly C[],
+ o: { n: number; spreadMax?: number; spreadable?: (c: C) => boolean },
+): { read: C[]; spread: string[]; quarters: number } {
+ const byScore = [...ranked].sort((a, b) => b.score - a.score || a.date.localeCompare(b.date) || a.id.localeCompare(b.id));
+ const top = byScore.slice(0, o.n);
+ const inTop = new Set(top.map((c) => c.id));
+ const covered = new Set(top.map((c) => quarterOf(c.date)).filter(Boolean));
+ const best = new Map<string, C>();
+ for (const c of byScore) {
+ const q = quarterOf(c.date);
+ if (!q || best.has(q) || (o.spreadable && !o.spreadable(c))) continue;
+ best.set(q, c);
+ }
+ const extra = [...best.entries()]
+ .filter(([q, c]) => !covered.has(q) && !inTop.has(c.id))
+ .map(([, c]) => c)
+ .sort((a, b) => b.score - a.score)
+ .slice(0, Math.max(0, o.spreadMax ?? Math.ceil(o.n / 2)));
+ const read = [...top, ...extra].sort((a, b) => b.score - a.score || a.date.localeCompare(b.date));
+ return { read, spread: extra.map((c) => c.id), quarters: best.size };
+}
+
+// How many recordings a time budget reads: calls a recording (measured on D0:
+// 2.3 extract calls per recording read) × seconds a call. Default 40.
+export const DEFAULT_READ = 40;
+export const CALLS_PER_RECORDING = 2.3;
+export function readingSize(o: { budgetMinutes?: number; secondsPerCall?: number } = {}): number {
+ if (!o.budgetMinutes || !o.secondsPerCall || o.budgetMinutes <= 0 || o.secondsPerCall <= 0) return DEFAULT_READ;
+ return Math.max(5, Math.min(150, Math.floor((o.budgetMinutes * 60) / (o.secondsPerCall * CALLS_PER_RECORDING))));
+}
+
+// Measured seconds a call on this machine (D0, 11 Nov 2026: an extract call
+// on the RX 6600 XT); the plan's estimate when the settings name none.
+export const MEASURED_SECONDS_PER_CALL: Readonly<Record<string, number>> = { "qwen2.5:7b": 4.3, "qwen3:8b": 10.4 };
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
@@ -28,6 +36,27 @@ 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 { 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, NEUTRAL_LINES_NOTE, neutralExtractSchema, neutralHeading, neutralSentence, neutralTitle, runTopicOf, topicLabel, type ClaimForm, type TopicLabel } from "./neutralClaim";
+import { cuesLine, READ_ALOUD_FLAG, readAloudCues, type ReadAloudCue, type ReadAloudMode } from "./readAloud";
+
+export { lintClaim };
+import {
+ cleanTerms,
+ normalizeTerm,
+ readingSet,
+ readingSize,
+ rareTermsOf,
+ scoreOf,
+ subjectNames,
+ termStats,
+ termsNear,
+ usableTerms,
+ type ChannelName,
+ type DroppedTerm,
+ type TermStat,
+} from "./selection";
import type { TaskDeps, TaskResult } from "./types";
export const CHUNK_CHARS = 7000; // one model call's transcript text (~2k tokens)
@@ -39,25 +68,30 @@ export const MAX_CLAIMS_PER_VIDEO = 6;
export const MIN_QUOTE_WORDS = 7;
export const MAX_QUOTE_WORDS = 60;
export const READ_BATCH = 8;
+// The meaning check's budget: one call per kept item, at most this many.
+export const MAX_MEANING_CHECKS = 60;
const STOP = new Set(
"what when where which about with from that this have said says their there they them were been into over under more most some such than then also just like make made making".split(
" ",
),
);
-const HEDGES = ["allegedly", "reportedly", "claims", "claimed", "may", "might", "maybe", "if", "probably", "likely", "i think", "apparently", "supposedly", "rumor", "rumour"];
-const NEGATIONS = /\b(never|not|no|nobody|nothing|none|neither|nor|cannot|without)\b|n't\b/i;
export const TERMS_SYSTEM =
"You plan keyword searches over automatic speech-recognition transcripts of streams and videos. Given a research " +
- "question, return search phrases likely to be SPOKEN, word for word, in the recordings that answer it. Mostly SINGLE " +
- "words (a name, a noun, a distinctive verb); a two-word phrase only for a fixed name. Lowercase, no quotation marks, " +
- "no boolean operators, no plural and singular of the same word. Prefer distinctive words over common ones. Return " +
- "between three and six.";
+ "question, return search phrases likely to be SPOKEN, word for word, in the recordings that answer it, and the topic: " +
+ "the thing the question is about, in at most five words. Terms name the TOPIC, not the person the question asks " +
+ "about: never the speaker's or the channel's own name, never generic words (say, show, video, comment, think, " +
+ "reason). Prefer the topic's distinctive names and nouns; keep a multi-word name together as one phrase (\"star " +
+ "wars\", \"wizards of the coast\"). Lowercase, no quotation marks, no boolean operators, no plural and singular of " +
+ "the same word. Return between three and six, the most distinctive first.";
export const TERMS_SCHEMA = {
type: "object",
- properties: { terms: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 6 } },
- required: ["terms"],
+ properties: {
+ terms: { type: "array", items: { type: "string" }, minItems: 1, maxItems: 6 },
+ topic: { type: "string" },
+ },
+ required: ["terms", "topic"],
};
export const EXTRACT_SYSTEM =
@@ -129,6 +163,20 @@ export type SweepPipelineInput = {
terms?: string[];
maxVideos?: number;
maxClaims?: number;
+ // The read budget (item 1): recordings read = minutes × 60 / (seconds a
+ // call × calls a recording), default 40. `maxVideos` wins when given.
+ readMinutes?: number;
+ 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.
@@ -243,27 +291,6 @@ export function locate(quote: string, chunk: readonly [number, string][]): numbe
return sec;
}
-export function lintClaim(claim: string, quote: string): string[] {
- const flags: string[] = [];
- const qn = quote.toLowerCase();
- const cn = claim.toLowerCase();
- if (NEGATIONS.test(qn) && !NEGATIONS.test(cn)) flags.push("negation: the quote has a not/never/no the claim does not");
- if (!NEGATIONS.test(qn) && NEGATIONS.test(cn)) flags.push("negation: the claim has a not/never/no the quote does not");
- for (const h of HEDGES) {
- const re = new RegExp(`\\b${h.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`);
- if (re.test(qn) && !re.test(cn)) {
- flags.push(`hedge dropped: the quote says “${h}”`);
- break;
- }
- }
- for (const num of claim.match(/\d[\d,.]*/g) ?? []) {
- if (!quote.includes(num.replace(/[.,]+$/, ""))) {
- flags.push(`number ${num} is not in the quote`);
- break;
- }
- }
- return flags;
-}
// ─── The run ───
@@ -278,6 +305,19 @@ type Kept = {
sec: number;
strength: number;
flags: string[];
+ // The transcript around the quote (400 characters before, 150 after) and
+ // the question's term the gate found in it (D2 item 2).
+ before: string;
+ after: string;
+ gate: string;
+ // The meaning check's answer and what code made of it (D2 item 3); `mark`:
+ // 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> {
@@ -288,7 +328,7 @@ export async function sweepPipeline(input: SweepPipelineInput, deps: TaskDeps):
}
// The model log's phase of a pipeline step (lib/llm/callLog.ts PHASE_ORDER).
-export const phaseOfStep = (what: string) => (what === "terms" ? "terms" : what.startsWith("extract") ? "reading" : what.startsWith("group") ? "grouping" : what);
+export const phaseOfStep = (what: string) => (what.startsWith("terms") ? "terms" : what.startsWith("extract") ? "reading" : what.startsWith("meaning") ? "meaning-check" : what.startsWith("group") ? "grouping" : what);
async function ask<T>(h: TaskHandle, model: string, system: string, user: string, schema: object, what: string, traceCost = false, slot?: CallSlot): Promise<T> {
const t0 = Date.now();
@@ -322,43 +362,53 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
const since = input.from ?? iteration.scope?.from;
const until = input.to ?? iteration.scope?.to;
const origin = input.origin.replace(/\/+$/, "");
- const maxVideos = input.maxVideos ?? 40;
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 } : {}) });
- // 1. terms (the model, unless given)
+ // 1. terms (the model, unless given), cleaned by code: never the subject's
+ // own names, never generic words; a phrase stays a phrase.
+ const channelNames = await channelNamesOf(deps.corpus, channels);
+ 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 = "";
+ // The first terms call's model-log slot: the run's topic is decided on it too.
+ const termsCall: { slot: CallSlot | null } = { slot: null };
+ const proposeTerms = async (user: string, what: string) => {
+ const slot = new CallSlot();
+ termsCall.slot ??= slot;
+ const ans = await ask<{ terms?: unknown; topic?: unknown }>(h, model, TERMS_SYSTEM, user, TERMS_SCHEMA, what, true, slot);
+ 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);
+ const termItems: CallItem[] = [...c.kept.map((t): CallItem => ({ text: t, outcome: "kept", why: "searched" })), ...c.dropped.map((d): CallItem => ({ text: d.term, outcome: "dropped", why: d.why }))];
+ slot.decide(c.kept.length ? "kept" : "dropped", c.kept.length ? `searched for ${c.kept.join(", ")}` : "no usable term", termItems);
+ return c.kept;
+ };
let terms: string[] = [];
if (input.terms?.length) terms = input.terms.map((t) => t.trim()).filter(Boolean);
- else {
- const termsSlot = new CallSlot();
- const ans = await ask<{ terms?: unknown }>(h, model, TERMS_SYSTEM, `Research question: ${question}`, TERMS_SCHEMA, "terms", true, termsSlot);
- const names = new Set(channels.flatMap((c) => [c.toLowerCase(), c.toLowerCase().replace(/-/g, " ")]));
- const termItems: CallItem[] = [];
- for (const t of Array.isArray(ans.terms) ? ans.terms : []) {
- const v = String(t).replace(/["“”]/g, "").trim().toLowerCase();
- if (v && v.length <= 40 && !terms.includes(v) && !names.has(v)) terms.push(v);
- termItems.push({
- text: v || String(t),
- ...(!v ? { outcome: "dropped", why: "empty" } : v.length > 40 ? { outcome: "dropped", why: "longer than 40 characters" } : names.has(v) ? { outcome: "dropped", why: "a channel's own name" } : terms.indexOf(v) >= 6 ? { outcome: "dropped", why: "past the sixth term" } : termItems.some((x) => x.text === v) ? { outcome: "dropped", why: "a repeat" } : { outcome: "kept", why: "searched" }),
- } as CallItem);
- }
- terms = terms.slice(0, 6);
- termsSlot.decide(terms.length ? "kept" : "dropped", terms.length ? `searched for ${terms.join(", ")}` : "no usable term", termItems);
- }
- if (!terms.length) return { status: "failed", summary: "no search terms" };
- h.log(`terms: ${terms.join(", ")}`);
- h.trace({ t: "terms", terms });
+ else terms = await proposeTerms(`Research question: ${question}`, "terms");
+ if (!terms.length && !input.terms?.length) terms = await proposeTerms(retermsPrompt(question, droppedTerms), "terms#2");
+ if (!terms.length) return { status: "failed", summary: `no search terms${droppedTerms.length ? ` (dropped: ${droppedTerms.map((d) => `${d.term}, ${d.why}`).join("; ")})` : ""}` };
+ h.log(`terms: ${terms.join(", ")}${topic ? ` (topic: ${topic})` : ""}${droppedTerms.length ? `; dropped ${droppedTerms.map((d) => `${d.term} (${d.why})`).join(", ")}` : ""}`);
+ h.trace({ t: "terms", terms, ...(topic ? { topic } : {}), ...(droppedTerms.length ? { dropped: droppedTerms } : {}) });
// 2. enumerate (code)
const found = new Map<string, EnumeratedVideo>();
const partial: string[] = [];
+ const counts = new Map<string, { videos: number; partial: boolean }>();
const enumerate = async (list: string[]) => {
for (const term of list) {
const text = await deps.corpus.call("enumerate_matches", {
@@ -370,6 +420,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
if (text.includes("COVERAGE PARTIAL")) partial.push(term);
const vids = parseEnumerate(text, term);
const e = enumerateOf(text);
+ counts.set(term, { videos: vids.length, partial: e.partial });
cov.enumerated(
vids.map((v) => v.id),
e.partial,
@@ -392,26 +443,77 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
else found.set(v.id, v);
}
event({ kind: "enumerate", term, videos: vids.length, partial: text.includes("COVERAGE PARTIAL") });
- h.log(`term "${term}": ${vids.length} video(s)`);
+ h.log(`term "${term}": ${vids.length} video(s)${e.partial ? " (capped)" : ""}`);
}
};
await enumerate(terms);
if (!input.terms?.length) {
- // A phrase that matched nothing: its distinctive words alone.
- const hit = new Set([...found.values()].flatMap((v) => Object.keys(v.hits)));
- const extra: string[] = [];
- for (const t of terms) {
- if (hit.has(t) || !t.includes(" ")) continue;
- for (const w of t.split(/\s+/)) if (w.length >= 4 && !STOP.has(w) && !terms.includes(w) && !extra.includes(w)) extra.push(w);
- }
+ // A phrase that matched nothing: its distinctive words alone (cleaned).
+ const extra = cleanTerms(
+ terms.filter((t) => t.includes(" ") && !counts.get(t)?.videos).flatMap((t) => t.split(/\s+/).filter((w) => w.length >= 4 && !STOP.has(w))),
+ { names },
+ ).kept.filter((w) => !terms.includes(w));
if (extra.length) {
h.log(`phrases with no match; trying words: ${extra.join(", ")}`);
h.trace({ t: "terms", terms: extra, extra: true });
await enumerate(extra);
- const hitNow = new Set([...found.values()].flatMap((v) => Object.keys(v.hits)));
- terms = [...terms.filter((t) => hit.has(t)), ...extra.filter((w) => hitNow.has(w))].slice(0, 8);
+ terms = [...terms, ...extra].slice(0, 8);
}
}
+ // Rarity over the scope: a term in more than a quarter of it is dropped.
+ const scopeSize = await scopeSizeOf(deps.corpus, channels, since, until, channelNames);
+ const statsOf = () => termStats(terms.map((t) => ({ term: t, ...(counts.get(t) ?? { videos: 0, partial: false }) })), scopeSize);
+ let stats = statsOf();
+ const noteCommon = (list: TermStat[]) => {
+ for (const st of list) {
+ if (!st.common || droppedTerms.some((d) => d.term === st.term)) continue;
+ droppedTerms.push({ term: st.term, why: `too common: in ${Math.round(st.share * 100)}% of the scope's recordings` });
+ }
+ for (const st of list) if (!st.videos && !droppedTerms.some((d) => d.term === st.term)) droppedTerms.push({ term: st.term, why: "no match" });
+ };
+ noteCommon(stats);
+ if (usableTerms(stats).length < 2 && !input.terms?.length) {
+ // Once more, naming what was dropped and why.
+ const more = (await proposeTerms(retermsPrompt(question, droppedTerms), "terms#2")).filter((t) => !terms.includes(t));
+ if (more.length) {
+ h.log(`fewer than two usable terms; asked again: ${more.join(", ")}`);
+ h.trace({ t: "terms", terms: more, extra: true, asked: "again" });
+ await enumerate(more);
+ terms = [...terms, ...more];
+ stats = statsOf();
+ noteCommon(stats);
+ }
+ }
+ const usable = usableTerms(stats).sort((a, b) => b.idf - a.idf);
+ terms = usable.map((s) => s.term);
+ if (!terms.length) return { status: "failed", summary: `no usable search terms (${droppedTerms.map((d) => `${d.term}: ${d.why}`).join("; ")})` };
+ const statMap = new Map(usable.map((st) => [st.term, st]));
+ // 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 and its report's title: the topic the
+ // model named for the question, else with the subject's names off, else the
+ // rarest term — the first that passes the label rules (never the model's
+ // raw words unchecked: a topic that attributes would be every refused
+ // label's and the title).
+ const hostNames = [...names];
+ const rt = runTopicOf([topicShown, topic, ...rare, ...terms], { hosts: hostNames, ground: [question, ...terms] });
+ const runTopic = rt.topic;
+ if (neutral && rt.refused.length) {
+ const line = `the run's topic: ${rt.refused.map((r) => `“${r.candidate}” refused (${r.why})`).join("; ")}; “${runTopic}” used`;
+ h.log(line);
+ h.trace({ t: "note", text: line });
+ // The model log: on the terms call, whose answer named the topic.
+ termsCall.slot?.items([
+ ...rt.refused.map((r): CallItem => ({ text: `topic: ${r.candidate}`, outcome: "dropped", why: `label refused: ${r.why}` })),
+ { text: `topic: ${runTopic}`, outcome: "kept", why: "the run's topic (its fallback label and the report's title)" },
+ ]);
+ }
+ 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(", ")}`,
+ });
+ h.log(`scope ${scopeSize} recording(s); by rarity: ${usable.map((st) => `${st.term} ${st.videos}${st.partial ? "+" : ""}`).join(", ")}`);
if (only?.length) {
// A restricted sweep: only these recordings, each read even when the
// terms did not find it (its windows are what the terms match in it).
@@ -422,16 +524,58 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
h.trace({ t: "note", text: `restricted to ${only.length} recording(s): ${only.slice(0, 20).join(", ")}` });
}
const nEnum = found.size;
- const weight = new Map(terms.map((t, i) => [t, 1 / (i + 1)]));
- const order = [...found.values()].sort((a, b) => {
- const wa = Object.keys(a.hits).reduce((s, t) => s + (weight.get(t) ?? 0.2), 0);
- const wb = Object.keys(b.hits).reduce((s, t) => s + (weight.get(t) ?? 0.2), 0);
- const ha = Object.values(a.hits).reduce((s, x) => s + x, 0);
- const hb = Object.values(b.hits).reduce((s, x) => s + x, 0);
- return wb - wa || hb - ha || a.date.localeCompare(b.date);
+ // Candidates: what a nominating term found (a capped list is a sample in
+ // page order, never a nomination) — or, when no term nominates, everything.
+ const nominators = usable.filter((st) => st.nominates).map((st) => st.term);
+ let candidates = [...found.values()].filter((v) => only?.length || !nominators.length || nominators.some((t) => (v.hits[t] ?? 0) > 0));
+ // A capped term counts again inside the candidates, uncapped.
+ const capped = usable.filter((st) => st.partial).map((st) => st.term);
+ if (capped.length && nominators.length && candidates.length) {
+ const ids = candidates.map((v) => v.id);
+ for (const term of capped) {
+ for (const v of candidates) delete v.hits[term];
+ for (let i = 0; i < ids.length; i += 400) {
+ const text = await deps.corpus.call("enumerate_matches", { query: term, channels, ids: ids.slice(i, i + 400) });
+ for (const r of parseEnumerate(text, term)) {
+ const v = found.get(r.id);
+ if (v) v.hits[term] = r.hits[term] ?? 0;
+ }
+ }
+ }
+ }
+ const nRead = input.maxVideos ?? readingSize({ budgetMinutes: input.readMinutes, secondsPerCall: input.secondsPerCall });
+ // Two terms within 90 s: read off the windows of the best by score (the
+ // same windows the read uses, fetched once).
+ const transcripts = new Map<string, ParsedTranscript>();
+ const windowsFor = async (ids: string[]) => {
+ const missing = ids.filter((id) => !transcripts.has(id));
+ for (let i = 0; i < missing.length; i += READ_BATCH) {
+ const text = await deps.corpus.call("get_transcripts", { video_ids: missing.slice(i, i + READ_BATCH), queries: terms.slice(0, 8), link_style: "base", channels });
+ for (const [id, p] of parseTranscripts(text)) transcripts.set(id, p);
+ }
+ };
+ let ranked = candidates.map((v) => ({ ...v, score: scoreOf(v.hits, statMap) }));
+ ranked.sort((a, b) => b.score - a.score || a.date.localeCompare(b.date));
+ if (terms.length > 1 && !only?.length) {
+ const head = ranked.slice(0, Math.min(ranked.length, 2 * nRead, 80));
+ await windowsFor(head.map((v) => v.id));
+ const near = new Set(head.filter((v) => termsNear(transcripts.get(v.id)?.lines ?? [], terms)).map((v) => v.id));
+ ranked = ranked.map((v) => (near.has(v.id) ? { ...v, score: scoreOf(v.hits, statMap, true) } : v));
+ }
+ const sel = only?.length ? { read: ranked, spread: [] as string[], quarters: 0 } : readingSet(ranked, { n: nRead, spreadable: (v) => rare.some((t) => (v.hits[t] ?? 0) > 0) });
+ const todo = sel.read;
+ const spreadSet = new Set(sel.spread);
+ h.trace({
+ t: "select",
+ scope: scopeSize,
+ terms: usable.map((st) => ({ term: st.term, videos: st.videos, partial: st.partial, idf: Math.round(st.idf * 1000) / 1000, nominates: st.nominates })),
+ rare,
+ candidates: ranked.length,
+ read: todo.map((v) => ({ id: v.id, date: v.date, score: Math.round(v.score * 100) / 100, hits: v.hits, why: spreadSet.has(v.id) ? "spread" : "top" })),
});
- const todo = order.slice(0, maxVideos);
- h.log(`${nEnum} video(s) matched; reading ${todo.length}`);
+ candidates = [];
+ h.log(`${nEnum} video(s) matched; reading ${todo.length} (the top ${Math.min(nRead, todo.length)} by score${sel.spread.length ? `, ${sel.spread.length} more for the date spread` : ""})`);
+ h.trace({ t: "note", text: `reading ${todo.length} of ${nEnum}: top ${Math.min(nRead, todo.length)} by rarity × hits${sel.spread.length ? ` + ${sel.spread.length} for the date spread (${sel.quarters} quarter(s) with hits)` : ""}; years ${yearSpread(todo)}` });
// 3. read windows and extract (the model judges, code verifies)
const kept: Kept[] = [];
@@ -449,13 +593,8 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
// The batch's trace: what the model returned, kept or dropped.
const batchLines: string[] = [];
const batchUsd = h.meter.usd;
- const text = await deps.corpus.call("get_transcripts", {
- video_ids: batch.map((v) => v.id),
- queries: terms.slice(0, 8),
- link_style: "base",
- channels,
- });
- const parsed = parseTranscripts(text);
+ await windowsFor(batch.map((v) => v.id));
+ const parsed = transcripts;
for (const v of batch) {
const p = parsed.get(v.id);
if (!p || !p.lines.length) {
@@ -493,7 +632,7 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
let ans: { relevant?: unknown; items?: unknown };
const slot = new CallSlot();
try {
- ans = await ask(h, model, EXTRACT_SYSTEM, user, EXTRACT_SCHEMA, `extract ${v.id}@${ch[0]![0]}`, false, slot);
+ 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]}`, false, slot);
} catch (e) {
if (deps.signal?.aborted) throw e;
event({ kind: "chunk-failed", video: v.id, at: ch[0]![0], error: (e as Error).message });
@@ -509,13 +648,14 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
const items = Array.isArray(ans.items) ? ans.items.slice(0, MAX_ITEMS_PER_CHUNK) : [];
// What code did with each of the model's items (the model log).
const fates: CallItem[] = [];
- 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.
@@ -535,20 +675,48 @@ 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";
+ // The gate (D2 item 2): the question's rare term (or the topic)
+ // in the quote or the 300 characters before it — code's call,
+ // whatever the model's on_topic said.
+ 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}]` : ""}`);
- fates.push({ text: quote ? `“${quote}” — ${claim || "(no claim)"}` : claim || "(empty)", outcome: why ? "dropped" : "kept", why: why ?? "verbatim in its window" });
+ // Kept: and flagged to check by ear, or with its topic label refused (the run's topic used).
+ const keptWhy = `verbatim in its window${cues.length ? `; flagged: check by ear (read-aloud cue: ${cuesLine(cues)})` : ""}${label?.from === "fallback" ? `; label refused: ${label.why} — the run's topic used` : ""}`;
+ fates.push({ text: quote ? `“${quote}” — ${claim || "(no claim)"}` : claim || "(empty)", outcome: why ? "dropped" : "kept", why: why ?? keptWhy });
if (why) {
dropped.push({ video: v.id, quote, why });
event({ kind: "dropped", why, video: v.id, quote, claim });
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,
@@ -559,7 +727,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 } : {}),
});
}
const nKept = fates.filter((f) => f.outcome === "kept").length;
@@ -575,29 +748,145 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
h.trace({ t: "batch", k, of: batches, ids: batch.map((v) => v.id), lines: batchLines, model, usd });
h.trace({ t: "cost", step: `batch ${k}`, usd, model, total: h.meter.usd });
}
- if (!kept.length) {
- h.check({ name: "evidence", ok: false, detail: `${nEnum} matched, ${readIds.length} read, ${dropped.length} quote(s) dropped` });
- return { status: "failed", summary: "no verbatim evidence found — nothing to report" };
+ // Too little on the question is a result, said in one sentence — never a
+ // report padded with what is off it (a restricted sweep, a refresh's, keeps
+ // even one).
+ const minKept = only?.length ? 1 : MIN_KEPT;
+ const nothingFound = async (stage: string) => {
+ const offQuestion = dropped.filter((d) => d.why.startsWith("off the question")).length;
+ const sentence =
+ `Nothing usable found: ${readIds.length} recording(s) read of ${nEnum} matching ${terms.join(", ")}; ` +
+ `${kept.length} passage(s) ${stage}${offQuestion ? ` (${offQuestion} more were verbatim but off it)` : ""}, ` +
+ `fewer than the ${minKept} a report needs.`;
+ h.check({ name: "evidence", ok: true, detail: sentence });
+ h.trace({ t: "note", text: sentence });
+ const title = question.replace(/["“”#]/g, "").trim().slice(0, 90);
+ const md = writeNothing(sentence, {
+ question,
+ title,
+ channels,
+ terms,
+ since,
+ until,
+ nEnum,
+ read: readIds.length,
+ nChunks,
+ nRelevant,
+ dropped: dropped.length,
+ partial,
+ todo: todo.length,
+ model,
+ });
+ await writeIterationFile(h.article, h.n, "sweep.md", md, h.paths);
+ const c = await convertSweepText(md, { id: h.article, title, cuesOf: deps.cuesOf, postChannelOf: deps.postChannelOf });
+ if (c.ok) await writeIterationFile(h.article, h.n, "report.json", c.report, h.paths);
+ return { status: "done" as const, summary: sentence };
+ };
+ if (kept.length < minKept) return nothingFound("were verbatim and on the question");
+
+ // 3b. the meaning check (D2 item 3): one call per kept item, with the
+ // transcript around its quote; code decides from the answer. Its answer is
+ // kept beside the item (items.jsonl: the prompt, the answer, the decision,
+ // 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)";
+ // 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.
+ // A quote kept on a read-aloud cue is checked last: it is shown marked to
+ // check by ear whatever the check says, so it never spends the budget of an
+ // unmarked one.
+ const toCheck = neutral ? [] : [...kept.filter((r) => !r.mark), ...kept.filter((r) => r.mark)].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[] = [];
+ for (const r of toCheck) {
+ deps.signal?.throwIfAborted();
+ const user = meaningPrompt({ question, host, before: r.before, quote: r.quote, after: r.after, sentence: r.claim });
+ const t0 = Date.now();
+ let answer: MeaningAnswer;
+ const slot = new CallSlot();
+ try {
+ answer = readMeaning(await ask(h, model, MEANING_SYSTEM, user, MEANING_SCHEMA, `meaning ${r.video}@${r.sec}`, false, slot));
+ } catch (e) {
+ if (deps.signal?.aborted) throw e;
+ tally["check failed"] = (tally["check failed"] ?? 0) + 1;
+ dropped.push({ video: r.video, quote: r.quote, why: `meaning check failed: ${(e as Error).message}` });
+ 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, error: (e as Error).message, decision: { action: "drop", why: "the meaning check failed" } });
+ continue;
+ }
+ 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;
+ // The model log: what code made of the answer (a read-aloud mark stays a flag).
+ const ear = r.readAloud?.length ? `; flagged: check by ear (read-aloud cue: ${cuesLine(r.readAloud)})` : "";
+ if (decision.action === "drop") slot.decide("dropped", `meaning check: ${decision.why}`);
+ else if (decision.action === "rewrite") slot.decide("rewritten", `meaning check: ${decision.why}${ear}`, [{ text: decision.sentence, outcome: "rewritten", why: `from: ${r.claim}` }]);
+ else if (decision.action === "mark") slot.decide("kept", `flagged: check by ear (${decision.why})${ear}`);
+ else slot.decide("kept", `meaning check: ${decision.why}${ear}`);
+ 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" || 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);
+ 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
- kept.sort((a, b) => b.strength - a.strength || a.date.localeCompare(b.date) || a.video.localeCompare(b.video) || a.sec - b.sec);
+ // "Check by ear" items are never grouped (never in the first section):
+ // they are a last section of their own.
+ const marked = kept.filter((r) => r.mark).slice(0, MAX_CLAIMS_PER_SECTION);
const perVideo = new Map<string, number>();
- const trimmed = kept.filter((r) => {
+ const trimmed = kept.filter((r) => !r.mark).filter((r) => {
perVideo.set(r.video, (perVideo.get(r.video) ?? 0) + 1);
return perVideo.get(r.video)! <= MAX_CLAIMS_PER_VIDEO;
});
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 }; slot: CallSlot; why: string } | null = null;
const groupSlots: { slot: CallSlot; why: string }[] = [];
- for (let attempt = 0; attempt < 2; attempt++) {
+ for (let attempt = 0; attempt < (pool.length ? 2 : 0); attempt++) {
let g: { title?: unknown; sections?: unknown };
const slot = new CallSlot();
try {
- g = await ask(h, model, GROUP_SYSTEM, `Research question: ${question}\n\nFindings:\n${listing}`, GROUP_SCHEMA, `group#${attempt + 1}`, true, slot);
+ 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, slot);
} catch (e) {
if (deps.signal?.aborted) throw e;
event({ kind: "group-failed", error: (e as Error).message });
@@ -617,7 +906,10 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
for (const x of groupSlots) if (best && x.slot !== best.slot) x.slot.decide("dropped", `${x.why}; the other grouping was kept`);
best?.slot.decide("kept", best.why);
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) => ({
@@ -632,9 +924,40 @@ 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 });
+ // The neutral form's headings are held down like its labels: a heading that
+ // is not a grounded noun-phrase topic (neutralHeading) is code's, built from
+ // the section's labels.
+ // A code-written heading's base (its ordinal off), to number them again
+ // once the caps have dropped what they drop.
+ const codeBase = new Map<string, string>();
+ const headingItems: CallItem[] = [];
+ if (neutral) {
+ const used = new Set<string>();
+ sections = sections.map((s) => {
+ const recs = s.nums.map((n) => pool[n - 1]!);
+ // The labels a code heading is built from are the model's that passed
+ // (a refused one is the run's topic, which is every section's).
+ const own = recs.filter((x) => x.label!.from === "model").map((x) => x.label!.label);
+ const r = neutralHeading(s.heading, { labels: own, ground: [...recs.flatMap((x) => [x.quote, x.title]), question, runTopic], topic: runTopic, hosts: hostNames, used });
+ if (r.from === "code") {
+ codeBase.set(r.heading, r.heading.replace(/ \(\d+\)$/, ""));
+ const line = `heading “${s.heading}” replaced by “${r.heading}” (${r.why})`;
+ h.log(line);
+ h.trace({ t: "note", text: line });
+ }
+ headingItems.push(
+ r.from === "model"
+ ? { text: `heading: ${s.heading}`, outcome: "kept", why: "a grounded noun-phrase topic" }
+ : { text: `heading: ${s.heading}`, outcome: "rewritten", why: `heading refused: ${r.why} — replaced by “${codeBase.get(r.heading)}” (written by code)` },
+ );
+ return { ...s, heading: r.heading };
+ });
+ // The model log: on the grouping call whose headings these were.
+ best?.slot.items(headingItems);
+ }
+ 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;
+ let leftOut = kept.length - pool.length - marked.length + unchecked;
for (const s of sections) {
s.nums.sort((a, b) => pool[b - 1]!.strength - pool[a - 1]!.strength || pool[a - 1]!.date.localeCompare(pool[b - 1]!.date) || pool[a - 1]!.sec - pool[b - 1]!.sec);
if (s.nums.length > MAX_CLAIMS_PER_SECTION) {
@@ -655,6 +978,20 @@ async function pipelineBody(h: TaskHandle, input: SweepPipelineInput): Promise<T
secs = secs.map((s, si) => ({ heading: s.heading, recs: s.recs.filter((_, ri) => keep.has(`${si}:${ri}`)) })).filter((s) => s.recs.length);
leftOut += total - maxClaims;
}
+ if (codeBase.size) {
+ // Ordinals in the order shown, with no gap: (2) follows the base, or a
+ // model heading of the same words.
+ const k = new Map<string, number>();
+ for (const s of secs) if (!codeBase.has(s.heading)) k.set(s.heading.toLowerCase(), 1);
+ for (const s of secs) {
+ const base = codeBase.get(s.heading);
+ if (base === undefined) continue;
+ const n = (k.get(base.toLowerCase()) ?? 0) + 1;
+ k.set(base.toLowerCase(), n);
+ s.heading = n === 1 ? base : `${base} (${n})`;
+ }
+ }
+ if (marked.length) secs.push({ heading: "To check by ear", recs: marked });
for (const s of secs) s.recs.sort((a, b) => a.date.localeCompare(b.date) || a.sec - b.sec);
// 5. the markdown, convert, the strict check (a failing finding is dropped)
@@ -676,6 +1013,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);
@@ -734,14 +1074,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)}`;
}
@@ -767,13 +1124,17 @@ 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.claim} "${r.quote}" — [${citeLabel(r)}](${momentHref(c.origin, r.slug, r.video, r.sec)})`);
+ 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)})`);
md.push("");
}
const scope = c.channels.join(", ") + (c.since ? `, from ${c.since}` : "") + (c.until ? ` to ${c.until}` : "");
@@ -783,10 +1144,116 @@ 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}; ${NEUTRAL_LINES_NOTE}; 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.` : ""),
"",
);
return md.join("\n");
}
+
+// The prompt that asks for terms again, naming what was dropped.
+function retermsPrompt(question: string, dropped: readonly DroppedTerm[]): string {
+ return (
+ `Research question: ${question}\n\n` +
+ `These terms were dropped: ${dropped.map((d) => `"${d.term}" (${d.why})`).join(", ") || "none"}. ` +
+ "Propose different, more distinctive terms for the topic."
+ );
+}
+
+// The scope's channels with their names (list_channels' lines).
+async function channelNamesOf(corpus: TaskDeps["corpus"], channels: readonly string[]): Promise<(ChannelName & { videos?: number })[]> {
+ const out: (ChannelName & { videos?: number })[] = channels.map((slug) => ({ slug }));
+ try {
+ const text = await corpus.call("list_channels", {});
+ for (const line of text.split("\n")) {
+ const m = /^\s*-\s+(.*?)\s+\(slug:\s*([^,\s)]+)(?:,\s*(\d+)\s+videos?)?/.exec(line);
+ if (!m) continue;
+ const c = out.find((x) => x.slug === m[2]);
+ if (c) {
+ c.name = m[1]!;
+ if (m[3]) c.videos = Number(m[3]);
+ }
+ }
+ } catch {
+ // the slugs alone
+ }
+ return out;
+}
+
+// How many recordings the scope holds: the listing when the corpus has one,
+// else the channels' counts.
+async function scopeSizeOf(corpus: TaskDeps["corpus"], channels: string[], since: string | undefined, until: string | undefined, names: readonly { videos?: number }[]): Promise<number> {
+ if (corpus.listRecordings) {
+ try {
+ const l = await corpus.listRecordings({ channels, ...(since ? { date_from: since } : {}), ...(until ? { date_to: until } : {}) });
+ if (l.rows.length) return l.rows.length;
+ } catch {
+ // the counts below
+ }
+ }
+ return names.reduce((s, c) => s + (c.videos ?? 0), 0);
+}
+
+function yearSpread(vids: readonly { date: string }[]): string {
+ const by = new Map<string, number>();
+ for (const v of vids) {
+ const y = /^\d{4}/.exec(v.date)?.[0] ?? "?";
+ by.set(y, (by.get(y) ?? 0) + 1);
+ }
+ return [...by.entries()].sort().map(([y, n]) => `${y}:${n}`).join(" ");
+}
+
+// "Nothing usable found": the question, the one sentence, and what was
+// searched and read.
+function writeNothing(
+ sentence: string,
+ c: {
+ question: string;
+ title: string;
+ channels: string[];
+ terms: string[];
+ since?: string;
+ until?: string;
+ nEnum: number;
+ read: number;
+ nChunks: number;
+ nRelevant: number;
+ dropped: number;
+ partial: string[];
+ todo: number;
+ model: string;
+ },
+): string {
+ const scope = c.channels.join(", ") + (c.since ? `, from ${c.since}` : "") + (c.until ? ` to ${c.until}` : "");
+ return [
+ `# ${c.title}`,
+ "",
+ `Question: ${c.question}`,
+ "",
+ "## Nothing usable found",
+ "",
+ sentence,
+ "",
+ "## Coverage",
+ "",
+ `Searched ${scope} for ${c.terms.join(", ")}. ${c.nEnum} video(s) matched; ${c.read} read (${c.nChunks} excerpt(s), ` +
+ `${c.nRelevant} judged relevant); ${c.dropped} quote(s) dropped. Drafted by ${c.model}.` +
+ (c.partial.length ? ` COVERAGE PARTIAL for: ${c.partial.join(", ")}.` : "") +
+ (c.nEnum > c.todo ? ` Only ${c.todo} of the ${c.nEnum} matching videos were read.` : ""),
+ "",
+ ].join("\n");
+}
+
+// The person the question asks about, as written ("Jeremy"), or null.
+function askedAboutName(question: string): string | null {
+ const m = /\b(?:has|have|does|do|did|is|was)\s+((?:[A-Z][\w'’.-]*\s+){0,2}[A-Z][\w'’.-]*?)(?:['’]s)?\s+(?:ever\s+|really\s+)?(?:said|say|think|thought|felt|feel|talked|talk|claimed|argued|told|stated|reacted|commented)\b/.exec(question);
+ return m ? m[1]!.trim() : null;
+}
diff --git a/common/lib/report/draft/tasks/trace.ts b/common/lib/report/draft/tasks/trace.ts
@@ -6,13 +6,15 @@
//
// {t: "run", phase: "start", task, model, extractor?}
// {t: "scope", source, channels, from?, to?, question, seed?: {chars}}
-// {t: "terms", terms} the pipeline's search terms
+// {t: "terms", terms, topic?, dropped?} the pipeline's search terms (and the ones code dropped)
// {t: "enumerate", query, n, ids, partial, unreached, total?}
// {t: "read", tool, ids} text read outside a batch
// {t: "batch", k, of, ids, lines, model, usd} the extractor's own lines
// {t: "cost", step, usd, model, total, turn?, calls?}
// {t: "check", quote, cite, ok, reason?, stage, dropped?}
// {t: "finding", section, claim, cites}
+// {t: "select", scope, terms, rare, candidates, read} what the pipeline reads and why (demo D2)
+// {t: "meaning", video, sec, quote, answer, action, why, from?, to?, seconds} an item's meaning check (D2)
// {t: "note", text}
// {t: "run", phase: "end", status, summary, usd, minutes, coverage?}
//
@@ -90,7 +92,27 @@ export type TraceInput =
// A sweep restricted to these recordings (umtool R4).
ids?: string[];
}
- | { t: "terms"; terms: string[]; extra?: boolean }
+ | { t: "terms"; terms: string[]; extra?: boolean; topic?: string; dropped?: { term: string; why: string }[]; asked?: "again" }
+ | {
+ t: "meaning";
+ video: string;
+ sec: number;
+ quote: string;
+ answer: { speaker: string; stance: string; sentence: string; fix: string | null };
+ action: "keep" | "rewrite" | "mark" | "drop";
+ why: string;
+ from?: string;
+ to?: string;
+ seconds: number;
+ }
+ | {
+ t: "select";
+ scope: number;
+ terms: { term: string; videos: number; partial: boolean; idf: number; nominates: boolean }[];
+ rare: string[];
+ candidates: number;
+ read: { id: string; date: string; score: number; hits: Record<string, number>; why: "top" | "spread" }[];
+ }
| { t: "enumerate"; query: string; n: number; ids: string[]; partial: boolean; unreached: string[]; total?: number; posts?: number; counts?: Record<string, number>; turn?: number; phase?: string; error?: string }
| { t: "read"; tool: string; ids: string[]; turn?: number; phase?: string }
| { t: "batch"; k: number; of: number; ids: string[]; lines: string[]; model: string; usd: number; cut?: boolean; turn?: number; phase?: string }
diff --git a/common/lib/report/iterations.ts b/common/lib/report/iterations.ts
@@ -80,10 +80,13 @@ export type IterationStepStatus = (typeof ITERATION_STEP_STATUSES)[number];
// draft/tasks/trace.ts) — one JSON object a line, like turns.jsonl.
// `refresh.json`: a refresh's fetches, build and delta (umtool R4,
// draft/refresh/types.ts RefreshFile).
+// `items.jsonl`: a local sweep's checked items, one a line — each quote with
+// the transcript around it, its gate, the meaning check's prompt, answer,
+// decision and seconds (demo epic D2; what the model log shows).
// `calls.jsonl` / `calls-text.jsonl`: the model log, every model call of the
// iteration's runs and its steps (demo epic D3, lib/llm/callLog.ts) —
// appended by its writer only, never through writeIterationFile.
-export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl", "refresh.json", "calls.jsonl", "calls-text.jsonl"] as const;
+export const ITERATION_FILES = ["report.json", "sweep.md", "turns.jsonl", "proposals.json", "seed.md", "trace.jsonl", "refresh.json", "items.jsonl", "calls.jsonl", "calls-text.jsonl"] as const;
export type IterationFile = (typeof ITERATION_FILES)[number];
// The files only their own writer appends to (lib/llm/callLog-server.ts): a
// name of the iteration, never one writeIterationFile replaces.
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/common/lib/vtt.test.ts b/common/lib/vtt.test.ts
@@ -95,3 +95,159 @@ test("parseVtt reads cue identifiers and settings as structure, not text", () =>
{ start: 3, end: 4, text: "Second line" },
]);
});
+
+// Regression: short FFmpeg timestamps previously produced zero index cues.
+// Test numeric seconds, not just cue counts, to catch unit/field shifts.
+test("parseVtt accepts short timestamps, mixed forms, settings, and CRLF", () => {
+ const src = "WEBVTT\r\n\r\n1\r\n00:00.250 --> 00:01.910 line:90%\r\nFirst\r\n\r\n"
+ + "2\r\n59:59.500 --> 01:00:01.250\r\nBoundary\r\n";
+ assert.deepEqual(parseVtt(src), [
+ { start: 0.25, end: 1 + 910 / 1000, text: "First" },
+ { start: 3599.5, end: 3601.25, text: "Boundary" },
+ ]);
+});
+test("parseVtt accepts hours longer than two digits", () => {
+ assert.deepEqual(parseVtt("WEBVTT\n\n100:00:01.000 --> 100:00:02.000\nLong recording\n"),
+ [{ start: 360001, end: 360002, text: "Long recording" }]);
+});
+test("short inline timing retains rolling-caption classification and strips timing tags", () => {
+ const src = "WEBVTT\n\n00:01.000 --> 00:02.000\n<00:01.000><c>Hello</c> <00:01.500><c>world</c>\n\n"
+ + "00:02.000 --> 00:02.010\nHello world\n";
+ assert.equal(hasWordTiming(src), true);
+ assert.deepEqual(parseVtt(src), [{ start: 1, end: 2, text: "Hello world" }]);
+});
+test("timing lines do not partially match malformed or out-of-range stamps", () => {
+ for (const stamp of ["00:60.000", "60:00.000", "00:00:60.000", "-00:01.000", "x00:01.000", "00:01.0000"]) {
+ assert.deepEqual(parseVtt(`WEBVTT\n\n${stamp} --> 00:02.000\nInvalid\n`), [], stamp);
+ }
+});
+test("a short-form stamp whose hours do not fit a number is not a cue line", () => {
+ const hours = "9".repeat(400);
+ assert.deepEqual(parseVtt(`WEBVTT\n\n${hours}:00:01.000 --> ${hours}:00:02.000\nToo long\n`), []);
+ assert.deepEqual(parseVtt(`WEBVTT\n\n00:01.000 --> ${hours}:00:02.000\nToo long\n\n00:03.000 --> 00:04.000\nKept\n`),
+ [{ start: 3, end: 4, text: "Kept" }]);
+});
+// A hostile line (a long run of digits, spaces, tags or stamps) is read in time
+// proportional to its length: every timing pattern is anchored or bounded.
+test("a long hostile timing line is read in linear time", () => {
+ const lines = [
+ "1".repeat(200_000) + ":00:01.000 --> 00:02.000",
+ "00:01.000" + " ".repeat(200_000) + "x",
+ "00:01.000 --> 00:02.000" + " ".repeat(200_000) + "\u0000",
+ "<".repeat(100_000) + "00:01.000".repeat(20_000),
+ "00:00:01.000 ".repeat(20_000),
+ ];
+ const started = Date.now();
+ for (const line of lines) parseVtt(`WEBVTT\n\n${line}\nText\n`);
+ assert.ok(Date.now() - started < 2000, `took ${Date.now() - started} ms`);
+});
+test("point cues preserve original text and timestamps", () => {
+ assert.deepEqual(parseVtt("WEBVTT\n\n00:01.000 --> 00:01.000\nPoint\n"),
+ [{ start: 1, end: 1, text: "Point" }]);
+});
+
+// THE OLD CUE LINE STAYS LENIENT. Short-form support is a second reading, tried
+// only on a line the hh:mm:ss.mmm one does not match; every published site's
+// cues came through the lenient one, so what it accepted it still accepts, to
+// the same numbers. Each test below is a tightening the contributed parser
+// made; each passes on the parser as it was before short-form support.
+test("a hh:mm:ss.mmm cue line is found anywhere in its line, as before", () => {
+ const cue = (line: string) => parseVtt(`WEBVTT\n\n${line}\nText\n`);
+ const want = [{ start: 1, end: 2, text: "Text" }];
+ assert.deepEqual(cue("x00:00:01.000 --> 00:00:02.000"), want);
+ assert.deepEqual(cue("-00:00:01.000 --> 00:00:02.000"), want);
+ assert.deepEqual(cue("cue-7 00:00:01.000 --> 00:00:02.000"), want);
+ assert.deepEqual(cue("00:00:01.000 --> 00:00:02.000align:start"), want);
+ // More than two hour digits at the START: the last two are read.
+ assert.deepEqual(cue("100:00:01.000 --> 00:00:02.000"), want);
+});
+
+test("a hh:mm:ss.mmm cue line's minutes and seconds are not range-checked, as before", () => {
+ assert.deepEqual(parseVtt("WEBVTT\n\n00:75:90.000 --> 01:99:60.500\nOut of range\n"), [
+ { start: 75 * 60 + 90, end: 3600 + 99 * 60 + 60.5, text: "Out of range" },
+ ]);
+});
+
+test("a hh:mm:ss.mmm end stamp with extra millisecond digits reads its first three, as before", () => {
+ assert.deepEqual(parseVtt("WEBVTT\n\n00:00:01.000 --> 00:00:02.5009\nLong fraction\n"), [
+ { start: 1, end: 2.5, text: "Long fraction" },
+ ]);
+});
+
+test("a hh:mm:ss.mmm cue line takes any whitespace around the arrow, as before", () => {
+ assert.deepEqual(parseVtt("WEBVTT\n\n00:00:01.000 --> \t00:00:02.000\nSpaced\n"), [
+ { start: 1, end: 2, text: "Spaced" },
+ ]);
+});
+
+// The contributed parser returned NaN for a stamp it could not read where the
+// old one returned 0. Neither is reachable through a matched hh:mm:ss.mmm line;
+// what is pinned is that every lenient line above yields finite numbers.
+test("no cue the old line accepts carries a NaN time", () => {
+ const src = "WEBVTT\n\nx00:00:01.000 --> 00:00:02.0009\nA\n\n00:75:90.000 --> 00:99:99.000\nB\n";
+ const cues = parseVtt(src);
+ assert.equal(cues.length, 2);
+ for (const c of cues) assert.ok(Number.isFinite(c.start) && Number.isFinite(c.end));
+});
+
+// A document the old parser read cues from keeps its SHAPE: short-form word
+// tags make a document rolling only when it has no hh:mm:ss.mmm cue line.
+test("short-form word tags do not reclassify a document with hh:mm:ss.mmm cue lines", () => {
+ const src = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\n<00:01.000><c>Hello</c> <00:01.500><c>world</c>\n\n"
+ + "00:00:02.000 --> 00:00:02.010\nHello again\n";
+ assert.equal(hasWordTiming(src), false);
+ assert.deepEqual(parseVtt(src), [
+ { start: 1, end: 2, text: "Hello world" },
+ { start: 2, end: 2.01, text: "Hello again" },
+ ]);
+});
+
+test("a short-form tag inside a hh:mm:ss.mmm rolling line stays text, as before", () => {
+ const src = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\none<00:00:01.500><c> two</c><00:01.800>\n";
+ assert.deepEqual(parseVtt(src), [{ start: 1, end: 2, text: "one two<00:01.800>" }]);
+});
+
+test("a short-form cue line in a body is that cue's text, and one on its own is a cue", () => {
+ const src = "WEBVTT\n\n00:00:01.000 --> 00:00:02.000\nFirst\n00:03.000 --> 00:04.000\n\n"
+ + "00:05.000 --> 00:06.000\nSecond\n";
+ assert.deepEqual(parseVtt(src), [
+ { start: 1, end: 2, text: "First 00:03.000 --> 00:04.000" },
+ { start: 5, end: 6, text: "Second" },
+ ]);
+});
+
+// Review 2 should-fixes: a short-form cue line never takes a line the old
+// parser read, and is held to the shape of a real cue line.
+test("a short-form cue's body stops at a hh:mm:ss.mmm cue line, which is read as the old parser read it", () => {
+ const src = "WEBVTT\n\n01:00.000 --> 01:02.000\n00:00:05.000 --> 00:00:06.000\nkept?\n";
+ // The short cue is left with no body and dropped, as a bodiless long cue is.
+ assert.deepEqual(parseVtt(src), [{ start: 5, end: 6, text: "kept?" }]);
+ assert.deepEqual(parseVtt("WEBVTT\n\n00:00:01.000 --> 00:00:02.000\n\nA\n"), []);
+});
+test("a short-form cue's body stops at another short-form cue line", () => {
+ assert.deepEqual(parseVtt("WEBVTT\n\n00:01.000 --> 00:02.000\nOne\n00:03.000 --> 00:04.000\nTwo\n"), [
+ { start: 1, end: 2, text: "One" },
+ { start: 3, end: 4, text: "Two" },
+ ]);
+});
+test("a short-form line that ends before it starts is not a cue line", () => {
+ assert.deepEqual(parseVtt("WEBVTT\n\n01:00.000 --> 00:01.000\nBackwards\n"), []);
+ // Nor does it end a short cue's body: it is that cue's text.
+ assert.deepEqual(parseVtt("WEBVTT\n\n00:01.000 --> 00:02.000\nOne\n01:00.000 --> 00:01.000\n"),
+ [{ start: 1, end: 2, text: "One 01:00.000 --> 00:01.000" }]);
+});
+test("short-form hours are two to four digits", () => {
+ assert.deepEqual(parseVtt("WEBVTT\n\n99999999999999999999:00:01.000 --> 99999999999999999999:00:02.000\nToo long\n"), []);
+ assert.deepEqual(parseVtt("WEBVTT\n\n12345:00:01.000 --> 12345:00:02.000\nFive\n"), []);
+ assert.deepEqual(parseVtt("WEBVTT\n\n1000:00:01.000 --> 1000:00:02.000\nFour\n"),
+ [{ start: 3600000 + 1, end: 3600000 + 2, text: "Four" }]);
+ assert.deepEqual(parseVtt("WEBVTT\n\n100:00:01.000 --> 100:00:02.000\nThree\n"),
+ [{ start: 360001, end: 360002, text: "Three" }]);
+});
+test("a short-form line ending in a stray \\r (a \\r\\r\\n file) reads like a hh:mm:ss.mmm one", () => {
+ const short = "WEBVTT\r\r\n\r\r\n00:01.000 --> 00:02.000\r\r\nHi\r\r\n";
+ const long = "WEBVTT\r\r\n\r\r\n00:00:01.000 --> 00:00:02.000\r\r\nHi\r\r\n";
+ assert.deepEqual(parseVtt(short), [{ start: 1, end: 2, text: "Hi" }]);
+ assert.deepEqual(parseVtt(short), parseVtt(long));
+ assert.deepEqual(parseVtt("WEBVTT\n\n00:01.000 --> 00:02.000 align:start\r\nHi\n"), [{ start: 1, end: 2, text: "Hi" }]);
+});
diff --git a/common/lib/vtt.ts b/common/lib/vtt.ts
@@ -1,12 +1,41 @@
export type Cue = { start: number; end: number; text: string };
const TIMING_TAG_RE = /<\d{2}:\d{2}:\d{2}\.\d{3}>/;
+// The cue line every existing corpus is read with: hh:mm:ss.mmm on both sides,
+// found ANYWHERE in the line and not range-checked. Lenient on purpose now —
+// every published site's cues came through it, so a line it matches is read
+// exactly as it always was (vtt.test.ts pins the leniencies).
+const CUE_TIMING_RE =
+ /(\d{2}:\d{2}:\d{2}\.\d{3})\s+-->\s+(\d{2}:\d{2}:\d{2}\.\d{3})/;
+
+// SHORT FORM (mm:ss.mmm — legal WebVTT, what FFmpeg and hand-made subtitle
+// files write). Tried only on a line CUE_TIMING_RE did not match, so it can add
+// cues to a document and never change one: it is strict where the old line is
+// lenient (anchored, minutes and seconds 00–59, exactly three millisecond
+// digits, end not before start), either side may carry hours, of two to four
+// digits. A stray \r before the line's end (a \r\r\n file) is allowed, as
+// the old line, unanchored, always allowed it.
+const SHORT_TIMESTAMP = "(?:\\d{2,4}:)?[0-5]\\d:[0-5]\\d\\.\\d{3}";
+const SHORT_TIMING_TAG_RE = new RegExp("<" + SHORT_TIMESTAMP + ">");
+const SHORT_TIMING_TAG_RE_G = new RegExp("<" + SHORT_TIMESTAMP + ">", "g");
+const SHORT_CUE_TIMING_RE = new RegExp(
+ "^[ \\t]*(" + SHORT_TIMESTAMP + ")[ \\t]+-->[ \\t]+(" + SHORT_TIMESTAMP + ")(?:[ \\t].*)?[ \\t\\r]*$",
+);
+
+// A rolling track written with short-form word tags (<mm:ss.mmm>). It counts
+// only in a document with no hh:mm:ss.mmm tag and no hh:mm:ss.mmm cue line —
+// one the old parser read no cue from — so a document it could read keeps the
+// shape it was always read as.
+function hasShortWordTiming(src: string): boolean {
+ if (!SHORT_TIMING_TAG_RE.test(src)) return false;
+ return !src.split("\n").some((line) => CUE_TIMING_RE.test(line));
+}
-// Whether VTT text carries inline word timing (<hh:mm:ss.mmm>) — the mark of
-// YouTube's rolling auto-caption shape, which parseVtt reads differently from
-// plain cue blocks.
+// Whether VTT text carries inline word timing (<hh:mm:ss.mmm>, or <mm:ss.mmm>
+// in a short-form document) — the mark of YouTube's rolling auto-caption
+// shape, which parseVtt reads differently from plain cue blocks.
export function hasWordTiming(src: string): boolean {
- return TIMING_TAG_RE.test(src);
+ return TIMING_TAG_RE.test(src) || hasShortWordTiming(src);
}
function parseTimestamp(ts: string): number {
@@ -16,6 +45,24 @@ function parseTimestamp(ts: string): number {
return +h * 3600 + +mm * 60 + +s + +ms / 1000;
}
+// A stamp SHORT_CUE_TIMING_RE captured: hours optional.
+function parseShortTimestamp(ts: string): number {
+ const m = ts.match(/^(?:(\d+):)?(\d{2}):(\d{2})\.(\d{3})$/);
+ if (!m) return Number.NaN;
+ const [, h = "0", mm, s, ms] = m;
+ return +h * 3600 + +mm * 60 + +s + +ms / 1000;
+}
+
+// A short-form cue line's times, or null when the line is not one: it must
+// match SHORT_CUE_TIMING_RE and not end before it starts.
+function shortCueTiming(line: string): { start: number; end: number } | null {
+ const m = line.match(SHORT_CUE_TIMING_RE);
+ if (!m) return null;
+ const start = parseShortTimestamp(m[1]);
+ const end = parseShortTimestamp(m[2]);
+ return Number.isFinite(start) && Number.isFinite(end) && end >= start ? { start, end } : null;
+}
+
function decodeEntities(s: string): string {
return s
.replace(/ /g, " ")
@@ -26,9 +73,9 @@ function decodeEntities(s: string): string {
.replace(/"/g, '"');
}
-function stripTags(s: string): string {
+function stripTags(s: string, shortForm: boolean): string {
return decodeEntities(s)
- .replace(/<\d{2}:\d{2}:\d{2}\.\d{3}>/g, "")
+ .replace(shortForm ? SHORT_TIMING_TAG_RE_G : /<\d{2}:\d{2}:\d{2}\.\d{3}>/g, "")
.replace(/<\/?c[^>]*>/g, "")
.replace(/\s+/g, " ")
.trim();
@@ -59,23 +106,29 @@ function stripPlainLine(s: string): string {
export function parseVtt(src: string): Cue[] {
const lines = src.replace(/\r\n/g, "\n").split("\n");
const cues: Cue[] = [];
- const rolling = hasWordTiming(src);
+ const shortRolling = !TIMING_TAG_RE.test(src) && hasShortWordTiming(src);
+ const rolling = shortRolling || TIMING_TAG_RE.test(src);
+ const tagRe = shortRolling ? SHORT_TIMING_TAG_RE : TIMING_TAG_RE;
let i = 0;
while (i < lines.length) {
const line = lines[i];
- const m = line.match(
- /(\d{2}:\d{2}:\d{2}\.\d{3})\s+-->\s+(\d{2}:\d{2}:\d{2}\.\d{3})/,
- );
- if (!m) {
+ const m = line.match(CUE_TIMING_RE);
+ const short = m ? null : shortCueTiming(line);
+ if (!m && !short) {
i++;
continue;
}
- const start = parseTimestamp(m[1]);
- const end = parseTimestamp(m[2]);
+ const start = m ? parseTimestamp(m[1]) : short!.start;
+ const end = m ? parseTimestamp(m[2]) : short!.end;
i++;
+ // A hh:mm:ss.mmm cue's body runs to the blank line, as it always did. A
+ // short-form cue's body also stops at the next cue line of either form,
+ // so a line the old parser read as a cue is still read as one. A short
+ // cue left with no body is dropped, as a bodiless hh:mm:ss.mmm cue is.
const body: string[] = [];
- while (i < lines.length && lines[i].trim() !== "") {
+ while (i < lines.length && lines[i].trim() !== ""
+ && (m || !(CUE_TIMING_RE.test(lines[i]) || shortCueTiming(lines[i])))) {
body.push(lines[i]);
i++;
}
@@ -84,9 +137,9 @@ export function parseVtt(src: string): Cue[] {
if (!rolling) {
text = body.map(stripPlainLine).filter(Boolean).join(" ");
} else {
- const taggedLines = body.filter((l) => TIMING_TAG_RE.test(l));
+ const taggedLines = body.filter((l) => tagRe.test(l));
if (taggedLines.length === 0) continue;
- text = stripTags(taggedLines[taggedLines.length - 1]);
+ text = stripTags(taggedLines[taggedLines.length - 1], shortRolling);
}
if (text) cues.push({ start, end, text });
diff --git a/common/testing/draft/runs/sweep-pipeline.json b/common/testing/draft/runs/sweep-pipeline.json
@@ -16,7 +16,28 @@
{
"message": {
"role": "assistant",
- "content": "{\"relevant\":true,\"items\":[{\"quote\":\"I did not enter the contest this year\",\"claim\":\"She says she did not enter the contest this year.\",\"on_topic\":true,\"strength\":3},{\"quote\":\"the judges were friends of mine so it felt wrong\",\"claim\":\"She says the judges were her friends, so entering felt wrong.\",\"on_topic\":true,\"strength\":3},{\"quote\":\"I entered the contest and I won it this year\",\"claim\":\"She says she won.\",\"on_topic\":true,\"strength\":3}]}"
+ "content": "{\"relevant\": true, \"items\": [{\"quote\": \"I did not enter the contest this year\", \"claim\": \"She says she did not enter the contest this year.\", \"on_topic\": true, \"strength\": 3}, {\"quote\": \"the judges were friends of mine so it felt wrong\", \"claim\": \"She says the judges were her friends, so entering felt wrong.\", \"on_topic\": true, \"strength\": 3}, {\"quote\": \"next year maybe I will enter again\", \"claim\": \"She says she may enter again next year.\", \"on_topic\": true, \"strength\": 2}]}"
+ },
+ "done": true
+ },
+ {
+ "message": {
+ "role": "assistant",
+ "content": "{\"speaker\": \"host\", \"stance\": \"asserts\", \"sentence\": \"supported\", \"fix\": \"\"}"
+ },
+ "done": true
+ },
+ {
+ "message": {
+ "role": "assistant",
+ "content": "{\"speaker\": \"host\", \"stance\": \"asserts\", \"sentence\": \"overstated\", \"fix\": \"She says the judges were friends of hers, so entering felt wrong to her.\"}"
+ },
+ "done": true
+ },
+ {
+ "message": {
+ "role": "assistant",
+ "content": "{\"speaker\": \"host\", \"stance\": \"unclear\", \"sentence\": \"supported\", \"fix\": \"\"}"
},
"done": true
},
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -8,9 +8,12 @@
- **umtool: an anonymous character is anonymous on screen too.** An anonymous character of a video ("Anon 1") went by its shown name only on umtool's own pages: the cut's post card still showed the author's name, handle and picture. Now the build and Play draw that author under the shown name wherever a card draws them -- the item's head, the strip, the posts it answers, quotes and links, a repost line, "Replying to", a thread read's and a scene's tiles, a side card, the vertical cut, the chapters -- with no handle, no verified badge and a neutral avatar (the shown name's initial on the card's muted colour). A mention of their handle in the words the card shows becomes `@Anon_1`, and a reply's captured thread shot that shows them is not drawn. A cut with no anonymous character renders exactly as before; a `narration/characters.json` the build cannot read now stops the build rather than show a real name. What a read says is unchanged.
- **umtool: the Voices page proposes characters and you accept, change or reject each.** A new "proposed" section: **Propose characters** runs the same rule as `umtool cast assign` (no model is needed or asked), each proposal shows its voice, why it was chosen and the items it would be named on, and **Accept**, **Change** (another stock voice, the name, anonymous) and **Reject** each go through the same writer as the CLI. Accepting never touches a picked read: one in another voice is listed as drift, as before.
- **umtool: every post author gets a character by rule, as a proposal you accept.** Giving each author of a video a voice meant one `cast project … keep` or Voices-page click per author. `umtool cast assign <p>` now goes through every post item's author: one the item, this video, its voice map or the cast already answers for is left as it is; one with none gets a PROPOSED character of this video -- an id from the handle, their name and a stock Kokoro voice, the next in one fixed rotation (a male and a female voice in turn) that the project does not use yet. A gender hint comes only from pronouns the profile itself states; today's captures carry none, so the rotation is neutral. Proposals are kept apart in `narration/characters.json` (the same writer and undo) and change nothing until a person acts: `--accept <id>` / `--accept-all` makes the character and names it on that author's items that name none, without touching any take; `--change <id>` sets its voice (a stock one only), speed, name or anonymity; `--reject <id>` drops it. `--dry-run` writes nothing.
+- **A local sweep's topic labels and section headings never attribute, a refresh keeps the local sweep's settings, and a revision keeps a speaker-neutral report neutral.** A heading the model wrote was kept unless it held one of a few words, and was never checked against the quotes, so a section could be headed "Main Actress's Comments" over quotes none of them hers, or "Fan Reactions"; a label could still say "acolyte writer blames filon" or "his love of the show" when the quote held those words. A label and a heading are now noun-phrase topics, read word by word against closed lists: no personal or possessive pronoun, no word of saying, thinking, feeling or judging in any of its forms (comments, reaction, response, statement, accusation, criticism, blames, hates, loves, admission, lying, defending, …), no "is / was / has / been" or contracted verb, no person-role in the possessive ("the showrunner's …"), no host's name — and every word found in the section's quotes, labels or titles, or the question. A heading that fails is written by code from its quotes' labels; the question's topic, the fallback label and the report's title, goes through the same rules. A recurring **refresh** of a report on the local route swept the new recordings in the old drafted-sentence form with no read-aloud check; it now uses `generation.localSweep`. A **revision** of a speaker-neutral report keeps its lines code's (a line is not rewritten; an added finding's line is written again from its recording's title and date and its checked topic), refuses a heading, a title or a summary that attributes, and keeps each claim's `check by ear` flag, which it used to lose. In the drafted-sentence form, a quote marked to check by ear is meaning-checked last, so it no longer takes the place of an unmarked one in the check's budget. The read-aloud patterns run in linear time: one of them took over a second on 40 letters of transcript and never returned on 60. In the **Model log**, each of these is said on the call it came from: an extract's quote "dropped: read aloud: <cue>", "kept: … flagged: check by ear (read-aloud cue: …)" or "kept: … label refused: <reason> — the run's topic used"; the grouping's heading "rewritten: heading refused: <reason> — replaced by “…” (written by code)"; a refused topic on the terms call; each meaning check kept, rewritten, dropped or flagged; and a local revision's ops applied or refused with code's reason.
+- **A local model's sweep no longer says who said it: code writes each finding around the quote, and a quote that may be read aloud is marked to check by ear.** A sweep on the `local` route (a small model on this machine) wrote "Jeremy says …" over words the host was reading out — a tweet, a headline, a review — because nothing in an automatic transcript marks a quotation and a small model cannot tell the reading from the speaking. Its findings are now written by code as `In <recording's title> (<date>), on <topic>: "<quote>"`, with the citation and the link: the model only copies the quote and names its topic in a few words, and a topic that names the speaker, says who thinks what, or uses words found nowhere around the quote is replaced by the question's topic. The report's title is written the same way, and it says where the words are, not whose they are. Before a quote is kept, code also looks at the transcript around it for signs of reading aloud — a tweet, likes and retweets read out, an article or headline being introduced, "it says", "he writes", "according to", a clip, a chat message, the host named in the third person. Such a quote goes to 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`; it can be left out instead. The signs are patterns, so a headline read with nothing announcing it is not caught: the section is where to listen first, not a guarantee about the rest. Both are settings (`generation.localSweep.claimForm`: `neutral` or `sentence`, the earlier drafted sentence with its meaning check; `generation.localSweep.readAloud`: `flag`, `drop` or `off`), set with `archilyzer gen local-sweep [--form …] [--read-aloud …]` or on umtool's **Settings → Generation**. Sweeps by Claude (Claude Code or the API) are not changed.
- **umtool: a Model log shows what the model was asked, what it answered, and what the code did with it.** Until now a prompt was shown nowhere, and a local model's calls were in no ledger. Every model call of a run is now recorded, on every route (a local model, the Claude API, this session), and listed in a **Model log** panel on the run page (`/research/runs/<article>/<n>`), the article's Iterations tab and each media draft. Calls are grouped by phase (terms, reading, meaning check, grouping). A row has the first lines of what was asked, what came back, the seconds, and whether its answer was kept, dropped or rewritten, with the reason and each item's fate. A row opens to the whole prompt and answer (40,000 characters of each are kept). A log holds 20,000 calls or 32 MB; past that the panel says the log is full, and later calls are not recorded. The header counts the calls, the seconds and the models; a filter narrows to kept, dropped or rewritten; the list follows a run while it runs. `umtool model-log <article> <n>` (or `--job <jobId>`) prints the same, with `--phase`, `--outcome`, `--task`, `--run`, `--call <run.call>` for one call's whole text, and `--json`; a control sequence in a recorded text is printed as its escape (`\x1b`), never sent to the terminal. `/settings/generation` shows, per task, the route and the model it will run on, "no API key configured" when there is none, and the model of its last run.
- **The job page has the Model log too, and a local model's calls are in the usage ledger.** A job that calls a model (a report draft, a refresh, triage, verdicts, a frame scan, clip suggestions, video assist) shows its calls on `/jobs/<id>`, as umtool does. Calls to a local model are appended to `.generation/usage.jsonl` with route `local` and cost 0, so `pnpm ops get generation-usage` lists every model a run called, and a run that was local only lists no other. `pnpm ops get iterations` gains each iteration's call count and seconds. The record keeps the text sent to the model and nothing else: no header and no model host; the editor's `WORKER_TOKEN`, an API key, every environment variable named like a credential, and host paths are taken out before a line is written, anything shaped like a credential (a URL's user and password, a token in a query string however its `&` and `=` are written — `\u0026`, `&`, `%26`, `%3D` — an `Authorization` value of any scheme, a `Bearer` value, a cookie line, a key that says what it is) loses its value whoever's it is, while a date or a time after `secret:` or `token:` is left as it is, and a failed call's message has its URLs and addresses removed. Links are kept.
- **Cancelling a job whose program never started no longer stops the editor.** A download cancelled after its channel directory was gone sent SIGTERM to the editor's whole process group: Node's `kill()` on a child that failed to spawn has no pid and signals the caller's own group. A kill on such a child is now a no-op in the editor, and umtool and the standalone scripts (the queue lock, `render-mode on -- <cmd>`, loudness, voice, TTS, diarization, `pnpm e2e:all`) check the child's pid before every kill; a sweep test holds them to it.
+- **A local media library's subtitles may use short cue timings (`01:02.500 --> 01:04.000`).** A Local Archive channel (New channel → Local Archive, or `pnpm ops local-media-configure`) scans a folder of recordings with their `.info.json` and `.vtt` or `.srt`, and imports them as records whose video stays in the library. A `.vtt` written with minutes and seconds only — what FFmpeg and hand-made subtitle files write — read as "no usable cues" and was held for review; it is now read, previewed with its cue count and imported byte for byte. The hours form every published site's captions are read with is unchanged and tried first, so no existing caption file reads differently (checked against 10,874 of the corpus's caption files: 0 cues differ); a short-form line is read only where it does not match, and only strictly: minutes and seconds 00–59, exactly three millisecond digits, hours optional and at most four digits, an end not before its start, and its text stopping at the next cue line of either form, so a line the old reading took as a cue is still one. A recording whose file name holds a control character, `\` or `:` is now held for review in the preview, saying so, instead of being offered as new and refused at import.
- **A published archive is a source: connect it once, sweep it, and fetch its cited clips with no local corpus.** A fresh clone pointed at jeralyzer.pages.dev could search it through the MCP and do nothing else: Create had no corpus to offer, and every clip of a channel the editor did not archive was a 404 `Channel "<slug>" not found`. An archive is now connected by its origin — `/sites` → **Connected archives**, or `pnpm ops archives --json '{"connect":"https://jeralyzer.pages.dev"}'` (`"dryRun": true` reads it and writes nothing; `pnpm ops get archives` lists them) — and kept in `settings.remoteArchives`. `TRANSCRIPT_SITE_URL`'s archive is offered without being connected, so a clone set up as AGENTS.md says starts with one. Create offers each connected archive as a sweep's source, preselected when this machine has no corpus of its own, the MCP's `list_sources` lists them and `generate` passes the choice. A sweep over an archive cites that archive's origin, whatever `generation.citationOrigin` says, and its revisions, drafts and refreshes inherit it. A clip window cited from one registers its channel **remote-only** on first need (`fetch-windows` and `fetch-window` take `"archive"`, and the MCP's `fetch_clip` names it): a `config.json` and nothing else, shown as "remote only" in the channel list, skipped by every sync, lane, scan and site build, and left out of the site form's channel picker. On a whole-recording platform (Rumble) a window means downloading the whole recording, which nobody planned for a channel that is not archived here: it is refused with the recording's length and estimated size until the ask carries `"allowWholeRecording": true`. The archive's documents are cached on disk by its build (512 MB by default), read one at a time and paced. `corpus.json` is spec 6 (the export's changelog): each channel names its platform and its page there; an older archive's platform is read from a record's `webpageUrl`.
- **A connected archive is untrusted input.** umtool can connect one and is open on the LAN, and everything an archive serves is someone else's JSON. An archive on this machine or its network — loopback, private, link-local and CGNAT addresses in any spelling (decimal, hex, IPv4 carried inside IPv6), a `.local`/`.internal`/`.lan` name, or a name that resolves to one — is refused at connect, before anything is asked of it, unless the editor runs with `ARCHILYZER_ALLOW_PRIVATE_ARCHIVES=1` or the origin is `TRANSCRIPT_SITE_URL`'s or already in `settings.json`; the check is made once, at connect. Its documents are read on its own origin only: a redirect elsewhere is refused unfollowed, a manifest its `corpus.json` names on another origin is not followed, and no document past 32 MB is read or kept. A record's page URL is fetched only when its host is its channel's video platform's own domain or a subdomain (`evilyoutube.com` and `youtube.com.evil.example` are not YouTube); a URL carrying a backslash, whitespace or a control character is refused unparsed, because Node and yt-dlp's Python read its host differently; and what reaches yt-dlp is the URL the check parsed, never the archive's own string. A remote-only channel whose archive was removed from settings is refused before its record is read.
- **umtool: the Source chip connects an archive, and an article swept over one is cut from it.** The Source chip takes an archive's address, reads it and connects it through the editor; a connected archive is offered as the source of **Article from a question** and of a new article, first when this machine has no corpus. The chain of an article swept over an archive asks the editor for its windows with the archive named and each record's page URL, so the cited channels are registered remote-only and fetched; a manifest with no sweep naming an origin takes the archive as its QR origin. A Rumble window fails the step with every recording's size, nothing fetched, until **Fetch the whole recordings** (`umtool chain <article> <n> --allow-whole-recording`). `--stop-before-render` ends Draft everything before the voices, and its new `cut-windows` step fetches the drafted cut's windows, asking the editor only for those not on disk. The cue walk, the link check and a source's build identity read an archive under the same rules as the editor (its own origin, 32 MB), and a chain whose archive is no longer connected stops and says to connect it again.
diff --git a/editor/e2e/local-media.spec.ts b/editor/e2e/local-media.spec.ts
@@ -13,6 +13,11 @@ import { join } from "node:path";
import { resetData, testPaths, writeChannelConfig } from "./helpers";
const VTT = "WEBVTT\n\n00:00:01.000 --> 00:00:03.000\nA synthetic library cue\n";
+// Short-form cue timings (mm:ss.mmm), what FFmpeg and hand-made subtitle files
+// write: the prepared recording carries them through preview (both cues
+// counted) and import (byte for byte). Its index is
+// common/controller/buildIndexLocalRecording.test.ts.
+const SHORT_VTT = "WEBVTT\n\n00:01.000 --> 00:03.000\nA short-form library cue\n\n01:02.500 --> 01:04.000\nA second short-form cue\n";
test("a Local Archive channel imports a library recording and a prepared one, playback left off", async ({ page }) => {
await resetData("empty");
@@ -26,7 +31,7 @@ test("a Local Archive channel imports a library recording and a prepared one, pl
}));
await writeFile(join(library, "aaaaaaaaaaa.vtt"), VTT);
await writeFile(join(library, "talk.mp4"), "synthetic mp4 talk");
- await writeFile(join(library, "talk.vtt"), VTT);
+ await writeFile(join(library, "talk.vtt"), SHORT_VTT);
const before = (await readdir(library)).sort();
await page.goto("/channels/new");
@@ -44,6 +49,10 @@ test("a Local Archive channel imports a library recording and a prepared one, pl
await expect(page.getByRole("status").filter({ hasText: "discovered" })).toHaveText(
"2 discovered · 1 new · 0 occupied · 1 need review",
);
+ // Cues / notes: the short-form transcript's two cues are read, not "no usable cues".
+ const cuesOf = (media: string) => page.getByRole("row").filter({ has: page.getByLabel(`Import ${media}`) }).getByRole("cell").nth(3);
+ await expect(cuesOf("talk.mp4")).toHaveText(/^2(?!\d)/);
+ await expect(cuesOf("aaaaaaaaaaa.mp4")).toHaveText(/^1(?!\d)/);
await page.getByLabel("Import aaaaaaaaaaa.mp4").check();
await page.getByRole("button", { name: "Prepare details for talk.mp4" }).click();
@@ -66,6 +75,8 @@ test("a Local Archive channel imports a library recording and a prepared one, pl
const local = ids.find((id) => id.startsWith("local-"))!;
expect((await readdir(join(data, local))).sort()).toEqual(["external-media.json", "metadata.info.json", "transcript.en.vtt"]);
expect(JSON.parse(await readFile(join(data, local, "metadata.info.json"), "utf8")).title).toBe("A prepared talk");
+ // The short-form transcript is imported byte for byte, never rewritten.
+ expect(await readFile(join(data, local, "transcript.en.vtt"), "utf8")).toBe(SHORT_VTT);
// A local record's page names it a local recording, with no download card.
await page.goto(`/channels/local-spec-library/videos/${local}`);
diff --git a/mcp/src/draftTasks.test.ts b/mcp/src/draftTasks.test.ts
@@ -323,18 +323,26 @@ test("sweep-pipeline: terms, enumerate, windows, extract (a non-verbatim quote d
assert.match(md, /^# The baker and the pie contest/);
assert.match(md, /## Why she stayed out/);
assert.ok(md.includes(`${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=10`));
- assert.ok(!md.includes("I entered the contest and I won"), "the invented quote never made it");
+ assert.ok(md.includes("next year maybe I will enter again"));
+ // The meaning check (D2 item 3): one call per item; an overstated sentence
+ // replaced by its fix; an unclear stance marked, in a last section of its own.
+ assert.ok(md.includes("- She says the judges were friends of hers, so entering felt wrong to her. \"the judges were friends of mine so it felt wrong\""));
+ assert.match(md, /## To check by ear\n\n- Check by ear: She says she may enter again next year\. "next year maybe I will enter again"/);
+ assert.ok(md.indexOf("## Why she stayed out") < md.indexOf("## To check by ear"));
+ const items = (await readIterationFile("synth-pipe", it.n, "items.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l));
+ assert.deepEqual(items.map((x) => x.decision.action), ["keep", "rewrite", "mark"]);
+ assert.match(items[0].prompt, /^Question: Did the baker enter the pie contest\?\n\nThe host: the channel's host \(its own voice\)\n\nBefore the quote: …good evening chat welcome to the pie stream a lot of you asked about the contest\n\nQUOTE: I did not enter the contest this year\n\nAfter the quote: the judges/);
+ assert.ok(items.every((x) => typeof x.seconds === "number" && x.answer.speaker === "host"));
assert.match(md, /## Coverage\n\nSearched synth-kitchen for contest, judges\. 1 video\(s\) matched; 1 read/);
// The job's progress: the recordings gone through, of the worklist (release 28 F3).
assert.deepEqual(d.progressed, [{ metric: "entries", current: 0, total: 1 }, { metric: "entries", current: 1, total: 1 }]);
const report = JSON.parse((await readIterationFile("synth-pipe", it.n, "report.json", paths))!);
- assert.equal(Object.keys(report.citations).length, 2);
+ assert.equal(Object.keys(report.citations).length, 3);
const turns = (await readIterationFile("synth-pipe", it.n, "turns.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l));
- assert.ok(turns.some((t) => t.kind === "dropped" && t.why === "not verbatim in its window"));
assert.ok(turns.some((t) => t.kind === "enumerate" && t.term === "contest"));
const after = (await readIteration("synth-pipe", it.n, paths))!;
assert.equal(after.usage["qwen3:8b"]!.usd, 0);
- assert.equal(after.usage["qwen3:8b"]!.calls, 3);
+ assert.equal(after.usage["qwen3:8b"]!.calls, 6);
// The trace (umtool R3): scope, terms, an enumeration per term, the read
// batch with the model's lines, the quote dropped in its window and why,
@@ -345,12 +353,8 @@ test("sweep-pipeline: terms, enumerate, windows, extract (a non-verbatim quote d
assert.deepEqual(trace.filter((e) => e.t === "enumerate").map((e) => e.query), ["contest", "judges"]);
const batch = trace.find((e) => e.t === "batch")!;
assert.deepEqual([batch.k, batch.of, batch.ids], [1, 1, ["pie-stream-02"]]);
- assert.ok(batch.lines.some((l: string) => l.includes("[dropped: not verbatim in its window]")));
- const drop = trace.find((e) => e.t === "check" && e.dropped)!;
- assert.deepEqual([drop.stage, drop.reason, drop.cite.video], ["extract", "not verbatim in its window", "pie-stream-02"]);
- assert.ok(drop.quote.includes("I entered the contest and I won"));
- assert.equal(trace.filter((e) => e.t === "check" && e.stage === "final").length, 2);
- assert.equal(trace.filter((e) => e.t === "finding").length, 2);
+ assert.equal(trace.filter((e) => e.t === "check" && e.stage === "final").length, 3);
+ assert.equal(trace.filter((e) => e.t === "finding").length, 3);
assert.deepEqual(trace.at(-1)!.status, "done");
assert.deepEqual(after.coverage, { matched: 1, read: 1, partial: false, unreached: [] });
@@ -358,25 +362,251 @@ test("sweep-pipeline: terms, enumerate, windows, extract (a non-verbatim quote d
const files = modelLogFilesIn(iterationDir(paths, "synth-pipe", it.n));
const log = await readModelLog(files);
assert.deepEqual(log.runs.map((x) => [x.task, x.model]), [["sweep", "qwen3:8b"]]);
- assert.deepEqual(log.calls.map((c) => [c.phase, c.route, c.model]), [["terms", "local", "qwen3:8b"], ["reading", "local", "qwen3:8b"], ["grouping", "local", "qwen3:8b"], ["grouping", "local", "qwen3:8b"]]);
- const [terms, extract, group, regroup] = log.calls;
+ assert.deepEqual(
+ log.calls.map((c) => [c.phase, c.route, c.model]),
+ [["terms", "local", "qwen3:8b"], ["reading", "local", "qwen3:8b"], ...Array(3).fill(["meaning-check", "local", "qwen3:8b"]), ["grouping", "local", "qwen3:8b"], ["grouping", "local", "qwen3:8b"]],
+ );
+ const [terms, extract, m1, m2, m3, group, regroup] = log.calls;
+ // The meaning check's decisions (D2 item 3): kept, rewritten to its fix, kept flagged to check by ear.
+ assert.deepEqual([m1, m2, m3].map((c) => c!.decision.outcome), ["kept", "rewritten", "kept"]);
+ assert.match(m3!.decision.why, /^flagged: check by ear \(stance unclear: check by ear\)/);
+ assert.deepEqual(m2!.items?.map((x) => x.text), ["She says the judges were friends of hers, so entering felt wrong to her."]);
// The second grouping ask (one section held every finding) met the fake's
// empty script: recorded as failed, the first one kept.
assert.match(regroup!.error ?? "", /no structured answer/);
assert.deepEqual(terms!.decision, { outcome: "kept", why: "searched for contest, judges" });
assert.equal(extract!.label, "extract pie-stream-02@0");
- const lost = extract!.items!.find((x) => x.outcome === "dropped")!;
- assert.equal(lost.why, "not verbatim in its window");
- assert.ok(lost.text.includes("I entered the contest and I won"));
- assert.equal(extract!.items!.filter((x) => x.outcome === "kept").length, 2);
+ // (This round's recording holds three verbatim items; a drop's row is the gate test's below.)
+ assert.deepEqual(extract!.items!.map((x) => [x.outcome, x.why]), [
+ ["kept", "verbatim in its window"],
+ ["kept", "verbatim in its window"],
+ ["kept", "verbatim in its window"],
+ ]);
assert.equal(group!.decision.outcome, "kept");
assert.match(group!.decision.why, /^placed 2 of 2 findings in \d section/);
- assert.ok(log.calls.slice(0, 3).every((c) => c.seconds >= 0 && typeof c.tokensIn === "number"));
+ assert.ok(log.calls.slice(0, 6).every((c) => c.seconds >= 0 && typeof c.tokensIn === "number"));
const text = (await readModelCallText(files, extract!.id))!;
assert.ok(text.system.startsWith("You read excerpts of an automatic transcript"));
assert.match(text.prompt, /^Research question: Did the baker enter the pie contest\?/);
});
+test("sweep-pipeline gate (D2 item 2): an item with no rare term in its quote or the 300 characters before it is dropped; fewer than three is 'nothing usable found', said in one sentence, with no grouping call", async () => {
+ const r = await run("sweep-pipeline");
+ // The terms are given ("judges"): the model is asked to extract only.
+ const turns = structuredClone(r.turns).slice(1, 2);
+ turns[0].message.content = JSON.stringify({
+ relevant: true,
+ items: [
+ { quote: "I did not enter the contest this year", claim: "She says she did not enter the contest this year.", on_topic: true, strength: 3 },
+ { quote: "the judges were friends of mine so it felt wrong", claim: "She says the judges were her friends.", on_topic: true, strength: 3 },
+ { quote: "I entered the contest and I won it this year", claim: "She says she won.", on_topic: true, strength: 3 },
+ ],
+ });
+ ol.push(...turns);
+ const it = await createIteration("synth-gate", { kind: "sweep", model: r.model, question: r.question, scope: { channels: r.channels } }, paths);
+ const d = deps();
+ const out = await runTask({ task: "sweep-pipeline", article: "synth-gate", n: it.n, origin: ORIGIN, terms: ["judges"] }, d);
+ assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`);
+ assert.equal(
+ out.summary,
+ "Nothing usable found: 1 recording(s) read of 1 matching judges; 1 passage(s) were verbatim and on the question (1 more were verbatim but off it), fewer than the 3 a report needs.",
+ );
+ assert.equal(ol.remaining(), 0, "no grouping call");
+ const trace = await traceOf("synth-gate", it.n);
+ const drops = trace.filter((e) => e.t === "check" && e.dropped).map((e) => [e.quote, e.reason]);
+ assert.deepEqual(drops, [
+ ["I did not enter the contest this year", "off the question: no “judges” in the quote or the 300 characters before it"],
+ ["I entered the contest and I won it this year", "not verbatim in its window"],
+ ]);
+ const md = (await readIterationFile("synth-gate", it.n, "sweep.md", paths))!;
+ assert.match(md, /## Nothing usable found\n\nNothing usable found: /);
+ assert.ok(!md.includes("the judges were friends"), "never padded with the one item");
+ const report = JSON.parse((await readIterationFile("synth-gate", it.n, "report.json", paths))!);
+ 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, "“says” is a word of saying, thinking or judging");
+ 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/);
+ // The model log: each item's fate on its extract call — a refused label and a read-aloud flag said there.
+ const log = await readModelLog(modelLogFilesIn(iterationDir(paths, "synth-neutral", it.n)));
+ const ex = log.calls.find((c) => c.phase === "reading")!;
+ assert.deepEqual(ex.items!.map((x) => [x.outcome, x.why]), [
+ ["kept", "verbatim in its window"],
+ ["kept", "verbatim in its window; label refused: “says” is a word of saying, thinking or judging — the run's topic used"],
+ // ("finalist" stands for the host's name: its label "meeting the finalist" names him.)
+ ["kept", "verbatim in its window; flagged: check by ear (read-aloud cue: names the host (quote: “finalist”)); label refused: it names finalist — the run's topic used"],
+ ]);
+ // The grouping's heading, refused and written by code.
+ const grp = log.calls.find((c) => c.phase === "grouping")!;
+ assert.deepEqual(grp.items!.map((x) => [x.text, x.outcome]), [["heading: What the baker thinks of the judges", "rewritten"]]);
+ assert.match(grp.items![0]!.why, /^heading refused: “thinks” is a word of saying, thinking or judging — replaced by “Entering the pie contest” \(written by code\)$/);
+});
+
+test("sweep-pipeline, the neutral form (review of round b): the run's topic and every heading pass the label rules — a topic that attributes is never the title or a fallback label, a heading that attributes or is not grounded is code's", async () => {
+ const { r, turns } = await neutralTurns();
+ turns[0].message.content = JSON.stringify({ terms: ["contest", "judges"], topic: "the baker hates the contest" });
+ turns[2].message.content = JSON.stringify({ title: "x", sections: [{ heading: "Fan Reactions", findings: [1] }, { heading: "The pie contest", findings: [2] }] });
+ ol.push(...turns);
+ const it = await createIteration("synth-neutral-heads", { 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-heads", 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 md = (await readIterationFile("synth-neutral-heads", it.n, "sweep.md", paths))!;
+ assert.ok(!/hates/.test(md.replace(/^Question: .*$/m, "")), md);
+ assert.ok(d.lines.some((l) => l.startsWith("the run's topic: “the baker hates the contest” refused (“hates” is a word of saying, thinking or judging)")), d.lines.join("\n"));
+ const runTopic = /“([^”]+)” used$/.exec(d.lines.find((l) => l.startsWith("the run's topic:"))!)![1]!;
+ assert.match(md, new RegExp(`^# ${runTopic[0]!.toUpperCase()}${runTopic.slice(1)}: quotes from Synth Kitchen$`, "m"));
+ assert.ok(md.includes(`on ${runTopic}: "the judges were friends of mine so it felt wrong"`), "a refused label is the checked run topic");
+ assert.deepEqual([...md.matchAll(/^## (.+)$/gm)].map((m) => m[1]), ["Entering the pie contest", "The pie contest", "To check by ear", "Coverage"]);
+ assert.ok(d.lines.includes("heading “Fan Reactions” replaced by “Entering the pie contest” (“reactions” is a word of saying, thinking or judging)"), d.lines.join("\n"));
+ // The model log: the refused topic on the terms call, each heading's fate on the grouping call.
+ const log = await readModelLog(modelLogFilesIn(iterationDir(paths, "synth-neutral-heads", it.n)));
+ const termsCall = log.calls.find((c) => c.phase === "terms")!;
+ assert.deepEqual(termsCall.items!.filter((x) => x.text.startsWith("topic: ")).map((x) => [x.text, x.outcome, x.why]), [
+ ["topic: the baker hates the contest", "dropped", "label refused: “hates” is a word of saying, thinking or judging"],
+ ...termsCall.items!.filter((x) => x.text.startsWith("topic: ") && x.outcome !== "kept").slice(1).map((x) => [x.text, x.outcome, x.why]),
+ [`topic: ${runTopic}`, "kept", "the run's topic (its fallback label and the report's title)"],
+ ]);
+ assert.deepEqual(log.calls.find((c) => c.phase === "grouping")!.items!.map((x) => [x.text, x.outcome]), [
+ ["heading: Fan Reactions", "rewritten"],
+ ["heading: The pie contest", "kept"],
+ ]);
+});
+
+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”)"]],
+ );
+ const log = await readModelLog(modelLogFilesIn(iterationDir(paths, "synth-neutral-drop", it.n)));
+ assert.deepEqual(
+ log.calls.find((c) => c.phase === "reading")!.items!.filter((x) => x.outcome === "dropped").map((x) => x.why),
+ ["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 — last, never spending an unmarked one's budget — and stays marked to check by ear", async () => {
+ const r = await run("sweep-pipeline");
+ // The meaning answers by the quote they judge (the checks' order is code's: marked last).
+ const meaningFor = (quote: string) => r.turns.slice(2, 5)[["I did not enter the contest this year", "the judges were friends of mine so it felt wrong", "next year maybe I will enter again"].indexOf(quote)];
+ const byQuote = (body: { messages?: { content?: string }[] }) => {
+ const user = String(body.messages?.at(-1)?.content ?? "");
+ const q = ["I did not enter the contest this year", "the judges were friends of mine so it felt wrong", "next year maybe I will enter again"].find((x) => user.includes(`QUOTE: ${x}\n`));
+ return meaningFor(q!);
+ };
+ ol.push(r.turns[0], r.turns[1], byQuote, byQuote, byQuote, r.turns[5]);
+ 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/);
+ const trace = await traceOf("synth-sentence-flag", it.n);
+ assert.equal(trace.filter((e) => e.t === "meaning").at(-1)!.quote, "the judges were friends of mine so it felt wrong", "the read-aloud-marked quote is checked last");
+});
+
+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);
+ turns[0].message.content = JSON.stringify({ terms: ["kitchen", "say", "contest", "judges"], topic: "the pie contest" });
+ ol.push(...turns);
+ const it = await createIteration("synth-select", { 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-select", n: it.n, origin: ORIGIN }, d);
+ assert.equal(out.status, "done", `${out.summary}\n${d.lines.join("\n")}`);
+ const trace = await traceOf("synth-select", it.n);
+ const t = trace.find((e) => e.t === "terms")!;
+ assert.deepEqual(t.terms, ["contest", "judges"]);
+ assert.equal(t.topic, "the pie contest");
+ assert.deepEqual(
+ t.dropped.map((x: { term: string; why: string }) => [x.term, x.why]),
+ [
+ ["kitchen", "the subject's own name"],
+ ["say", "a generic word"],
+ ],
+ );
+ assert.deepEqual(trace.filter((e) => e.t === "enumerate").map((e) => e.query).sort(), ["contest", "judges"]);
+ const sel = trace.find((e) => e.t === "select")!;
+ assert.deepEqual(sel.read.map((x: { id: string; why: string }) => [x.id, x.why]), [["pie-stream-02", "top"]]);
+ assert.ok(sel.read[0].score > 0);
+});
+
test("revise-report: ops over the parent's sweep.md — applied, refused with reasons; quotes untouched; a new quote checked", async () => {
await drainFake();
const r = await run("revise-report");
diff --git a/mcp/src/refreshTask.test.ts b/mcp/src/refreshTask.test.ts
@@ -14,6 +14,12 @@ 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 { modelLogFilesIn, readModelLog } from "yt-dlp-transcript-common/lib/llm/callLog-server";
+import { iterationDir } from "yt-dlp-transcript-common/lib/report/iterations";
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 +31,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 +44,7 @@ before(async () => {
after(async () => {
await later.close();
await api.close();
+ await ol.close();
await rm(tmp, { recursive: true, force: true });
});
@@ -115,3 +124,137 @@ 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 model log: every call of the refresh, and what code did with the revision's ops.
+ const log = await readModelLog(modelLogFilesIn(iterationDir(paths, art, 2)));
+ assert.deepEqual(log.calls.map((c) => c.phase), ["reading", "grouping", "grouping", "revision"]);
+ const rev = log.calls.at(-1)!;
+ assert.equal(rev.decision.outcome, "kept");
+ assert.deepEqual(rev.items!.map((x) => [x.outcome, x.why.split(":")[0]]), [
+ ["kept", "applied"],
+ ["dropped", "refused"],
+ ["dropped", "refused"],
+ ["dropped", "refused"],
+ ["dropped", "refused"],
+ ]);
+ assert.match(rev.items![1]!.why, /^refused: a speaker-neutral report's lines are written by code/);
+ // The extract call's item.
+ assert.deepEqual(log.calls[0]!.items!.map((x) => [x.outcome, x.why]), [["kept", "verbatim in its window"]]);
+ // 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],
+ ],
+ );
+});
diff --git a/settings.json.example b/settings.json.example
@@ -360,6 +360,10 @@
"localModel": "qwen2.5vl:7b",
"maxUsd": 5,
"everySeconds": 10
+ },
+ "localSweep": {
+ "claimForm": "neutral",
+ "readAloud": "flag"
}
},
"clips": {
diff --git a/umtool/app/api/research/cases/[id]/handoff/route.ts b/umtool/app/api/research/cases/[id]/handoff/route.ts
@@ -10,7 +10,7 @@ export const dynamic = "force-dynamic";
// { to: "article", confirm: true, … } -> { href, jobId, iteration }
// { to: "video", slug?, title? } -> { plan: VideoPlan }
// { to: "video", confirm: true, … } -> { href }
-// { to: "sweep", article?, model?, question? } -> { plan: ArticlePlan } (seeded: false)
+// { to: "sweep", article?, model?, question?, dateFrom?, dateTo? } -> { plan: ArticlePlan } (seeded: false; the dates override the scope's)
// { to: "sweep", confirm: true, … } -> { href (the run's page), jobId, iteration }
// An article is a seeded report-draft sweep the editor runs (it spends: the
// plan says on what model, under which cap); a video is a project scaffolded
@@ -28,7 +28,13 @@ export async function POST(request: Request, ctx: { params: Promise<{ id: string
return ok(confirm ? await confirmArticle(id, over) : { plan: (await planArticle(id, over)).plan });
}
if (b.to === "sweep") {
- const over = { ...(s("article") ? { article: s("article") } : {}), ...(s("model") ? { model: s("model") } : {}), ...(s("question") ? { question: s("question") } : {}) };
+ const over = {
+ ...(s("article") ? { article: s("article") } : {}),
+ ...(s("model") ? { model: s("model") } : {}),
+ ...(s("question") ? { question: s("question") } : {}),
+ ...(s("dateFrom") ? { dateFrom: s("dateFrom") } : {}),
+ ...(s("dateTo") ? { dateTo: s("dateTo") } : {}),
+ };
return ok(confirm ? await confirmScopeSweep(id, over) : { plan: (await planScopeSweep(id, over)).plan });
}
if (b.to === "video") {
diff --git a/umtool/components/articles/PolicyPanel.tsx b/umtool/components/articles/PolicyPanel.tsx
@@ -237,6 +237,37 @@ export default function PolicyPanel({
</Button>
</form>
+ <div className="micro pt-1">local sweep</div>
+ <div className="flex flex-wrap items-center gap-x-4 gap-y-1" data-policy-local-sweep={`${g.localSweep.claimForm} ${g.localSweep.readAloud}`}>
+ <label className="flex items-center gap-1.5">
+ <span className="text-[var(--color-dim)]">each finding's line</span>
+ <select
+ aria-label="local sweep claim form"
+ className={field}
+ value={g.localSweep.claimForm}
+ disabled={busy}
+ onChange={(e) => save({ localSweep: { ...g.localSweep, claimForm: e.target.value } }, "the local sweep's claim form")}
+ >
+ <option value="neutral">written by code: In title (date), on topic: quote</option>
+ <option value="sentence">drafted by the model, then checked</option>
+ </select>
+ </label>
+ <label className="flex items-center gap-1.5">
+ <span className="text-[var(--color-dim)]">a quote that may be read aloud</span>
+ <select
+ aria-label="local sweep read-aloud quotes"
+ className={field}
+ value={g.localSweep.readAloud}
+ disabled={busy}
+ onChange={(e) => save({ localSweep: { ...g.localSweep, readAloud: e.target.value } }, "the local sweep's read-aloud rule")}
+ >
+ <option value="flag">kept, marked to check by ear</option>
+ <option value="drop">left out</option>
+ <option value="off">not looked for</option>
+ </select>
+ </label>
+ </div>
+
<div className="micro pt-1">API key</div>
<div className="flex items-center gap-2" data-key-file-exists={policy.keyFile.exists ? "yes" : "no"}>
<code className="font-mono text-[11px]">{policy.keyFile.path}</code>
diff --git a/umtool/components/research/HandoffDialog.tsx b/umtool/components/research/HandoffDialog.tsx
@@ -3,6 +3,7 @@
import { useEffect, useState } from "react";
import { buttonVariants } from "@/components/ui/button";
import { Dialog } from "@/components/ui/dialog";
+import { controlClass } from "@/components/ui/field";
import { researchCaseHandoffApi } from "@/lib/research/hrefs";
import type { ArticlePlan, HandoffPlan, VideoPlan } from "@/lib/research/case-types";
@@ -29,7 +30,7 @@ function Row({ k, children }: { k: string; children: React.ReactNode }) {
);
}
-function ArticleBody({ p }: { p: ArticlePlan }) {
+function ArticleBody({ p, dates, setDates }: { p: ArticlePlan; dates?: { from: string; to: string }; setDates?: (d: { from: string; to: string }) => void }) {
return (
<dl className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5 text-[12.5px]">
<Row k="Article">
@@ -37,9 +38,30 @@ function ArticleBody({ p }: { p: ArticlePlan }) {
</Row>
<Row k="Question">{p.question}</Row>
<Row k="Channels">{p.channels.join(", ") || "—"}</Row>
- {(p.dateFrom || p.dateTo) && (
+ {dates && setDates ? (
<Row k="Dates">
- {p.dateFrom ?? "…"} – {p.dateTo ?? "…"}
+ <span className="inline-flex flex-wrap items-center gap-1.5">
+ <label className="inline-flex items-center gap-1">
+ From
+ <input type="date" aria-label="From" className={controlClass} value={dates.from} onChange={(e) => setDates({ ...dates, from: e.target.value })} />
+ </label>
+ <label className="inline-flex items-center gap-1">
+ To
+ <input type="date" aria-label="To" className={controlClass} value={dates.to} onChange={(e) => setDates({ ...dates, to: e.target.value })} />
+ </label>
+ </span>
+ </Row>
+ ) : (
+ (p.dateFrom || p.dateTo) && (
+ <Row k="Dates">
+ {p.dateFrom ?? "…"} – {p.dateTo ?? "…"}
+ </Row>
+ )
+ )}
+ {p.reading && (
+ <Row k="Reads">
+ the top {p.reading.recordings} recordings by rarity × hits, plus one per year-quarter a rare term hits (at most {p.reading.spreadMax})
+ {p.reading.minutes !== undefined ? `; about ${p.reading.minutes} min of model time` : ""}
</Row>
)}
{p.seeded !== false ? (
@@ -109,13 +131,19 @@ export default function HandoffDialog({
const [plan, setPlan] = useState<HandoffPlan | null>(null);
const [error, setError] = useState<string | null>(null);
const [working, setWorking] = useState(false);
+ // A scope sweep's dates (D2): the scope's, changeable here for this run.
+ const [dates, setDates] = useState<{ from: string; to: string }>({ from: "", to: "" });
useEffect(() => {
setPlan(null);
setError(null);
if (!to) return;
let live = true;
post<{ plan: HandoffPlan }>(researchCaseHandoffApi(caseId), { to })
- .then((r) => live && setPlan(r.plan))
+ .then((r) => {
+ if (!live) return;
+ setPlan(r.plan);
+ if (r.plan.to === "article") setDates({ from: r.plan.dateFrom ?? "", to: r.plan.dateTo ?? "" });
+ })
.catch((e: Error) => live && setError(e.message));
return () => {
live = false;
@@ -127,7 +155,12 @@ export default function HandoffDialog({
setWorking(true);
setError(null);
try {
- const r = await post<{ href: string }>(researchCaseHandoffApi(caseId), { to, confirm: true, ...(plan.to === "article" ? { article: plan.article } : { slug: plan.slug }) });
+ const r = await post<{ href: string }>(researchCaseHandoffApi(caseId), {
+ to,
+ confirm: true,
+ ...(plan.to === "article" ? { article: plan.article } : { slug: plan.slug }),
+ ...(to === "sweep" ? { dateFrom: dates.from, dateTo: dates.to } : {}),
+ });
onDone(r.href, plan.to === "article" ? `The sweep for ${plan.article} is queued${to === "sweep" ? ": its run page follows it" : ""}` : `Project ${plan.slug} written`);
} catch (e) {
setError((e as Error).message);
@@ -145,7 +178,7 @@ export default function HandoffDialog({
Reading the plan…
</p>
)}
- {plan && (plan.to === "article" ? <ArticleBody p={plan} /> : <VideoBody p={plan} />)}
+ {plan && (plan.to === "article" ? <ArticleBody p={plan} {...(to === "sweep" ? { dates, setDates } : {})} /> : <VideoBody p={plan} />)}
{plan && plan.refusals.length > 0 && (
<ul data-refusals="" className="mt-3 grid list-none gap-1 p-0 text-[12.5px] text-reject-text">
{plan.refusals.map((r) => (
diff --git a/umtool/e2e/fixtures/run-sweep.ts b/umtool/e2e/fixtures/run-sweep.ts
@@ -38,10 +38,27 @@ if (!article || !Number.isInteger(n) || !articlesDir || !corpusDir) {
process.exit(2);
}
-const run = JSON.parse(await readFile(path.join(RUNS, "sweep-pipeline.json"), "utf8")) as { turns: unknown[] };
+const run = JSON.parse(await readFile(path.join(RUNS, "sweep-pipeline.json"), "utf8")) as { turns: { message: { content: string } }[] };
+// The recorded run (terms, one extract, a meaning check per kept item, the
+// grouping), with one more term ("oven") so a second recording is read, whose
+// one item is not in its transcript: code drops it (not verbatim), so the log
+// has a dropped quote and its reason, beside the recording's three kept ones
+// (a report needs three). Each answer is picked by what the request asks.
+const t = (content: unknown) => ({ ...run.turns[0]!, message: { ...run.turns[0]!.message, content: typeof content === "string" ? content : JSON.stringify(content) } });
+const meaning = [run.turns[2]!, run.turns[3]!, run.turns[4]!];
+const answerFor = (body: { messages?: { content?: string }[] }) => {
+ const user = String(body.messages?.at(-1)?.content ?? "");
+ if (user.includes("Transcript excerpt:")) {
+ return /Video: Pie stream/.test(user) ? run.turns[1]! : t({ relevant: true, items: [{ quote: "I entered the contest and I won it this year", claim: "She says she won.", on_topic: true, strength: 3 }] });
+ }
+ if (user.includes("QUOTE: ")) return meaning.shift()!;
+ if (user.includes("Findings:")) return run.turns[5]!;
+ return t({ terms: ["contest", "judges", "oven"] });
+};
const ol = await startFakeOllama();
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
-ol.push(...run.turns.map((t) => async () => (await wait(delay), t)) as never[]);
+// Seven answers: terms, two extracts, three meaning checks, one grouping (a second grouping ask meets an empty script).
+ol.push(...Array.from({ length: 7 }, () => async (body: { messages?: { content?: string }[] }) => (await wait(delay), answerFor(body))) as never[]);
const dir = existsSync(path.join(corpusDir, "corpus.json")) ? corpusDir : await writeDraftCorpus(corpusDir);
const corpus = await createCorpusTools({ source: `local:${dir}` });
const exportIndexDir = path.join(articlesDir, "..", ".export-index-run-sweep");
diff --git a/umtool/e2e/model-log.spec.ts b/umtool/e2e/model-log.spec.ts
@@ -64,20 +64,26 @@ test("a local sweep's calls appear live by phase; a dropped quote says why; a ca
await shot(page, "run-page-live");
// It ends: every call, in the sweep's phases, the count header says so.
await expect(page.locator("[data-run-mode]")).toHaveAttribute("data-run-mode", "replay", { timeout: 60_000 });
- await expect(log(page).locator("[data-model-log-count]")).toHaveAttribute("data-model-log-count", "4", { timeout: 10_000 });
- await expect(log(page).locator("[data-phase]")).toHaveCount(3);
- expect(await log(page).locator("[data-phase]").evaluateAll((els) => els.map((e) => e.getAttribute("data-phase")))).toEqual(["terms", "reading", "grouping"]);
+ await expect(log(page).locator("[data-model-log-count]")).toHaveAttribute("data-model-log-count", "8", { timeout: 10_000 });
+ await expect(log(page).locator("[data-phase]")).toHaveCount(4);
+ expect(await log(page).locator("[data-phase]").evaluateAll((els) => els.map((e) => e.getAttribute("data-phase")))).toEqual(["terms", "reading", "meaning-check", "grouping"]);
await expect(log(page).locator("[data-model-log-models]")).toHaveAttribute("data-model-log-models", "qwen3:8b");
await expect(log(page)).toContainText("qwen3:8b (local)");
// The terms call: kept, and what was searched.
const terms = log(page).locator("[data-phase=terms] [data-call]");
- await expect(terms.locator("[data-call-decision]")).toContainText("searched for contest, judges");
- // The reading call: two quotes kept, one dropped, and why.
+ await expect(terms.locator("[data-call-decision]")).toContainText("searched for contest, judges, oven");
+ // The reading calls (two recordings): three quotes kept, one dropped, and why.
const reading = log(page).locator("[data-phase=reading] [data-call]");
- await expect(reading.locator("[data-item-outcome=kept]")).toHaveCount(2);
+ await expect(reading).toHaveCount(2);
+ await expect(reading.locator("[data-item-outcome=kept]")).toHaveCount(3);
const dropped = reading.locator("[data-item-outcome=dropped]");
await expect(dropped).toContainText("I entered the contest and I won");
await expect(dropped.locator("[data-item-why]")).toHaveText("why: not verbatim in its window");
+ // The meaning check (D2 item 3), a call per kept quote: kept, rewritten to its fix, flagged to check by ear.
+ const meaning = log(page).locator("[data-phase=meaning-check] [data-call]");
+ await expect(meaning).toHaveCount(3);
+ await expect(meaning.nth(2).locator("[data-call-decision]")).toContainText("flagged: check by ear");
+ await expect(meaning.nth(1).locator("[data-item-outcome=rewritten]")).toContainText("She says the judges were friends of hers");
// The second grouping ask met the fake's empty script: shown failed.
await expect(log(page).locator("[data-phase=grouping] [data-call]").nth(1).locator("[data-call-answer]")).toContainText("failed:");
await shot(page, "run-page-done");
@@ -96,7 +102,7 @@ test("a local sweep's calls appear live by phase; a dropped quote says why; a ca
await expect(calls(page)).toHaveCount(1);
await expect(calls(page).first()).toHaveAttribute("data-call-phase", "reading");
await log(page).getByRole("button", { name: /^All/ }).click();
- await expect(calls(page)).toHaveCount(4);
+ await expect(calls(page)).toHaveCount(8);
// The steps are one press away, and the address keeps the pane.
await page.getByRole("button", { name: "Steps" }).click();
@@ -106,9 +112,9 @@ test("a local sweep's calls appear live by phase; a dropped quote says why; a ca
// The Iterations tab: the count on the toggle, the same log under it.
await page.goto(urls.articleHref({ site: "articles", id: SWEEP }, { tab: "iterations" }));
const toggle = page.locator("[data-iteration='1'] [data-model-log-toggle]");
- await expect(toggle).toHaveText("Model log · 4");
+ await expect(toggle).toHaveText("Model log · 8");
await toggle.click();
- await expect(page.locator("[data-iteration='1'] [data-model-log-count]")).toHaveAttribute("data-model-log-count", "4");
+ await expect(page.locator("[data-iteration='1'] [data-model-log-count]")).toHaveAttribute("data-model-log-count", "8");
await shot(page, "iterations-tab");
});
diff --git a/umtool/e2e/run-trace.spec.ts b/umtool/e2e/run-trace.spec.ts
@@ -183,6 +183,9 @@ test("a case's scope: Run a sweep on this scope plans it (no seed, the model and
await expect(dlg).not.toContainText("the board as cited markdown");
await expect(dlg).toContainText(/Runs on\s*(claude-|qwen)/);
await expect(dlg.getByRole("button", { name: /^Start the sweep/ })).toBeVisible();
+ // The run's own dates (D2 item 1): two date fields, the scope's to start with.
+ await expect(dlg.getByLabel("From", { exact: true })).toBeVisible();
+ await expect(dlg.getByLabel("To", { exact: true })).toBeVisible();
await page.keyboard.press("Escape");
await expect(dlg).toBeHidden();
@@ -193,3 +196,13 @@ test("a case's scope: Run a sweep on this scope plans it (no seed, the model and
await page.locator(`[data-run-row="${RUN_ARTICLE}/1"]`).getByRole("link").click();
await expect(page).toHaveURL(new RegExp(`/research/runs/${RUN_ARTICLE}/1$`));
});
+
+test("a scope sweep's plan takes the run's own dates (D2 item 1); bad or backwards dates are refused", async ({ request }) => {
+ const url = `/api/research/cases/${BOARD_CASE}/handoff`;
+ const plan = (await (await request.post(url, { data: { to: "sweep", dateFrom: "2024-01-01", dateTo: "2024-12-31" } })).json()).plan;
+ expect([plan.dateFrom, plan.dateTo, plan.seeded]).toEqual(["2024-01-01", "2024-12-31", false]);
+ const back = (await (await request.post(url, { data: { to: "sweep", dateFrom: "2024-12-31", dateTo: "2024-01-01" } })).json()).plan;
+ expect(back.refusals).toContain("the dates run backwards: 2024-12-31 is after 2024-01-01");
+ const bad = (await (await request.post(url, { data: { to: "sweep", dateFrom: "June 2024" } })).json()).plan;
+ expect(bad.refusals).toContain('the "from" date "June 2024" is not YYYY-MM-DD');
+});
diff --git a/umtool/e2e/settings.spec.ts b/umtool/e2e/settings.spec.ts
@@ -87,6 +87,20 @@ test("generation: presets write their routes, a route alone makes it custom, cap
await again.getByRole("button", { name: "Save caps" }).click();
await expect(again.getByRole("textbox", { name: "cap sweep" })).toHaveValue("5");
+ // The local sweep's two knobs (demo epic D2): who writes a finding's line,
+ // and what happens to a quote that may be read aloud. The defaults, then
+ // each written through the editor and put back.
+ const local = again.locator("[data-policy-local-sweep]");
+ await expect(local).toHaveAttribute("data-policy-local-sweep", "neutral flag");
+ await again.getByRole("combobox", { name: "local sweep read-aloud quotes" }).selectOption("drop");
+ await expect(again.getByRole("status")).toHaveText("saved the local sweep's read-aloud rule");
+ expect(stubAsked("settings").at(-1)).toMatchObject({ patch: { generation: { localSweep: { claimForm: "neutral", readAloud: "drop" } } } });
+ await again.getByRole("combobox", { name: "local sweep claim form" }).selectOption("sentence");
+ await expect(local).toHaveAttribute("data-policy-local-sweep", "sentence drop");
+ await again.getByRole("combobox", { name: "local sweep claim form" }).selectOption("neutral");
+ await again.getByRole("combobox", { name: "local sweep read-aloud quotes" }).selectOption("flag");
+ await expect(local).toHaveAttribute("data-policy-local-sweep", "neutral flag");
+
await again.getByRole("button", { name: "balanced" }).click();
await expect(again).toHaveAttribute("data-policy-preset", "balanced");
});
diff --git a/umtool/lib/articles/generation.ts b/umtool/lib/articles/generation.ts
@@ -242,7 +242,7 @@ export async function readPolicy(): Promise<PolicyView> {
// What umtool may write of `generation`. The key file's path is not here: the
// panel shows it, and the editor's own settings page sets it.
-const POLICY_KEYS = ["routes", "models", "caps", "cacheTtl", "triage"] as const;
+const POLICY_KEYS = ["routes", "models", "caps", "cacheTtl", "triage", "localSweep"] as const;
/** Write the policy through the editor's settings action. Answers the policy as read back. */
export async function writePolicy(patch: Record<string, unknown>): Promise<PolicyView> {
diff --git a/umtool/lib/research/case-types.ts b/umtool/lib/research/case-types.ts
@@ -167,6 +167,8 @@ export type ArticlePlan = {
channels: string[];
dateFrom?: string;
dateTo?: string;
+ /** A local sweep's reading set (D2): the top `recordings` by rarity × hits, plus one per year-quarter a rare term hits (at most `spreadMax`); `minutes`: the estimate on this machine's measured seconds a call. */
+ reading?: { recordings: number; spreadMax: number; minutes?: number };
source: string;
model: string | null;
/** The API agent's extractor (the policy's), when the sweep runs on Claude. */
diff --git a/umtool/lib/research/handoff.ts b/umtool/lib/research/handoff.ts
@@ -16,6 +16,7 @@ import { CaseError, recordHandoff } from "./cases.mjs";
import { boardGroups, caseView, mutateBoard } from "./boards";
import { boardGate } from "./case-private";
import type { ArticlePlan, CaseDoc, VideoPlan } from "./case-types";
+import { CALLS_PER_RECORDING, MEASURED_SECONDS_PER_CALL, readingSize } from "yt-dlp-transcript-common/lib/report/draft/tasks/selection";
// ---------------------------------------------------------------------------
// HAND-OFFS from a board (plans/umtool-redesign.md, R2), both PLAN THEN
@@ -61,9 +62,13 @@ function channelsOf(doc: CaseDoc): string[] {
// ── the article ──
+export type ArticleOver = { article?: string; model?: string; question?: string; dateFrom?: string; dateTo?: string };
+
+const YMD = /^\d{4}-\d{2}-\d{2}$/;
+
export async function planArticle(
id: string,
- over: { article?: string; model?: string; question?: string } = {},
+ over: ArticleOver = {},
o: { seeded?: boolean } = {},
): Promise<{ plan: ArticlePlan; seed: string }> {
const seeded = o.seeded !== false;
@@ -81,6 +86,11 @@ export async function planArticle(
const localChannels = channels.filter((c) => isLocalOnly(c));
if (!seeded && localChannels.length) refusals.push(`${localChannels.join(", ")} ${localChannels.length === 1 ? "is" : "are"} local-only: a sweep makes an article, which can be published`);
const question = (over.question ?? doc.scope.query ?? doc.title).trim();
+ // The sweep's dates (D2): the run's own when the plan names them, else the scope's.
+ const dateFrom = over.dateFrom ?? doc.scope.dateFrom;
+ const dateTo = over.dateTo ?? doc.scope.dateTo;
+ for (const [k, v] of [["from", dateFrom], ["to", dateTo]] as const) if (v && !YMD.test(v)) refusals.push(`the "${k}" date "${v}" is not YYYY-MM-DD`);
+ if (dateFrom && dateTo && YMD.test(dateFrom) && YMD.test(dateTo) && dateFrom > dateTo) refusals.push(`the dates run backwards: ${dateFrom} is after ${dateTo}`);
if (seeded) {
const drifted = doc.quotes.filter((q) => q.verify?.status === "drifted" || q.verify?.status === "missing").length;
if (drifted) warnings.push(`${drifted} ${drifted === 1 ? "quote" : "quotes"} drifted or missing at the last re-verify: the sweep checks every quote again`);
@@ -134,8 +144,9 @@ export async function planArticle(
articleExists,
question,
channels,
- ...(doc.scope.dateFrom ? { dateFrom: doc.scope.dateFrom } : {}),
- ...(doc.scope.dateTo ? { dateTo: doc.scope.dateTo } : {}),
+ ...(dateFrom ? { dateFrom } : {}),
+ ...(dateTo ? { dateTo } : {}),
+ ...(!seeded && model && !model.startsWith("claude-") ? { reading: readingOf(model) } : {}),
source: doc.scope.source,
model,
extractor,
@@ -152,7 +163,7 @@ export async function planArticle(
};
}
-export async function confirmArticle(id: string, over: { article?: string; model?: string; question?: string }): Promise<{ href: string; jobId: string; iteration: number }> {
+export async function confirmArticle(id: string, over: ArticleOver): Promise<{ href: string; jobId: string; iteration: number }> {
const { plan, seed } = await planArticle(id, over);
if (plan.refusals.length) throw new CaseError(plan.refusals.join("; "), 409);
if (plan.policyError) throw new CaseError(`the editor cannot be asked: ${plan.policyError}`, 502);
@@ -177,9 +188,17 @@ export async function confirmArticle(id: string, over: { article?: string; model
// ── a sweep on the case's scope (R3) ──
-export const planScopeSweep = (id: string, over: { article?: string; model?: string; question?: string } = {}) => planArticle(id, over, { seeded: false });
+export const planScopeSweep = (id: string, over: ArticleOver = {}) => planArticle(id, over, { seeded: false });
+
+/** What a local sweep reads (D2): the top N by rarity × hits plus the date spread, and about how long. */
+function readingOf(model: string): NonNullable<ArticlePlan["reading"]> {
+ const recordings = readingSize();
+ const spreadMax = Math.ceil(recordings / 2);
+ const perCall = MEASURED_SECONDS_PER_CALL[model];
+ return { recordings, spreadMax, ...(perCall ? { minutes: Math.round((recordings * CALLS_PER_RECORDING * perCall) / 60) } : {}) };
+}
-export async function confirmScopeSweep(id: string, over: { article?: string; model?: string; question?: string }): Promise<{ href: string; jobId: string; iteration: number }> {
+export async function confirmScopeSweep(id: string, over: ArticleOver): Promise<{ href: string; jobId: string; iteration: number }> {
const { plan } = await planScopeSweep(id, over);
if (plan.refusals.length) throw new CaseError(plan.refusals.join("; "), 409);
if (plan.policyError) throw new CaseError(`the editor cannot be asked: ${plan.policyError}`, 502);