// A refresh's update end to end (umtool R4): the task over the MCP's own corpus // tools (a later build of the synthetic draft corpus holding one recording // more), the fake Anthropic, a temp iterations store. The parent is a done // sweep with its trace; the refresh finds the new recording, sweeps ONLY it // (the sweep's `ids` restriction: the enumeration answers its row alone), and // revises the parent's report with the finding. Stage 1's fetches and build // are common's tests (lib/report/draft/refresh/refresh.test.ts); here they // are skipped (`fetch: false`). import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, readFile, rm } from "node:fs/promises"; 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"; import type { RefreshFile } from "yt-dlp-transcript-common/lib/report/draft/refresh/types"; import { createCorpusTools, type CorpusTools } from "./callTool"; const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../common/testing/draft"); 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}` }); api = await startFakeAnthropic(); }); after(async () => { await later.close(); await api.close(); await ol.close(); await rm(tmp, { recursive: true, force: true }); }); const article = "synth-basic"; test("refresh: the new recording found, a sweep restricted to it, the report revised with its finding — updated", async () => { const paths = { articlesDir: path.join(tmp, "reports"), exportIndexDir: path.join(tmp, "idx") }; // i1: the basic sweep, done, with the trace of the enumeration it ran. await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "What does the baker say about the contest?", scope: { channels: ["synth-kitchen"] } }, paths); await writeIterationFile(article, 1, "sweep.md", await readFile(path.join(DRAFT, "sweeps", "basic.md"), "utf8"), paths); await writeIterationFile(article, 1, "report.json", JSON.parse(await readFile(path.join(DRAFT, "reports", "basic.report.json"), "utf8")), paths); const trace = [ { t: "run", run: 1, phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" }, { t: "scope", run: 1, source: "local:/the/first/build", channels: ["synth-kitchen"], question: "What does the baker say about the contest?" }, { t: "enumerate", run: 1, query: "contest", n: 1, ids: ["pie-stream-02"], partial: false, unreached: [], counts: { "pie-stream-02": 2 } }, ]; await writeIterationFile(article, 1, "trace.jsonl", trace.map((e) => JSON.stringify(e)).join("\n") + "\n", paths); await updateIteration(article, 1, { status: "done" }, paths); await createIteration(article, { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths); const finding = `- She says she was not a judge: "I was not a judge at the contest this year either" [Contest results @ 0:05](${ORIGIN}/?v=synth-kitchen%2Fcontest-stream-04&t=5)`; api.push( // The restricted sweep: one enumeration (its answer the new row only), the report, done. toolTurn("enumerate_matches", { query: "contest", channels: ["synth-kitchen"] }), toolTurn("write_report", { markdown: `# New on the contest\n\nOne new stream mentions it.\n\n## The contest\n\n${finding}\n` }), textTurn("sweep.md: 1 finding."), // The revision: the finding added, as given. toolTurn("apply_ops", { ops: [{ 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: `${ORIGIN}/?v=synth-kitchen%2Fcontest-stream-04&t=5` }], }), textTurn("Added the new finding."), ); const lines: string[] = []; const deps: TaskDeps = { llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY }, sleep: async () => {} }, ollama: { baseUrl: "http://127.0.0.1:9" } }, corpus: later, cuesOf: corpusCuesOf(later), postTextOf: async (channel, id) => POSTS.find((p) => p.channelSlug === channel && p.id === id)?.text ?? null, 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, n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3, fetch: false }, deps); assert.equal(out.status, "done", `${out.summary}\n${lines.join("\n")}`); assert.equal(api.remaining(), 0, "every scripted turn was used"); assert.ok(out.usd > 0); const f = JSON.parse((await readIterationFile(article, 2, "refresh.json", paths))!) as RefreshFile; assert.equal(f.status, "updated"); assert.deepEqual(f.delta?.newIds, ["contest-stream-04"]); assert.equal(f.delta?.drifted.length, 0); assert.deepEqual(f.update?.sweep, { ids: ["contest-stream-04"], status: "done", summary: f.update!.sweep!.summary, findings: 1 }); assert.equal(f.update?.revision?.status, "done"); assert.match(f.summary, /^1 new recording matches — updated: 1 op\(s\) applied/); // The sweep was restricted: its scope says so, and its enumeration answered the new row alone. const events = (await readIterationFile(article, 2, "trace.jsonl", paths))!.trim().split("\n").map((l) => JSON.parse(l)); assert.deepEqual(events.find((e) => e.t === "scope")?.ids, ["contest-stream-04"]); assert.deepEqual(events.find((e) => e.t === "enumerate")?.ids, ["contest-stream-04"]); assert.equal(events.find((e) => e.t === "delta")?.status, "changed"); assert.equal(events.at(-1).t, "run"); assert.equal(events.at(-1).status, "done"); // The report: the parent's findings, and the new one. const report = JSON.parse((await readIterationFile(article, 2, "report.json", paths))!); const quotes = Object.values(report.citations as Record); assert.ok(quotes.some((c) => c.id === "contest-stream-04" && c.quote === "I was not a judge at the contest this year either")); assert.ok(quotes.some((c) => c.quote === "I did not enter the contest this year"), "the parent's findings stay"); const it = await readIteration(article, 2, paths); 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 (<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], ], ); });