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 { FAKE_KEY, startFakeAnthropic, 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 { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft"; import { planProposeGroupsJob } from "yt-dlp-transcript-common/controller/proposeGroups"; import { readGroupProposals } from "yt-dlp-transcript-common/lib/report/groupProposals.mjs"; import { GENERATION_PRESETS, sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { readGenerationUsage } from "yt-dlp-transcript-common/controller/generationUsage"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/_proposeGroups.test.ts" // // The `report-draft` task `propose-groups` (lane L4) end to end in this // process: the controller the ops route adapts, a synthetic deck cut in a temp // dir, the fake Anthropic and ollama servers, a temp jobs dir and usage ledger. let tmp: string; let api: FakeAnthropic; let ol: FakeOllama; let paths: Paths; let gen: GenerationSettings; before(async () => { tmp = await mkdtemp(path.join(os.tmpdir(), "propose-groups-")); api = await startFakeAnthropic(); ol = await startFakeOllama(); const keyFile = path.join(tmp, "anthropic.env"); await writeFile(keyFile, `ANTHROPIC_API_KEY=${FAKE_KEY}\n`); await chmod(keyFile, 0o600); paths = { jobsDir: path.join(tmp, ".jobs"), transcriptsDir: path.join(tmp, "transcripts"), channelsDir: path.join(tmp, "transcripts", "channels"), generationUsageFile: path.join(tmp, ".generation", "usage.jsonl"), ollamaUrl: ol.url, } as Paths; gen = sanitizeGeneration({ apiKeyFile: keyFile, anthropicBaseUrl: api.url, caps: { daily: 20, max: 10 }, routes: { ...GENERATION_PRESETS.balanced } }); }); after(async () => { await api.close(); await ol.close(); await rm(tmp, { recursive: true, force: true }); }); const deps = (g: Partial = {}) => ({ paths, corpusTools: async () => { throw new Error("no corpus tools here"); }, settings: () => ({ generation: { ...gen, ...g } }) }) as ReportDraftDeps; async function project(name: string) { const dir = path.join(tmp, name); await mkdir(dir, { recursive: true }); const clip = (id: string, i: number) => ({ type: "clip", id, video: "v1", start: 10 * i, end: 10 * i + 8, quote: `words of ${id}` }); const m = { slug: "s", render: { chrome: { engine: "hyperframes", layout: "deck", deck: { markers: [{ after: "c02", label: "Two" }] } } }, timeline: ["c01", "c02", "c03", "c04"].map(clip) }; await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(m, null, 2) + "\n"); return dir; } async function finished(o: Awaited>) { assert.ok(o.result.ok, (o.result as { error?: string }).error); const job = getRegistry().get(o.result.jobId)!; void o.result.stream.cancel(); const done = await o.result.done; return { job, done, log: await readFile(job.logPath, "utf8") }; } const ANSWER = { groups: [{ section: 0, claim: "The opening claim", ids: ["c01", "c02"], why: "w" }, { section: 1, claim: "Across", ids: ["c02", "c03"], why: "w" }] }; test("the body: a project, words optional, no note or scope", () => { assert.throws(() => parseReportDraftBody({ task: "propose-groups" }), /"project" is the video project's absolute directory/); assert.throws(() => parseReportDraftBody({ task: "propose-groups", article: "a", project: "/p" }), /a propose-groups job names its "project"/); assert.throws(() => parseReportDraftBody({ task: "propose-groups", project: "/p", note: "n_abcd1234" }), /takes no "note"/); assert.throws(() => parseReportDraftBody({ task: "propose-groups", project: "/p", scope: "all" }), /a video-assist job's/); assert.throws(() => parseReportDraftBody({ task: "propose-groups", project: "/p", iteration: 2 }), /takes no iteration/); assert.deepEqual(parseReportDraftBody({ task: "propose-groups", project: "/p", request: " by day ", dryRun: true }), { task: "propose-groups", article: "", project: "/p", request: "by day", dryRun: true }); }); test("on the local model (the default route): draft:local, one ask, proposals written, ollama unloaded, the manifest untouched", async () => { const dir = await project("local"); const before = await readFile(path.join(dir, "video.manifest.json"), "utf8"); assert.equal(gen.routes["propose-groups"], "local"); ol.push(jsonReply(ANSWER)); const { job, done, log } = await finished(await enqueueReportDraft({ task: "propose-groups", project: dir }, deps())); assert.equal(done.status, "done", log); assert.equal(job.queueKey, "draft:local"); assert.match(log, /proposed: §0 c01 c02 — The opening claim/); assert.match(log, /@@report-draft \{"article":"","iteration":0,"task":"propose-groups","project":"[^"]+local","status":"done","summary":"1 group proposed, 1 refused on qwen3:8b"/); assert.match(log, /unloaded qwen3:8b from ollama/); const { doc } = await readGroupProposals(dir); assert.deepEqual(doc!.groups.map((g) => [g.id, g.status, g.claim]), [["p1", "proposed", "The opening claim"]]); assert.equal(await readFile(path.join(dir, "video.manifest.json"), "utf8"), before); }); test("on the API: draft:api, a ledger row as task propose-groups; the code route: refused unanswered, planned, a session's answer on no model", async () => { const dir = await project("api"); api.push(toolTurn("answer", ANSWER)); const { job, done, log } = await finished(await enqueueReportDraft({ task: "propose-groups", project: dir }, deps({ routes: { ...gen.routes, "propose-groups": "api" } }))); assert.equal(done.status, "done", log); assert.equal(job.queueKey, "draft:api"); const rows = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); assert.deepEqual(rows.map((r) => [r.task, r.model]), [["propose-groups", "claude-sonnet-5-5"]]); const code = { routes: { ...gen.routes, "propose-groups": "code" as const } }; const refused = await enqueueReportDraft({ task: "propose-groups", project: dir }, deps(code)); assert.ok(!refused.result.ok && /routed to Claude Code/.test((refused.result as { error: string }).error)); const plan = await planProposeGroupsJob(parseReportDraftBody({ task: "propose-groups", project: dir, dryRun: true }), deps(code)); assert.equal(plan.provider, "code"); assert.match(plan.request.user, /§1 Two/); const asked = api.requests.length + ol.requests.length; const r = await finished(await enqueueReportDraft({ task: "propose-groups", project: dir, answers: { groups: [{ section: 1, claim: "Late", ids: ["c03", "c04"], why: "" }] } }, deps(code))); assert.equal(r.done.status, "done", r.log); assert.equal(api.requests.length + ol.requests.length, asked); assert.equal((await readGroupProposals(dir)).doc!.model, "claude-code"); });