import { test } from "node:test"; import assert from "node:assert/strict"; import { connectWith, fakeEditor, isError, textOf } from "./editorOps.testkit"; import { GENERATION_PRESETS, sanitizeGeneration } from "yt-dlp-transcript-common/lib/generationSettings"; import { GENERATE_POLL_MS, GENERATE_TASKS, generateTool, generationPolicyTool, planGeneration, renderIterationSummary, resultMarkerOf, validateGenerateArgs, } from "./generation"; // ─── The Claude Code balance (release 27 S9) ─── // // generation_policy and generate against a fake editor: no network, no timers // (sleep advances a fake clock). const POLICY = { preset: "balanced", routes: { sweep: "code", "revise-report": "api", "revise-video": "local", narrate: "local", research: "api" }, models: { api: "claude-sonnet-5-5", local: "qwen3:8b", extractor: "claude-haiku-4-5" }, caps: { sweep: 5, revision: 2, narration: 1, daily: 20, max: 10 }, cacheTtl: "5m", // The editor redacts it (its key matches the secret pattern); the tool must // not render it either way. apiKeyFile: "", anthropicBaseUrl: "", ollamaUrl: "", projectsRoot: "/srv/projects-root-never-shown", }; type Sent = { url: string; method: string; body?: unknown }; // An editor that serves the policy, the day's usage, a report-draft POST, a // job that runs for `runPolls` polls and then ends `end`, and the iteration. function editor(opts: { policy?: Record; runPolls?: number; end?: string; iteration?: Record; marker?: boolean; task?: string; markerJson?: Record; plan?: Record } = {}) { let policy = { ...POLICY, ...(opts.policy ?? {}) }; let polls = 0; const runPolls = opts.runPolls ?? 0; const iteration = { n: 3, kind: "revise-report", model: "claude-sonnet-5-5", status: opts.end ?? "done", parent: 2, copyOf: null, usage: { "claude-sonnet-5-5": { usd: 0.42, inputTokens: 1, outputTokens: 1 }, "claude-haiku-4-5": { usd: 0.03, inputTokens: 1, outputTokens: 1 } }, ops: { applied: [{ op: "drop" }, { op: "title" }], refused: [{ op: "merge", why: "finding 9 does not exist" }] }, minutes: 2.5, checks: [ { name: "strict-quotes", ok: true }, { name: "verify-quotes", ok: false, detail: "1 inexact (an old quote)" }, ], steps: [], ...(opts.iteration ?? {}), }; const marker = `@@report-draft ${JSON.stringify(opts.markerJson ?? { article: "synth-a", iteration: 3, task: opts.task ?? "revise-report", status: opts.end ?? "done", summary: "2 op(s) applied, 1 refused — “A title”", usd: 0.45, minutes: 2.5 })}`; const fake = fakeEditor((s) => { const u = new URL(s.url); if (u.pathname === "/api/ops/settings" && s.method === "GET") return { status: 200, body: { ok: true, key: "generation", value: policy } }; if (u.pathname === "/api/ops/settings" && s.method === "POST") { const routes = (s.body as { patch: { generation: { routes: Record } } }).patch.generation.routes; // The editor's own sanitizer names the preset the routes are. policy = { ...policy, routes: routes as typeof policy.routes, preset: sanitizeGeneration({ routes }).preset }; return { status: 200, body: { ok: true, changed: ["generation"], value: { generation: policy } } }; } if (u.pathname === "/api/ops/generation-usage") return { status: 200, body: { ok: true, day: "2026-10-13", usd: 1.75, jobs: 2, daily: 20 } }; if (u.pathname === "/api/ops/report-draft" && opts.plan && (s.body as { dryRun?: boolean } | undefined)?.dryRun) return { status: 200, body: { ok: true, plan: opts.plan } }; if (u.pathname === "/api/ops/report-draft") return { status: 200, body: { ok: true, jobId: "job-1", iteration: 3 } }; if (u.pathname === "/api/ops/job/job-1") { polls++; const status = polls > runPolls ? (opts.end ?? "done") : "running"; const tail = status === "running" ? [`turn ${polls}: reading`] : ["applying ops", ...(opts.marker === false ? [] : [marker])]; return { status: 200, body: { ok: true, job: { id: "job-1", kind: "report-draft", status }, tail } }; } if (u.pathname === "/api/ops/iterations") { return { status: 200, body: { ok: true, article: "synth-a", iteration, dir: "/srv/t/reports/synth-a/iterations/3", files: { "report.json": "/srv/t/reports/synth-a/iterations/3/report.json", "sweep.md": "/srv/t/reports/synth-a/iterations/3/sweep.md", "turns.jsonl": "/srv/t/reports/synth-a/iterations/3/turns.jsonl", "proposals.json": null, }, }, }; } return { status: 404, body: { ok: false, error: `no route ${u.pathname}` } }; }); // A clock that a sleep advances. let clock = 0; fake.deps.now = () => clock; fake.deps.sleep = async (ms: number) => { clock += ms; }; return { ...fake, sentOf: (path: string) => fake.sent.filter((x: Sent) => new URL(x.url).pathname === path) }; } test("generation_policy reads the routes, models, caps and the day's spend — never the key file or other settings", async () => { const e = editor(); const a = await generationPolicyTool({}, e.deps as never); assert.equal(a.isError, undefined, a.text); assert.match(a.text, /preset \*\*balanced\*\*/); assert.match(a.text, /- sweep → code \(this Claude Code session\)/); assert.match(a.text, /- revise-report → api \(the Claude API, claude-sonnet-5-5\)/); assert.match(a.text, /- narrate → local \(the local model, qwen3:8b\)/); assert.match(a.text, /- research → api \(the Claude API, claude-sonnet-5-5\)/); assert.match(a.text, /extractor claude-haiku-4-5/); assert.match(a.text, /sweep \$5\.00 · revision \$2\.00 · narration \$1\.00 · any job at most \$10\.00 · daily \$20\.00/); assert.match(a.text, /Today \(2026-10-13, UTC\): \$1\.75 spent on the Claude API in 2 job\(s\) of the \$20\.00 daily cap/); assert.doesNotMatch(a.text, /redacted|apiKey|anthropic\.env|projects-root-never-shown/); assert.deepEqual(e.sentOf("/api/ops/settings").map((s) => s.url), ["http://editor.test/api/ops/settings?key=generation"]); // Nothing written by a read. assert.equal(e.sent.filter((s) => s.method === "POST").length, 0); }); test("generation_policy sets a preset as its routes, and one route alone", async () => { const e = editor(); const a = await generationPolicyTool({ preset: "api" }, e.deps as never); assert.equal(a.isError, undefined, a.text); const post = e.sentOf("/api/ops/settings").find((s) => s.method === "POST")!; assert.deepEqual(post.body, { patch: { generation: { routes: { sweep: "api", "revise-report": "api", "revise-video": "api", narrate: "api", research: "api", // The media drafts (release 28) take narrate's route in every preset. cut: "api", onscreen: "api", teaser: "api", flips: "api", threads: "api", youtube: "api", social: "api", // Verdict proposals (release 29 M8): on a model in verdicts.models only. verdicts: "api", // The frame scan (release 30): routed like every task. frames: "api", // The clip finder's labels (release 36 lane D). "clips-suggest": "api", // The video assistant (release 38 lane E): api only in the api preset. "video-assist": "api", // Claim groups for a cut (lane L4): api only in the api preset. "propose-groups": "api", // Character proposals (characters C3): api only in the api preset. "cast-assign": "api", // A lookout's run (lane/lookout slice 2): routed like every task. lookout: "api", }, }, }, }); assert.match(a.text, /^Set preset api\./); assert.match(a.text, /preset \*\*api\*\*/); const one = await generationPolicyTool({ task: "sweep", route: "local" }, e.deps as never); const post2 = e.sentOf("/api/ops/settings").filter((s) => s.method === "POST")[1]; // The whole routes object (the writer merges one level; a nested object replaces). assert.deepEqual(post2.body, { patch: { generation: { routes: { ...GENERATION_PRESETS.api, sweep: "local" } } }, }); assert.match(one.text, /^Routed sweep to local\./); assert.match(one.text, /preset \*\*custom\*\*/); }); test("generation_policy refuses a muddle before it asks the editor", async () => { const e = editor(); for (const [args, re] of [ [{ preset: "api", task: "sweep", route: "api" }, /not both/], [{ task: "sweep" }, /names both task and route/], [{ preset: "cheap" }, /preset is one of code, balanced, api, local/], [{ task: "sweep", route: "cloud" }, /route is one of code, api, local/], ] as const) { const a = await generationPolicyTool(args as Record, e.deps as never); assert.equal(a.isError, true); assert.match(a.text, re); } assert.equal(e.sent.length, 0); const unknown = await generationPolicyTool({ task: "nope", route: "api" }, e.deps as never); assert.match(unknown.text, /no task "nope" — the policy routes sweep, revise-report, revise-video, narrate, research/); assert.equal(e.sent.filter((s) => s.method === "POST").length, 0); const none = await generationPolicyTool({}, fakeEditor(() => ({ status: 200, body: {} }), {}).deps as never); assert.equal(none.isError, true); assert.match(none.text, /ARCHILYZER_EDITOR_URL.*WORKER_TOKEN/); }); test("generate: a task routed to code is this session's — nothing is enqueued", async () => { const e = editor(); const a = await generateTool({ task: "sweep", article: "synth-a", question: "q?", channels: ["synth-kitchen"] }, e.deps as never); assert.equal(a.isError, true); assert.match(a.text, /sweep is routed to Claude Code \(preset balanced\) — do it in this session/); assert.equal(e.sentOf("/api/ops/report-draft").length, 0); // via overrides it, with the route's model. const b = await generateTool({ task: "sweep", article: "synth-a", question: "q?", channels: ["synth-kitchen"], via: "api" }, e.deps as never); assert.equal(b.isError, undefined, b.text); assert.deepEqual(e.sentOf("/api/ops/report-draft")[0].body, { task: "sweep", article: "synth-a", question: "q?", channels: ["synth-kitchen"], model: "claude-sonnet-5-5", }); assert.match(b.text, /queued as job job-1, making synth-a i3 on claude-sonnet-5-5\. .*generate \(job: "job-1", article: "synth-a", iteration: 3, wait: true\)/); }); test("generate: enqueue, follow politely, and summarise the iteration with what to review", async () => { const e = editor({ runPolls: 3 }); const progress: string[] = []; const a = await generateTool( { task: "revise-report", article: "synth-a", iteration: 2, feedback: "Drop the second finding.", wait: true }, e.deps as never, (p) => { progress.push(p.status); }, ); assert.equal(a.isError, false, a.text); // The route's model is the editor's to pick: no model sent. assert.deepEqual(e.sentOf("/api/ops/report-draft")[0].body, { task: "revise-report", article: "synth-a", iteration: 2, feedback: "Drop the second finding.", }); assert.deepEqual(progress, ["running: turn 1: reading", "running: turn 2: reading", "running: turn 3: reading"]); assert.match(a.text, /^generate: revise-report of synth-a i3 — \*\*done\*\* on claude-sonnet-5-5 \(job job-1\)/); assert.match(a.text, /2 op\(s\) applied, 1 refused/); assert.match(a.text, /Cost: \$0\.45 \(claude-sonnet-5-5 \$0\.42, claude-haiku-4-5 \$0\.03\) · 2\.5 min/); assert.match(a.text, /Ops: 2 applied, 1 refused\n {2}- refused merge: finding 9 does not exist/); assert.match(a.text, /Checks: 1 passed, 1 not\n {2}- verify-quotes: 1 inexact/); assert.match(a.text, /sweep\.md: \/srv\/t\/reports\/synth-a\/iterations\/3\/sweep\.md/); assert.doesNotMatch(a.text, /turns\.jsonl/); assert.match(a.text, /Review it — you are the reviewer/); assert.match(a.text, /`get_transcript`/); assert.match(a.text, /Use this iteration/); // Polite: one poll per GENERATE_POLL_MS; the iteration read once at the end. assert.equal(e.sentOf("/api/ops/job/job-1").length, 5); assert.equal(e.sentOf("/api/ops/iterations").length, 1); assert.equal(new URL(e.sentOf("/api/ops/iterations")[0].url).search, "?article=synth-a&n=3"); }); test("generate: a wait that runs out answers how to resume; resuming summarises", async () => { const e = editor({ runPolls: 1000 }); const a = await generateTool( { task: "revise-video", article: "synth-a", iteration: 2, feedback: "Shorter.", wait: true, wait_seconds: 12 }, e.deps as never, ); assert.equal(a.isError, undefined, a.text); assert.match(a.text, /Still running after 15s\. Last log line: turn 4: reading/); assert.match(a.text, /generate again with job: "job-1", article: "synth-a", iteration: 3 to keep waiting — never start the same task again/); assert.equal(e.sentOf("/api/ops/job/job-1").length, Math.floor((12 * 1000) / GENERATE_POLL_MS) + 2); const done = editor(); const b = await generateTool({ job: "job-1" }, done.deps as never); assert.equal(b.isError, false, b.text); assert.equal(done.sentOf("/api/ops/report-draft").length, 0); assert.match(b.text, /revise-report of synth-a i3 — \*\*done\*\*/); }); test("generate: a failed job says why, with its log; a job whose log names no iteration still answers", async () => { const e = editor({ end: "failed", iteration: { status: "failed", error: "the daily cap" } }); const a = await generateTool({ job: "job-1" }, e.deps as never); assert.equal(a.isError, true); assert.match(a.text, /\*\*failed\*\*/); assert.match(a.text, /error: the daily cap/); assert.match(a.text, /last log lines:\n```\napplying ops\n```/); assert.match(a.text, /Running it again, or here instead, is their call/); const bare = editor({ marker: false }); const b = await generateTool({ job: "job-1" }, bare.deps as never); assert.match(b.text, /its log names no iteration \(pass article and iteration to read it\)/); const named = await generateTool({ job: "job-1", article: "synth-a", iteration: 3 }, editor({ marker: false }).deps as never); assert.match(named.text, /of synth-a i3 — \*\*done\*\*/); }); test("generate: the arguments are checked before any request; research is a task", () => { assert.ok(GENERATE_TASKS.includes("research")); const ok = validateGenerateArgs({ task: "research", article: "synth-a", question: "what was said?", channels: ["synth-kitchen"] }); assert.equal(ok.ok, true); // A sweep's extractor, per job (release 28 F2), passed through as the editor's key. const ex = validateGenerateArgs({ task: "sweep", article: "a", question: "q", channels: ["c"], extractorModel: " claude-haiku-5-5 " }); assert.ok(ex.ok && ex.request.kind === "start"); if (ex.ok && ex.request.kind === "start") assert.equal(ex.request.body.extractorModel, "claude-haiku-5-5"); for (const [args, re] of [ [{ task: "nope", article: "a" }, /task is one of sweep, revise-report, revise-video, narrate, research, cut, onscreen, teaser, flips, threads, youtube/], [{ task: "cut", article: "a", iteration: 1, entries: [] }, /entries is a non-empty list/], // The media drafts (release 28): a step on the iteration it names. [{ task: "onscreen", article: "a" }, /a onscreen draft names the iteration it drafts on/], [{ task: "teaser", article: "a", iteration: 1, copyOf: 1 }, /a teaser draft is a step on its iteration: it has no copyOf/], [{ task: "youtube", article: "a", iteration: 1, feedback: "shorter" }, /feedback is not a youtube draft's/], [{ task: "sweep", article: "a", question: "q", channels: ["c"], entries: ["c01"] }, /entries is a media draft's/], [{ task: "sweep", article: "Not An Id" }, /article is an article id/], [{ task: "sweep", article: "a", channels: [] }, /channels is a non-empty list/], [{ task: "sweep", article: "a", iteration: 0 }, /iteration is an iteration number/], [{ task: "sweep", article: "a", maxUsd: -1 }, /maxUsd is a positive number/], [{ task: "sweep", article: "a", via: "code" }, /via is "api" or "local"/], [{ task: "sweep", article: "a", via: "api", model: "x" }, /model or via, not both/], [{ task: "sweep", article: "a", wait_seconds: -2 }, /wait_seconds/], [{ job: "../etc" }, /is not a job id/], [{ task: "revise-report", article: "a", iteration: 1, feedback: "f", extractorModel: "claude-haiku-4-5" }, /extractorModel is a sweep's/], [{ task: "sweep", article: "a", extractorModel: "qwen3:8b" }, /extractorModel is a Claude model id/], ] as const) { const v = validateGenerateArgs(args as Record); assert.equal(v.ok, false, JSON.stringify(args)); assert.match((v as { error: string }).error, re); } }); test("generate: a media draft is a step on its iteration, routed like any task; done, the review is the operator's in umtool", async () => { for (const task of ["cut", "onscreen", "teaser", "flips", "threads", "narrate", "youtube", "social"]) { assert.ok(GENERATE_TASKS.includes(task), task); const v = validateGenerateArgs({ task, article: "synth-a", iteration: 3, entries: ["c01"], force: true }); assert.equal(v.ok, true, task); } // Routed by the policy: the editor runs it on the route's model. const e = editor({ task: "onscreen", policy: { routes: { ...POLICY.routes, onscreen: "local" } }, iteration: { kind: "sweep", ops: undefined, checks: [{ name: "onscreen", ok: false, detail: "3 title(s) written, 1 not written (a hard check)" }], steps: [{ task: "onscreen", model: "qwen3:8b", status: "done", jobId: "job-1", detail: "3 title(s) written" }], projectDir: "/srv/projects/synth-a/i3", }, }); const a = await generateTool({ task: "onscreen", article: "synth-a", iteration: 3, entries: ["c01", "c02"], wait: true }, e.deps as never); assert.ok(!a.isError, a.text); assert.deepEqual(e.sentOf("/api/ops/report-draft")[0].body, { task: "onscreen", article: "synth-a", iteration: 3, entries: ["c01", "c02"] }); const queued = await generateTool({ task: "onscreen", article: "synth-a", iteration: 3 }, e.deps as never); assert.match(queued.text, /drafting its onscreen on synth-a i3 on the policy's model/); assert.match(a.text, /onscreen: 3 title\(s\) written/); assert.match(a.text, /\*\*Review the draft — the approval is the operator's\.\*\* It drafted each clip's on-screen title and subtitle in the video project \(`\/srv\/projects\/synth-a\/i3`\)/); assert.match(a.text, /`onscreen-draft\.json`/); assert.match(a.text, /never by writing `drafts\.review\.json` yourself/); assert.match(a.text, /A final build refuses any drafted field not approved/); assert.doesNotMatch(a.text, /Review it — you are the reviewer/); // A task routed to code is this session's, as any. const code = await generateTool({ task: "youtube", article: "synth-a", iteration: 3 }, editor({ policy: { routes: { ...POLICY.routes, youtube: "code" } } }).deps as never); assert.equal(code.isError, true); assert.match(code.text, /youtube is routed to Claude Code/); }); test("a media draft's answer puts its video project first, above the iteration's files (release 29 D1); any other task's keeps it under them", () => { const iteration = { n: 3, kind: "sweep", model: "qwen3:8b", status: "done", usage: {}, steps: [{ task: "social", model: "qwen3:8b", status: "done", jobId: "job-9", detail: "2 social posts drafted" }], projectDir: "/srv/projects/synth-a/i3", }; const files = { "sweep.md": "/srv/reports/synth-a/iterations/3/sweep.md", "report.json": "/srv/reports/synth-a/iterations/3/report.json" }; const step = renderIterationSummary({ task: "social", article: "synth-a", jobId: "job-9", marker: null, iteration: iteration as never, dir: "/srv/reports/synth-a/iterations/3", files }).split("\n"); assert.match(step[0]!, /^generate: social of synth-a i3 — \*\*done\*\*/); assert.equal(step[1], "Video project: /srv/projects/synth-a/i3"); assert.equal(step.filter((l) => l.startsWith("Video project:")).length, 1); assert.ok(step.indexOf("Where (the editor's disk): /srv/reports/synth-a/iterations/3") > 1); // The run's records are not listed as paths: the turns, the trace, the model log. const records = { ...files, "turns.jsonl": "/srv/x/turns.jsonl", "trace.jsonl": "/srv/x/trace.jsonl", "calls.jsonl": "/srv/x/calls.jsonl", "calls-text.jsonl": "/srv/x/calls-text.jsonl" }; const listed = renderIterationSummary({ task: "social", article: "synth-a", jobId: "job-9", marker: null, iteration: iteration as never, dir: "/srv/reports/synth-a/iterations/3", files: records }); assert.ok(!/turns\.jsonl|trace\.jsonl|calls\.jsonl|calls-text\.jsonl/.test(listed), listed); assert.match(listed, /sweep\.md: \/srv/); const revise = renderIterationSummary({ task: "revise-video", article: "synth-a", jobId: "job-8", marker: null, iteration: { ...iteration, kind: "revise-video", steps: [] } as never, dir: "/srv/reports/synth-a/iterations/3", files }).split("\n"); assert.ok(revise.indexOf("Video project: /srv/projects/synth-a/i3") > revise.indexOf("Where (the editor's disk): /srv/reports/synth-a/iterations/3")); }); test("resultMarkerOf reads the job's @@report-draft line", () => { assert.deepEqual(resultMarkerOf(["x", '@@report-draft {"article":"a","iteration":2}', "y"]), { article: "a", iteration: 2 }); assert.equal(resultMarkerOf(["nothing here"]), null); }); test("planGeneration: the policy when the editor answers; nothing without an editor; a note when it fails", async () => { const p = await planGeneration(editor().deps as never); assert.deepEqual(p.generation, { preset: "balanced", routes: POLICY.routes, models: { api: "claude-sonnet-5-5", local: "qwen3:8b" }, }); assert.deepEqual(await planGeneration(fakeEditor(() => ({ status: 200, body: {} }), {}).deps as never), {}); const down = await planGeneration(fakeEditor(() => new TypeError("fetch failed")).deps as never); assert.match(down.note!, /the generation policy could not be read \(.*did not answer: fetch failed\) — this plan is for this session/); }); test("the server serves both tools, and sweep_plan routes by the policy it reads", async () => { const routed = editor({ policy: { routes: { ...POLICY.routes, sweep: "api" }, preset: "custom" } }); const client = await connectWith(routed.deps); const policy = await client.callTool({ name: "generation_policy", arguments: {} }); assert.equal(isError(policy), false, textOf(policy)); assert.match(textOf(policy), /- sweep → api/); const plan = await client.callTool({ name: "sweep_plan", arguments: { request: "coffee channels=demo" } }); const text = textOf(plan); assert.match(text, /^A \*\*corpus sweep\*\* for "coffee", scoped to channels "demo" — \*\*routed to the Claude API\*\*/); assert.match(text, /1\. \*\*Generate — do not sweep it yourself\.\*\*.*Call `generate` with task: "sweep"/); assert.match(text, /channels: \["demo"\], model: "claude-sonnet-5-5", wait: true/); assert.doesNotMatch(text, /enumerate_matches/); const local = await connectWith(editor().deps); const unrouted = textOf(await local.callTool({ name: "sweep_plan", arguments: { request: "coffee channels=demo" } })); assert.match(unrouted, /^Run a \*\*corpus sweep\*\*/); assert.match(unrouted, /`enumerate_matches`/); const down = await connectWith(fakeEditor(() => new TypeError("fetch failed")).deps); const fallback = textOf(await down.callTool({ name: "sweep_plan", arguments: { request: "coffee channels=demo" } })); assert.match(fallback, /^Run a \*\*corpus sweep\*\*/); assert.match(fallback, /the generation policy could not be read/); const gen = await client.callTool({ name: "generate", arguments: { task: "sweep", article: "synth-a", question: "q?", channels: ["demo"] } }); assert.equal(isError(gen), false, textOf(gen)); assert.match(textOf(gen), /queued as job job-1/); }); test("generate: research takes its autonomy; a continuation is a sweep with the run's iteration", async () => { const e = editor(); const a = await generateTool( { task: "research", article: "synth-a", question: "what is missing?", channels: ["synth-kitchen"], autonomy: "limits" }, e.deps as never, ); assert.equal(a.isError, undefined, a.text); assert.deepEqual(e.sentOf("/api/ops/report-draft")[0].body, { task: "research", article: "synth-a", question: "what is missing?", channels: ["synth-kitchen"], autonomy: "limits", }); const wrong = await generateTool({ task: "sweep", article: "synth-a", question: "q", channels: ["x"], autonomy: "auto" }, e.deps as never); assert.match(wrong.text, /autonomy is a research run's/); const bad = await generateTool({ task: "research", article: "synth-a", question: "q", autonomy: "yolo" }, e.deps as never); assert.match(bad.text, /autonomy is one of propose, limits, auto/); // Continuing a research run with sweeps routed to code: say so, enqueue nothing. const cont = await generateTool({ task: "sweep", article: "synth-a", iteration: 4 }, e.deps as never); assert.equal(cont.isError, true); assert.match(cont.text, /a sweep continuing research run i4 is routed to Claude Code/); assert.equal(e.sentOf("/api/ops/report-draft").length, 1); const via = await generateTool({ task: "sweep", article: "synth-a", iteration: 4, via: "api", force: true }, e.deps as never); assert.deepEqual(e.sentOf("/api/ops/report-draft")[1].body, { task: "sweep", article: "synth-a", iteration: 4, force: true, model: "claude-sonnet-5-5" }); assert.equal(via.isError, undefined, via.text); }); test("generate: a research run's summary is its phase and proposals, with what is the operator's", async () => { const e = editor({ iteration: { kind: "research", ops: undefined, checks: [], research: { autonomy: "propose", phase: "wait", notes: ["p01 waits for approval: a new channel"] }, }, }); const a = await generateTool({ job: "job-1", article: "synth-a", iteration: 3 }, e.deps as never); assert.match(a.text, /Research: phase wait, autonomy propose/); assert.match(a.text, /- p01 waits for approval: a new channel/); assert.match(a.text, /\*\*Review its proposals\*\*/); assert.match(a.text, /the yes or no is theirs \(umtool's research queue, or `pnpm ops research-approve`\)/); assert.match(a.text, /generate with task "sweep", article "synth-a", iteration: 3, wait: true/); assert.doesNotMatch(a.text, /Review it — you are the reviewer/); }); test("generate verdicts: never this session's — a code route with no model refuses; done, the marker's counts and the operator's review", async () => { const e = editor({ policy: { routes: { ...POLICY.routes, verdicts: "code" } } }); const a = await generateTool({ task: "verdicts", article: "synth-ruled" }, e.deps as never); assert.equal(a.isError, true); assert.match(a.text, /verdict proposals run only on a model that cleared the verdict bench's bar \(settings\.generation\.verdicts\.models\)/); assert.match(a.text, /never proposes or rules claims' verdicts itself/); assert.equal(e.sentOf("/api/ops/report-draft").length, 0); const done = editor({ markerJson: { article: "synth-ruled", iteration: 0, task: "verdicts", status: "done", summary: "3 verdicts proposed on qwen3:8b", usd: 0, verdicts: { proposed: 3, failed: 0, skipped: 5, promptVersion: "2" } }, }); const b = await generateTool({ task: "verdicts", article: "synth-ruled", model: "qwen3:8b", wait: true }, done.deps as never); assert.equal(b.isError, false, b.text); assert.match(b.text, /^generate verdicts: job job-1 ended \*\*done\*\* — 3 verdicts proposed on qwen3:8b/); assert.match(b.text, /Article: synth-ruled · 3 proposed, 0 failed, 5 skipped · prompt v2/); assert.match(b.text, /Review verdicts/); assert.match(b.text, /Never set a claim's verdict yourself/); assert.equal(done.sentOf("/api/ops/iterations").length, 0); }); test("generate clips-suggest: a project, not an article; routed to code, the editor's plan is this session's request; the answers go back to the editor", async () => { assert.ok(GENERATE_TASKS.includes("clips-suggest")); assert.match(String((validateGenerateArgs({ task: "clips-suggest", article: "a" }) as { error: string }).error), /names its project/); assert.match(String((validateGenerateArgs({ task: "clips-suggest", project: "/r/p", iteration: 2 }) as { error: string }).error), /iteration is not a clips-suggest job's/); assert.match(String((validateGenerateArgs({ task: "sweep", article: "a", project: "/r/p" }) as { error: string }).error), /a clips-suggest job's/); assert.match(String((validateGenerateArgs({ task: "clips-suggest", project: "/r/p", answers: { items: [] }, model: "m" }) as { error: string }).error), /no model/); const plan = { proposals: 2, calls: 0, wordsFrom: "words.json", estimate: { inputTokens: 900, outputTokens: 120, usd: 0 }, request: { system: "You read moments from a livestream…", user: "2 moments. Answer every id once.\n\n[p001] 1:28–1:39 (11 s) · heard: laugh\nHOST: haha", ids: ["p001", "p002"] }, }; const code = editor({ policy: { routes: { ...POLICY.routes, "clips-suggest": "code" } }, plan }); const a = await generateTool({ task: "clips-suggest", project: "/r/p" }, code.deps as never); assert.equal(a.isError, undefined, a.text); assert.match(a.text, /^generate clips-suggest: routed to Claude Code \(preset balanced\) — label these 2 proposals in this session\./); assert.match(a.text, /call generate with task "clips-suggest", project "\/r\/p", answers: \{"items"/); assert.match(a.text, /Never write that file, the manifest or a clip yourself/); assert.match(a.text, /\[p001\] 1:28–1:39 \(11 s\) · heard: laugh\nHOST: haha/); assert.deepEqual(code.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "clips-suggest", project: "/r/p", dryRun: true }]); const answers = { items: [{ id: "p001", label: "the laugh", why: "He loses it.", score: 8 }] }; const done = editor({ markerJson: { article: "", iteration: 0, task: "clips-suggest", project: "/r/p", kind: "labels", status: "done", summary: "1 proposal labelled on claude-code", usd: 0, suggestions: { labelled: 1, refused: 0, failed: 0 } }, }); const b = await generateTool({ task: "clips-suggest", project: "/r/p", answers, wait: true }, done.deps as never); assert.equal(b.isError, false, b.text); assert.deepEqual(done.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "clips-suggest", project: "/r/p", answers }]); assert.equal(done.sentOf("/api/ops/settings").length, 0, "a session's answers need no policy read"); assert.match(b.text, /^generate clips-suggest: job job-1 ended \*\*done\*\* — 1 proposal labelled on claude-code/); assert.match(b.text, /Project: \/r\/p · 1 labelled, 0 refused, 0 in failed batches/); assert.match(b.text, /Nothing in the cut changed/); assert.equal(done.sentOf("/api/ops/iterations").length, 0); }); test("generate video-assist: a project and a request (or a note); routed to code, the plan is this session's request; the answer goes back to the editor", async () => { assert.ok(GENERATE_TASKS.includes("video-assist")); assert.match(String((validateGenerateArgs({ task: "video-assist", article: "a" }) as { error: string }).error), /names its project/); assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p" }) as { error: string }).error), /needs its request/); assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p", request: "x", note: "n_abcd1234" }) as { error: string }).error), /not both/); assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p", request: "x", scope: "everything" }) as { error: string }).error), /scope is look, clips, fx or all/); assert.match(String((validateGenerateArgs({ task: "video-assist", project: "/r/p", request: "x", iteration: 2 }) as { error: string }).error), /iteration is not a video-assist job's/); assert.match(String((validateGenerateArgs({ task: "sweep", article: "a", request: "x" }) as { error: string }).error), /a video-assist job's/); const plan = { scope: "all", estimate: { inputTokens: 700 }, request: { system: "You adjust a video project's settings…", user: "THE REQUEST:\nno QR\n\nTHE PROJECT NOW:\n- qr = true" } }; const code = editor({ policy: { routes: { ...POLICY.routes, "video-assist": "code" } }, plan }); const a = await generateTool({ task: "video-assist", project: "/r/p", request: "no QR" }, code.deps as never); assert.equal(a.isError, undefined, a.text); assert.match(a.text, /^generate video-assist: routed to Claude Code \(preset balanced\) — answer this request on the project in this session \(scope all\)\./); assert.match(a.text, /call generate with task "video-assist", project "\/r\/p", the same request "no QR", answers: \{"ops": \[\.\.\.\], "reply": "\.\.\."\}/); assert.match(a.text, /Never write that file or the manifest yourself/); assert.match(a.text, /- qr = true/); assert.deepEqual(code.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "video-assist", project: "/r/p", request: "no QR", dryRun: true }]); const answers = { ops: [{ op: "look", id: "", key: "qr", value: false }], reply: "QR off." }; const done = editor({ markerJson: { article: "", iteration: 0, task: "video-assist", project: "/r/p", status: "done", summary: "1 edit proposed (QR code on → off) on claude-code", usd: 0, assist: { proposed: 1, refused: 0, diff: ["QR code on → off"] } }, }); const b = await generateTool({ task: "video-assist", project: "/r/p", request: "no QR", answers, wait: true }, done.deps as never); assert.equal(b.isError, false, b.text); assert.deepEqual(done.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "video-assist", project: "/r/p", request: "no QR", answers }]); assert.equal(done.sentOf("/api/ops/settings").length, 0, "a session's answer needs no policy read"); assert.match(b.text, /^generate video-assist: job job-1 ended \*\*done\*\* — 1 edit proposed \(QR code on → off\) on claude-code/); assert.match(b.text, /Project: \/r\/p · 1 proposed, 0 refused\n- QR code on → off/); assert.match(b.text, /Nothing in the cut changed/); assert.equal(done.sentOf("/api/ops/iterations").length, 0); }); test("generate propose-groups: a project (words optional); routed to code, the plan is this session's request; the answer goes back to the editor", async () => { assert.ok(GENERATE_TASKS.includes("propose-groups")); assert.match(String((validateGenerateArgs({ task: "propose-groups", article: "a" }) as { error: string }).error), /names its project/); assert.match(String((validateGenerateArgs({ task: "propose-groups", project: "/r/p", scope: "all" }) as { error: string }).error), /scope is not a propose-groups job's/); assert.match(String((validateGenerateArgs({ task: "propose-groups", project: "/r/p", answers: [] }) as { error: string }).error), /answers is \{"groups"/); const plan = { estimate: { inputTokens: 900 }, request: { system: "You organise a video's cut…", user: "THE CUT NOW:\n§0 (the opening)\n- c01: \"words\"" } }; const code = editor({ policy: { routes: { ...POLICY.routes, "propose-groups": "code" } }, plan }); const a = await generateTool({ task: "propose-groups", project: "/r/p" }, code.deps as never); assert.equal(a.isError, undefined, a.text); assert.match(a.text, /^generate propose-groups: routed to Claude Code \(preset balanced\) — propose the claim groups for this cut in this session\./); assert.match(a.text, /call generate with task "propose-groups", project "\/r\/p", answers: \{"groups": \[\.\.\.\]\}/); assert.match(a.text, /- c01: "words"/); assert.deepEqual(code.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "propose-groups", project: "/r/p", dryRun: true }]); const answers = { groups: [{ section: 0, claim: "One claim", ids: ["c01"], why: "" }] }; const done = editor({ markerJson: { article: "", iteration: 0, task: "propose-groups", project: "/r/p", status: "done", summary: "1 group proposed on claude-code", usd: 0, groups: { proposed: 1, refused: 0, file: "/r/p/group-proposals.json" } }, }); const b = await generateTool({ task: "propose-groups", project: "/r/p", answers, wait: true }, done.deps as never); assert.equal(b.isError, false, b.text); assert.deepEqual(done.sentOf("/api/ops/report-draft").map((x) => x.body), [{ task: "propose-groups", project: "/r/p", answers }]); assert.match(b.text, /^generate propose-groups: job job-1 ended \*\*done\*\* — 1 group proposed on claude-code/); assert.match(b.text, /Project: \/r\/p · 1 proposed, 0 refused/); assert.match(b.text, /Nothing in the cut changed/); }); // demo epic D1: a sweep over a published archive names it to the editor. test("generate carries source for a sweep or research run, refuses it elsewhere", async () => { const { generateArgsWithSource } = await import("./server"); const ok = validateGenerateArgs({ task: "sweep", article: "a", question: "q", channels: ["c"], source: "remote:https://stub.test" }); assert.equal(ok.ok, true); assert.equal((ok as { request: { body: Record } }).request.body.source, "remote:https://stub.test"); const bad = validateGenerateArgs({ task: "revise-report", article: "a", iteration: 1, feedback: "x", source: "remote:https://stub.test" }); assert.match(String((bad as { error: string }).error), /source is a sweep's or a research run's/); assert.match(String((validateGenerateArgs({ task: "sweep", article: "a", question: "q", channels: ["c"], source: "nope" }) as { error: string }).error), /corpus handle/); // The server's resolution: the canonical handle of a remote or hub, never a local dir; only sweep and research. const remote = { handle: "remote:https://stub.test", spec: { kind: "remote" as const, url: "https://stub.test" } }; assert.equal(generateArgsWithSource({ task: "sweep", source: "https://stub.test/" }, remote).source, "remote:https://stub.test"); assert.equal(generateArgsWithSource({ task: "research" }, remote).source, "remote:https://stub.test"); assert.equal("source" in generateArgsWithSource({ task: "narrate", source: "x" }, remote), false); const local = { handle: "local:/x", spec: { kind: "local" as const, dir: "/x" } }; assert.equal("source" in generateArgsWithSource({ task: "sweep" }, local), false); });