// A refresh (umtool R4): the basis read from an iteration's records, the // candidates against a stubbed corpus, the quotes read again, and the task's // stages over stubbed editor actions — no change ($0), a cap's hold, and the // fetch steps (a held platform skipped, a posts channel, what landed sent to // transcription, the build waited for). The update over the MCP's own corpus // tools and the fake Anthropic is mcp/src/refreshTask.test.ts. Temp stores // only. import { after, 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 { createIteration, iterationFile, readIteration, updateIteration, writeIterationFile } from "../../iterations"; import { checkWordsInWindow, enOrigDifference, holdsWords, windowAround, wordsOf } from "../../quoteWords"; import { restrictEnumerateText, restrictTools } from "../tasks/restrict"; import type { AgentTool } from "../agentTool"; import type { CorpusToolsLike, TaskDeps } from "../tasks/types"; import { fromTrace, fromTurns, knownOf, refreshBasis } from "./basis"; import { deltaCandidates, recheckQuotes, type RecordRead } from "./delta"; import { estimateUpdateUsd, refresh, refreshFeedback, type RefreshHooks } from "./task"; import { deltaLine, goneParts, outcomeOf, type RefreshDelta, type RefreshFile } from "./types"; const tmp = await mkdtemp(path.join(os.tmpdir(), "refresh-")); after(() => rm(tmp, { recursive: true, force: true })); let k = 0; const store = () => { k++; return { articlesDir: path.join(tmp, `reports-${k}`), exportIndexDir: path.join(tmp, `idx-${k}`) }; }; // ─── a corpus, stubbed: enumerate_matches and get_transcript as the MCP answers them ─── type Rec = { channel: string; name: string; id: string; date: string; title: string; lines: string[] }; const BASE: Rec[] = [ { channel: "synth-kitchen", name: "Synth Kitchen", id: "pie-02", date: "20260210", title: "Pie stream", lines: ["a lot of you asked about the contest", "I did not enter the contest this year", "the judges were friends of mine"] }, { channel: "synth-kitchen", name: "Synth Kitchen", id: "bread-01", date: "20260105", title: "Bread day", lines: ["welcome back", "the contest rumor again", "I paid for the new mixer myself"] }, { channel: "synth-kitchen", name: "Synth Kitchen", id: "qa-03", date: "20260301", title: "Q and A", lines: ["no mention here", "only flour and water"] }, ]; function fakeCorpus(recs: Rec[]): CorpusToolsLike & { calls: { name: string; args: Record }[] } { const calls: { name: string; args: Record }[] = []; return { source: "local:/fake/build/out", tools: [], calls, async call(name, args = {}) { calls.push({ name, args }); if (name === "enumerate_matches") { const q = String(args.query).toLowerCase(); const chans = Array.isArray(args.channels) ? (args.channels as string[]) : null; const rows = recs .filter((r) => !chans || chans.includes(r.channel)) .map((r) => ({ r, n: r.lines.filter((l) => l.toLowerCase().includes(q)).length })) .filter((x) => x.n > 0); if (!rows.length) return `No matches for "${args.query}".\n\n(complete set: yes; 0 match(es))`; const date = (d: string) => `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`; return ( `${rows.length} match(es) for "${args.query}" — the complete worklist:\n\n` + rows.map(({ r, n }) => `- ${r.id} | video | ${r.name} | ${date(r.date)} | ${n} match(es) | ${r.title}`).join("\n") + `\n\n(complete set: yes; ${rows.length} match(es); 1 batch(es) of 8)` ); } throw new Error(`the stub has no ${name}`); }, }; } const cuesOfRec = (r: Rec) => r.lines.map((text, i) => ({ start: i * 5, end: i * 5 + 4.8, text })); const recordReader = (recs: Rec[], extra: Partial>> = {}) => async (channel: string, id: string): Promise => { const r = recs.find((x) => x.channel === channel && x.id === id); if (!r) return null; return { cues: cuesOfRec(r), ...(extra[id] ?? {}) }; }; // ─── a done sweep with its trace and report ─── const REPORT = { format: "archilyzer-report", version: 1, id: "synth", kind: "sweep", title: "The contest", summary: "What she says.", citations: { c1: { kind: "video", channel: "synth-kitchen", id: "pie-02", start: 5, end: 9.8, quote: "I did not enter the contest this year" }, c2: { kind: "video", channel: "synth-kitchen", id: "bread-01", start: 10, end: 14.8, quote: "I paid for the new mixer myself" }, c3: { kind: "post", channel: "synth-social", id: "1700", quote: "No, I did not enter the pie contest." }, }, sections: [{ id: "s1", title: "The contest", body: "She [did not enter](cite:c1). [Mixer](cite:c2). [Post](cite:c3)." }], }; const TRACE = [ { t: "run", at: "2026-10-01T10:00:00.000Z", run: 1, phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" }, { t: "scope", at: "2026-10-01T10:00:01.000Z", run: 1, source: "local:/fake/build/out", channels: ["synth-kitchen", "synth-other"], question: "What does she say about the contest?", model: "claude-sonnet-5-5" }, { t: "enumerate", at: "2026-10-01T10:00:02.000Z", run: 1, query: "contest", n: 2, ids: ["pie-02", "bread-01"], partial: false, unreached: [], counts: { "pie-02": 2, "bread-01": 1 } }, { t: "run", at: "2026-10-01T10:05:00.000Z", run: 1, phase: "end", status: "done", summary: "ok", usd: 0.8, minutes: 5, coverage: { matched: 2, read: 2, partial: false, unreached: [] } }, ]; async function doneSweep(paths: ReturnType, article = "synth") { await createIteration(article, { kind: "sweep", model: "claude-sonnet-5-5", question: "What does she say about the contest?", scope: { channels: ["synth-kitchen", "synth-other"] } }, paths); await writeIterationFile(article, 1, "report.json", REPORT, paths); await writeIterationFile(article, 1, "trace.jsonl", TRACE.map((e) => JSON.stringify(e)).join("\n") + "\n", paths); await updateIteration(article, 1, { status: "done", usage: { "claude-sonnet-5-5": { usd: 0.8, inputTokens: 1, outputTokens: 1 } }, coverage: { matched: 2, read: 2, partial: false, unreached: [] } }, paths); } // ─── the words ─── test("quoteWords: R2's check — words, the window, ok / moved / drifted, en vs en-orig", () => { assert.equal(wordsOf("I’d NEVER, ever!"), "i'd never ever"); assert.ok(holdsWords("so I did not enter the contest this year, ok", "I did not enter the contest")); assert.ok(!holdsWords("I did not enter", "I did not enter the contest")); const cues = [ { start: 0, end: 4, text: "a lot of you asked" }, { start: 5, end: 9, text: "I did not enter" }, { start: 10, end: 14, text: "the contest this year" }, ]; assert.deepEqual(checkWordsInWindow("I did not enter the contest", { t: 5, end: 14 }, windowAround(cues, 5)), { status: "ok" }); assert.deepEqual(checkWordsInWindow("I did not enter the contest", { t: 0, end: 9 }, windowAround(cues, 0)), { status: "ok", nowAt: 5 }); const drift = checkWordsInWindow("I never entered", { t: 5, end: 9 }, windowAround(cues, 5)); assert.equal(drift.status, "drifted"); assert.equal(drift.status === "drifted" && drift.now, "I did not enter"); assert.deepEqual(checkWordsInWindow("x", { t: 500, end: 501 }, windowAround(cues, 500)), { status: "drifted", now: "", empty: true }); assert.equal(enOrigDifference(cues, cues, { t: 5, end: 9 }), null); assert.deepEqual(enOrigDifference(cues, [{ start: 5, end: 9, text: "I did enter" }], { t: 5, end: 9 }), { en: "I did not enter", orig: "I did enter" }); }); // ─── the sweep's ids restriction ─── test("restrict: an enumeration answers only the given rows; reads outside are refused; search is not offered", async () => { const text = '3 match(es) for "contest" — the complete worklist:\n\n- a | video | C | 2026-01-01 | 1 match(es) | A\n- b | video | C | 2026-01-02 | 2 match(es) | B\n- c | video | C | 2026-01-03 | 1 match(es) | C\n\n(complete set: yes)'; const out = restrictEnumerateText(text, new Set(["b"])); assert.ok(out.includes("- b | video")); assert.ok(!out.includes("- a | video") && !out.includes("- c | video")); assert.match(out, /restricted to 1 recording\(s\): 1 of the 3 row\(s\) above are kept/); const seen: unknown[] = []; const tool = (name: string): AgentTool => ({ name, description: name, inputSchema: { type: "object" }, run: async (i: unknown) => (seen.push(i), name === "enumerate_matches" ? text : "ok") }); const tools = restrictTools([tool("enumerate_matches"), tool("search_transcripts"), tool("get_transcripts"), tool("get_transcript"), tool("list_channels")], ["b"]); assert.deepEqual(tools.map((t) => t.name), ["enumerate_matches", "get_transcripts", "get_transcript", "list_channels"]); const byName = Object.fromEntries(tools.map((t) => [t.name, t])); assert.ok(!(await byName.enumerate_matches!.run({ query: "contest" }, {})).includes("- a |")); assert.match(await byName.get_transcripts!.run({ video_ids: ["a", "b"] }, {}), /not read — outside this sweep's recordings: a/); assert.deepEqual(seen.at(-1), { video_ids: ["b"] }); await assert.rejects(byName.get_transcripts!.run({ video_ids: ["a"] }, {}), /restricted: a is not one of/); await assert.rejects(byName.get_transcript!.run({ video_id: "c" }, {}), /restricted: c/); assert.equal(await byName.get_transcript!.run({ video_id: "b" }, {}), "ok"); assert.equal(restrictTools([tool("search_transcripts")], undefined).length, 1, "no ids: the tools as they are"); }); // ─── the basis ─── test("basis: a trace's last run (its queries, counts and scope); turns' calls; known summed over queries", () => { const two = [...TRACE, { t: "run", run: 2, phase: "start" }, { t: "scope", run: 2, channels: ["synth-other"], question: "q", source: "local:/b2" }, { t: "enumerate", run: 2, query: "oven", ids: ["x9"], counts: { x9: 3 } }]; const f = fromTrace(two.map((e) => JSON.stringify(e)).join("\n") + "\n{torn"); assert.equal(f?.from, "trace"); assert.deepEqual(f?.queries, [{ query: "oven" }]); assert.deepEqual(f?.scope?.channels, ["synth-other"]); assert.equal(f?.source, "local:/b2"); assert.deepEqual(knownOf(f!.perQuery), { x9: 3 }); assert.equal(fromTrace('{"t":"run","phase":"start"}'), null, "no enumeration: nothing to read"); const turns = [ { kind: "response", turn: 0, content: [] }, { kind: "tool", name: "enumerate_matches", input: { query: "contest", channels: ["synth-kitchen"], date_from: "2026-01-01" }, result: "- pie-02 | video | Synth Kitchen | 2026-02-10 | 2 match(es) | Pie stream" }, { kind: "tool", name: "enumerate_matches", input: { query: "mixer" } }, { kind: "enumerate", term: "oven", videos: 3 }, ]; const t = fromTurns(turns.map((e) => JSON.stringify(e)).join("\n")); assert.deepEqual(t?.queries, [{ query: "contest", channels: ["synth-kitchen"], from: "2026-01-01" }, { query: "mixer" }, { query: "oven" }]); assert.deepEqual(knownOf(t!.perQuery), { "pie-02": 2 }); }); test("refreshBasis: the iteration's trace, the report's quotes; a revision reads its sweep's; no records → the question", async () => { const paths = store(); await doneSweep(paths); const b = await refreshBasis("synth", 1, paths); assert.equal(b.from, "trace"); assert.equal(b.queriesOf, 1); assert.deepEqual(b.queries, [{ query: "contest" }]); assert.deepEqual(b.scope.channels, ["synth-kitchen", "synth-other", "synth-social"], "the trace's scope, plus every channel cited"); assert.deepEqual(b.known, { "pie-02": 2, "bread-01": 1 }); assert.equal(b.knownComplete, true); assert.equal(b.countsKnown, true); assert.deepEqual(b.cited.map((c) => c.citation), ["c1", "c2", "c3"]); assert.equal(b.source, "local:/fake/build/out"); // A revision: its own report, its sweep's records. await createIteration("synth", { kind: "revise-report", model: "claude-sonnet-5-5", parent: 1, feedback: "tighten" }, paths); await writeIterationFile("synth", 2, "report.json", { ...REPORT, citations: { c1: REPORT.citations.c1 } }, paths); await updateIteration("synth", 2, { status: "done" }, paths); const r = await refreshBasis("synth", 2, paths); assert.equal(r.queriesOf, 1); assert.deepEqual(r.cited.map((c) => c.citation), ["c1"]); assert.equal(r.question, "What does she say about the contest?"); // Nothing recorded: the question, and new only by upload date. const p2 = store(); await createIteration("bare", { kind: "sweep", model: "qwen3:8b", question: "contest", scope: { channels: ["synth-kitchen"] } }, p2); await writeIterationFile("bare", 1, "report.json", { ...REPORT, id: "bare" }, p2); await updateIteration("bare", 1, { status: "done" }, p2); const q = await refreshBasis("bare", 1, p2); assert.equal(q.from, "question"); assert.deepEqual(q.queries, [{ query: "contest" }]); assert.equal(q.knownComplete, false); assert.equal(q.countsKnown, false); assert.deepEqual(Object.keys(q.known).sort(), ["bread-01", "pie-02"], "the cited are known"); }); // ─── the candidates ─── test("deltaCandidates: new against known, changed by matching lines, unmatched; `since` without known (R6's tier 0)", async () => { const recs = [ ...BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: [...r.lines, "the contest came up twice"] } : r)), { channel: "synth-kitchen", name: "Synth Kitchen", id: "late-04", date: "20250101", title: "An old one, transcribed late", lines: ["the contest was rigged"] }, { channel: "synth-kitchen", name: "Synth Kitchen", id: "new-05", date: "20261012", title: "New stream", lines: ["the contest again"] }, ]; const corpus = fakeCorpus(recs); const c = await deltaCandidates({ queries: [{ query: "contest" }, { query: "contest" }], scope: { channels: ["synth-kitchen"], from: "2020-01-01" } }, corpus, { known: { "pie-02": 2, "bread-01": 1, "gone-09": 1 } }); assert.equal(corpus.calls.length, 1, "the same query twice runs once"); assert.deepEqual(corpus.calls[0]!.args, { query: "contest", channels: ["synth-kitchen"], date_from: "2020-01-01" }); assert.deepEqual(c.newIds.sort(), ["late-04", "new-05"]); assert.deepEqual(c.changed, ["bread-01"]); assert.deepEqual(c.unmatched, ["gone-09"]); assert.equal(c.rows.get("new-05")?.date, "2026-10-12"); const since = await deltaCandidates({ queries: [{ query: "contest" }], scope: { channels: ["synth-kitchen"] } }, fakeCorpus(recs), { since: "2026-10-01T00:00:00Z" }); assert.deepEqual(since.newIds, ["new-05"], "uploaded on or after the day"); }); test("recheckQuotes: ok, moved, drifted, missing, gone from its platform, en-orig, a post", async () => { const recs = BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: ["welcome back", "the contest rumor again", "I bought the mixer with sponsor money"] } : r)); const cited = [ { citation: "c1", kind: "video" as const, channel: "synth-kitchen", id: "pie-02", start: 5, end: 9.8, quote: "I did not enter the contest this year" }, { citation: "c2", kind: "video" as const, channel: "synth-kitchen", id: "bread-01", start: 10, end: 14.8, quote: "I paid for the new mixer myself" }, { citation: "c4", kind: "video" as const, channel: "synth-kitchen", id: "pie-02", start: 0, end: 4, quote: "the judges were friends of mine" }, { citation: "c5", kind: "video" as const, channel: "synth-kitchen", id: "nope", start: 0, end: 1, quote: "x" }, { citation: "c3", kind: "post" as const, channel: "synth-social", id: "1700", quote: "No, I did not enter the pie contest." }, ]; const out = await recheckQuotes(cited, { recordOf: recordReader(recs, { "pie-02": { state: "deleted", tracks: [{ name: "transcript.en.vtt", cues: cuesOfRec(recs[0]!) }, { name: "transcript.en-orig.vtt", cues: [{ start: 5, end: 9.8, text: "I did enter the contest this year" }] }] } }), postTextOf: async () => "No, I did not enter the pie contest. The judges are my friends.", }); const by = Object.fromEntries(out.map((q) => [q.citation, q])); assert.equal(by.c1!.status, "ok"); assert.equal(by.c1!.state, "deleted"); assert.deepEqual(by.c1!.enOrig, { en: "I did not enter the contest this year", orig: "I did enter the contest this year" }); assert.equal(by.c2!.status, "drifted"); assert.equal(by.c2!.now, "I bought the mixer with sponsor money"); assert.equal(by.c4!.status, "moved"); assert.equal(by.c4!.nowAt, 10); assert.equal(by.c5!.status, "missing"); assert.equal(by.c3!.status, "ok"); }); // ─── the task ─── type Call = { action: string; args: Record }; function harness(o: { recs: Rec[]; refusal?: string | null; held?: string[] }) { const calls: Call[] = []; const polls = new Map(); let n = 0; const holder = { source: "", tools: [] as AgentTool[], call: (_: string, __?: Record) => Promise.reject(new Error("not open")) } as CorpusToolsLike; const corpus = fakeCorpus(o.recs); const buckets: Record = { "synth-kitchen": ["old-1"] }; const hooks: RefreshHooks = { editor: { async run(action, args) { calls.push({ action, args }); if (action === "sync") buckets["synth-kitchen"] = ["old-1", "landed-7"]; if (action === "publish") return { ok: true, jobs: [{ target: "synth", kind: "build-site", jobId: `job-${++n}` }] }; return { ok: true, jobId: `job-${++n}` }; }, }, // A job runs for one poll, then is done. jobOf: async (id) => { const k = (polls.get(id) ?? 0) + 1; polls.set(id, k); return { status: k < 2 ? "running" : "done", endedAt: Date.now() }; }, channelOf: async (slug) => (slug === "synth-kitchen" ? { kind: "video", platform: "youtube" } : slug === "synth-social" ? { kind: "posts", platform: "x" } : slug === "synth-other" ? { kind: "video", platform: "rumble" } : null), platformRefusal: async (p) => ((o.held ?? []).includes(p) ? `${p} is held` : null), bucketOf: async (slug) => buckets[slug] ?? null, siteOf: async () => ({ site: "synth" }), openCorpus: async () => { Object.assign(holder, { source: corpus.source, tools: corpus.tools, call: corpus.call.bind(corpus) }); return { source: corpus.source, origin: "https://synth.example", build: "synth" }; }, recordOf: recordReader(o.recs), capRefusal: async () => o.refusal ?? null, pollMs: 1, sleep: async () => {}, }; const lines: string[] = []; const deps = (paths: ReturnType): TaskDeps => ({ llm: { anthropic: { baseUrl: "http://127.0.0.1:9", env: {} }, ollama: { baseUrl: "http://127.0.0.1:9" } }, corpus: holder, cuesOf: async () => null, postTextOf: async () => "No, I did not enter the pie contest.", paths, log: (l) => lines.push(l), refresh: hooks, }); return { calls, deps, lines, corpus }; } const readJson = async (file: string) => JSON.parse(await readFile(file, "utf8")); const traceOf = async (paths: ReturnType, n: number) => (await readFile(iterationFile(paths, "synth", n, "trace.jsonl"), "utf8")) .trim() .split("\n") .map((l) => JSON.parse(l) as Record); test("refresh, nothing changed: the fetches and the build waited for, the delta $0, the iteration done with no report", async () => { const paths = store(); await doneSweep(paths); await createIteration("synth", { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths); const h = harness({ recs: BASE, held: ["rumble"] }); const out = await refresh({ article: "synth", n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3 }, h.deps(paths)); assert.equal(out.status, "done", h.lines.join("\n")); assert.equal(out.usd, 0); assert.match(out.summary, /^Nothing new since 2026-/); // The actions, in order per channel: a sync, its report, what landed to transcription; the posts; the build. // (The channels run side by side: the posts channel's one action lands between.) assert.deepEqual( h.calls.map((c) => c.action).filter((a) => a !== "fetch-posts"), ["sync", "refresh-report", "transcribe-bucket", "publish"], ); assert.equal(h.calls.filter((c) => c.action === "fetch-posts").length, 1); assert.deepEqual(h.calls.find((c) => c.action === "transcribe-bucket")!.args, { slug: "synth-kitchen", ids: ["landed-7"] }); assert.deepEqual(h.calls.find((c) => c.action === "publish")!.args, { verb: "build", siteId: "synth", force: false }); const f = (await readJson(iterationFile(paths, "synth", 2, "refresh.json"))) as RefreshFile; assert.equal(f.status, "no-change"); assert.equal(f.parent, 1); assert.deepEqual(f.fetch.find((s) => s.channel === "synth-other"), { channel: "synth-other", action: "sync", status: "skipped", reason: "rumble is held" }); assert.equal(f.build?.status, "done"); assert.equal(f.delta?.status, "no-change"); assert.deepEqual(f.delta?.matchedSet, { "pie-02": 2, "bread-01": 1 }); assert.equal(f.update, undefined); const it = await readIteration("synth", 2, paths); assert.equal(it?.status, "done"); assert.deepEqual((it as { refresh?: unknown }).refresh, { status: "no-change", newIds: 0, changed: 0, drifted: 0, deleted: 0, summary: f.summary }); await assert.rejects(readFile(iterationFile(paths, "synth", 2, "report.json")), /ENOENT/); const trace = await traceOf(paths, 2); assert.deepEqual(trace.map((e) => e.t).filter((t) => t !== "note"), ["run", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "fetch", "build", "build", "delta", "run"]); assert.equal(trace.at(-1)!.status, "done"); }); test("refresh, something new but the cap refuses: held-by-cap with the delta and the estimate, no model called", async () => { const paths = store(); await doneSweep(paths); await createIteration("synth", { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths); const recs = [ ...BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: ["welcome back", "the contest rumor again", "I bought the mixer with sponsor money"] } : r)), { channel: "synth-kitchen", name: "Synth Kitchen", id: "new-05", date: "20261012", title: "New stream", lines: ["about the contest", "it was rigged"] }, ]; const h = harness({ recs, refusal: "the day's Claude API spend is $20.00, at the daily cap" }); const out = await refresh({ article: "synth", n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3, fetch: false }, h.deps(paths)); assert.equal(out.status, "done"); assert.equal(out.usd, 0); assert.deepEqual(h.calls, [], "fetch: false runs no editor action"); const f = (await readJson(iterationFile(paths, "synth", 2, "refresh.json"))) as RefreshFile; assert.equal(f.status, "held-by-cap"); assert.deepEqual(f.delta?.newIds, ["new-05"]); assert.deepEqual(f.delta?.drifted, ["c2"]); assert.equal(f.update?.refusal, "the day's Claude API spend is $20.00, at the daily cap"); // The parent spent $0.80 reading 2 recordings: one more is $0.40, and a revision. assert.equal(f.update?.estimateUsd, 0.7); assert.equal(f.summary, "1 new recording matches · 1 quote changed — held by the cap (about $0.70 to update): the day's Claude API spend is $20.00, at the daily cap"); assert.equal(deltaLine(f.delta!), "1 new recording matches · 1 quote changed"); }); test("the estimate and the revision's feedback", () => { assert.equal(estimateUpdateUsd({ recordings: 4, model: "claude-sonnet-5-5" }), 0.62); assert.equal(estimateUpdateUsd({ recordings: 4, model: "qwen3:8b" }), 0); assert.equal(estimateUpdateUsd({ recordings: 0, model: "claude-sonnet-5-5" }), 0.3); const fb = refreshFeedback({ parent: 3, since: "2026-10-01T10:05:00.000Z", findings: "## New\n\n- She says it was rigged: \"it was rigged\" — [New stream @ 0:05](https://synth.example/?v=synth-kitchen%2Fnew-05&t=5)", delta: { quotes: [ { citation: "c2", kind: "video", channel: "synth-kitchen", id: "bread-01", start: 10, status: "drifted", quote: "I paid for the new mixer myself", now: "I bought the mixer" }, { citation: "c1", kind: "video", channel: "synth-kitchen", id: "pie-02", start: 5, status: "ok", quote: "q", state: "deleted" }, ], } as never, }); assert.match(fb, /^A REFRESH of i3 \(made 2026-10-01\)/); assert.match(fb, /NEW FINDINGS[\s\S]*it was rigged/); assert.match(fb, /QUOTES THAT CHANGED[\s\S]*"I paid for the new mixer myself" \(synth-kitchen\/bread-01 @ 0:10\) — now: "I bought the mixer"/); assert.match(fb, /SOURCES GONE FROM THEIR PLATFORM[\s\S]*synth-kitchen\/pie-02 \(deleted on its platform\)/); }); test("a refresh iteration names its parent; refresh.json is an iteration file", async () => { const paths = store(); await doneSweep(paths); await assert.rejects(createIteration("synth", { kind: "refresh", model: "m" }, paths), /needs the iteration it refreshes/); await createIteration("synth", { kind: "refresh", model: "m", parent: 1 }, paths); await writeIterationFile("synth", 2, "refresh.json", { ok: 1 }, paths); }); test("the sources gone, said by where; changes not tracked before an older parent, never a silent 0", async () => { const d = { newIds: [], changed: [], drifted: [], deleted: ["a/1", "a/2", "b/3", "c/4"], goneFromArchive: ["c/4"], removedOnPlatform: [{ source: "a/1", state: "deleted", platform: "youtube" }, { source: "a/2", state: "deleted", platform: "youtube" }, { source: "b/3", state: "private", platform: "rumble" }] }; assert.deepEqual(goneParts(d), ["2 sources deleted on YouTube", "1 source made private on Rumble", "1 source gone from the archive"]); assert.equal(deltaLine({ ...d, deleted: ["c/4"], goneFromArchive: ["c/4"], removedOnPlatform: [] }), "1 source gone from the archive"); assert.equal(deltaLine({ newIds: [], changed: [], drifted: [], deleted: ["x/1"] }), "1 source deleted", "a record from before the split"); // A trace with no counts: the refresh says changes were not tracked, and the outcome's `changed` is null. const paths = store(); await doneSweep(paths); const noCounts = TRACE.map((e) => (e.t === "enumerate" ? { ...e, counts: undefined } : e)); await writeIterationFile("synth", 1, "trace.jsonl", noCounts.map((e) => JSON.stringify(e)).join("\n") + "\n", paths); const b = await refreshBasis("synth", 1, paths); assert.equal(b.countsKnown, false); await createIteration("synth", { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths); const h = harness({ recs: BASE.map((r) => (r.id === "bread-01" ? { ...r, lines: [...r.lines, "the contest came up twice"] } : r)) }); const out = await refresh({ article: "synth", n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3, fetch: false }, h.deps(paths)); assert.equal(out.status, "done"); const f = (await readJson(iterationFile(paths, "synth", 2, "refresh.json"))) as RefreshFile; assert.equal(f.delta?.changedTracked, false); assert.deepEqual(f.delta?.changed, [], "bread-01's lines changed, but nothing recorded them before"); assert.equal(f.delta?.changedSince, f.basis.at); assert.ok(f.warnings.some((w) => w.startsWith(`changed recordings are not tracked before ${f.basis.at.slice(0, 10)}`)), f.warnings.join("; ")); assert.equal(outcomeOf(f).changed, null); assert.equal(outcomeOf({ ...f, delta: { ...(f.delta as RefreshDelta), changedTracked: true } }).changed, 0); }); test("a source deleted on its platform: the recheck carries the platform the summary names", async () => { const out = await recheckQuotes( [{ citation: "c1", kind: "video", channel: "synth-kitchen", id: "pie-02", start: 5, end: 9.8, quote: "I did not enter the contest this year" }], { recordOf: recordReader(BASE, { "pie-02": { state: "deleted", platform: "youtube" } }) }, ); assert.deepEqual({ status: out[0]!.status, state: out[0]!.state, platform: out[0]!.platform }, { status: "ok", state: "deleted", platform: "youtube" }); }); // ─── R6.1: no silent zeros; R4.1: fetch under a transcription hold ─── import { enumerateOf } from "../tasks/trace"; import { fetchAndBuild } from "./fetch"; /** The stub corpus, its enumerations answered as a CAPPED scan (the MCP's head and coverage note). */ function cappedCorpus(recs: Rec[]): ReturnType { const c = fakeCorpus(recs); const call = c.call.bind(c); c.call = async (name, args = {}) => { const text = await call(name, args); if (name !== "enumerate_matches") return text; return ( "⚠ COVERAGE PARTIAL — the scan hit its page/video cap before the corpus was exhausted. The 2 match(es) below are a SAMPLE, not the full set: …\n" + "The sample is biased by CHANNEL ORDER, not random — fully scanned (1): Synth Kitchen; stopped inside Synth Other at page 3/9; NEVER REACHED (2): Synth Rumble (Mirror), Synth Live.\n\n" + text.replace("(complete set: yes", "(complete set: NO — capped") ); }; return c; } test("enumerateOf reads a capped scan's coverage: names with parentheses whole, the channel it stopped inside", () => { const e = enumerateOf( "⚠ COVERAGE PARTIAL — …\nThe sample is biased by CHANNEL ORDER, not random — fully scanned (1): A; stopped inside TheQuartering at page 29/29; NEVER REACHED (3): Jeremy Hambly, Melonie Mac, TheQuartering (Rumble).\n\n- x | video | A | 2026-10-01 | 1 match(es) | X\n\n(complete set: NO — capped; 1 match(es))", ); assert.equal(e.partial, true); assert.deepEqual(e.unreached, ["Jeremy Hambly", "Melonie Mac", "TheQuartering (Rumble)"]); assert.equal(e.stopped, "TheQuartering (stopped at page 29 of 29)"); }); test("deltaCandidates with no known set: the scan is bounded by `since` (date_from), never the whole scope; `ids` restricts it", async () => { const corpus = fakeCorpus(BASE); await deltaCandidates({ queries: [{ query: "contest" }], scope: { channels: ["synth-kitchen"], from: "2020-01-01" } }, corpus, { since: "2026-10-07T00:00:00Z", ids: ["pie-02"] }); assert.deepEqual(corpus.calls[0]!.args, { query: "contest", channels: ["synth-kitchen"], date_from: "2026-10-07", ids: ["pie-02"] }); // A known set keeps the whole scan (changed and unmatched need it). const whole = fakeCorpus(BASE); await deltaCandidates({ queries: [{ query: "contest" }], scope: { channels: ["synth-kitchen"] } }, whole, { known: { "pie-02": 2 }, since: "2026-10-07" }); assert.deepEqual(whole.calls[0]!.args, { query: "contest", channels: ["synth-kitchen"] }); // A capped answer is partial, with what it did not reach (the stopped channel first). const capped = await deltaCandidates({ queries: [{ query: "contest" }], scope: { channels: ["synth-kitchen"] } }, cappedCorpus(BASE), { known: {} }); assert.equal(capped.partial, true); assert.deepEqual(capped.unreached, ["Synth Live", "Synth Other (stopped at page 3 of 9)", "Synth Rumble (Mirror)"]); assert.deepEqual(capped.unmatched, [], "unmatched is never said of a partial scan"); }); test("refresh, a capped search again with nothing new: partial (naming what it did not reach), never no-change", async () => { const paths = store(); await doneSweep(paths); await createIteration("synth", { kind: "refresh", model: "claude-sonnet-5-5", parent: 1 }, paths); const h = harness({ recs: BASE }); const deps = h.deps(paths); const capped = cappedCorpus(BASE); deps.refresh!.openCorpus = async () => { Object.assign(deps.corpus, { source: capped.source, tools: capped.tools, call: capped.call.bind(capped) }); return { source: capped.source, origin: "https://synth.example", build: "synth" }; }; const out = await refresh({ article: "synth", n: 2, model: "claude-sonnet-5-5", extractorModel: "claude-haiku-4-5", maxUsd: 3, fetch: false }, deps); assert.equal(out.status, "done", h.lines.join("\n")); const f = (await readJson(iterationFile(paths, "synth", 2, "refresh.json"))) as RefreshFile; assert.equal(f.status, "partial"); assert.match(f.summary, /^partial — not reached: Synth Live, Synth Other \(stopped at page 3 of 9\), Synth Rumble \(Mirror\); Nothing new since \d{4}-\d{2}-\d{2} in what was read$/); assert.equal(f.delta?.partial, true); assert.equal(outcomeOf(f).status, "partial"); }); test("R4.1 fetch: transcription held — transcribe-bucket is skipped and said (a warning to the caller), never waited on; nothing to transcribe is a routine skip; a cancelled job is a warning", async () => { const calls: Call[] = []; const buckets: Record = { held: ["old"], one: ["old"], quiet: ["old"], gone: [] }; const hooks = { editor: { async run(action: string, args: Record) { calls.push({ action, args }); if (action === "sync" && args.slug === "held") buckets.held = ["old", "n1", "n2"]; if (action === "sync" && args.slug === "one") buckets.one = ["old", "m1"]; if (action === "sync" && args.slug === "gone") return { ok: true, jobId: "cancel-me" }; return { ok: true, jobId: `job-${calls.length}` }; }, }, jobOf: async (id: string) => ({ status: id === "cancel-me" ? "cancelled" : "done", endedAt: Date.now() }), channelOf: async () => ({ kind: "video" as const, platform: "youtube" }), bucketOf: async (slug: string) => buckets[slug] ?? null, transcriptionHeld: async () => "no transcription worker is enabled", siteOf: async () => ({ site: null, reason: "no build" }), pollMs: 1, sleep: async () => {}, }; const r = await fetchAndBuild({ channels: ["held", "one", "quiet", "gone"] }, hooks); assert.ok(!calls.some((c) => c.action === "transcribe-bucket"), "nothing queued for a held transcription"); const tb = r.fetch.find((s) => s.channel === "held" && s.action === "transcribe-bucket")!; assert.deepEqual(tb, { channel: "held", action: "transcribe-bucket", status: "skipped", reason: "transcription is paused (no transcription worker is enabled) — 2 recordings wait; a later run reads them once transcribed", ids: ["n1", "n2"], }); // R6.2: one recording "waits" (not "wait"), and a later run reads "it". assert.equal(r.fetch.find((s) => s.channel === "one" && s.action === "transcribe-bucket")!.reason, "transcription is paused (no transcription worker is enabled) — 1 recording waits; a later run reads it once transcribed"); const routine = r.fetch.find((s) => s.channel === "quiet" && s.action === "transcribe-bucket")!; assert.deepEqual(routine, { channel: "quiet", action: "transcribe-bucket", status: "skipped", reason: "nothing new to transcribe", routine: true }); assert.ok(r.warnings.some((w) => /^gone: sync cancelled — the job ended cancelled$/.test(w)), JSON.stringify(r.warnings)); assert.ok(!r.warnings.some((w) => /nothing new to transcribe/.test(w))); }); // lane/local-media: a local media library channel has nothing online to sync — // a routine skip, no job and no warning (it used to be a refused sync). test("fetch: a local media library channel's sync is a routine skip, not a refused job", async () => { const calls: Call[] = []; const hooks = { editor: { async run(action: string, args: Record) { calls.push({ action, args }); return { ok: true, jobId: "j" }; } }, jobOf: async () => ({ status: "done", endedAt: Date.now() }), channelOf: async () => ({ kind: "video" as const, localLibrary: true as const }), siteOf: async () => ({ site: null, reason: "no build" }), pollMs: 1, sleep: async () => {}, }; const r = await fetchAndBuild({ channels: ["library"] }, hooks); assert.deepEqual(calls, []); assert.deepEqual(r.fetch, [{ channel: "library", action: "sync", status: "skipped", reason: "a local media library: nothing online to sync", routine: true }]); assert.deepEqual(r.warnings, []); });