import { after, before, test } from "node:test"; import assert from "node:assert/strict"; import { chmod, 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 { labelAnswer, writeReactionProject, PROJECT_NOTE } from "yt-dlp-transcript-common/testing/clips/reactionProject.mjs"; import { enqueueReportDraft, parseReportDraftBody, type ReportDraftDeps } from "yt-dlp-transcript-common/controller/reportDraft"; import { planClipsSuggestJob, projectDirOf, umtoolOrigin, type ClipsSuggestJobDeps } from "yt-dlp-transcript-common/controller/clipsSuggest"; import { readSuggestions } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; import { GENERATION_PRESETS, sanitizeGeneration, type GenerationSettings } from "yt-dlp-transcript-common/lib/generationSettings"; import { getRegistry } from "yt-dlp-transcript-common/jobs/registry"; import { appendGenerationUsage, isLocalUsage, readGenerationUsage, utcDay } from "yt-dlp-transcript-common/controller/generationUsage"; import type { AskProposal } from "yt-dlp-transcript-common/lib/clips/suggest.mjs"; import type { Paths } from "yt-dlp-transcript-common/lib/paths"; // Run with: // pnpm -C editor exec tsx --test "app/api/ops/_clipsSuggest.test.ts" // // The `report-draft` task `clips-suggest` (release 36 lane D) end to end in // this process: the controller the ops route adapts, a synthetic reactions // project in a temp dir (common/testing/clips/reactionProject.mjs), 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; // The ids a labels prompt asks, in its order. const idsOf = (text: string) => [...text.matchAll(/^\[(p\d+)\]/gm)].map((m) => m[1]!); const userOf = (body: { messages: { content: unknown }[] }) => JSON.stringify(body.messages[0]!.content).replace(/\\n/g, "\n"); const labelTurn = (body: { messages: { content: unknown }[] }) => toolTurn("answer", labelAnswer(idsOf(userOf(body).replace(/^"/, "")))); before(async () => { tmp = await mkdtemp(path.join(os.tmpdir(), "clips-suggest-")); 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, "clips-suggest": "api" } }); }); after(async () => { await api.close(); await ol.close(); await rm(tmp, { recursive: true, force: true }); }); const deps = (g: Partial = {}, more: Partial = {}) => ({ paths, corpusTools: async () => { throw new Error("no corpus tools here"); }, settings: () => ({ generation: { ...gen, ...g } }), ...more }) as ReportDraftDeps & ClipsSuggestJobDeps; const out = (o: Awaited>) => o.result as { ok: boolean; error: string }; async function finished(out: Awaited>) { assert.ok(out.result.ok, (out.result as { error?: string }).error); const job = getRegistry().get(out.result.jobId)!; void out.result.stream.cancel(); const done = await out.result.done; return { job, done, log: await readFile(job.logPath, "utf8") }; } test("the body: a project, not an article; the clips keys are its own; dryRun plans", () => { assert.throws(() => parseReportDraftBody({ task: "clips-suggest" }), /"project" is the reactions project's absolute directory/); assert.throws(() => parseReportDraftBody({ task: "clips-suggest", project: "rel/dir" }), /absolute directory/); assert.throws(() => parseReportDraftBody({ task: "clips-suggest", article: "a", project: "/p" }), /not an article/); assert.throws(() => parseReportDraftBody({ task: "sweep", article: "a", project: "/p" }), /"project" is a clips-suggest job's/); assert.throws(() => parseReportDraftBody({ task: "clips-suggest", project: "/p", note: "n_x" }), /"note" is a note id/); assert.throws(() => parseReportDraftBody({ task: "clips-suggest", project: "/p", note: PROJECT_NOTE, proposals: ["p001"] }), /an Ask \("note"\) takes no/); assert.throws(() => parseReportDraftBody({ task: "clips-suggest", project: "/p", answers: { items: [] }, model: "m" }), /no "model"/); assert.throws(() => parseReportDraftBody({ task: "clips-suggest", project: "/p", iteration: 2 }), /takes no iteration/); assert.deepEqual(parseReportDraftBody({ task: "clips-suggest", project: "/p", proposals: "p001, p002", dryRun: true }), { task: "clips-suggest", article: "", project: "/p", proposals: ["p001", "p002"], dryRun: true, }); assert.throws(() => projectDirOf("/x/../y", paths), /plain absolute path/); assert.throws(() => projectDirOf(path.join(paths.transcriptsDir, "reports", "x"), paths), /never inside the corpus/); assert.equal(umtoolOrigin({ UMTOOL_URL: " http://localhost:3050/ " }), "http://localhost:3050"); assert.equal(umtoolOrigin({}), null); }); test("labels on the API: batches asked, clip-suggestions.json written whole and ranked, the spend in the ledger; the plan first", async () => { const dir = path.join(tmp, "api-project"); writeReactionProject(dir); const plan = await planClipsSuggestJob(parseReportDraftBody({ task: "clips-suggest", project: dir, dryRun: true }), deps()); assert.equal(plan.model, "claude-sonnet-5-5"); assert.equal(plan.proposals, 5); assert.equal(plan.calls, 1); assert.equal(plan.wordsFrom, "words.json"); assert.ok(plan.estimate.usd > 0 && plan.estimate.inputTokens > 200); assert.deepEqual(plan.request.ids, ["p001", "p002", "p003", "p004", "p005"]); api.push(labelTurn); const { job, done, log } = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir }, deps())); assert.equal(done.status, "done", log); assert.equal(job.queueKey, "draft:api"); assert.match(log, /@@report-draft \{"article":"","iteration":0,"task":"clips-suggest","project":"[^"]+api-project","status":"done","summary":"5 proposals labelled on claude-sonnet-5-5 · \$0\.\d+"/); assert.ok(!log.includes(FAKE_KEY)); const { doc } = await readSuggestions(dir); assert.equal(doc!.model, "claude-sonnet-5-5"); assert.deepEqual(Object.entries(doc!.items).map(([id, it]) => [id, (it as { rank: number }).rank, (it as { label: string }).label]), [ ["p005", 1, "the p005 moment"], ["p004", 2, "the p004 moment"], ["p003", 3, "the p003 moment"], ["p002", 4, "the p002 moment"], ["p001", 5, "the p001 moment"], ]); const rows = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); assert.deepEqual(rows.map((r) => [r.task, r.model, r.article, r.iteration]), [["clips-suggest", "claude-sonnet-5-5", "", 0]]); assert.ok(rows[0]!.usd > 0); // It never touched the manifest or reactions.json. assert.equal(JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")).timeline.length, 3); }); test("a malformed answer is refused: no file, the job fails, the batch named", async () => { const dir = path.join(tmp, "malformed-project"); writeReactionProject(dir); api.push(toolTurn("answer", { labels: "everything is funny" })); const { done, log } = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir }, deps())); assert.equal(done.status, "failed", log); assert.match(log, /batch 1\/1 \(p001…p005\): no labels — the answer is not \{ items: \[\.\.\.\] \}/); assert.deepEqual(await readSuggestions(dir), { doc: null, error: null }); }); test("the cap: a run whose first batch would pass maxUsd stops capped and writes nothing; past the day's cap it is refused", async () => { const dir = path.join(tmp, "cap-project"); writeReactionProject(dir); const asked = api.requests.length; const { done, log } = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir, maxUsd: 0.00001 }, deps())); assert.equal(done.status, "done", log); assert.match(log, /stopped at the cap/); assert.equal(api.requests.length, asked); assert.equal((await readSuggestions(dir)).doc, null); // A cap over caps.max is refused at the ask. const over = await enqueueReportDraft({ task: "clips-suggest", project: dir, maxUsd: 50 }, deps()); assert.ok(!out(over).ok && /over the settings' max/.test(out(over).error)); const usage = path.join(tmp, "spent.jsonl"); await appendGenerationUsage(usage, [{ at: new Date().toISOString(), day: utcDay(), jobId: "x", article: "a", iteration: 1, task: "sweep", model: "claude-sonnet-5-5", inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, usd: 25 }]); const refused = await enqueueReportDraft({ task: "clips-suggest", project: dir }, { ...deps(), paths: { ...paths, generationUsageFile: usage } } as ReportDraftDeps); assert.ok(!out(refused).ok && /daily cap/.test(out(refused).error)); }); test("labels on the local model: draft:local through the arbiter, batches fitted, a label over six words refused, ollama unloaded", async () => { const dir = path.join(tmp, "local-project"); writeReactionProject(dir); ol.push((body: { messages: { content: string }[] }) => { const ids = idsOf(body.messages[1]!.content); const a = labelAnswer(ids); a.items[0]!.label = "a label with far too many words to keep"; return jsonReply(a); }); const { job, done, log } = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir }, deps({ routes: { ...gen.routes, "clips-suggest": "local" } }))); assert.equal(done.status, "done", log); assert.equal(job.queueKey, "draft:local"); assert.match(log, /p001: refused — a label of 9 words \(at most 6\)/); assert.match(log, /unloaded qwen3:8b from ollama/); const { doc } = await readSuggestions(dir); assert.equal(doc!.model, "qwen3:8b"); assert.deepEqual(Object.keys(doc!.items).sort(), ["p002", "p003", "p004", "p005"]); assert.ok(ol.unloads.includes("qwen3:8b")); // A local run spends nothing on the ledger; its calls are there at no cost (demo epic D3). const mine = (await readGenerationUsage(paths.generationUsageFile)).filter((r) => r.jobId === job.id); assert.equal(mine.filter((r) => !isLocalUsage(r)).length, 0); assert.ok(mine.length > 0 && mine.every((r) => r.model === "qwen3:8b" && r.usd === 0 && (r.calls ?? 0) > 0)); }); test("the code route: no model is asked; a session's answers are read as a model's and written as claude-code's", async () => { const dir = path.join(tmp, "code-project"); writeReactionProject(dir); const code = { routes: { ...gen.routes, "clips-suggest": "code" as const } }; // Routed to code with no answers: refused at the ask, naming the route. const refused = await enqueueReportDraft({ task: "clips-suggest", project: dir }, deps(code)); assert.ok(!out(refused).ok && /routed to Claude Code/.test(out(refused).error)); // The plan is the request a session answers. const plan = await planClipsSuggestJob(parseReportDraftBody({ task: "clips-suggest", project: dir, dryRun: true }), deps(code)); assert.equal(plan.provider, "code"); assert.equal(plan.calls, 0); assert.match(plan.request.user, /\[p004\] 0:40–0:47/); const asked = api.requests.length + ol.requests.length; const { job, done, log } = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir, answers: labelAnswer(["p001", "p002"]) }, deps(code))); assert.equal(done.status, "done", log); assert.equal(job.queueKey, "draft:api"); assert.equal(api.requests.length + ol.requests.length, asked); const { doc } = await readSuggestions(dir); assert.equal(doc!.model, "claude-code"); assert.deepEqual(Object.keys(doc!.items), ["p002", "p001"]); // Junk answers are refused. const junk = await finished(await enqueueReportDraft({ task: "clips-suggest", project: dir, answers: { nope: true } }, deps(code))); assert.equal(junk.done.status, "failed"); assert.match(junk.log, /the session's answers are refused/); }); test("Ask the assistant: the note and the clip's words asked, the reply posted as the agent's with its proposal, nothing applied", async () => { const dir = path.join(tmp, "ask-project"); writeReactionProject(dir, { note: { clip: "r002", text: "start it where he laughs" } }); // Without UMTOOL_URL the ask is refused (its reply has nowhere to go). const nowhere = await enqueueReportDraft({ task: "clips-suggest", project: dir, note: PROJECT_NOTE }, deps({}, { umtoolUrl: null, workerToken: "t" })); assert.ok(!out(nowhere).ok && /UMTOOL_URL is not set/.test(out(nowhere).error)); const missing = await enqueueReportDraft({ task: "clips-suggest", project: dir, note: "n_absent00" }, deps({}, { umtoolUrl: "http://x", workerToken: "t" })); assert.ok(!out(missing).ok && /no note n_absent00/.test(out(missing).error)); let prompt = ""; api.push((body: { messages: { content: unknown }[] }) => { prompt = userOf(body); return toolTurn("answer", { reply: "Start it on the laugh at 95 s.", proposal: { kind: "trim", from: 94.8, to: 99 } }); }); const posted: { project: string; note: string; text: string; proposal: AskProposal | null }[] = []; const { done, log } = await finished( await enqueueReportDraft({ task: "clips-suggest", project: dir, note: PROJECT_NOTE }, deps({}, { postReply: async (r) => void posted.push(r) })), ); assert.equal(done.status, "done", log); assert.match(prompt, /The comment on clip r002 \(88\.0–99\.0 s\): start it where he laughs/); assert.match(prompt, /HOST: haha/); assert.deepEqual(posted, [ { project: dir, note: PROJECT_NOTE, text: "Start it on the laugh at 95 s.", proposal: { kind: "trim", clip: "r002", from: 94.8, to: 99, basis: { cutStart: 88, cutEnd: 99 } } }, ]); assert.match(log, /"kind":"ask","ask":\{"note":"n_synth0001","clip":"r002","proposal":\{"kind":"trim"/); // The manifest is as it was: the operator's Apply does the trim. const m = JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")); assert.deepEqual([m.timeline[1].cutStart, m.timeline[1].cutEnd], [88, 99]); });