// Research RUNS (release 27 S11): the state a run keeps (proposals.json, the // refresh from job states, the phase, the continuation's scope) and the // `research` task end to end against the fake Anthropic and ollama servers, // a stub corpus and a fake editor. The editor job, the approval and the // continuation through `report-draft` are editor/app/api/ops/_researchRuns.test.ts. import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { FAKE_KEY, startFakeAnthropic, type FakeAnthropic } from "../../../../testing/llm/fakeAnthropic.mjs"; import { startFakeOllama, toolCallsReply, reply, type FakeOllama } from "../../../../testing/llm/fakeOllama.mjs"; import { ORIGIN } from "../../../../testing/draft/corpus.mjs"; import { createIteration, readIteration } from "../../iterations"; import type { AgentTool } from "../../../llm"; import { research } from "../tasks/research"; import type { TaskDeps } from "../tasks/types"; import { DEFAULT_RESEARCH_LIMITS, type Proposal } from "./decide"; import type { ResearchEditor } from "./tools"; import { isSettled, lastAcquiredAt, newResearchState, parseResearchState, phaseOf, readResearchState, refreshProposals, waitingOn, widenedChannels, } from "./state"; const RUN = path.join(path.dirname(new URL(import.meta.url).pathname), "../../../../testing/draft/runs/research.json"); let tmp: string; let api: FakeAnthropic; let ol: FakeOllama; let caseN = 0; before(async () => { tmp = await mkdtemp(path.join(os.tmpdir(), "research-runs-")); api = await startFakeAnthropic(); ol = await startFakeOllama(); }); after(async () => { await api.close(); await ol.close(); await rm(tmp, { recursive: true, force: true }); }); const prop = (id: string, action: Proposal["action"], args: Record, status: Proposal["status"], extra: Partial = {}): Proposal => ({ id, action, args, reason: "r", evidence: [], status, ...extra, }); test("state: an enqueued acquisition settles from its jobs — all done is done, one failed or lost is failed, a running one waits", async () => { const s = newResearchState("limits", DEFAULT_RESEARCH_LIMITS); s.proposals = [ prop("p01", "import-archive-org", { slug: "synth-kitchen" }, "enqueued", { jobId: "j1,j2" }), prop("p02", "import-video", { slug: "synth-kitchen" }, "enqueued", { jobId: "j3" }), prop("p03", "import-post", { slug: "synth-social" }, "enqueued", { jobId: "j4" }), prop("p04", "fetch-posts", { slug: "synth-social" }, "enqueued", { jobId: "j5" }), prop("p05", "create-channel", { fields: {} }, "proposed", { note: "a new channel needs the operator's approval" }), ]; const jobs: Record = { j1: { status: "done", endedAt: Date.UTC(2026, 9, 13, 10) }, j2: { status: "done", endedAt: Date.UTC(2026, 9, 13, 11) }, j3: { status: "failed" }, j4: { status: "running" }, j5: { status: "archived" }, }; assert.deepEqual(waitingOn(s), { approval: ["p05"], jobs: ["j1", "j2", "j3", "j4", "j5"] }); assert.equal(await refreshProposals(s, async (id) => jobs[id] ?? null), true); assert.deepEqual( s.proposals.map((p) => [p.id, p.status, p.note ?? ""]), [ ["p01", "done", ""], ["p02", "failed", "job j3 ended failed"], ["p03", "enqueued", ""], ["p04", "failed", "job j5 was lost (the editor restarted)"], ["p05", "proposed", "a new channel needs the operator's approval"], ], ); assert.equal(s.proposals[0]!.doneAt, "2026-10-13T11:00:00.000Z", "the last of its jobs"); assert.equal(phaseOf(s), "wait"); assert.equal(await refreshProposals(s, async (id) => jobs[id] ?? null), false, "nothing new"); jobs.j4 = { status: "done", endedAt: Date.UTC(2026, 9, 13, 12) }; s.proposals[4]!.status = "rejected"; await refreshProposals(s, async (id) => jobs[id] ?? null); assert.equal(isSettled(s), true); assert.equal(phaseOf(s), "ready"); assert.equal(phaseOf(s, true), "continued"); assert.equal(lastAcquiredAt(s), Date.UTC(2026, 9, 13, 12)); assert.deepEqual(waitingOn(s), { approval: [], jobs: [] }); }); test("state: a continuation sweeps the run's channels and every channel a done acquisition wrote into", () => { const s = newResearchState("auto", DEFAULT_RESEARCH_LIMITS); s.proposals = [ prop("p01", "create-channel", { fields: { name: "Synth Radio" } }, "done", { channel: "synth-radio" }), prop("p02", "import-archive-org", { slug: "synth-radio", item: "x" }, "done"), prop("p03", "import-post", { slug: "synth-social", url: "u" }, "done"), prop("p04", "persist-videos", { items: [{ slug: "synth-other", id: "a" }] }, "done"), prop("p05", "priority-bump", { slug: "synth-bumped" }, "done"), prop("p06", "import-video", { slug: "synth-failed", url: "u" }, "failed"), prop("p07", "import-video", { slug: "synth-waiting", url: "u" }, "proposed"), ]; assert.deepEqual(widenedChannels(["synth-kitchen"], s), ["synth-kitchen", "synth-radio", "synth-social", "synth-other"]); }); test("state: proposals.json is read leniently — a bare list, unknown statuses dropped, limits defaulted", () => { const s = parseResearchState([{ id: "p01", action: "import-video", args: { slug: "s" }, status: "proposed" }, { id: "p02", status: "weird", action: "x" }]); assert.equal(s.proposals.length, 1); assert.equal(s.autonomy, "propose"); assert.deepEqual(s.limits, DEFAULT_RESEARCH_LIMITS); assert.deepEqual(s.proposals[0]!.evidence, []); }); // ─── the task ─── function stubCorpus(): TaskDeps["corpus"] { const tool = (name: string, out: string): AgentTool => ({ name, description: name, inputSchema: { type: "object", properties: { query: { type: "string" } } }, run: async () => out }); return { source: "local:/stub", tools: [ tool("search_transcripts", `1 match: synth-kitchen/pie-stream-02 @ 0:30 "the second shop" ${ORIGIN}/?v=synth-kitchen%2Fpie-stream-02&t=30`), tool("list_channels", "synth-kitchen, synth-other"), tool("get_video_metadata", "{}"), tool("get_transcripts", "never offered to a research run"), ], call: async () => "", }; } function fakeEditor() { const calls: { action: string; args: Record }[] = []; const editor: ResearchEditor = { run: async (action, args) => { calls.push({ action, args }); if (action === "archive-search") return { ok: true, found: 1, items: [{ identifier: "synth-kitchen-episodes-2026", title: "Synth Kitchen — episodes" }] }; if (action === "archive-item") return { ok: true, item: { identifier: "synth-kitchen-episodes-2026", files: [{ name: "Bread day.mp4", size: 104857600 }] } }; return { ok: true, jobId: `job-${calls.length}` }; }, }; return { editor, calls }; } async function newRun(autonomy: "propose" | "limits" | "auto", model: string) { caseN++; const paths = { articlesDir: path.join(tmp, `reports-${caseN}`), exportIndexDir: path.join(tmp, `idx-${caseN}`) }; await mkdir(paths.articlesDir, { recursive: true }); const r = JSON.parse(await readFile(RUN, "utf8")); await createIteration("synth-research", { kind: "research", model, question: r.question, scope: { channels: r.channels } }, paths); const lines: string[] = []; const { editor, calls } = fakeEditor(); const deps: TaskDeps = { llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: FAKE_KEY }, sleep: async () => {} }, ollama: { baseUrl: ol.url } }, corpus: stubCorpus(), cuesOf: async () => null, paths, editor, editorChannels: async () => [{ slug: "synth-kitchen", name: "Synth Kitchen", platform: "youtube", kind: "videos" }], log: (l) => lines.push(l), }; return { r, paths, deps, calls, lines, autonomy }; } test("research (API, limits): discovers, enqueues the import under the caps, leaves the new channel waiting, refuses the Twitch VOD", async () => { const run = await newRun("limits", "claude-sonnet-5-5"); api.push(...run.r.turns); const before = api.requests.length; const out = await research( { article: "synth-research", n: 1, origin: ORIGIN, maxUsd: 2, autonomy: "limits", limits: DEFAULT_RESEARCH_LIMITS }, run.deps, ); assert.equal(out.status, "done", out.summary); assert.match(out.summary, /^3 acquisition\(s\) \(1 enqueued, 1 waiting for approval, 1 refused\) — waiting/); // The editor saw the reads and ONE acquisition, its body the action's own keys. assert.deepEqual( run.calls.map((c) => c.action), ["archive-search", "archive-item", "import-archive-org"], ); assert.deepEqual(run.calls[2]!.args, { slug: "synth-kitchen", item: "synth-kitchen-episodes-2026", files: ["Bread day.mp4"] }); const state = (await readResearchState("synth-research", 1, run.paths))!; assert.equal(state.autonomy, "limits"); assert.deepEqual( state.proposals.map((p) => [p.id, p.action, p.status]), [ ["p01", "import-archive-org", "enqueued"], ["p02", "create-channel", "proposed"], ["p03", "import-video", "rejected"], ], ); assert.equal(state.proposals[0]!.jobId, "job-3"); assert.match(state.proposals[1]!.note!, /new channel needs the operator's approval/); assert.match(state.proposals[2]!.note!, /Twitch VOD is never fetched again/); assert.deepEqual(state.spent, { items: 1, gb: 0.1, transcribeHours: 0.02 }); const it = (await readIteration("synth-research", 1, run.paths))!; assert.equal(it.status, "done"); const rec = (it as { research?: Record }).research!; assert.equal(rec.autonomy, "limits"); assert.equal(rec.phase, "wait"); assert.match(String(rec.notes), /radio tape/); // The model was told its autonomy and the standing rules, and offered no bulk transcript read. const first = api.requests[before]!; const system = JSON.stringify(first.system); assert.match(system, /WITHIN LIMITS/); assert.match(system, /never a Twitch VOD URL/); assert.match(system, /always created on NO site/); const names = (first.tools as { name: string }[]).map((t) => t.name); assert.ok(names.includes("editor_channels") && names.includes("archive-item") && names.includes("persist-videos"), names.join(",")); assert.ok(!names.includes("get_transcripts"), "no bulk transcript read"); }); test("research (API, propose): every acquisition waits; nothing but the reads reaches the editor", async () => { const run = await newRun("propose", "claude-sonnet-5-5"); api.push(...run.r.turns); const out = await research({ article: "synth-research", n: 1, origin: ORIGIN, maxUsd: 2, autonomy: "propose", limits: DEFAULT_RESEARCH_LIMITS }, run.deps); assert.equal(out.status, "done", out.summary); assert.deepEqual(run.calls.map((c) => c.action), ["archive-search", "archive-item"]); const state = (await readResearchState("synth-research", 1, run.paths))!; assert.deepEqual(state.proposals.map((p) => p.status), ["proposed", "proposed", "rejected"]); assert.deepEqual(state.spent, { items: 0, gb: 0, transcribeHours: 0 }); }); test("research (local): the tool loop fits the 8k prompt, and a run with nothing to acquire is ready", async () => { const run = await newRun("auto", "qwen3:8b"); ol.push(toolCallsReply([{ name: "search_transcripts", arguments: { query: "second shop" } }]), reply("The archive already holds the whole story; nothing to acquire.")); const out = await research({ article: "synth-research", n: 1, origin: ORIGIN, maxUsd: Number.POSITIVE_INFINITY, autonomy: "auto", limits: DEFAULT_RESEARCH_LIMITS }, run.deps); assert.equal(out.status, "done", `${out.summary}\n${run.lines.join("\n")}`); assert.match(out.summary, /^0 acquisition\(s\) — nothing pending: ready to continue/); const it = (await readIteration("synth-research", 1, run.paths))!; assert.equal((it as { research?: { phase?: string } }).research!.phase, "ready"); }); test("research: refused without the editor, or on an iteration that is not a research run", async () => { const run = await newRun("propose", "claude-sonnet-5-5"); const { editor: _e, ...noEditor } = run.deps; const out = await research({ article: "synth-research", n: 1, origin: ORIGIN, maxUsd: 1, autonomy: "propose", limits: DEFAULT_RESEARCH_LIMITS }, noEditor); assert.equal(out.status, "failed"); assert.match(out.summary, /needs the editor/); await createIteration("synth-research", { kind: "sweep", model: "claude-sonnet-5-5", question: "q", scope: { channels: ["synth-kitchen"] } }, run.paths); await assert.rejects( research({ article: "synth-research", n: 2, origin: ORIGIN, maxUsd: 1, autonomy: "propose", limits: DEFAULT_RESEARCH_LIMITS }, run.deps), /is a sweep iteration, not research/, ); });