import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { createCorpusTools } from "yt-dlp-transcript-mcp/callTool"; import { LATE_RECORD, ORIGIN, withRecords, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; import { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft"; import { fetchScope, planRefresh } from "yt-dlp-transcript-common/controller/reportRefresh"; import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { createIteration, readIteration, readIterationFile, updateIteration, writeIterationFile } from "yt-dlp-transcript-common/lib/report/iterations"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; import type { RefreshFile } from "yt-dlp-transcript-common/lib/report/draft/refresh/types"; import { refreshEditor } from "./_researchEditor"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/_reportRefresh.test.ts" // // `report-draft {"task": "refresh"}` (umtool R4) in this process: the body, // the plan, and the job end to end over a stubbed editor door (the actions a // refresh asks for, answered with job ids the stubbed registry calls done), // the MCP's corpus tools over the synthetic draft corpus as a composed site // build, and a temp store. No model is called: the paths here end no-change // or held by the cap (the update itself is mcp/src/refreshTask.test.ts). const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../common/testing/draft"); let tmp: string; let paths: Paths; let gen: GenerationSettings; before(async () => { tmp = await mkdtemp(path.join(os.tmpdir(), "report-refresh-")); paths = { jobsDir: path.join(tmp, ".jobs"), articlesDir: path.join(tmp, "reports"), exportIndexDir: path.join(tmp, ".export-index"), exportBuildsDir: path.join(tmp, ".export-builds"), sitesDir: path.join(tmp, "sites"), channelsDir: path.join(tmp, "channels"), generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), ollamaUrl: "http://127.0.0.1:9", } as Paths; // The site whose composed build holds the channel, and the channel. await writeDraftCorpus(path.join(paths.exportBuildsDir, "synth", "out")); await mkdir(path.join(paths.sitesDir, "synth"), { recursive: true }); await writeFile(path.join(paths.sitesDir, "synth", "site.json"), JSON.stringify({ title: "Synth", siteUrl: ORIGIN })); await mkdir(path.join(paths.channelsDir, "synth-kitchen"), { recursive: true }); await writeFile(path.join(paths.channelsDir, "synth-kitchen", "config.json"), JSON.stringify({ name: "Synth Kitchen", handling: "youtube", url: "https://www.youtube.com/@synth/videos" })); gen = sanitizeGeneration({ citationOrigin: ORIGIN, routes: { sweep: "api" }, models: { api: "claude-sonnet-5-5" }, caps: { sweep: 2, daily: 20, max: 5 } }); }); after(() => rm(tmp, { recursive: true, force: true })); // The door, stubbed: what was asked, and a job id the registry stub calls done. const asked: { action: string; args: Record }[] = []; const door = { async run(action: string, args: Record) { asked.push({ action, args }); if (action === "publish") return { ok: true, runId: "r1", jobs: [{ target: "synth", kind: "build-site", jobId: `job-${asked.length}` }] }; return { ok: true, jobId: `job-${asked.length}` }; }, }; const deps = (g: Partial = {}): ReportDraftDeps => ({ paths, corpusTools: (s: string) => createCorpusTools({ source: s }), settings: () => ({ generation: { ...gen, ...g } }), refreshEditor: door, jobOf: async () => ({ status: "done", endedAt: Date.now() }), refreshTiming: { pollMs: 1, sleep: async () => {} }, }); async function doneSweep(article: string) { 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")), id: article }, paths); const trace = [ { t: "run", run: 1, phase: "start", task: "sweep-agent", model: "claude-sonnet-5-5" }, { t: "scope", run: 1, source: `local:${path.join(paths.exportBuildsDir, "synth", "out")}`, 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", usage: { "claude-sonnet-5-5": { usd: 0.4, inputTokens: 1, outputTokens: 1 } }, coverage: { matched: 1, read: 2, partial: false, unreached: [] } }, paths); } test("the body: a refresh takes its iteration, model, caps, fetch and dryRun — never a question or a scope; ids are a sweep's, a refresh's (R6: a triage's flags) or a triage's", () => { assert.deepEqual(parseReportDraftBody({ task: "refresh", article: "a" }), { task: "refresh", article: "a" }); assert.deepEqual(parseReportDraftBody({ task: "refresh", article: "a", iteration: 3, fetch: false, dryRun: true, maxUsd: 1, extractorModel: "claude-haiku-4-5" }), { task: "refresh", article: "a", iteration: 3, extractorModel: "claude-haiku-4-5", maxUsd: 1, fetch: false, dryRun: true, }); assert.throws(() => parseReportDraftBody({ task: "refresh", article: "a", question: "q", channels: ["x"] }), /a refresh takes its question and scope from the iteration it refreshes — not question, channels/); assert.deepEqual(parseReportDraftBody({ task: "refresh", article: "a", ids: ["x"], fetch: false }), { task: "refresh", article: "a", ids: ["x"], fetch: false }); assert.throws(() => parseReportDraftBody({ task: "revise-report", article: "a", iteration: 1, feedback: "f", ids: ["x"] }), /"ids" is a sweep's/); // A triage (umtool R6): its own keys, and only its. assert.deepEqual( parseReportDraftBody({ task: "triage", article: "watch-a", question: "q", channels: ["x"], terms: "co-host", regex: true, topics: "guest, panel", threshold: { strong: 1, weak: 2 }, since: "2026-10-07", maxCandidates: 20, windows: { v1: [{ start: 5, end: 30 }] } }), { task: "triage", article: "watch-a", question: "q", channels: ["x"], terms: "co-host", regex: true, topics: ["guest", "panel"], threshold: { strong: 1, weak: 2 }, since: "2026-10-07", maxCandidates: 20, windows: { v1: [{ start: 5, end: 30 }] } }, ); assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], topics: ["t"] }), /"topics" is a triage's/); assert.throws(() => parseReportDraftBody({ task: "triage", article: "a", question: "q" }), /a triage needs its channels/); assert.throws(() => parseReportDraftBody({ task: "triage", article: "a", question: "q", channels: ["x"], threshold: { strong: -1 } }), /"threshold" is/); assert.throws(() => parseReportDraftBody({ task: "triage", article: "a", question: "q", channels: ["x"], windows: { v1: [{ start: 9, end: 2 }] } }), /end ≥ start/); assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], ids: ["v1"], triage: "watch-a/3" }).triage, { owner: "watch-a", k: 3 }); assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], triage: "nope" }), /names a triage run/); assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], fetch: false }), /"fetch" is a refresh's/); assert.throws(() => parseReportDraftBody({ task: "refresh", article: "a", dryRun: "yes" }), /"dryRun" is true or false/); assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: ["x"], ids: "v1, v2, v1" }).ids, ["v1", "v2"]); }); test("the plan: the iteration refreshed (the current report's, else the newest with a report), its queries, the channel's actions, the site built, the cap", async () => { await doneSweep("synth-plan"); const plan = await planRefresh({ task: "refresh", article: "synth-plan" }, deps()); assert.equal(plan.parent.n, 1); assert.equal(plan.parent.from, "trace"); assert.deepEqual(plan.parent.queries, ["contest"]); assert.equal(plan.parent.citedCount, 6); assert.deepEqual(plan.channels, [{ slug: "synth-kitchen", kind: "video", platform: "youtube", actions: ["sync", "refresh-report", "transcribe-bucket (what lands)"] }]); assert.equal(plan.build.site, "synth"); assert.equal(plan.corpus.build, "synth"); assert.equal(plan.model, "claude-sonnet-5-5"); assert.equal(plan.capUsd, 2); assert.deepEqual(plan.estimate, { perRecordingUsd: 0.2, revisionUsd: 0.3, from: "parent" }); assert.deepEqual(plan.refusals, []); const none = await planRefresh({ task: "refresh", article: "synth-plan", fetch: false }, deps()); assert.deepEqual(none.channels[0]!.actions, []); assert.equal(none.build.site, null); await assert.rejects(planRefresh({ task: "refresh", article: "synth-none" }, deps()), /has no report to refresh/); }); test("refused: no editor door; the iteration named is not done", async () => { await doneSweep("synth-refuse"); const noDoor = await enqueueReportDraft({ task: "refresh", article: "synth-refuse" }, { ...deps(), refreshEditor: undefined }); assert.match((noDoor.result as { error: string }).error, /a refresh runs in the editor/); const missing = await enqueueReportDraft({ task: "refresh", article: "synth-refuse", iteration: 7 }, deps()); assert.match((missing.result as { error: string }).error, /has no iteration i7/); assert.equal(await readIteration("synth-refuse", 2, paths), null); }); test("a refresh with nothing new: one job on draft:refresh — the sync, its report, the build — no change, $0, the marker", async () => { await doneSweep("synth-same"); asked.length = 0; const out = await enqueueReportDraft({ task: "refresh", article: "synth-same" }, deps()); assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); assert.equal(out.iteration, 2); const job = getRegistry().get(out.result.jobId)!; assert.equal(job.kind, "report-draft"); assert.equal(job.queueKey, "draft:refresh"); void out.result.stream.cancel(); const done = await out.result.done; const log = await readFile(job.logPath, "utf8"); assert.equal(done.status, "done", log); assert.deepEqual(asked.map((a) => a.action), ["sync", "refresh-report", "publish"]); assert.deepEqual(asked.at(-1)!.args, { verb: "build", siteId: "synth", force: false }); assert.match(log, /@@report-draft \{"article":"synth-same","iteration":2,"task":"refresh","status":"done",.*"refresh":\{"status":"no-change","newIds":0,"changed":0,"drifted":0,"deleted":0,"summary":"Nothing new since 20\d\d-/); const it = (await readIteration("synth-same", 2, paths))!; assert.equal(it.kind, "refresh"); assert.equal(it.parent, 1); assert.equal(it.status, "done"); assert.equal(it.jobId, out.result.jobId); assert.deepEqual(it.usage, {}); const f = JSON.parse((await readIterationFile("synth-same", 2, "refresh.json", paths))!) as RefreshFile; assert.equal(f.status, "no-change"); assert.equal(f.corpus?.build, "synth"); assert.equal(f.fetch.find((s) => s.action === "transcribe-bucket")?.reason, "no channel report before the sync: what landed is not known"); assert.equal(f.delta?.quotes.length, 6); assert.ok(f.delta?.quotes.every((q) => q.status === "ok"), JSON.stringify(f.delta?.quotes)); }); test("a refresh with a new recording past the daily cap: held by the cap, the delta and the estimate kept, no model called", async () => { // A later build holds one recording more. await writeDraftCorpus(path.join(paths.exportBuildsDir, "synth", "out"), { channels: withRecords([LATE_RECORD]) }); await mkdir(path.dirname(paths.generationUsageFile), { recursive: true }); const day = new Date().toISOString().slice(0, 10); await writeFile(paths.generationUsageFile, `${JSON.stringify({ at: new Date().toISOString(), day, jobId: "earlier", article: "x", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 0.9 })}\n`); await doneSweep("synth-held"); const out = await enqueueReportDraft({ task: "refresh", article: "synth-held", fetch: false }, deps({ caps: { ...gen.caps, daily: 1 } })); assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); void out.result.stream.cancel(); const done = await out.result.done; const job = getRegistry().get(out.result.jobId)!; const log = await readFile(job.logPath, "utf8"); assert.equal(done.status, "done", log); const f = JSON.parse((await readIterationFile("synth-held", 2, "refresh.json", paths))!) as RefreshFile; assert.equal(f.status, "held-by-cap"); assert.deepEqual(f.delta?.newIds, ["contest-stream-04"]); assert.equal(f.update?.estimateUsd, 0.5); assert.match(f.update?.refusal ?? "", /about \$0\.50 more would pass the \$1\.00 daily cap/); assert.match(log, /"refresh":\{"status":"held-by-cap","newIds":1,/); assert.deepEqual(f.fetch, []); assert.equal(f.build, null); }); test("R5's seam: stage 1 on its own for a scope — the fetches and the build, awaited", async () => { asked.length = 0; const got = await fetchScope({ channels: ["synth-kitchen", "nobody-here"] }, deps()); assert.deepEqual(asked.map((a) => a.action), ["sync", "refresh-report"]); assert.deepEqual(got.fetch.find((s) => s.channel === "nobody-here"), { channel: "nobody-here", action: "sync", status: "skipped", reason: "not a channel of this editor" }); assert.equal(got.build?.status, "skipped", "no composed build holds a channel no site carries: nothing is built"); assert.match(got.build?.reason ?? "", /no composed build holds synth-kitchen, nobody-here/); const one = await fetchScope({ channels: ["synth-kitchen"] }, deps()); assert.equal(one.build?.site, "synth"); assert.equal(one.build?.status, "done"); }); test("the editor's refresh door never deploys", async () => { await assert.rejects(refreshEditor.run("publish", { verb: "deploy", siteId: "x" }), /a refresh only builds/); await assert.rejects(refreshEditor.run("delete-channel", { slug: "x" }), /"delete-channel" is not an action a refresh may ask the editor for/); });