import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { chmod, 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 { ORIGIN, writeDraftCorpus } from "yt-dlp-transcript-common/testing/draft/corpus.mjs"; import { FAKE_KEY, startFakeAnthropic, type FakeAnthropic } from "yt-dlp-transcript-common/testing/llm/fakeAnthropic.mjs"; import { enqueueReportDraft, parseReportDraftBody } from "yt-dlp-transcript-common/controller/reportDraft"; import { approveResearch, researchState } from "yt-dlp-transcript-common/controller/researchRuns"; import { sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { createIteration, readIteration, updateIteration } from "yt-dlp-transcript-common/lib/report/iterations"; import { readResearchState, writeResearchState, newResearchState } from "yt-dlp-transcript-common/lib/report/draft/research/state"; import { DEFAULT_RESEARCH_LIMITS } from "yt-dlp-transcript-common/lib/report/draft/research/decide"; import type { ResearchEditor } from "yt-dlp-transcript-common/lib/report/draft/research/tools"; import { getPaths, type Paths } from "yt-dlp-transcript-common/lib/paths"; import { callPost, setupOpsCorpus, type OpsCorpus } from "./_testCorpus"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/_researchRuns.test.ts" // // Research runs (release 27 S11) end to end in this process: a `report-draft` // research job over the synthetic corpus (the MCP's tools) against the fake // Anthropic server and a fake editor; the operator's yes and no // (research-approve's controller), the refresh from job states, and the // continuation into a sweep. Then the in-process editor and the route's door // over the ops test corpus. const DRAFT = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../common/testing/draft"); let tmp: string; let api: FakeAnthropic; let source: string; let paths: Paths; let gen: GenerationSettings; let ops: OpsCorpus; before(async () => { tmp = await mkdtemp(path.join(os.tmpdir(), "research-runs-")); source = `local:${await writeDraftCorpus(path.join(tmp, "corpus"))}`; api = await startFakeAnthropic(); const keyFile = path.join(tmp, "anthropic.env"); await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`); await chmod(keyFile, 0o600); await mkdir(path.join(tmp, "channels"), { recursive: true }); 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; gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, citationOrigin: ORIGIN, caps: { sweep: 2, daily: 20, max: 5 } }); ops = await setupOpsCorpus("one-youtube-channel-with-data"); }); after(async () => { await api.close(); await ops.cleanup(); await rm(tmp, { recursive: true, force: true }); }); // A fake editor: the archive reads answer, every acquisition is a job. const editorCalls: { action: string; args: Record }[] = []; const fakeEditor: ResearchEditor = { run: async (action, args) => { editorCalls.push({ action, args }); if (action === "archive-search") return { ok: true, found: 1, items: [{ identifier: "synth-kitchen-episodes-2026" }] }; if (action === "archive-item") return { ok: true, item: { identifier: "synth-kitchen-episodes-2026", files: [{ name: "Bread day.mp4", size: 104857600 }] } }; if (action === "create-channel") return { ok: true, slug: "synth-radio", jobIds: ["job-c1"], jobId: "job-c1" }; return { ok: true, jobId: `job-${action}` }; }, }; const jobs: Record = {}; const jobOf = async (id: string) => jobs[id] ?? (getRegistry().get(id) ? { status: getRegistry().get(id)!.status } : null); const deps = (g: Partial = {}) => ({ paths, corpusTools: (s: string) => createCorpusTools({ source: s }), settings: () => ({ generation: { ...gen, ...g } }), researchEditor: fakeEditor, jobOf, }); const run = async (name: string) => JSON.parse(await readFile(path.join(DRAFT, "runs", `${name}.json`), "utf8")); test("the body: research needs its question and takes an autonomy; a sweep with an iteration continues", () => { assert.throws(() => parseReportDraftBody({ task: "research", article: "a" }), /research run needs its question/); assert.throws(() => parseReportDraftBody({ task: "research", article: "a", question: "q", autonomy: "yolo" }), /"autonomy" is one of propose, limits, auto/); assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", question: "q", channels: "x", autonomy: "auto" }), /a research run's/); assert.deepEqual(parseReportDraftBody({ task: "research", article: "a", question: "q", autonomy: "limits" }), { task: "research", article: "a", question: "q", autonomy: "limits" }); assert.deepEqual(parseReportDraftBody({ task: "sweep", article: "a", iteration: 2 }), { task: "sweep", article: "a", iteration: 2 }); }); test("refused: research with no editor in the deps; a continuation of what is not a research run", async () => { const { researchEditor: _e, ...noEditor } = deps(); const out = await enqueueReportDraft({ task: "research", article: "synth-noeditor", model: "claude-sonnet-5-5", question: "q", source }, noEditor); assert.match((out.result as { error: string }).error, /research run runs in the editor/); await createIteration("synth-notresearch", { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); const cont = await enqueueReportDraft({ task: "sweep", article: "synth-notresearch", iteration: 1, model: "claude-sonnet-5-5", source }, deps()); assert.match((cont.result as { error: string }).error, /continues a research run; "synth-notresearch" i1 is a sweep iteration/); }); test("a research run: the job proposes, the operator approves and rejects, the jobs settle, a sweep continues it", async () => { const r = await run("research"); api.push(...r.turns); const article = "synth-research"; const out = await enqueueReportDraft({ task: "research", article, model: r.model, question: r.question, channels: r.channels, source }, deps()); assert.ok(out.result.ok && "iteration" in out, (out.result as { error?: string }).error); const job = getRegistry().get(out.result.jobId)!; assert.equal(job.queueKey, "draft:api"); 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.match(log, /@@report-draft \{"article":"synth-research","iteration":1,"task":"research","status":"done"/); // settings' autonomy: propose — only the reads reached the editor. assert.deepEqual(editorCalls.map((c) => c.action), ["archive-search", "archive-item"]); let it = (await readIteration(article, 1, paths))!; assert.equal(it.kind, "research"); assert.equal((it as { research?: { phase?: string } }).research!.phase, "wait"); // Not continued while it waits. const early = await enqueueReportDraft({ task: "sweep", article, iteration: 1, model: "claude-sonnet-5-5", source }, deps()); assert.match((early.result as { error: string }).error, /i1 still waits — for approval: p01, p02/); // The operator: yes to the import, no to the channel; the refused one cannot be approved. jobs["job-import-archive-org"] = { status: "running" }; const yes = await approveResearch({ article, iteration: 1, ids: ["p01", "p03"], approve: true }, { paths, editor: fakeEditor, jobOf }); assert.ok(yes.ok, (yes as { error?: string }).error); assert.deepEqual(yes.outcomes[0], { id: "p01", status: "enqueued", jobId: "job-import-archive-org" }); assert.match(yes.outcomes[1]!.error!, /p03 is rejected, not waiting for approval/); assert.deepEqual(editorCalls.at(-1), { action: "import-archive-org", args: { slug: "synth-kitchen", item: "synth-kitchen-episodes-2026", files: ["Bread day.mp4"] } }); const no = await approveResearch({ article, iteration: 1, ids: ["p02"], approve: false, note: "not this one" }, { paths, editor: fakeEditor, jobOf }); assert.ok(no.ok); assert.equal(no.view.proposals[1]!.note, "the operator said no: not this one"); assert.equal(no.view.phase, "wait"); assert.deepEqual(no.view.waitingOn, { approval: [], jobs: ["job-import-archive-org"] }); // The import's job ends: the next read settles it, and the run is ready. jobs["job-import-archive-org"] = { status: "done", endedAt: Date.now() }; const ready = await researchState(article, 1, { paths, jobOf }); assert.equal(ready.phase, "ready"); assert.equal(ready.proposals[0]!.status, "done"); assert.equal((await readResearchState(article, 1, paths))!.proposals[0]!.status, "done", "written"); // Continue: a sweep over the widened scope, its parent the research run. const sw = await run("sweep-agent"); api.push(...sw.turns); const cont = await enqueueReportDraft({ task: "sweep", article, iteration: 1, model: sw.model, source }, deps()); assert.ok(cont.result.ok && "iteration" in cont, (cont.result as { error?: string }).error); void cont.result.stream.cancel(); const cdone = await cont.result.done; assert.equal(cdone.status, "done", await readFile(getRegistry().get(cont.result.jobId)!.logPath, "utf8")); const sweep = (await readIteration(article, cont.iteration, paths))!; assert.equal(sweep.kind, "sweep"); assert.equal(sweep.parent, 1); assert.equal(sweep.question, r.question); assert.deepEqual(sweep.scope?.channels, ["synth-kitchen"]); assert.equal(sweep.status, "done"); it = (await readIteration(article, 1, paths))!; assert.deepEqual((it as { research?: { phase?: string; continuedBy?: number[] } }).research, { ...(it as { research?: object }).research, phase: "continued", continuedBy: [cont.iteration], }); }); test("approve is refused while the run's job is going; force continues a run that still waits", async () => { const article = "synth-research-two"; await createIteration(article, { kind: "research", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, paths); const state = newResearchState("propose", DEFAULT_RESEARCH_LIMITS); state.proposals.push({ id: "p01", action: "import-video", args: { slug: "synth-kitchen", url: "https://video.example/v/9" }, reason: "r", evidence: [], status: "proposed" }); await writeResearchState(article, 1, state, paths); await updateIteration(article, 1, { status: "running" }, paths); const busy = await approveResearch({ article, iteration: 1, ids: ["p01"], approve: true }, { paths, editor: fakeEditor, jobOf }); assert.equal(busy.ok, false); assert.match((busy as { error: string }).error, /is running: its proposals are the run's until it ends/); await updateIteration(article, 1, { status: "done" }, paths); const sw = await run("sweep-agent"); api.push(...sw.turns); const forced = await enqueueReportDraft({ task: "sweep", article, iteration: 1, model: sw.model, source, force: true }, deps()); assert.ok(forced.result.ok && "iteration" in forced, (forced.result as { error?: string }).error); void forced.result.stream.cancel(); await forced.result.done; }); // ─── the editor, in process, and the route's door ─── test("the research editor is this editor's own ops routes, in process: their doors and words", async () => { const { researchEditor } = await import("./_researchEditor"); await assert.rejects(researchEditor.run("archive-item", { item: "../../etc" }), /is not an archive\.org identifier/); await assert.rejects(researchEditor.run("import-post", { slug: "test-youtube", url: "https://x.com/synthbaker/status/1" }), /test-youtube is not a posts channel/); await assert.rejects(researchEditor.run("delete-channel", { slug: "test-youtube" }), /not an action a research run may ask the editor for/); }); test("research-approve: the door — keys, ids, a run that is not there", async () => { const route = (await import("./research-approve/route")).POST as Parameters[0]; const extra = await callPost(route, { article: "a", iteration: 1, sites: [] }); assert.equal(extra.status, 400); assert.match(String(extra.body.error), /unknown key\(s\): sites/); const badIds = await callPost(route, { article: "a", iteration: 1, ids: ["x1"], approve: true }); assert.match(String(badIds.body.error), /"ids" is a list of proposal ids/); const noSay = await callPost(route, { article: "a", iteration: 1, ids: ["p01"] }); assert.match(String(noSay.body.error), /say "approve": true or false/); const none = await callPost(route, { article: "synth-nothing", iteration: 1 }); assert.equal(none.status, 400); assert.match(String(none.body.error), /"synth-nothing" has no iteration i1/); // A run on the corpus the route reads: its state, refreshed. const p = getPaths(); await createIteration("synth-door", { kind: "research", model: "claude-sonnet-5-5", question: "q" }, p); await writeResearchState("synth-door", 1, newResearchState("limits", DEFAULT_RESEARCH_LIMITS), p); await updateIteration("synth-door", 1, { status: "done" }, p); const view = await callPost(route, { article: "synth-door", iteration: 1 }); assert.equal(view.status, 200, String(view.body.error)); const research = view.body.research as { phase: string; autonomy: string }; assert.equal(research.phase, "ready"); assert.equal(research.autonomy, "limits"); });